Documentation
¶
Overview ¶
Package ir is the compiler's mid-level intermediate representation: a statement-level CFG of BasicBlocks holding IR nodes. It is a Go port of sonolus.py's sonolus/backend (ir.py, place.py, optimize/flow.py, finalize.py).
The IR is CFG-shaped and mutable (suited to SSA + optimization passes). It is distinct from snode.SNode, which is the final immutable node tree. finalize.go bridges the two: CFGToSNode lowers an optimized CFG into an snode.SNode.
Index ¶
- Constants
- func CFGToSNode(gen *IDGen, entry *BasicBlock) (snode.SNode, error)
- func Cond(v float64) *float64
- func FloorMod(a, b float64) float64
- func IEEERem(a, b float64) float64
- func Lower(n Node) (snode.SNode, error)
- func Pure(op Op) bool
- func SideEffects(op Op) bool
- func Walk(n Node, visit func(Node))
- type BasicBlock
- type BlockPlace
- type BlockSet
- type Const
- type FlowEdge
- type Get
- type IDGen
- type Instr
- type Mode
- type Node
- type Op
- type Phi
- type Place
- type SSAPlace
- type Set
- type TempBlock
Constants ¶
const ( BlockEntityMemory = 4000 BlockEntityData = 4001 BlockEntityInfo = 4003 BlockEntityDespawn = 4004 BlockEntityInput = 4005 BlockEntityScore = 4006 BlockEntityLife = 4007 BlockTempMemory = 10000 )
Canonical block ID constants referenced by all packages. Values must match the blockTables above.
const ( BlockRuntimeEnvironment = 1000 BlockRuntimeUpdate = 1001 // RuntimeCanvas in Preview mode BlockRuntimeTouch = 1002 BlockEngineRom = 3000 TouchFieldStride = 9 )
Runtime memory block IDs used by the Sonolus engine across all modes.
const ( // Arithmetic OpAdd = resource.RuntimeFunctionAdd OpSubtract = resource.RuntimeFunctionSubtract OpMultiply = resource.RuntimeFunctionMultiply OpDivide = resource.RuntimeFunctionDivide OpPower = resource.RuntimeFunctionPower OpMod = resource.RuntimeFunctionMod OpRem = resource.RuntimeFunctionRem OpNegate = resource.RuntimeFunctionNegate OpAbs = resource.RuntimeFunctionAbs OpSign = resource.RuntimeFunctionSign // Comparison OpEqual = resource.RuntimeFunctionEqual OpNotEqual = resource.RuntimeFunctionNotEqual OpLess = resource.RuntimeFunctionLess OpLessOr = resource.RuntimeFunctionLessOr OpGreater = resource.RuntimeFunctionGreater OpGreaterOr = resource.RuntimeFunctionGreaterOr // Logic OpAnd = resource.RuntimeFunctionAnd OpOr = resource.RuntimeFunctionOr OpNot = resource.RuntimeFunctionNot // Min / Max / Clamp OpMax = resource.RuntimeFunctionMax OpMin = resource.RuntimeFunctionMin OpClamp = resource.RuntimeFunctionClamp // Math OpLog = resource.RuntimeFunctionLog OpCeil = resource.RuntimeFunctionCeil OpFloor = resource.RuntimeFunctionFloor OpRound = resource.RuntimeFunctionRound OpFrac = resource.RuntimeFunctionFrac OpSin = resource.RuntimeFunctionSin OpCos = resource.RuntimeFunctionCos OpTan = resource.RuntimeFunctionTan OpSinh = resource.RuntimeFunctionSinh OpCosh = resource.RuntimeFunctionCosh OpTanh = resource.RuntimeFunctionTanh OpAsin = resource.RuntimeFunctionArcsin OpAcos = resource.RuntimeFunctionArccos OpAtan = resource.RuntimeFunctionArctan OpAtan2 = resource.RuntimeFunctionArctan2 OpRad = resource.RuntimeFunctionRadian OpDeg = resource.RuntimeFunctionDegree // Interpolation / remapping OpLerp = resource.RuntimeFunctionLerp OpLerpClamped = resource.RuntimeFunctionLerpClamped OpRemap = resource.RuntimeFunctionRemap OpRemapClamped = resource.RuntimeFunctionRemapClamped // Control flow OpIf = resource.RuntimeFunctionIf OpWhile = resource.RuntimeFunctionWhile OpSwitch = resource.RuntimeFunctionSwitch OpSwitchInteger = resource.RuntimeFunctionSwitchInteger OpSwitchWithDefault = resource.RuntimeFunctionSwitchWithDefault OpSwitchIntegerWithDefault = resource.RuntimeFunctionSwitchIntegerWithDefault // Memory OpGet = resource.RuntimeFunctionGet OpGetShifted = resource.RuntimeFunctionGetShifted OpSet = resource.RuntimeFunctionSet OpSetShifted = resource.RuntimeFunctionSetShifted // Block / execution OpExecute = resource.RuntimeFunctionExecute OpBlock = resource.RuntimeFunctionBlock OpJumpLoop = resource.RuntimeFunctionJumpLoop )
Canonical short aliases for runtime functions used throughout the compiler. These replace bare resource.RuntimeFunction* literals and the previously duplicated op* / rf* aliases in ir/optimize, ir/finalize, and snode.
ir/finalize.go and ir/optimize use these directly. snode keeps its own independent aliases (with the same names) because ir imports snode, so snode cannot import ir without a cycle.
const DefaultTempMemoryBlock = BlockTempMemory
DefaultTempMemoryBlock is the memory block temps are allocated into by default (sonolus.py play-mode TemporaryMemory). This is an alias for BlockTempMemory defined in blocks.go.
Variables ¶
This section is empty.
Functions ¶
func CFGToSNode ¶
func CFGToSNode(gen *IDGen, entry *BasicBlock) (snode.SNode, error)
CFGToSNode lowers an (optimized) CFG into a single snode.SNode tree, encoding inter-block control flow as a Block(JumpLoop(...)) of per-block Execute nodes. Port of sonolus.py finalize.cfg_to_engine_node.
func FloorMod ¶
FloorMod computes a floored modulo (result has the sign of the divisor), matching Python's % and the runtime RuntimeFunctionMod semantics. Used by frontend constant folding (value.go) and SCCP (sccp.go).
func IEEERem ¶
IEEERem computes IEEE 754 remainder, matching the runtime RuntimeFunctionRem semantics. Used by frontend constant folding and SCCP for compile-time evaluation.
func Lower ¶
Lower converts a single IR node into an snode.SNode. Port of finalize.ir_to_engine_node.
func Pure ¶
Pure reports whether an operation is pure (side-effect-free and deterministic in its arguments). The classification is generated from sonolus.py's Op.pure.
func SideEffects ¶
SideEffects reports whether an operation has observable side effects. The classification is generated from sonolus.py's Op.side_effects.
func Walk ¶
Walk traverses the IR tree depth-first, calling visit for each node. Nodes are visited bottom-up: children first, then the node itself. Unlike Map, Walk does not reconstruct nodes — it is intended for read-only analysis (use counting, liveness collection, etc.).
Nil nodes are visited as-is (visit(nil) is called). Callers that collect nodes into a slice should guard against nil entries.
Types ¶
type BasicBlock ¶
type BasicBlock struct {
Phis []*Phi
Statements []Node
Test Node // defaults to Const(0)
Incoming []*FlowEdge
Outgoing []*FlowEdge
}
BasicBlock is a CFG node: phi nodes, a list of statements, a branch test expression, and incoming/outgoing edges. Port of sonolus.py BasicBlock.
func AllocateTestBlocks ¶
func AllocateTestBlocks(entry *BasicBlock, blockID int) (*BasicBlock, error)
AllocateTestBlocks is the exported test-only wrapper around allocateTempBlocks. It assigns each distinct TempBlock a slot in the given memory block (no reuse, deterministic first-seen order).
Production code must use optimize.AllocateLive instead. This function is exported solely for unit tests that need a pre-SSA, pre-optimize allocation, because those tests call the frontend tracer directly and the result contains unresolved TempBlocks.
func NewBlock ¶
func NewBlock() *BasicBlock
NewBlock creates an empty block with a default test of Const(0).
func Preorder ¶
func Preorder(entry *BasicBlock) []*BasicBlock
Preorder returns reachable blocks in a BFS preorder that visits outgoing edges in sortedOutgoing order. Mirrors sonolus.py traverse_cfg_preorder.
func ReversePostorder ¶
func ReversePostorder(entry *BasicBlock) []*BasicBlock
ReversePostorder returns reachable blocks in reverse-postorder (the order used for block numbering in finalization and dominance).
func (*BasicBlock) ConnectTo ¶
func (b *BasicBlock) ConnectTo(other *BasicBlock, cond *float64)
ConnectTo adds an edge from b to other with the given condition (nil = default).
type BlockPlace ¶
BlockPlace addresses block[index + offset]. Block and Index are themselves IR nodes (typically Const for concrete block ids / indices, but may be expressions). Mirrors sonolus.py BlockPlace.
func Cell ¶
func Cell(block, index int) BlockPlace
Cell is a convenience for a fixed block[index] location with constant ids.
func NewBlockPlace ¶
func NewBlockPlace(block, index Node, offset int) BlockPlace
NewBlockPlace builds a BlockPlace addressing block[index + offset].
func TempCell ¶
func TempCell(t *TempBlock) BlockPlace
TempCell returns the place for a size-1 temp block.
type BlockSet ¶
type BlockSet struct {
// contains filtered or unexported fields
}
BlockSet answers block read/write questions for a given mode. It satisfies the optimizer's BlockOracle interface structurally.
func (BlockSet) RuntimeConstant ¶
RuntimeConstant reports whether the block holds runtime-constant data.
type Const ¶
type Const float64
Const is a numeric literal (sonolus.py IRConst). Non-finite values lower to ROM reads during finalization.
type FlowEdge ¶
type FlowEdge struct {
Src *BasicBlock
Dst *BasicBlock
Cond *float64
}
FlowEdge is a directed CFG edge with a branch condition. Cond semantics (matching sonolus.py): nil = unconditional / default / true branch; 0 = false branch; other numbers = switch cases.
type IDGen ¶
type IDGen struct {
// contains filtered or unexported fields
}
IDGen generates monotonic node identifiers for a single compilation. Each compilation entry point creates one IDGen and threads it through the frontend tracer, optimizer pipeline, and finalizer. This eliminates shared mutable state, making concurrent compilations safe.
func (*IDGen) ImpureInstr ¶
ImpureInstr builds an operation node that may have side effects.
type Instr ¶
Instr is an operation applied to argument nodes. Pure marks side-effect-free operations (sonolus.py distinguishes IRPureInstr from IRInstr); the flag is for optimization passes and does not affect lowering. ID is a monotonic identifier used by liveness analysis.
type Node ¶
type Node interface {
// contains filtered or unexported methods
}
Node is any IR node that can be lowered to an snode.SNode.
func Map ¶
Map transforms the IR tree bottom-up. For each node, children are mapped first (with recursive calls to Map), then a structurally-equivalent node is reconstructed with the new children (preserving Instr.ID, Set.ID, and Instr.Pure), and finally fn is called on that result. fn may return a different node to replace the original.
type Op ¶
type Op = resource.RuntimeFunction
Op is an IR/runtime operation. It shares the runtime function vocabulary with the final node list.
type Phi ¶
type Phi struct {
Var *TempBlock
Target Place
Args map[*BasicBlock]Place
}
Phi is an SSA phi node placed at a control-flow merge. Var is the original variable (the temp block) it was created for; Target is the SSA value it defines (assigned during SSA renaming); Args maps each predecessor block to the SSA value flowing in along that edge.
INVARIANT: During SSA form (between ToSSA and FromSSA), Target and all Args values are of concrete type SSAPlace. After FromSSA, phis are removed — they should never appear in post-SSA passes. Unchecked type assertions to ir.SSAPlace in ssa.go, sccp.go, and inlining.go depend on this invariant.
type Place ¶
type Place interface {
Node
// contains filtered or unexported methods
}
Place is an addressable memory location: a BlockPlace or an SSAPlace. Port of sonolus.py place.py.
type SSAPlace ¶
SSAPlace is an SSA value (sonolus.py SSAPlace). It must be removed by register allocation before finalization.
type Set ¶
Set writes value to a memory place (sonolus.py IRSet). ID is a monotonic identifier used by liveness analysis.
type TempBlock ¶
TempBlock is a virtual scratch block backing a local variable (sonolus.py TempBlock). It is identified by pointer: each local gets one TempBlock that is shared by all its accesses. TempBlock-backed places must be resolved to a concrete memory block by allocateTempBlocks before finalization.