Files
ziran/cmd/compiler_machine_lower.zi
T
waozi 31d291f337 Keep native records and arrays in place
Records spent all its time copying: every member update copied the whole
2048-byte array word by word, extracts copied each 32-byte record out and
loop edges copied the array again. The native backend now plans aggregate
storage the way zx2wasm does, in a new cmd/compiler_machine_aggregate.zi:

- Aggregate values whose lifetimes never overlap share one frame object, so
  an insert whose source dies there writes only its member, and loop-carried
  and branch-joined values reuse their arguments' object with no edge copy.
- On x86-64 an extract read only by extracts in its block is a view: its
  members are read and changed in place through one address register
  (StackAddress, then FieldAddress or ElementAddress), shared with a
  dominating view of the same storage and member. A changed view put back
  where it came from emits nothing. AggregateExtract/AggregateInsert take
  that register as their aggregate operand.
- Dynamic indices carry the shared facts' proven bound and skip their check;
  others are checked once per address.
- Copies and zeroing of 64 bytes or more run a 16-byte movups loop with a new
  indexed x86 operand instead of unrolled 8-byte pairs.

Per the owner, speed comes first and only correctness guardrails stay: no
new verifier obligations; the remaining checks are unproven index bounds,
interference before sharing a slot, and the view write/read windows. The
allocator's aggregate cycle temporaries now have the aggregate's own size,
which 8-byte record swaps needed once coalescing made such cycles common.

tests/spec/zx_lowered_aggregates.zi joins the ZX parity suite: the Records
kernel (68788), a whole-array snapshot after insert, a two-array swap cycle,
in-place branch updates, a record parameter changed in place, loop-carried
and edge-carried records, a small-record swap at a join and scalar stores at
runtime indices, matched against C, the interpreter, native and Wasm.

On Omega (receipts in bench/results/*records-before/after.json) Records goes
from 1951 to 32 us natively and 1858 to 29 us on the zx engine (C 8.7 us,
Wasm 17.0 us); its image shrinks from 69,760 to 12,416 bytes and Sieve's
from 94,336 to 8,320. make check (276/276) and make check-bootstrap pass.
2026-11-15 19:40:16 -03:00

1347 lines
69 KiB
Ziran

using ABI :: #import "compiler_abi"
using Aggregates :: #import "compiler_machine_aggregate"
using Lir :: #import "compiler_lowered_ir"
using LirVerifyModule :: #import "compiler_lowered_verify"
using Image :: #import "compiler_machine_image"
using Machine :: #import "compiler_machine_ir"
using MachineVerifyModule :: #import "compiler_machine_verify"
using Proven :: #import "compiler_lowered_proven"
using Target :: #import "compiler_target"
using Vectors :: #import "std/vec"
#scope_file
LowerState :: struct {
owner: *MachineOwner
lir: LirProgram
target: TargetDescription
options: MachineOptions
limits: MachineLimits
problem: MachineProblem
diagnostic: MachineDiagnostic
lir_diagnostic_problem: s32
remaining: s64
used: s64
bytes: s64
// The shared LIR facts, and per value of the function being lowered the
// raw-storage virtual of its `allocate`, or MachineNoId.
proven: *LirProvenOwner
frame_raw: *Vec(s32)
aggregates: *AggregateLowering
}
// The aggregate plan of the function being lowered (see
// compiler_machine_aggregate), the virtual holding each view's address, and
// per type its size when stack-class (else -1) and the pointer type made to it.
AggregateLowering :: struct {
plan: MachineAggregatePlan
view_address: Vec(s32)
stack_size: Vec(s64)
pointer_to: Vec(s32)
}
AggregateLoweringFree :: (lowering: *AggregateLowering) {
MachineAggregatePlanFree(*lowering.plan)
VecFree(lowering.view_address)
VecFree(lowering.stack_size)
VecFree(lowering.pointer_to)
}
EmptyDiagnostic :: () -> MachineDiagnostic {
return .{problem = .None, function = MachineNoId, block = MachineNoId,
instruction = MachineNoId, operand = MachineNoId, virtual = MachineNoId}
}
Fail :: (state: *LowerState, problem: MachineProblem) -> bool {
if state.problem == .None { state.problem = problem }
return false
}
Spend :: (state: *LowerState, count: s64) -> bool {
if count < 0 || count > state.remaining { return Fail(state, .Limit) }
state.remaining -= count
state.used += count
return true
}
Reserve :: (state: *LowerState, count: s64, width: s64, limit: s64) -> bool {
if count < 0 || width < 1 || count > limit || state.bytes > state.limits.bytes ||
count > (state.limits.bytes - state.bytes) / width { return Fail(state, .Limit) }
state.bytes += count * width
return true
}
Text :: (state: *LowerState, text: string) -> s32 {
if text.count < 0 || state.owner.text.count > 2147483647 - text.count ||
!Reserve(state, text.count, 1, state.limits.bytes) { return MachineNoId }
offset := cast(s32)state.owner.text.count
for byte: text {
if !VecPush(state.owner.text, byte) { Fail(state, .Allocation); return MachineNoId }
}
return offset
}
Alignment :: (size: s64) -> s32 {
if size >= 8 { return 8 }
if size >= 4 { return 4 }
if size >= 2 { return 2 }
return 1
}
AddType :: (state: *LowerState, type: MachineType) -> s32 {
if state.owner.types.count >= state.limits.types { Fail(state, .Limit); return MachineNoId }
if !Reserve(state, 1, size_of(MachineType), state.limits.types) { return MachineNoId }
index := cast(s32)state.owner.types.count
if !VecPush(state.owner.types, type) { Fail(state, .Allocation); return MachineNoId }
return index
}
AddTypeId :: (state: *LowerState, id: s32) -> bool {
if state.owner.type_ids.count >= state.limits.type_ids { return Fail(state, .Limit) }
if !Reserve(state, 1, size_of(s32), state.limits.type_ids) { return false }
if !VecPush(state.owner.type_ids, id) { return Fail(state, .Allocation) }
return true
}
AddGlobal :: (state: *LowerState, global: MachineGlobal) -> bool {
if state.owner.globals.count >= state.limits.globals { return Fail(state, .Limit) }
if !Reserve(state, 1, size_of(MachineGlobal), state.limits.globals) { return false }
if !VecPush(state.owner.globals, global) { return Fail(state, .Allocation) }
return true
}
AddData :: (state: *LowerState, bytes: []u8) -> s32 {
if bytes.count < 0 || state.owner.data.count > 2147483647 - bytes.count ||
!Reserve(state, bytes.count, 1, state.limits.bytes) { return MachineNoId }
begin := cast(s32)state.owner.data.count
for byte: bytes {
if !VecPush(state.owner.data, byte) { Fail(state, .Allocation); return MachineNoId }
}
return begin
}
AddConstant :: (state: *LowerState, constant: MachineConstant) -> bool {
if state.owner.constants.count >= state.limits.constants { return Fail(state, .Limit) }
if !Reserve(state, 1, size_of(MachineConstant), state.limits.constants) { return false }
if !VecPush(state.owner.constants, constant) { return Fail(state, .Allocation) }
return true
}
AddFunction :: (state: *LowerState, function: MachineFunction) -> s32 {
if state.owner.functions.count >= state.limits.functions { Fail(state, .Limit); return MachineNoId }
if !Reserve(state, 1, size_of(MachineFunction), state.limits.functions) { return MachineNoId }
index := cast(s32)state.owner.functions.count
if !VecPush(state.owner.functions, function) { Fail(state, .Allocation); return MachineNoId }
return index
}
AddBlock :: (state: *LowerState, block: MachineBlock) -> s32 {
if state.owner.blocks.count >= state.limits.blocks { Fail(state, .Limit); return MachineNoId }
if !Reserve(state, 1, size_of(MachineBlock), state.limits.blocks) { return MachineNoId }
index := cast(s32)state.owner.blocks.count
if !VecPush(state.owner.blocks, block) { Fail(state, .Allocation); return MachineNoId }
return index
}
AddVirtual :: (state: *LowerState, value: MachineVirtual) -> s32 {
if state.owner.virtuals.count >= state.limits.virtuals { Fail(state, .Limit); return MachineNoId }
if !Reserve(state, 1, size_of(MachineVirtual), state.limits.virtuals) { return MachineNoId }
index := cast(s32)state.owner.virtuals.count
if !VecPush(state.owner.virtuals, value) { Fail(state, .Allocation); return MachineNoId }
return index
}
AddStack :: (state: *LowerState, object: MachineStackObject) -> s32 {
if state.owner.stack_objects.count >= state.limits.stack_objects { Fail(state, .Limit); return MachineNoId }
if !Reserve(state, 1, size_of(MachineStackObject), state.limits.stack_objects) { return MachineNoId }
index := cast(s32)state.owner.stack_objects.count
if !VecPush(state.owner.stack_objects, object) { Fail(state, .Allocation); return MachineNoId }
return index
}
AddOperand :: (state: *LowerState, operand: MachineOperand) -> s32 {
if state.owner.operands.count >= state.limits.operands { Fail(state, .Limit); return MachineNoId }
if !Reserve(state, 1, size_of(MachineOperand), state.limits.operands) { return MachineNoId }
index := cast(s32)state.owner.operands.count
if !VecPush(state.owner.operands, operand) { Fail(state, .Allocation); return MachineNoId }
return index
}
AddInstruction :: (state: *LowerState, instruction: MachineInstruction) -> s32 {
if state.owner.instructions.count >= state.limits.instructions { Fail(state, .Limit); return MachineNoId }
if !Reserve(state, 1, size_of(MachineInstruction), state.limits.instructions) { return MachineNoId }
index := cast(s32)state.owner.instructions.count
if !VecPush(state.owner.instructions, instruction) { Fail(state, .Allocation); return MachineNoId }
return index
}
AddCopy :: (state: *LowerState, copy: MachineCopy) -> s32 {
if state.owner.copies.count >= state.limits.copies { Fail(state, .Limit); return MachineNoId }
if !Reserve(state, 1, size_of(MachineCopy), state.limits.copies) { return MachineNoId }
index := cast(s32)state.owner.copies.count
if !VecPush(state.owner.copies, copy) { Fail(state, .Allocation); return MachineNoId }
return index
}
AddEdge :: (state: *LowerState, edge: MachineEdge) -> s32 {
if state.owner.edges.count >= state.limits.edges { Fail(state, .Limit); return MachineNoId }
if !Reserve(state, 1, size_of(MachineEdge), state.limits.edges) { return MachineNoId }
index := cast(s32)state.owner.edges.count
if !VecPush(state.owner.edges, edge) { Fail(state, .Allocation); return MachineNoId }
return index
}
AddRelocation :: (state: *LowerState, relocation: MachineRelocation) -> bool {
if state.owner.relocations.count >= state.limits.relocations { return Fail(state, .Limit) }
if !Reserve(state, 1, size_of(MachineRelocation), state.limits.relocations) { return false }
if !VecPush(state.owner.relocations, relocation) { return Fail(state, .Allocation) }
return true
}
AddCall :: (state: *LowerState, call: MachineCall) -> s32 {
if state.owner.calls.count >= state.limits.calls { Fail(state, .Limit); return MachineNoId }
if !Reserve(state, 1, size_of(MachineCall), state.limits.calls) { return MachineNoId }
index := cast(s32)state.owner.calls.count
if !VecPush(state.owner.calls, call) { Fail(state, .Allocation); return MachineNoId }
return index
}
Origin :: (state: *LowerState, origin: s32) -> s32 {
if !state.options.preserve_origins { return MachineNoId }
return origin
}
VirtualOperand :: (state: *LowerState, id: s32, role: MachineOperandRole,
fixed: s32 = MachineNoId, tied: s32 = MachineNoId) -> s32 {
if id < 0 || id >= state.owner.virtuals.count { Fail(state, .Virtual); return MachineNoId }
value := state.owner.virtuals[id]
return AddOperand(state, .{kind = .Virtual, role = role, class = value.class, id = id,
type = value.type, fixed_register = fixed, tied_to = tied, value = id})
}
ImmediateOperand :: (state: *LowerState, value: u64, class: MachineRegisterClass = .General) -> s32 {
return AddOperand(state, .{kind = .Immediate, role = .Use, class = class,
id = MachineNoId, type = MachineNoId, fixed_register = MachineNoId,
tied_to = MachineNoId, immediate = value, value = MachineNoId})
}
SymbolOperand :: (state: *LowerState, kind: MachineOperandKind, symbol: s32) -> s32 {
return AddOperand(state, .{kind = kind, role = .Use, class = .General, id = symbol,
type = MachineNoId, fixed_register = MachineNoId, tied_to = MachineNoId, value = MachineNoId})
}
StackOperand :: (state: *LowerState, object: s32) -> s32 {
return AddOperand(state, .{kind = .StackObject, role = .Use, class = .Stack, id = object,
type = state.owner.stack_objects[object].type, fixed_register = MachineNoId,
tied_to = MachineNoId, value = MachineNoId})
}
PhysicalOperand :: (state: *LowerState, physical: s32, role: MachineOperandRole,
class: MachineRegisterClass = .General) -> s32 {
return AddOperand(state, .{kind = .Physical, role = role, class = class, id = physical,
type = MachineNoId, fixed_register = physical, tied_to = MachineNoId, value = MachineNoId})
}
BeginInstruction :: (state: *LowerState, opcode: MachineOpcode, origin: s32) -> MachineInstruction {
return .{opcode = opcode, operand_begin = cast(s32)state.owner.operands.count,
edge_begin = cast(s32)state.owner.edges.count, flags_use = MachineNoId,
flags_def = MachineNoId, call = MachineNoId, origin = Origin(state, origin)}
}
FinishInstruction :: (state: *LowerState, instruction: MachineInstruction) -> s32 {
instruction.operand_count = cast(s32)state.owner.operands.count - instruction.operand_begin
instruction.edge_count = cast(s32)state.owner.edges.count - instruction.edge_begin
return AddInstruction(state, instruction)
}
AddSource :: (state: *LowerState, source: MachineSource) -> bool {
if !Reserve(state, 1, size_of(MachineSource), 2147483647) { return false }
if !VecPush(state.owner.sources, source) { return Fail(state, .Allocation) }
return true
}
AddOrigin :: (state: *LowerState, origin: MachineOrigin) -> bool {
if !Reserve(state, 1, size_of(MachineOrigin), 2147483647) { return false }
if !VecPush(state.owner.origins, origin) { return Fail(state, .Allocation) }
return true
}
CopyMetadata :: (state: *LowerState) -> bool {
if !state.options.preserve_origins { return true }
for source: state.lir.sources {
if !Spend(state, 1) { return false }
offset := Text(state, source)
if state.problem != .None || !AddSource(state, .{text_offset = offset,
text_length = cast(s32)source.count}) { return false }
}
for source: state.lir.origins {
if !Spend(state, 1) || !AddOrigin(state, .{file = source.file, line = source.line,
column = source.column, end_line = source.end_line, end_column = source.end_column,
begin = source.begin, end = source.end, parent = source.parent}) { return false }
}
return true
}
TypeKind :: (kind: LirTypeKind) -> MachineTypeKind {
if kind == .Void { return .Void }
if kind == .Bool { return .Bool }
if kind == .Integer { return .Integer }
if kind == .Float { return .Float }
if kind == .Pointer { return .Pointer }
if kind == .Array { return .Array }
if kind == .Record { return .Record }
if kind == .Function { return .Function }
return .Invalid
}
CopyTypes :: (state: *LowerState) -> bool {
for type_id: cast(s64)0..state.lir.types.count - 1 {
if !Spend(state, 1) { return false }
source := state.lir.types[type_id]
kind := TypeKind(source.kind)
class := MachineAbiClass(state.lir, cast(s32)type_id)
if source.kind == .Void { class = .Stack }
size := MachineAbiTypeSize(state.lir, cast(s32)type_id)
if kind == .Invalid || class == .Invalid || size < 0 { return Fail(state, .Unsupported) }
fields_begin := cast(s32)state.owner.type_ids.count
for field: source.fields { if !AddTypeId(state, field) { return false } }
parameters_begin := cast(s32)state.owner.type_ids.count
for parameter: source.parameters { if !AddTypeId(state, parameter) { return false } }
type := MachineType.{.kind = kind, .class = class, .bits = source.bits,
.is_signed = source.is_signed, .native_width = source.native_width,
.size = size, .alignment = Alignment(size),
.element = ifx source.kind == .Array || source.kind == .Pointer then source.element else MachineNoId,
.count = source.count, .fields_begin = fields_begin,
.fields_count = cast(s32)source.fields.count,
.parameters_begin = parameters_begin,
.parameters_count = cast(s32)source.parameters.count,
.result = ifx source.kind == .Function then source.result else MachineNoId}
if AddType(state, type) != type_id { return false }
}
for source: state.lir.constants {
if !Spend(state, 1) { return false }
begin := AddData(state, source.bytes)
if begin == MachineNoId || !AddConstant(state, .{type = source.type, bits = source.bits,
bytes_begin = begin, bytes_count = cast(s32)source.bytes.count}) { return false }
}
for global: state.lir.globals {
if !Spend(state, 1) || !AddGlobal(state, .{type = global.type,
constant = global.constant, writable = global.writable}) {
return false
}
}
for initializer: state.lir.initializers {
if !Spend(state, 1) || !Reserve(state, 1, size_of(s32), state.limits.functions) ||
!VecPush(state.owner.initializers, initializer) { return Fail(state, .Allocation) }
}
return true
}
FunctionCalling :: (state: *LowerState, source: LirFunction) -> MachineCalling {
if !source.external { return .Internal }
if source.module >= 0 && source.module < state.lir.modules.count &&
state.lir.modules[source.module] == "ziran.platform" { return .Platform }
return .Host
}
AddFunctionRecords :: (state: *LowerState) -> bool {
for function_id: cast(s64)0..state.lir.functions.count - 1 {
if !Spend(state, 1) { return false }
source := state.lir.functions[function_id]
offset := Text(state, source.name)
if state.problem != .None { return false }
calling := FunctionCalling(state, source)
function := MachineFunction.{.lir_function = ifx calling == .Internal then cast(s32)function_id else MachineNoId,
.name_offset = offset, .name_length = cast(s32)source.name.count,
.parameter_count = cast(s32)source.parameters.count, .result_type = source.result,
.calling = calling, .entry = MachineNoId,
.origin = Origin(state, source.origin)}
if AddFunction(state, function) != function_id { return false }
}
return true
}
NewStack :: (state: *LowerState, function: s32, kind: MachineStackKind,
type: s32, origin: s32 = MachineNoId) -> s32 {
if type < 0 || type >= state.owner.types.count { Fail(state, .Stack); return MachineNoId }
machine_type := state.owner.types[type]
return AddStack(state, .{function = function, kind = kind, size = machine_type.size,
alignment = machine_type.alignment, type = type, origin = Origin(state, origin)})
}
CreateVirtuals :: (state: *LowerState, function_id: s32) -> bool {
source := state.lir.functions[function_id]
function := state.owner.functions[function_id]
function.virtual_begin = cast(s32)state.owner.virtuals.count
function.stack_begin = cast(s32)state.owner.stack_objects.count
plan := *state.aggregates.plan
for value_id: cast(s64)0..source.values.count - 1 {
if !Spend(state, 1) { return false }
type := source.values[value_id]
class := state.owner.types[type].class
stack: s32 = MachineNoId
// A storage class's representative owns its frame object.
if class == .Stack && plan.slot[value_id] == cast(s32)value_id && plan.storage[value_id] {
stack = NewStack(state, function_id, .Value, type)
if stack == MachineNoId { return false }
}
if AddVirtual(state, .{class = class, type = type, fixed_register = MachineNoId,
stack_object = stack, origin = MachineNoId}) == MachineNoId { return false }
}
// The rest of a class shares it; a class of views alone names its root's.
for value_id: cast(s64)0..source.values.count - 1 {
virtual_id := function.virtual_begin + cast(s32)value_id
if state.owner.virtuals[virtual_id].class != .Stack ||
state.owner.virtuals[virtual_id].stack_object != MachineNoId { continue }
owner := plan.slot[value_id]
if !plan.storage[owner] { owner = plan.root[value_id] }
state.owner.virtuals[virtual_id].stack_object = state.owner.virtuals[function.virtual_begin + owner].stack_object
}
if source.result != MachineNoId && state.owner.types[source.result].class == .Stack &&
state.lir.types[source.result].kind != .Void {
if AddStack(state, .{function = function_id, kind = .ResultAddress, size = 8,
alignment = 8, type = 0, origin = Origin(state, source.origin),
value = MachineNoId}) == MachineNoId { return false }
}
integer_ordinal: s32
float_ordinal: s32
for parameter: cast(s64)0..source.parameters.count - 1 {
virtual_id := function.virtual_begin + cast(s32)parameter
value := state.owner.virtuals[virtual_id]
ordinal := integer_ordinal
if value.class == .Float { ordinal = float_ordinal; float_ordinal += 1 }
else if value.class == .General { integer_ordinal += 1 }
fixed := MachineAbiArgumentRegister(state.target, value.class, ordinal)
if fixed >= 0 { value.fixed_register = fixed }
else if value.class == .General || value.class == .Float {
value.stack_object = NewStack(state, function_id, .IncomingArgument, value.type)
if value.stack_object == MachineNoId { return false }
} else if value.class == .Stack {
object := state.owner.stack_objects[value.stack_object]
object.kind = .IncomingArgument
state.owner.stack_objects[value.stack_object] = object
}
state.owner.virtuals[virtual_id] = value
}
function.virtual_count = cast(s32)state.owner.virtuals.count - function.virtual_begin
function.stack_count = cast(s32)state.owner.stack_objects.count - function.stack_begin
state.owner.functions[function_id] = function
return true
}
GlobalVirtual :: (state: *LowerState, function: *MachineFunction, local: s32) -> s32 {
if local < 0 || local >= function.virtual_count { Fail(state, .Virtual); return MachineNoId }
return function.virtual_begin + local
}
AddEdges :: (state: *LowerState, function: *MachineFunction, edges: []LirEdge) -> bool {
source_function := state.lir.functions[function.lir_function]
for source: edges {
if !Spend(state, 1) || source.block < 0 || source.block >= source_function.blocks.count {
return Fail(state, .Edge)
}
target := source_function.blocks[source.block]
if source.arguments.count != target.parameters.count { return Fail(state, .Edge) }
copy_begin := cast(s32)state.owner.copies.count
for at: cast(s64)0..source.arguments.count - 1 {
from := GlobalVirtual(state, function, source.arguments[at])
to := GlobalVirtual(state, function, target.parameters[at])
if state.problem != .None || state.owner.virtuals[from].class != state.owner.virtuals[to].class {
return Fail(state, .Copy)
}
if AddCopy(state, .{destination = to, source = from,
class = state.owner.virtuals[from].class}) == MachineNoId { return false }
}
if AddEdge(state, .{target = function.block_begin + source.block, copy_begin = copy_begin,
copy_count = cast(s32)source.arguments.count}) == MachineNoId { return false }
}
return true
}
Condition :: (op: LirOp) -> MachineCondition {
if op == .Equal { return .Equal }
if op == .NotEqual { return .NotEqual }
if op == .Less { return .Less }
if op == .LessEqual { return .LessEqual }
if op == .Greater { return .Greater }
if op == .GreaterEqual { return .GreaterEqual }
return .None
}
BinaryOpcode :: (op: LirOp, class: MachineRegisterClass) -> MachineOpcode {
if op == .Add { return ifx class == .Float then .FloatAdd else .IntegerAdd }
if op == .Subtract { return ifx class == .Float then .FloatSubtract else .IntegerSubtract }
if op == .Multiply { return ifx class == .Float then .FloatMultiply else .IntegerMultiply }
if op == .Divide { return ifx class == .Float then .FloatDivide else .IntegerDivide }
if op == .Remainder { return .IntegerRemainder }
if op == .BitAnd { return .IntegerAnd }
if op == .BitOr { return .IntegerOr }
if op == .BitXor { return .IntegerXor }
if op == .ShiftLeft { return .ShiftLeft }
if op == .ShiftRight { return .ShiftRight }
return .Invalid
}
UnaryOpcode :: (op: LirOp, class: MachineRegisterClass) -> MachineOpcode {
if op == .Negate { return ifx class == .Float then .FloatNegate else .IntegerNegate }
if op == .BitNot { return .IntegerNot }
return .Invalid
}
LowerConstant :: (state: *LowerState, function: *MachineFunction,
source: LirInstruction, opcode: MachineOpcode) -> bool {
instruction := BeginInstruction(state, opcode, source.origin)
result := GlobalVirtual(state, function, source.result)
if VirtualOperand(state, result, .Define) == MachineNoId { return false }
class := state.owner.virtuals[result].class
if ImmediateOperand(state, ifx source.op == .Null then 0 else state.lir.constants[source.symbol].bits,
class) == MachineNoId { return false }
// x86 has no scalar floating immediate. The encoder materializes its bits
// through r11, which must be an explicit clobber for allocation.
if class == .Float &&
PhysicalOperand(state, MachineAbiScratchRegister(state.target), .Define) == MachineNoId {
return false
}
return FinishInstruction(state, instruction) != MachineNoId
}
LowerAddress :: (state: *LowerState, function: *MachineFunction,
source: LirInstruction, opcode: MachineOpcode, kind: MachineOperandKind,
relocation_kind: MachineRelocationKind) -> bool {
instruction := BeginInstruction(state, opcode, source.origin)
result := GlobalVirtual(state, function, source.result)
if VirtualOperand(state, result, .Define) == MachineNoId { return false }
operand := SymbolOperand(state, kind, source.symbol)
if operand == MachineNoId { return false }
instruction_id := FinishInstruction(state, instruction)
return instruction_id != MachineNoId && AddRelocation(state, .{instruction = instruction_id,
operand = operand, kind = relocation_kind, symbol = source.symbol})
}
// A flags virtual for an instruction whose sequence changes the flags.
FlagsVirtual :: (state: *LowerState, function: *MachineFunction, origin: s32) -> s32 {
flags := AddVirtual(state, .{class = .Flags, type = 0, fixed_register = MachineNoId,
stack_object = MachineNoId, origin = Origin(state, origin)})
function.virtual_count = cast(s32)state.owner.virtuals.count - function.virtual_begin
return flags
}
// A raw-address virtual with the type of TOKEN, a checked pointer.
RawVirtual :: (state: *LowerState, function: *MachineFunction, token: s32) -> s32 {
raw := AddVirtual(state, .{class = .General, type = state.owner.virtuals[token].type,
fixed_register = MachineNoId, stack_object = MachineNoId, origin = MachineNoId})
function.virtual_count = cast(s32)state.owner.virtuals.count - function.virtual_begin
return raw
}
// raw = the address WIDTH bytes may be accessed at through TOKEN (a width
// value when WIDTH_VALUE is a virtual), or the bounds trap. FLAGS: 1 for a
// write, 2 when a zero width needs no live pointer.
LowerResolve :: (state: *LowerState, function: *MachineFunction, token: s32, width: s64,
width_value: s32, flags: u64, origin: s32) -> s32 {
raw := RawVirtual(state, function, token)
if raw == MachineNoId { return MachineNoId }
instruction := BeginInstruction(state, .PointerResolve, origin)
instruction.flags_def = FlagsVirtual(state, function, origin)
if instruction.flags_def == MachineNoId { return MachineNoId }
if VirtualOperand(state, raw, .Define) == MachineNoId ||
VirtualOperand(state, token, .Use) == MachineNoId { return MachineNoId }
if width_value != MachineNoId {
if VirtualOperand(state, width_value, .Use) == MachineNoId { return MachineNoId }
} else if ImmediateOperand(state, cast(u64)width) == MachineNoId { return MachineNoId }
if PhysicalOperand(state, MachineAbiAddressScratchRegister(state.target), .UseDefine) == MachineNoId ||
ImmediateOperand(state, flags) == MachineNoId ||
FinishInstruction(state, instruction) == MachineNoId { return MachineNoId }
return raw
}
LowerUnary :: (state: *LowerState, function: *MachineFunction, source: LirInstruction) -> bool {
result := GlobalVirtual(state, function, source.result)
input := GlobalVirtual(state, function, source.operands[0])
opcode := UnaryOpcode(source.op, state.owner.virtuals[result].class)
if opcode == .Invalid { return Fail(state, .Unsupported) }
instruction := BeginInstruction(state, opcode, source.origin)
if VirtualOperand(state, result, .Define, tied = 1) == MachineNoId ||
VirtualOperand(state, input, .Use, tied = 0) == MachineNoId { return false }
scratch := MachineAbiScratchRegister(state.target)
if opcode == .FloatNegate && PhysicalOperand(state, scratch, .Define) == MachineNoId { return false }
return FinishInstruction(state, instruction) != MachineNoId
}
LowerBinary :: (state: *LowerState, function: *MachineFunction, source: LirInstruction) -> bool {
result := GlobalVirtual(state, function, source.result)
left := GlobalVirtual(state, function, source.operands[0])
right := GlobalVirtual(state, function, source.operands[1])
class := state.owner.virtuals[result].class
opcode := BinaryOpcode(source.op, class)
if opcode == .Invalid { return Fail(state, .Unsupported) }
instruction := BeginInstruction(state, opcode, source.origin)
// Fixed registers come from the target description; -1 is no constraint.
divide := opcode == .IntegerDivide || opcode == .IntegerRemainder
result_fixed: s32 = MachineNoId
left_fixed: s32 = MachineNoId
right_fixed: s32 = MachineNoId
clobber: s32 = MachineNoId
if divide {
result_fixed = MachineAbiFixedRegister(state.target, .DivideResult)
left_fixed = MachineAbiFixedRegister(state.target, .DivideDividend)
clobber = MachineAbiFixedRegister(state.target, .DivideClobber)
} else if opcode == .ShiftLeft || opcode == .ShiftRight {
right_fixed = MachineAbiFixedRegister(state.target, .ShiftCount)
}
if VirtualOperand(state, result, .Define, result_fixed, cast(s32)1) == MachineNoId ||
VirtualOperand(state, left, .Use, left_fixed, cast(s32)0) == MachineNoId ||
VirtualOperand(state, right, .Use, right_fixed) == MachineNoId { return false }
if clobber >= 0 && PhysicalOperand(state, clobber, .UseDefine) == MachineNoId { return false }
return FinishInstruction(state, instruction) != MachineNoId
}
LowerCompare :: (state: *LowerState, function: *MachineFunction, source: LirInstruction) -> bool {
left := GlobalVirtual(state, function, source.operands[0])
right := GlobalVirtual(state, function, source.operands[1])
result := GlobalVirtual(state, function, source.result)
flags := AddVirtual(state, .{class = .Flags, type = state.owner.virtuals[result].type,
fixed_register = MachineNoId, stack_object = MachineNoId, origin = Origin(state, source.origin)})
if flags == MachineNoId { return false }
compare := BeginInstruction(state, .Compare, source.origin)
compare.flags_def = flags
compare.condition = Condition(source.op)
if VirtualOperand(state, left, .Use) == MachineNoId ||
VirtualOperand(state, right, .Use) == MachineNoId ||
FinishInstruction(state, compare) == MachineNoId { return false }
set := BeginInstruction(state, .SetCondition, source.origin)
set.flags_use = flags
set.condition = compare.condition
if VirtualOperand(state, result, .Define) == MachineNoId { return false }
if state.owner.virtuals[left].class == .Float &&
PhysicalOperand(state, MachineAbiScratchRegister(state.target), .Define) == MachineNoId {
return false
}
if FinishInstruction(state, set) == MachineNoId { return false }
function.virtual_count = cast(s32)state.owner.virtuals.count - function.virtual_begin
return true
}
LowerMove :: (state: *LowerState, function: *MachineFunction, source: LirInstruction,
opcode: MachineOpcode) -> bool {
instruction := BeginInstruction(state, opcode, source.origin)
result := GlobalVirtual(state, function, source.result)
if VirtualOperand(state, result, .Define) == MachineNoId { return false }
for operand: source.operands {
if VirtualOperand(state, GlobalVirtual(state, function, operand), .Use) == MachineNoId { return false }
}
if opcode == .Convert && source.operands.count == 1 {
input := GlobalVirtual(state, function, source.operands[0])
if state.owner.virtuals[result].class == .Float || state.owner.virtuals[input].class == .Float {
// Checked float conversions use r11 for exact bit constants and
// xmm15 as the comparison/arithmetic temporary.
if PhysicalOperand(state, MachineAbiScratchRegister(state.target), .Define) == MachineNoId ||
PhysicalOperand(state, MachineAbiScratchFloatRegister(state.target), .Define, .Float) == MachineNoId {
return false
}
}
}
return FinishInstruction(state, instruction) != MachineNoId
}
// The raw start of the root a shared LIR fact gives pointer LOCAL, when that
// fact covers an access of WIDTH bytes: a fresh GlobalAddress for a global,
// the `allocate`'s storage for a frame slot. MachineNoId keeps the check.
// AArch64 elides after its checked-memory stage lands.
DirectBase :: (state: *LowerState, function: *MachineFunction, local: s32, width: s64,
write: bool, origin: s32) -> s32 {
if state.target.arch != .X86_64 { return MachineNoId }
fact := LirProvenPointerOf(state.proven, function.lir_function, local)
if !LirProvenCovers(fact, width, write) { return MachineNoId }
if fact.root == .Frame {
if fact.symbol < 0 || fact.symbol >= state.frame_raw.count { return MachineNoId }
return (<<state.frame_raw)[fact.symbol]
}
if fact.root != .Global || fact.symbol < 0 || fact.symbol >= state.owner.globals.count { return MachineNoId }
base := RawVirtual(state, function, GlobalVirtual(state, function, local))
if base == MachineNoId { return MachineNoId }
instruction := BeginInstruction(state, .GlobalAddress, origin)
if VirtualOperand(state, base, .Define) == MachineNoId { return MachineNoId }
operand := SymbolOperand(state, .Global, fact.symbol)
if operand == MachineNoId { return MachineNoId }
instruction_id := FinishInstruction(state, instruction)
kind: MachineRelocationKind = ifx state.owner.globals[fact.symbol].writable then .GlobalAddress else .ConstantAddress
if instruction_id == MachineNoId || !AddRelocation(state, .{instruction = instruction_id,
operand = operand, kind = kind, symbol = fact.symbol}) { return MachineNoId }
return base
}
// raw = BASE + TOKEN's offset for an access the verifier re-derives as safe.
LowerDirect :: (state: *LowerState, function: *MachineFunction, token: s32, base: s32, width: s64,
write: bool, origin: s32) -> s32 {
raw := RawVirtual(state, function, token)
if raw == MachineNoId { return MachineNoId }
instruction := BeginInstruction(state, .PointerDirect, origin)
instruction.flags_def = FlagsVirtual(state, function, origin)
if instruction.flags_def == MachineNoId || VirtualOperand(state, raw, .Define) == MachineNoId ||
VirtualOperand(state, token, .Use) == MachineNoId || VirtualOperand(state, base, .Use) == MachineNoId ||
ImmediateOperand(state, cast(u64)width) == MachineNoId ||
ImmediateOperand(state, ifx write then cast(u64)1 else 0) == MachineNoId ||
FinishInstruction(state, instruction) == MachineNoId { return MachineNoId }
return raw
}
// An element whose index the shared facts prove below a bound needs no
// index check: ElementAddress result, base, index, bound.
LowerElement :: (state: *LowerState, function: *MachineFunction, source: LirInstruction) -> bool {
bound: s64
if state.target.arch == .X86_64 && source.operands.count >= 2 && source.operands.count <= 3 {
bound = LirProvenIndexBound(state.proven, function.lir_function, source.result)
}
if bound <= 0 { return LowerMemory(state, function, source, .ElementAddress) }
instruction := BeginInstruction(state, .ElementAddress, source.origin)
if VirtualOperand(state, GlobalVirtual(state, function, source.result), .Define) == MachineNoId ||
VirtualOperand(state, GlobalVirtual(state, function, source.operands[0]), .Use) == MachineNoId ||
VirtualOperand(state, GlobalVirtual(state, function, source.operands[1]), .Use) == MachineNoId ||
ImmediateOperand(state, cast(u64)bound) == MachineNoId { return false }
return FinishInstruction(state, instruction) != MachineNoId
}
LowerMemory :: (state: *LowerState, function: *MachineFunction, source: LirInstruction,
opcode: MachineOpcode) -> bool {
// A load, store or zero goes through the address its checked pointer
// resolves to, or the one a shared fact proves needs no check.
resolved: s32 = MachineNoId
if (opcode == .Load || opcode == .Store || opcode == .Zero) && source.operands.count >= 1 {
token := GlobalVirtual(state, function, source.operands[0])
if token == MachineNoId { return false }
width: s64
if opcode == .Zero {
pointer := state.owner.types[state.owner.virtuals[token].type]
if pointer.kind != .Pointer || pointer.element < 0 { return Fail(state, .Unsupported) }
width = state.owner.types[pointer.element].size
} else {
accessed := ifx opcode == .Load then source.result else source.operands[source.operands.count - 1]
width = state.owner.types[state.owner.virtuals[GlobalVirtual(state, function, accessed)].type].size
}
write := opcode != .Load
base := DirectBase(state, function, source.operands[0], width, write, source.origin)
if state.problem != .None { return false }
if base != MachineNoId {
resolved = LowerDirect(state, function, token, base, width, write, source.origin)
} else {
resolved = LowerResolve(state, function, token, width, MachineNoId,
ifx write then cast(u64)1 else 0, source.origin)
}
if resolved == MachineNoId { return false }
}
instruction := BeginInstruction(state, opcode, source.origin)
if source.result != LirNoId &&
VirtualOperand(state, GlobalVirtual(state, function, source.result), .Define) == MachineNoId { return false }
for operand, at: source.operands {
value := ifx at == 0 && resolved != MachineNoId then resolved else GlobalVirtual(state, function, operand)
if VirtualOperand(state, value, .Use) == MachineNoId { return false }
}
if source.op == .FieldAddress && ImmediateOperand(state, source.immediate) == MachineNoId { return false }
return FinishInstruction(state, instruction) != MachineNoId
}
// Every execution of `allocate` gets fresh storage that stays valid until
// its frame returns, as on the portable engine: frame arena bytes, zeroed or
// given their initial value, named by a new slot on the frame's chain.
LowerAllocate :: (state: *LowerState, function: *MachineFunction, source: LirInstruction) -> bool {
result := GlobalVirtual(state, function, source.result)
pointer := state.owner.types[state.owner.virtuals[result].type]
if pointer.kind != .Pointer || pointer.element < 0 { return Fail(state, .Unsupported) }
if function.pointer_chain == 0 { return Fail(state, .Stack) }
size := state.owner.types[pointer.element].size
if source.result < 0 || source.result >= state.frame_raw.count { return Fail(state, .Virtual) }
raw := (<<state.frame_raw)[source.result]
if raw == MachineNoId { return Fail(state, .Virtual) }
scratch := MachineAbiAddressScratchRegister(state.target)
allocate := BeginInstruction(state, .ArenaAllocate, source.origin)
allocate.flags_def = FlagsVirtual(state, function, source.origin)
if allocate.flags_def == MachineNoId || VirtualOperand(state, raw, .Define) == MachineNoId ||
ImmediateOperand(state, cast(u64)size) == MachineNoId ||
PhysicalOperand(state, scratch, .UseDefine) == MachineNoId ||
FinishInstruction(state, allocate) == MachineNoId { return false }
if source.operands.count == 1 {
store := BeginInstruction(state, .Store, source.origin)
if VirtualOperand(state, raw, .Use) == MachineNoId ||
VirtualOperand(state, GlobalVirtual(state, function, source.operands[0]), .Use) == MachineNoId ||
FinishInstruction(state, store) == MachineNoId { return false }
} else {
zero := BeginInstruction(state, .Zero, source.origin)
if VirtualOperand(state, raw, .Use) == MachineNoId ||
FinishInstruction(state, zero) == MachineNoId { return false }
}
create := BeginInstruction(state, .PointerCreate, source.origin)
create.flags_def = FlagsVirtual(state, function, source.origin)
if create.flags_def == MachineNoId || VirtualOperand(state, result, .Define) == MachineNoId ||
VirtualOperand(state, raw, .Use) == MachineNoId ||
ImmediateOperand(state, cast(u64)size) == MachineNoId ||
PhysicalOperand(state, scratch, .UseDefine) == MachineNoId ||
ImmediateOperand(state, cast(u64)(MachinePointerLive | MachinePointerWritable)) == MachineNoId ||
StackOperand(state, function.stack_begin + function.pointer_chain - 1) == MachineNoId ||
FinishInstruction(state, create) == MachineNoId { return false }
return true
}
LowerBytesEqual :: (state: *LowerState, function: *MachineFunction, source: LirInstruction) -> bool {
if source.operands.count != 4 { return Fail(state, .Unsupported) }
// Both byte views are read through their resolved addresses; an empty
// view needs no live pointer.
values: [4]s32
for at: cast(s64)0..3 { values[at] = GlobalVirtual(state, function, source.operands[at]) }
for at: cast(s64)0..1 {
values[at * 2] = LowerResolve(state, function, values[at * 2], 0, values[at * 2 + 1], 2, source.origin)
if values[at * 2] == MachineNoId { return false }
}
instruction := BeginInstruction(state, .BytesEqual, source.origin)
result := GlobalVirtual(state, function, source.result)
if VirtualOperand(state, result, .Define, 0) == MachineNoId { return false }
for at: cast(s64)0..3 {
if VirtualOperand(state, values[at], .Use,
MachineAbiFormFixedRegister(state.target, .BytesEqual, cast(s32)at)) == MachineNoId {
return false
}
}
for at: cast(s64)0..2 {
if PhysicalOperand(state, MachineAbiFormClobberRegister(state.target, .BytesEqual,
cast(s32)at), .Define) == MachineNoId { return false }
}
return FinishInstruction(state, instruction) != MachineNoId
}
LowerResize :: (state: *LowerState, function: *MachineFunction, source: LirInstruction) -> bool {
if source.operands.count != 3 { return Fail(state, .Unsupported) }
instruction := BeginInstruction(state, .Resize, source.origin)
result := GlobalVirtual(state, function, source.result)
if VirtualOperand(state, result, .Define, 0) == MachineNoId { return false }
for at: cast(s64)0..2 {
if VirtualOperand(state, GlobalVirtual(state, function, source.operands[at]), .Use,
MachineAbiFormFixedRegister(state.target, .Resize, cast(s32)at)) == MachineNoId {
return false
}
}
for at: cast(s64)0..7 {
if PhysicalOperand(state, MachineAbiFormClobberRegister(state.target, .Resize,
cast(s32)at), .Define) == MachineNoId { return false }
}
runtime := ImmediateOperand(state, 0)
if runtime == MachineNoId { return false }
instruction_id := FinishInstruction(state, instruction)
if instruction_id == MachineNoId { return false }
return AddRelocation(state, .{instruction = instruction_id, operand = runtime,
kind = .RuntimeResize, symbol = 0})
}
RoundEight :: (value: s64) -> s64 {
if value < 0 || value > 9223372036854775799 { return -1 }
return (value + 7) & ~cast(s64)7
}
LowerCall :: (state: *LowerState, function: *MachineFunction, source: LirInstruction) -> bool {
indirect := source.op == .CallIndirect
if source.op != .Call && source.op != .HostCall && !indirect { return Fail(state, .Unsupported) }
// Platform services take raw addresses: a pointer argument is resolved
// for the byte count that follows it, or for its pointee.
resolved: [16]s32
for at: 0..15 { resolved[at] = MachineNoId }
if !indirect && source.symbol >= 0 && source.symbol < state.owner.functions.count &&
state.owner.functions[source.symbol].calling == .Platform && source.operands.count <= 16 {
for at: cast(s64)0..source.operands.count - 1 {
token := GlobalVirtual(state, function, source.operands[at])
type := state.owner.types[state.owner.virtuals[token].type]
if type.kind != .Pointer { continue }
width: s64 = 0
width_value: s32 = MachineNoId
if at + 1 < source.operands.count &&
state.owner.types[state.owner.virtuals[GlobalVirtual(state, function, source.operands[at + 1])].type].kind == .Integer {
width_value = GlobalVirtual(state, function, source.operands[at + 1])
} else if type.element >= 0 { width = state.owner.types[type.element].size }
resolved[at] = LowerResolve(state, function, token, width, width_value, 2, source.origin)
if resolved[at] == MachineNoId { return false }
}
}
instruction := BeginInstruction(state, ifx indirect then .CallIndirect else .CallDirect, source.origin)
result_operand: s32 = MachineNoId
result_class := MachineRegisterClass.Invalid
if source.result != LirNoId {
result := GlobalVirtual(state, function, source.result)
result_class = state.owner.virtuals[result].class
fixed := MachineAbiResultRegister(state.target, result_class)
result_operand = VirtualOperand(state, result, .Define, fixed)
if result_operand == MachineNoId { return false }
}
argument_offset: s32
parameter_types: []s32
if indirect {
callable := GlobalVirtual(state, function, source.operands[0])
fixed := MachineAbiIndirectCallRegister(state.target)
if fixed < 0 { fixed = MachineNoId }
if VirtualOperand(state, callable, .Use, fixed) == MachineNoId { return false }
signature := state.lir.types[state.lir.functions[function.lir_function].values[source.operands[0]]]
if signature.kind != .Function { return Fail(state, .Unsupported) }
parameter_types = signature.parameters
argument_offset = 1
} else {
symbol_operand := SymbolOperand(state, .Function, source.symbol)
if symbol_operand == MachineNoId { return false }
if source.symbol < 0 || source.symbol >= state.lir.functions.count { return Fail(state, .Function) }
parameter_types = state.lir.functions[source.symbol].parameters
argument_offset = 0
}
argument_begin := cast(s32)state.owner.operands.count
integer_ordinal: s32
float_ordinal: s32
stack_bytes: s64
for at: cast(s64)0..parameter_types.count - 1 {
local := source.operands[at + cast(s64)argument_offset]
value := GlobalVirtual(state, function, local)
if argument_offset == 0 && at < 16 && resolved[at] != MachineNoId { value = resolved[at] }
class := state.owner.virtuals[value].class
ordinal := integer_ordinal
if class == .Float { ordinal = float_ordinal; float_ordinal += 1 }
else if class == .General { integer_ordinal += 1 }
fixed := MachineAbiArgumentRegister(state.target, class, ordinal)
if VirtualOperand(state, value, .Use, fixed) == MachineNoId { return false }
if fixed < 0 || class == .Stack {
size := RoundEight(state.owner.types[parameter_types[at]].size)
if size < 0 || stack_bytes > 9223372036854775807 - size { return Fail(state, .Limit) }
stack_bytes += size
}
}
if stack_bytes > 0 {
stack := AddStack(state, .{function = function.lir_function, kind = .OutgoingArgument,
size = stack_bytes, alignment = 8, type = 0, origin = Origin(state, source.origin)})
if stack == MachineNoId || AddOperand(state, .{kind = .StackObject, role = .Use,
class = .Stack, id = stack, type = 0, fixed_register = MachineNoId,
tied_to = MachineNoId, value = MachineNoId}) == MachineNoId { return false }
function.stack_count = cast(s32)state.owner.stack_objects.count - function.stack_begin
}
instruction_id := cast(s32)state.owner.instructions.count
calling := MachineCalling.Internal
if !indirect { calling = state.owner.functions[source.symbol].calling }
call_id := AddCall(state, .{instruction = instruction_id, calling = calling,
argument_begin = argument_begin, argument_count = cast(s32)parameter_types.count,
result_operand = result_operand, stack_argument_bytes = stack_bytes,
clobber_general = MachineAbiCallGeneralClobbers(state.target),
clobber_float = MachineAbiCallFloatClobbers(state.target),
clobber_vector = MachineAbiCallFloatClobbers(state.target), indirect = indirect})
if call_id == MachineNoId { return false }
instruction.call = call_id
instruction_id = FinishInstruction(state, instruction)
if instruction_id == MachineNoId { return false }
if !indirect {
symbol_operand := argument_begin - 1
relocation := MachineRelocationKind.FunctionCall
if calling == .Host { relocation = .HostCapability }
if calling == .Platform { relocation = .PlatformService }
if !AddRelocation(state, .{instruction = instruction_id, operand = symbol_operand,
kind = relocation, symbol = source.symbol}) { return false }
}
return true
}
LowerControl :: (state: *LowerState, function: *MachineFunction, source: LirInstruction,
opcode: MachineOpcode) -> bool {
instruction := BeginInstruction(state, opcode, source.origin)
for operand: source.operands {
id := GlobalVirtual(state, function, operand)
fixed: s32 = MachineNoId
if opcode == .Return { fixed = MachineAbiResultRegister(state.target, state.owner.virtuals[id].class) }
if VirtualOperand(state, id, .Use, fixed) == MachineNoId { return false }
}
if source.op == .Fuel || source.op == .Trap {
if ImmediateOperand(state, source.immediate) == MachineNoId { return false }
}
counter: s32 = MachineNoId
if source.op == .Fuel {
// A fuel check subtracts from the instance counter and traps on
// exhaustion, so it names the counter through a relocation and
// defines (clobbers) the flags before liveness sees it.
counter = ImmediateOperand(state, 0)
if counter == MachineNoId { return false }
flags := AddVirtual(state, .{class = .Flags, type = 0, fixed_register = MachineNoId,
stack_object = MachineNoId, origin = Origin(state, source.origin)})
if flags == MachineNoId { return false }
instruction.flags_def = flags
function.virtual_count = cast(s32)state.owner.virtuals.count - function.virtual_begin
}
if !AddEdges(state, function, source.edges) { return false }
instruction_id := FinishInstruction(state, instruction)
if instruction_id == MachineNoId { return false }
if counter != MachineNoId {
return AddRelocation(state, .{instruction = instruction_id, operand = counter,
kind = .FuelCounter, symbol = 0})
}
return true
}
// ---------------------------------------------------------------------------
// Aggregate storage and views (compiler_machine_aggregate)
AggregateTypes :: (state: *LowerState) -> bool {
lowering := state.aggregates
count := state.owner.types.count
if !VecResizeBounded(lowering.stack_size, count, state.limits.bytes) ||
!VecResizeBounded(lowering.pointer_to, count, state.limits.bytes) { return Fail(state, .Allocation) }
for type: cast(s64)0..count - 1 {
machine := state.owner.types[type]
lowering.stack_size[type] = ifx machine.class == .Stack then machine.size else -1
lowering.pointer_to[type] = MachineNoId
}
return true
}
// A pointer type to ELEMENT, made once per lowering.
PointerTo :: (state: *LowerState, element: s32) -> s32 {
lowering := state.aggregates
if lowering.pointer_to[element] != MachineNoId { return lowering.pointer_to[element] }
size := cast(s64)(state.target.pointer_bits / 8)
empty := cast(s32)state.owner.type_ids.count
pointer := AddType(state, .{kind = .Pointer, class = .General, bits = state.target.pointer_bits, size = size,
alignment = Alignment(size), element = element, count = 0, fields_begin = empty, fields_count = 0,
parameters_begin = empty, parameters_count = 0, result = MachineNoId})
lowering.pointer_to[element] = pointer
return pointer
}
// A General virtual holding the frame address of a value of type ELEMENT.
AddressVirtual :: (state: *LowerState, function: *MachineFunction, element: s32) -> s32 {
pointer := PointerTo(state, element)
if pointer == MachineNoId { return MachineNoId }
address := AddVirtual(state, .{class = .General, type = pointer, fixed_register = MachineNoId,
stack_object = MachineNoId, origin = MachineNoId})
function.virtual_count = cast(s32)state.owner.virtuals.count - function.virtual_begin
return address
}
// Each view that computes an address gets the virtual holding it; every other
// view takes the virtual of the view whose address it shares.
ViewAddresses :: (state: *LowerState, function: *MachineFunction, source: LirFunction) -> bool {
lowering := state.aggregates
plan := *lowering.plan
count := source.values.count
if !VecResizeBounded(lowering.view_address, count, state.limits.bytes) { return Fail(state, .Allocation) }
for value: cast(s32)0..cast(s32)count - 1 {
lowering.view_address[value] = MachineNoId
if MachineAggregateViewed(plan.view[value]) && plan.address[value] == value {
lowering.view_address[value] = AddressVirtual(state, function, source.values[value])
if lowering.view_address[value] == MachineNoId { return false }
}
}
for value: cast(s32)0..cast(s32)count - 1 {
if MachineAggregateViewed(plan.view[value]) { lowering.view_address[value] = lowering.view_address[plan.address[value]] }
}
return true
}
// The bound the shared facts prove the dynamic index of SOURCE below, so
// x86-64 code needs no check for it, or 0.
ProvenBound :: (state: *LowerState, function: *MachineFunction, source: LirInstruction) -> s64 {
if state.target.arch != .X86_64 { return 0 }
return LirProvenIndexBound(state.proven, function.lir_function, source.result)
}
// Operands after the aggregate of a member access: the member immediate, or
// a dynamic index with the r10/r11 it may clobber and then its proven bound
// (0 keeps the check).
MemberOperands :: (state: *LowerState, function: *MachineFunction, source: LirInstruction, fixed: s64) -> bool {
if source.operands.count != fixed + 1 { return ImmediateOperand(state, source.immediate) != MachineNoId }
return VirtualOperand(state, GlobalVirtual(state, function, source.operands[fixed]), .Use) != MachineNoId &&
PhysicalOperand(state, MachineAbiAddressScratchRegister(state.target), .Define) != MachineNoId &&
PhysicalOperand(state, MachineAbiScratchRegister(state.target), .Define) != MachineNoId &&
ImmediateOperand(state, cast(u64)ProvenBound(state, function, source)) != MachineNoId
}
// An extract or insert copying through frame objects: result, aggregate
// [, value], then the member operands.
LowerAggregate :: (state: *LowerState, function: *MachineFunction, source: LirInstruction,
opcode: MachineOpcode, fixed: s64) -> bool {
instruction := BeginInstruction(state, opcode, source.origin)
if VirtualOperand(state, GlobalVirtual(state, function, source.result), .Define) == MachineNoId { return false }
for at: cast(s64)0..fixed - 1 {
if VirtualOperand(state, GlobalVirtual(state, function, source.operands[at]), .Use) == MachineNoId { return false }
}
return MemberOperands(state, function, source, fixed) && FinishInstruction(state, instruction) != MachineNoId
}
// A view that computes its address: from its source view's address, or the
// frame address of the storage it reads, then the member it names.
ViewAddress :: (state: *LowerState, function: *MachineFunction, source: LirInstruction) -> bool {
lowering := state.aggregates
result := source.result
if lowering.plan.address[result] != result { return true }
aggregate := source.operands[0]
base: s32
if MachineAggregateViewed(lowering.plan.view[aggregate]) {
base = lowering.view_address[aggregate]
} else {
stored := state.owner.virtuals[GlobalVirtual(state, function, aggregate)]
base = AddressVirtual(state, function, stored.type)
if base == MachineNoId { return false }
frame := BeginInstruction(state, .StackAddress, source.origin)
if VirtualOperand(state, base, .Define) == MachineNoId || StackOperand(state, stored.stack_object) == MachineNoId ||
FinishInstruction(state, frame) == MachineNoId { return false }
}
// A proven element address carries its bound and is not checked.
dynamic := source.operands.count == 2
bound := ifx dynamic then ProvenBound(state, function, source) else 0
instruction := BeginInstruction(state, ifx dynamic then MachineOpcode.ElementAddress else .FieldAddress, source.origin)
if VirtualOperand(state, lowering.view_address[result], .Define) == MachineNoId ||
VirtualOperand(state, base, .Use) == MachineNoId { return false }
if dynamic {
if VirtualOperand(state, GlobalVirtual(state, function, source.operands[1]), .Use) == MachineNoId ||
bound > 0 && ImmediateOperand(state, cast(u64)bound) == MachineNoId { return false }
} else if ImmediateOperand(state, source.immediate) == MachineNoId { return false }
return FinishInstruction(state, instruction) != MachineNoId
}
// A view computes or shares its address; a member of a view is read in place
// through it; any other extract copies the member out of its frame object.
LowerExtract :: (state: *LowerState, function: *MachineFunction, source: LirInstruction) -> bool {
lowering := state.aggregates
if lowering.plan.view[source.result] == .Read { return ViewAddress(state, function, source) }
aggregate := source.operands[0]
if !MachineAggregateViewed(lowering.plan.view[aggregate]) { return LowerAggregate(state, function, source, .AggregateExtract, 1) }
instruction := BeginInstruction(state, .AggregateExtract, source.origin)
if VirtualOperand(state, GlobalVirtual(state, function, source.result), .Define) == MachineNoId ||
VirtualOperand(state, lowering.view_address[aggregate], .Use) == MachineNoId ||
!MemberOperands(state, function, source, 1) { return false }
return FinishInstruction(state, instruction) != MachineNoId
}
// A changed view's insert replaces the member in place through the view's
// address, and putting the view back emits nothing.
LowerInsert :: (state: *LowerState, function: *MachineFunction, source: LirInstruction) -> bool {
lowering := state.aggregates
view := lowering.plan.view[source.result]
if view == .PutBack { return true }
if view != .Changed { return LowerAggregate(state, function, source, .AggregateInsert, 2) }
instruction := BeginInstruction(state, .AggregateInsert, source.origin)
if VirtualOperand(state, lowering.view_address[source.result], .Use) == MachineNoId ||
VirtualOperand(state, GlobalVirtual(state, function, source.operands[1]), .Use) == MachineNoId ||
!MemberOperands(state, function, source, 2) { return false }
return FinishInstruction(state, instruction) != MachineNoId
}
LowerInstruction :: (state: *LowerState, function: *MachineFunction,
source: LirInstruction) -> bool {
if !Spend(state, 1) { return false }
if source.op == .Constant { return LowerConstant(state, function, source, .MoveImmediate) }
if source.op == .Null { return LowerConstant(state, function, source, .MoveImmediate) }
if source.op == .GlobalAddress {
// Global G is pointer slot 1 + G, version 0, from instance start.
instruction := BeginInstruction(state, .MoveImmediate, source.origin)
if VirtualOperand(state, GlobalVirtual(state, function, source.result), .Define) == MachineNoId ||
ImmediateOperand(state, MachinePointerToken(1 + cast(s64)source.symbol, 0, 0)) == MachineNoId {
return false
}
return FinishInstruction(state, instruction) != MachineNoId
}
if source.op == .FunctionAddress {
return LowerAddress(state, function, source, .FunctionAddress, .Function, .FunctionAddress)
}
if source.op == .Negate || source.op == .BitNot { return LowerUnary(state, function, source) }
if source.op == .Add || source.op == .Subtract || source.op == .Multiply || source.op == .Divide ||
source.op == .Remainder || source.op == .BitAnd || source.op == .BitOr || source.op == .BitXor ||
source.op == .ShiftLeft || source.op == .ShiftRight { return LowerBinary(state, function, source) }
if source.op == .Equal || source.op == .NotEqual || source.op == .Less || source.op == .LessEqual ||
source.op == .Greater || source.op == .GreaterEqual { return LowerCompare(state, function, source) }
if source.op == .Convert { return LowerMove(state, function, source, .Convert) }
if source.op == .Bitcast { return LowerMove(state, function, source, .Bitcast) }
if source.op == .Aggregate { return LowerMove(state, function, source, .AggregateBuild) }
if source.op == .Extract { return LowerExtract(state, function, source) }
if source.op == .Insert { return LowerInsert(state, function, source) }
if source.op == .Allocate { return LowerAllocate(state, function, source) }
if source.op == .Load { return LowerMemory(state, function, source, .Load) }
if source.op == .Store { return LowerMemory(state, function, source, .Store) }
if source.op == .Copy { return LowerMemory(state, function, source, .Copy) }
if source.op == .Zero { return LowerMemory(state, function, source, .Zero) }
if source.op == .FieldAddress { return LowerMemory(state, function, source, .FieldAddress) }
if source.op == .ElementAddress { return LowerElement(state, function, source) }
if source.op == .BytesEqual { return LowerBytesEqual(state, function, source) }
if source.op == .Resize { return LowerResize(state, function, source) }
if source.op == .Call || source.op == .CallIndirect || source.op == .HostCall {
return LowerCall(state, function, source)
}
if source.op == .Fuel { return LowerControl(state, function, source, .Fuel) }
if source.op == .Trap { return LowerControl(state, function, source, .Trap) }
if source.op == .Jump { return LowerControl(state, function, source, .Jump) }
if source.op == .Branch { return LowerControl(state, function, source, .Branch) }
if source.op == .Return { return LowerControl(state, function, source, .Return) }
if source.op == .Unreachable { return LowerControl(state, function, source, .Unreachable) }
return Fail(state, .Unsupported)
}
LowerFunction :: (state: *LowerState, function_id: s32) -> bool {
source := state.lir.functions[function_id]
if source.external { return true }
function := state.owner.functions[function_id]
// Views read and change members in place through x86-64 address
// registers; other targets share storage only.
problem := MachineAggregatePlanBuild(*state.aggregates.plan, state.lir, source, state.aggregates.stack_size[:],
state.target.arch == .X86_64, state.remaining, state.limits.bytes)
if problem != .None { return Fail(state, problem) }
if !Spend(state, state.aggregates.plan.work) || !CreateVirtuals(state, function_id) { return false }
function = state.owner.functions[function_id]
if !ViewAddresses(state, *function, source) { return false }
// A function that allocates keeps the frame arena's top at entry and
// the head of its pointer chain in two frame words. Each `allocate` gets
// its raw-storage virtual up front, so a direct access in any block it
// dominates can name it.
frame_raw := state.frame_raw
if !VecResizeBounded(<<frame_raw, source.values.count, state.limits.bytes / 4) { return Fail(state, .Allocation) }
for at: cast(s64)0..source.values.count - 1 { (<<frame_raw)[at] = MachineNoId }
allocates := false
for block: source.blocks {
for instruction: block.instructions {
if instruction.op != .Allocate { continue }
allocates = true
if instruction.result < 0 || instruction.result >= source.values.count { return Fail(state, .Virtual) }
raw := RawVirtual(state, *function, GlobalVirtual(state, *function, instruction.result))
if raw == MachineNoId { return false }
(<<frame_raw)[instruction.result] = raw
}
}
if allocates {
for at: 0..1 {
object := AddStack(state, .{function = function_id, kind = .Local, size = 8,
alignment = 8, type = 0, origin = Origin(state, source.origin), value = MachineNoId})
if object == MachineNoId { return false }
relative := object - function.stack_begin + 1
if at == 0 { function.arena_mark = relative } else { function.pointer_chain = relative }
}
function.stack_count = cast(s32)state.owner.stack_objects.count - function.stack_begin
}
function.block_begin = cast(s32)state.owner.blocks.count
function.block_count = cast(s32)source.blocks.count
for block_id: cast(s64)0..source.blocks.count - 1 {
if AddBlock(state, .{function = function_id, lir_block = cast(s32)block_id}) == MachineNoId { return false }
}
function.entry = function.block_begin + source.entry
state.owner.functions[function_id] = function
for block_id: cast(s64)0..source.blocks.count - 1 {
block_index := function.block_begin + cast(s32)block_id
block := state.owner.blocks[block_index]
block.instruction_begin = cast(s32)state.owner.instructions.count
for instruction: source.blocks[block_id].instructions {
if !LowerInstruction(state, *function, instruction) { return false }
}
block.instruction_count = cast(s32)state.owner.instructions.count - block.instruction_begin
state.owner.blocks[block_index] = block
}
function.virtual_count = cast(s32)state.owner.virtuals.count - function.virtual_begin
function.stack_count = cast(s32)state.owner.stack_objects.count - function.stack_begin
state.owner.functions[function_id] = function
return true
}
Finalize :: (state: *LowerState) {
owner := state.owner
owner.program = .{version = MachineVersion, target = state.target,
text = owner.text[:], sources = owner.sources[:], origins = owner.origins[:],
types = owner.types[:], type_ids = owner.type_ids[:], data = owner.data[:],
constants = owner.constants[:], globals = owner.globals[:], initializers = owner.initializers[:],
functions = owner.functions[:],
blocks = owner.blocks[:], virtuals = owner.virtuals[:], instructions = owner.instructions[:],
operands = owner.operands[:], edges = owner.edges[:], copies = owner.copies[:],
stack_objects = owner.stack_objects[:], relocations = owner.relocations[:],
calls = owner.calls[:], entry = state.lir.entry, stage = .Virtual,
frames = owner.frames[:], spills = owner.spills[:],
scratch_general = MachineNoId, scratch_float = MachineNoId}
}
Result :: (state: LowerState) -> MachineResult {
return .{problem = state.problem, diagnostic = state.diagnostic,
lir_diagnostic_problem = state.lir_diagnostic_problem,
work = state.used, bytes = state.bytes}
}
#scope_export
MachineFree :: (owner: *MachineOwner) {
if owner == null { return }
owner.valid = false
owner.program = .{version = MachineVersion, entry = MachineNoId}
VecFree(owner.text)
VecFree(owner.sources)
VecFree(owner.origins)
VecFree(owner.types)
VecFree(owner.type_ids)
VecFree(owner.data)
VecFree(owner.constants)
VecFree(owner.globals)
VecFree(owner.initializers)
VecFree(owner.functions)
VecFree(owner.blocks)
VecFree(owner.virtuals)
VecFree(owner.instructions)
VecFree(owner.operands)
VecFree(owner.edges)
VecFree(owner.copies)
VecFree(owner.stack_objects)
VecFree(owner.relocations)
VecFree(owner.calls)
VecFree(owner.frames)
VecFree(owner.spills)
}
MachineProgramView :: (owner: *MachineOwner) -> MachineProgram {
if owner == null || !owner.valid { return .{version = MachineVersion, entry = MachineNoId} }
return owner.program
}
MachineLower :: (owner: *MachineOwner, program: LirProgram, target: TargetDescription,
options: MachineOptions, limits: MachineLimits) -> MachineResult {
state := LowerState.{.owner = owner, .lir = program, .target = target,
.options = options, .limits = limits, .diagnostic = EmptyDiagnostic(),
.remaining = limits.work}
if owner == null { state.problem = .Owner; return Result(state) }
MachineFree(owner)
if !TargetValid(target) { state.problem = .Target; return Result(state) }
if !TargetMachineLoweringSupported(target) {
state.problem = .UnsupportedTarget
return Result(state)
}
if limits.work < 0 || limits.bytes < 0 { state.problem = .Limit; return Result(state) }
lir_diagnostic := LirVerify(program, LirDefaultLimits())
if lir_diagnostic.problem != .None {
state.lir_diagnostic_problem = cast(s32)lir_diagnostic.problem
state.problem = ifx lir_diagnostic.problem == .Unsupported then .Unsupported else .VerifyInput
return Result(state)
}
// Facts are an optimization: a program too large to prove keeps every
// check.
proven: LirProvenOwner
defer LirProvenFree(*proven)
unused LirProvenBuild(*proven, program, LirDefaultLimits())
state.proven = *proven
frame_raw: Vec(s32)
defer VecFree(frame_raw)
state.frame_raw = *frame_raw
aggregates: AggregateLowering
defer AggregateLoweringFree(*aggregates)
state.aggregates = *aggregates
if !CopyMetadata(*state) || !CopyTypes(*state) || !AggregateTypes(*state) || !AddFunctionRecords(*state) {
result := Result(state)
MachineFree(owner)
return result
}
for function_id: cast(s64)0..program.functions.count - 1 {
if !LowerFunction(*state, cast(s32)function_id) {
result := Result(state)
MachineFree(owner)
return result
}
}
Finalize(*state)
diagnostic := MachineVerify(owner.program, limits)
if diagnostic.problem != .None {
state.problem = diagnostic.problem
state.diagnostic = diagnostic
result := Result(state)
MachineFree(owner)
return result
}
owner.valid = true
return Result(state)
}