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.
This commit is contained in:
1 parent
c0efdfd534
commit
31d291f337
13 files changed
+4230
-135
No files matched your search
@@ -95,6 +95,20 @@ activation. It therefore is not represented as `StackAddress` plus one static
|
||||
stack object per instruction site. Allocation and encoding must preserve the
|
||||
pseudo until they implement that exact dynamic frame-storage behavior.
|
||||
|
||||
Aggregate values are stack-class virtuals whose frame objects follow the plan
|
||||
of `compiler_machine_aggregate.zi`, the native counterpart of zx2wasm's
|
||||
aggregate slots. Values whose lifetimes never overlap share one object, so an
|
||||
`AggregateInsert` whose destination is its source's object changes only its
|
||||
member, and a block parameter that shares its arguments' object needs no edge
|
||||
copy. On x86-64 an extract read only by extracts in its own block is a view:
|
||||
`StackAddress` and `FieldAddress` or `ElementAddress` compute its address once,
|
||||
shared with an earlier view of the same storage and member that dominates it,
|
||||
and `AggregateExtract`/`AggregateInsert` forms whose aggregate operand is that
|
||||
pointer register read and change its members in place. A changed view put back
|
||||
where it came from emits nothing. A dynamic member's trailing immediate, like
|
||||
the optional fourth `ElementAddress` operand, is the bound the shared LIR facts
|
||||
prove its index below, or 0; a proven index is not checked.
|
||||
|
||||
## Linux x86-64 ABI facts
|
||||
|
||||
Register numbers follow x86-64 encoding order. General-register argument
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
## [Unreleased]
|
||||
|
||||
- Native x86-64 code drops the index check of an element the shared interval analysis proves in range (fixed arrays and constant-count views such as a string constant's bytes), and reads a constant text directly, so the Sieve and Hash loops carry no pointer or index checks; Wasm drops proven view checks too. A runtime index that can leave the array or view keeps its check and traps.
|
||||
- Native code keeps records and arrays in place: aggregate values whose lifetimes never overlap share one frame slot, so an update writes only the changed member and loop-carried or branch-joined values need no copy, and on x86-64 a member read or changed through an element is done at that element's address, computed and checked once where it dominates (not at all when the shared facts prove its index); remaining copies and zeroing of 64 bytes or more run a 16-byte loop. On Omega the Records kernel drops from 1951 to 32 µs natively and from 1858 to 29 µs on the zx engine (C 8.7 µs), its image from 69,760 to 12,416 bytes, and the Sieve image from 94,336 to 8,320 bytes.
|
||||
- A closed C program, linked with `--entry` and built with `--exe` or its own `main`, carries only the code it uses: each module header declares just what another generated file names, the module's `.c` keeps what only it reads, header inline copies stay only for procedures other modules call, and a module whose header would declare nothing has none. For Kryon's examples, headers shrink from 18 to 8.5 KB (window), 288 to 91 KB (hello), 319 to 102 KB (box) and 692 to 420 KB (image).
|
||||
- A closed C program's runtime headers, such as `zir_bounds.h`, `zir_slice.h`, `zir_string.h` and `zir_vec.h`, keep only the helpers its generated files call; Kryon's window headers shrink to 6.6 KB.
|
||||
- Native x86-64 code reaches a global or a frame allocation directly when one shared LIR pass proves the access stays inside a live root, instead of resolving its checked pointer; the machine verifier now checks every load, store, zero and byte comparison and re-derives each direct access, and Wasm takes its index proofs from the same pass. Parameters, loaded pointers and heap blocks keep their resolves, so stale aliases, resized blocks and out-of-range runtime indices still trap. A LIR `zero` is now resolved like a store instead of writing through the raw token.
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
ASSEMBLY_C := $(BUILD_DIR)/compiler-assembly
|
||||
ASSEMBLY_MACHINE_SOURCES := cmd/compiler_target.zi cmd/compiler_machine_image.zi cmd/compiler_abi.zi cmd/compiler_machine_ir.zi \
|
||||
cmd/compiler_machine_verify.zi cmd/compiler_machine_lower.zi cmd/compiler_machine_verify_allocated.zi \
|
||||
cmd/compiler_regalloc.zi cmd/compiler_x86_bytes.zi cmd/compiler_x86_64.zi \
|
||||
cmd/compiler_machine_verify.zi cmd/compiler_machine_aggregate.zi cmd/compiler_machine_lower.zi \
|
||||
cmd/compiler_machine_verify_allocated.zi cmd/compiler_regalloc.zi cmd/compiler_x86_bytes.zi cmd/compiler_x86_64.zi \
|
||||
cmd/compiler_aarch64.zi \
|
||||
cmd/compiler_arm_bytes.zi \
|
||||
cmd/compiler_machine_elf.zi cmd/compiler_machine_pipeline.zi cmd/compiler_native_cache.zi
|
||||
@@ -57,7 +57,7 @@ $(BUILD_DIR)/obj/assembly-core.o: assembly.mk $(ASSEMBLY_C)/.generated $(BUILD_D
|
||||
# second copy of those public symbols from assembly-core.o.
|
||||
ASSEMBLY_NATIVE_MODULES := compiler_abi compiler_machine_image \
|
||||
compiler_machine_ir compiler_machine_verify \
|
||||
compiler_machine_lower compiler_machine_verify_allocated compiler_regalloc \
|
||||
compiler_machine_aggregate compiler_machine_lower compiler_machine_verify_allocated compiler_regalloc \
|
||||
compiler_target compiler_x86_bytes compiler_x86_64 compiler_aarch64 \
|
||||
compiler_arm_bytes \
|
||||
compiler_machine_elf \
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,720 @@
|
||||
using Lir :: #import "compiler_lowered_ir"
|
||||
using Machine :: #import "compiler_machine_ir"
|
||||
using Vectors :: #import "std/vec"
|
||||
|
||||
// Frame storage and in-place views for the aggregate (stack-class) values of
|
||||
// one LIR function, planned before machine lowering. This is the native
|
||||
// counterpart of zx2wasm's coalesce_aggregates and plan_views.
|
||||
//
|
||||
// Storage: aggregate values whose lifetimes never overlap share one frame
|
||||
// object. An insert takes its source's object when the source dies there, so
|
||||
// it changes one member in place; a block parameter takes its arguments'
|
||||
// objects, so loop-carried and branch-joined aggregates need no edge copy.
|
||||
// This is SSA coalescing over the liveness of the aggregate values alone; an
|
||||
// instruction's aggregate operands conflict with its result, except the
|
||||
// source of an insert.
|
||||
//
|
||||
// Views: an extract read only by extracts in its own block, while nothing
|
||||
// writes the storage it reads, is read in place through its address. One
|
||||
// that a single insert then changes and puts straight back where it came
|
||||
// from is changed in place, and the put-back insert emits nothing. A view
|
||||
// takes the address an earlier view of the same storage and member computed
|
||||
// where that one dominates it, so a loop body checks an index once.
|
||||
|
||||
MachineAggregateView :: enum s32 { None; Read; Changed; PutBack }
|
||||
|
||||
MachineAggregatePlan :: struct {
|
||||
// Per value: the representative whose frame object it uses (itself for
|
||||
// a scalar); its view kind; for a view, the representative of the storage
|
||||
// it reads and the view whose address it uses (itself when it computes
|
||||
// it). Per representative: whether a value of its class needs the object.
|
||||
slot: Vec(s32)
|
||||
view: Vec(MachineAggregateView)
|
||||
root: Vec(s32)
|
||||
address: Vec(s32)
|
||||
storage: Vec(bool)
|
||||
// Work spent by the last build.
|
||||
work: s64
|
||||
// Scratch, reused across functions.
|
||||
index: Vec(s32)
|
||||
parent: Vec(s32)
|
||||
representative: Vec(s32)
|
||||
live: Vec(u64)
|
||||
live_in: Vec(u64)
|
||||
live_out: Vec(u64)
|
||||
interfere: Vec(u64)
|
||||
members: Vec(u64)
|
||||
home: Vec(s32)
|
||||
read: Vec(s32)
|
||||
update: Vec(s32)
|
||||
other: Vec(s32)
|
||||
uses: Vec(s32)
|
||||
successor_begin: Vec(s32)
|
||||
successors: Vec(s32)
|
||||
predecessor_begin: Vec(s32)
|
||||
predecessors: Vec(s32)
|
||||
cursor: Vec(s32)
|
||||
pending: Vec(s32)
|
||||
order: Vec(s32)
|
||||
position: Vec(s32)
|
||||
dominator: Vec(s32)
|
||||
block_of: Vec(s32)
|
||||
key_parent: Vec(s32)
|
||||
key_member: Vec(u64)
|
||||
key_dynamic: Vec(bool)
|
||||
chain_head: Vec(s32)
|
||||
chain_next: Vec(s32)
|
||||
}
|
||||
|
||||
// Read and changed views have no storage of their own; a put-back value is
|
||||
// stored in its root like any other.
|
||||
MachineAggregateViewed :: (view: MachineAggregateView) -> bool { return view == .Read || view == .Changed }
|
||||
|
||||
#scope_file
|
||||
|
||||
// Coalescing compares every pair of aggregate values; past these sizes each
|
||||
// value keeps its own object, which is always correct.
|
||||
MaximumAggregates :: 8192
|
||||
MaximumLiveWords :: 4194304
|
||||
|
||||
Context :: struct {
|
||||
plan: *MachineAggregatePlan
|
||||
function: LirFunction
|
||||
program: LirProgram
|
||||
stack_size: []s64
|
||||
budget: s64
|
||||
bytes: s64
|
||||
problem: MachineProblem
|
||||
count: s64
|
||||
width: s64
|
||||
}
|
||||
|
||||
Fail :: (context: *Context, problem: MachineProblem) -> bool {
|
||||
if context.problem == .None { context.problem = problem }
|
||||
return false
|
||||
}
|
||||
|
||||
Spend :: (context: *Context, count: s64) -> bool {
|
||||
if count < 0 || count > context.budget - context.plan.work { return Fail(context, .Limit) }
|
||||
context.plan.work += count
|
||||
return true
|
||||
}
|
||||
|
||||
Aggregate :: (context: *Context, value: s32) -> bool {
|
||||
return value >= 0 && context.stack_size[context.function.values[value]] >= 0
|
||||
}
|
||||
|
||||
TypeOf :: (context: *Context, value: s32) -> s32 { return context.function.values[value] }
|
||||
|
||||
Mask :: (bit: s32) -> u64 { return cast(u64)1 << cast(u64)(bit & 63) }
|
||||
|
||||
Word :: (bit: s32) -> s64 { return cast(s64)(bit >> 6) }
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Liveness of aggregate values, in the working row `live`
|
||||
|
||||
Use :: (plan: *MachineAggregatePlan, value: s32) {
|
||||
if value < 0 { return }
|
||||
at := plan.index[value]
|
||||
if at >= 0 { plan.live[Word(at)] = plan.live[Word(at)] | Mask(at) }
|
||||
}
|
||||
|
||||
Kill :: (plan: *MachineAggregatePlan, value: s32) {
|
||||
if value < 0 { return }
|
||||
at := plan.index[value]
|
||||
if at >= 0 { plan.live[Word(at)] = plan.live[Word(at)] & ~Mask(at) }
|
||||
}
|
||||
|
||||
// Stores the working row as row ROW of ROWS; true when that changed it.
|
||||
Save :: (live: []u64, rows: []u64, row: s64) -> bool {
|
||||
changed := false
|
||||
for word: cast(s64)0..live.count - 1 {
|
||||
if rows[row + word] != live[word] {
|
||||
rows[row + word] = live[word]
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// Live sets to a fixed point. An edge's arguments are used at the end of its
|
||||
// block; a block's parameters are defined at its start.
|
||||
Liveness :: (context: *Context) -> bool {
|
||||
plan := context.plan
|
||||
blocks := context.function.blocks
|
||||
width := context.width
|
||||
changed := true
|
||||
while changed {
|
||||
changed = false
|
||||
block := blocks.count - 1
|
||||
while block >= 0 {
|
||||
instructions := blocks[block].instructions
|
||||
if !Spend(context, width * 2 + instructions.count) { return false }
|
||||
for word: cast(s64)0..width - 1 { plan.live[word] = 0 }
|
||||
for instruction: instructions {
|
||||
for edge: instruction.edges {
|
||||
if !Spend(context, width) { return false }
|
||||
row := cast(s64)edge.block * width
|
||||
for word: cast(s64)0..width - 1 { plan.live[word] = plan.live[word] | plan.live_in[row + word] }
|
||||
for parameter: blocks[edge.block].parameters { Kill(plan, parameter) }
|
||||
}
|
||||
}
|
||||
if Save(plan.live[:], plan.live_out[:], block * width) { changed = true }
|
||||
at := instructions.count - 1
|
||||
while at >= 0 {
|
||||
instruction := instructions[at]
|
||||
Kill(plan, instruction.result)
|
||||
for operand: instruction.operands { Use(plan, operand) }
|
||||
for edge: instruction.edges { for argument: edge.arguments { Use(plan, argument) } }
|
||||
at -= 1
|
||||
}
|
||||
for parameter: blocks[block].parameters { Kill(plan, parameter) }
|
||||
if Save(plan.live[:], plan.live_in[:], block * width) { changed = true }
|
||||
block -= 1
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Interference and coalescing. A class's row holds the values live where one
|
||||
// of its members is defined, so two classes conflict when either row meets
|
||||
// the other's members.
|
||||
|
||||
Conflict :: (context: *Context, defined: s32) {
|
||||
plan := context.plan
|
||||
row := cast(s64)defined * context.width
|
||||
for word: cast(s64)0..context.width - 1 { plan.interfere[row + word] = plan.interfere[row + word] | plan.live[word] }
|
||||
}
|
||||
|
||||
Pair :: (context: *Context, defined: s32, value: s32) {
|
||||
if !Aggregate(context, value) { return }
|
||||
plan := context.plan
|
||||
other := plan.index[value]
|
||||
if other == defined { return }
|
||||
at := cast(s64)defined * context.width + Word(other)
|
||||
plan.interfere[at] = plan.interfere[at] | Mask(other)
|
||||
}
|
||||
|
||||
// Defines VALUES at one point: each conflicts with what is live there and
|
||||
// with the others.
|
||||
DefineTogether :: (context: *Context, values: []s32) -> bool {
|
||||
plan := context.plan
|
||||
if !Spend(context, values.count * (context.width + values.count)) { return false }
|
||||
for value: values { Kill(plan, value) }
|
||||
for value: values {
|
||||
if !Aggregate(context, value) { continue }
|
||||
Conflict(context, plan.index[value])
|
||||
for other: values { Pair(context, plan.index[value], other) }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
Interference :: (context: *Context) -> bool {
|
||||
plan := context.plan
|
||||
function := context.function
|
||||
width := context.width
|
||||
for block_index: cast(s64)0..function.blocks.count - 1 {
|
||||
block := function.blocks[block_index]
|
||||
if !Spend(context, width * (block.instructions.count + 1)) { return false }
|
||||
row := block_index * width
|
||||
for word: cast(s64)0..width - 1 { plan.live[word] = plan.live_out[row + word] }
|
||||
at := block.instructions.count - 1
|
||||
while at >= 0 {
|
||||
instruction := block.instructions[at]
|
||||
for edge: instruction.edges { for argument: edge.arguments { Use(plan, argument) } }
|
||||
if Aggregate(context, instruction.result) {
|
||||
Kill(plan, instruction.result)
|
||||
defined := plan.index[instruction.result]
|
||||
Conflict(context, defined)
|
||||
for operand, local: instruction.operands {
|
||||
// An insert updating its source in place is the one
|
||||
// instruction that may write the object it reads.
|
||||
if instruction.op != .Insert || local != 0 { Pair(context, defined, operand) }
|
||||
}
|
||||
}
|
||||
for operand: instruction.operands { Use(plan, operand) }
|
||||
at -= 1
|
||||
}
|
||||
// The entry block's parameters are the function's.
|
||||
if !DefineTogether(context, block.parameters) { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
Find :: (plan: *MachineAggregatePlan, at: s32) -> s32 {
|
||||
while plan.parent[at] != at {
|
||||
plan.parent[at] = plan.parent[plan.parent[at]]
|
||||
at = plan.parent[at]
|
||||
}
|
||||
return at
|
||||
}
|
||||
|
||||
Join :: (context: *Context, left: s32, right: s32) -> bool {
|
||||
plan := context.plan
|
||||
if !Aggregate(context, left) || !Aggregate(context, right) || TypeOf(context, left) != TypeOf(context, right) {
|
||||
return true
|
||||
}
|
||||
a := Find(plan, plan.index[left])
|
||||
b := Find(plan, plan.index[right])
|
||||
if a == b { return true }
|
||||
if !Spend(context, context.width) { return false }
|
||||
row_a := cast(s64)a * context.width
|
||||
row_b := cast(s64)b * context.width
|
||||
for word: cast(s64)0..context.width - 1 {
|
||||
if (plan.interfere[row_a + word] & plan.members[row_b + word]) != 0 ||
|
||||
(plan.interfere[row_b + word] & plan.members[row_a + word]) != 0 { return true }
|
||||
}
|
||||
plan.parent[b] = a
|
||||
for word: cast(s64)0..context.width - 1 {
|
||||
plan.interfere[row_a + word] = plan.interfere[row_a + word] | plan.interfere[row_b + word]
|
||||
plan.members[row_a + word] = plan.members[row_a + word] | plan.members[row_b + word]
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// In program order: updates in place first, then edges.
|
||||
Coalesce :: (context: *Context) -> bool {
|
||||
function := context.function
|
||||
for block: function.blocks {
|
||||
for instruction: block.instructions {
|
||||
if instruction.op == .Insert && instruction.operands.count > 0 &&
|
||||
!Join(context, instruction.result, instruction.operands[0]) { return false }
|
||||
}
|
||||
}
|
||||
for block: function.blocks {
|
||||
for instruction: block.instructions {
|
||||
for edge: instruction.edges {
|
||||
parameters := function.blocks[edge.block].parameters
|
||||
for argument, at: edge.arguments {
|
||||
if !Join(context, parameters[at], argument) { return false }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Each class is named by its function parameter (an entry block parameter),
|
||||
// whose object is the incoming argument, or else by its smallest value.
|
||||
AssignSlots :: (context: *Context) {
|
||||
plan := context.plan
|
||||
function := context.function
|
||||
for at: cast(s64)0..context.count - 1 { plan.representative[at] = MachineNoId }
|
||||
for parameter: function.blocks[function.entry].parameters {
|
||||
if Aggregate(context, parameter) {
|
||||
plan.representative[Find(plan, plan.index[parameter])] = parameter
|
||||
}
|
||||
}
|
||||
for value: cast(s32)0..cast(s32)function.values.count - 1 {
|
||||
if !Aggregate(context, value) { continue }
|
||||
class := Find(plan, plan.index[value])
|
||||
if plan.representative[class] == MachineNoId { plan.representative[class] = value }
|
||||
plan.slot[value] = plan.representative[class]
|
||||
}
|
||||
}
|
||||
|
||||
Storage :: (context: *Context) -> bool {
|
||||
plan := context.plan
|
||||
function := context.function
|
||||
blocks := cast(s64)function.blocks.count
|
||||
context.count = 0
|
||||
for value: cast(s32)0..cast(s32)function.values.count - 1 {
|
||||
plan.index[value] = MachineNoId
|
||||
if Aggregate(context, value) {
|
||||
plan.index[value] = cast(s32)context.count
|
||||
context.count += 1
|
||||
}
|
||||
}
|
||||
context.width = (context.count + 63) / 64
|
||||
if context.count < 2 || context.count > MaximumAggregates || blocks * context.width > MaximumLiveWords {
|
||||
return true
|
||||
}
|
||||
width := context.width
|
||||
bound := context.bytes
|
||||
if !VecResizeBounded(plan.live, width, bound) || !VecResizeBounded(plan.live_in, blocks * width, bound) ||
|
||||
!VecResizeBounded(plan.live_out, blocks * width, bound) ||
|
||||
!VecResizeBounded(plan.interfere, context.count * width, bound) ||
|
||||
!VecResizeBounded(plan.members, context.count * width, bound) ||
|
||||
!VecResizeBounded(plan.parent, context.count, bound) ||
|
||||
!VecResizeBounded(plan.representative, context.count, bound) { return Fail(context, .Allocation) }
|
||||
if !Spend(context, (blocks + context.count) * width * 2) { return false }
|
||||
for at: cast(s64)0..plan.live_in.count - 1 { plan.live_in[at] = 0; plan.live_out[at] = 0 }
|
||||
for at: cast(s64)0..plan.interfere.count - 1 { plan.interfere[at] = 0; plan.members[at] = 0 }
|
||||
for at: cast(s32)0..cast(s32)context.count - 1 {
|
||||
plan.parent[at] = at
|
||||
plan.members[cast(s64)at * width + Word(at)] = Mask(at)
|
||||
}
|
||||
if !Liveness(context) || !Interference(context) || !Coalesce(context) { return false }
|
||||
AssignSlots(context)
|
||||
return true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Views
|
||||
|
||||
// Where each value is used: uses counts operands and edge arguments; home is
|
||||
// the block of all its uses (-1 unused, -2 several blocks or an edge); read
|
||||
// the last extract from it; update the one insert that changes it (-2 for
|
||||
// more); other its last other operand use.
|
||||
Uses :: (context: *Context) -> bool {
|
||||
plan := context.plan
|
||||
for block, block_index: context.function.blocks {
|
||||
if !Spend(context, block.instructions.count) { return false }
|
||||
home := cast(s32)block_index
|
||||
for instruction, item: block.instructions {
|
||||
for value, at: instruction.operands {
|
||||
plan.uses[value] += 1
|
||||
if plan.home[value] != -1 && plan.home[value] != home { plan.home[value] = -2 }
|
||||
else { plan.home[value] = home }
|
||||
if instruction.op == .Extract && at == 0 { plan.read[value] = cast(s32)item }
|
||||
else if instruction.op == .Insert && at == 0 {
|
||||
plan.update[value] = ifx plan.update[value] == -1 then cast(s32)item else -2
|
||||
} else { plan.other[value] = cast(s32)item }
|
||||
}
|
||||
for edge: instruction.edges {
|
||||
for argument: edge.arguments {
|
||||
plan.uses[argument] += 1
|
||||
plan.home[argument] = -2
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Whether two inserts or extracts name the same member.
|
||||
SameMember :: (left: LirInstruction, left_fixed: s64, right: LirInstruction, right_fixed: s64) -> bool {
|
||||
dynamic := left.operands.count == left_fixed + 1
|
||||
if dynamic != (right.operands.count == right_fixed + 1) { return false }
|
||||
if dynamic { return left.operands[left_fixed] == right.operands[right_fixed] }
|
||||
return left.immediate == right.immediate
|
||||
}
|
||||
|
||||
// Whether an instruction strictly between FROM and UNTIL reads SOURCE or a
|
||||
// view of ROOT.
|
||||
ReadsBetween :: (context: *Context, instructions: []LirInstruction, from: s32, until: s32,
|
||||
source: s32, root: s32) -> bool {
|
||||
plan := context.plan
|
||||
for between: from + 1..until - 1 {
|
||||
for value: instructions[between].operands {
|
||||
if value == source || MachineAggregateViewed(plan.view[value]) && plan.root[value] == root { return true }
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Whether an instruction strictly between FROM and UNTIL writes ROOT: defines
|
||||
// a value stored there, or changes a view of it.
|
||||
WritesBetween :: (context: *Context, instructions: []LirInstruction, from: s32, until: s32, root: s32) -> bool {
|
||||
plan := context.plan
|
||||
for between: from + 1..until - 1 {
|
||||
value := instructions[between].result
|
||||
if !Aggregate(context, value) { continue }
|
||||
if !MachineAggregateViewed(plan.view[value]) && plan.slot[value] == root ||
|
||||
plan.view[value] == .Changed && plan.root[value] == root { return true }
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Plans the extract at ITEM; false only when the work budget runs out.
|
||||
PlanView :: (context: *Context, instructions: []LirInstruction, block: s32, item: s32) -> bool {
|
||||
plan := context.plan
|
||||
instruction := instructions[item]
|
||||
result := instruction.result
|
||||
// An unused extract is a view too: a dynamic one keeps only its check.
|
||||
// An empty value has nothing to view.
|
||||
if instruction.op != .Extract || context.stack_size[TypeOf(context, result)] <= 0 || plan.other[result] >= 0 ||
|
||||
plan.update[result] == -2 || plan.home[result] != block && plan.home[result] != -1 { return true }
|
||||
source := instruction.operands[0]
|
||||
if instruction.operands.count == 2 && context.program.types[TypeOf(context, source)].kind != .Array { return true }
|
||||
viewed := MachineAggregateViewed(plan.view[source])
|
||||
root := ifx viewed then plan.root[source] else plan.slot[source]
|
||||
// A changed view: its insert follows its last read, the changed value
|
||||
// goes straight back into an insert of the source at the same member
|
||||
// stored in place, and nothing reads the source in between.
|
||||
changed := plan.update[result]
|
||||
changed_value: s32 = MachineNoId
|
||||
put: s32 = MachineNoId
|
||||
until := plan.read[result]
|
||||
if changed >= 0 {
|
||||
changed_value = instructions[changed].result
|
||||
if changed <= plan.read[result] || viewed || plan.home[changed_value] != block ||
|
||||
plan.uses[changed_value] != 1 || plan.other[changed_value] < 0 { return true }
|
||||
until = plan.other[changed_value]
|
||||
putting := instructions[until]
|
||||
put = putting.result
|
||||
if putting.op != .Insert || putting.operands.count < 2 || putting.operands[0] != source ||
|
||||
putting.operands[1] != changed_value || !SameMember(putting, 2, instruction, 1) ||
|
||||
put < 0 || plan.slot[put] != root { return true }
|
||||
}
|
||||
if until > item && !Spend(context, cast(s64)(until - item) * 2) { return false }
|
||||
if changed >= 0 && ReadsBetween(context, instructions, changed, until, source, root) ||
|
||||
until > item && WritesBetween(context, instructions, item, until, root) { return true }
|
||||
plan.view[result] = .Read
|
||||
plan.root[result] = root
|
||||
if changed >= 0 {
|
||||
plan.view[changed_value] = .Changed
|
||||
plan.root[changed_value] = root
|
||||
plan.view[put] = .PutBack
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
Views :: (context: *Context) -> bool {
|
||||
if !Uses(context) { return false }
|
||||
for block, block_index: context.function.blocks {
|
||||
if !Spend(context, block.instructions.count) { return false }
|
||||
for item: cast(s32)0..cast(s32)block.instructions.count - 1 {
|
||||
if !PlanView(context, block.instructions, cast(s32)block_index, item) { return false }
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared view addresses: reverse postorder and immediate dominators
|
||||
|
||||
Order :: (context: *Context) -> bool {
|
||||
plan := context.plan
|
||||
function := context.function
|
||||
blocks := cast(s64)function.blocks.count
|
||||
bound := context.bytes
|
||||
edges: s64
|
||||
for block: function.blocks { for instruction: block.instructions { edges += instruction.edges.count } }
|
||||
if !Spend(context, blocks * 4 + edges * 2) { return false }
|
||||
if !VecResizeBounded(plan.successor_begin, blocks + 1, bound) || !VecResizeBounded(plan.successors, edges, bound) ||
|
||||
!VecResizeBounded(plan.predecessor_begin, blocks + 1, bound) ||
|
||||
!VecResizeBounded(plan.predecessors, edges, bound) || !VecResizeBounded(plan.cursor, blocks, bound) ||
|
||||
!VecResize(plan.pending, 0) || !VecResize(plan.order, 0) ||
|
||||
!VecResizeBounded(plan.position, blocks, bound) || !VecResizeBounded(plan.dominator, blocks, bound) {
|
||||
return Fail(context, .Allocation)
|
||||
}
|
||||
for at: cast(s64)0..blocks { plan.predecessor_begin[at] = 0 }
|
||||
at: s32 = 0
|
||||
for block, block_index: function.blocks {
|
||||
plan.successor_begin[block_index] = at
|
||||
for instruction: block.instructions {
|
||||
for edge: instruction.edges {
|
||||
plan.successors[at] = edge.block
|
||||
plan.predecessor_begin[edge.block + 1] += 1
|
||||
at += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
plan.successor_begin[blocks] = at
|
||||
for block: cast(s64)0..blocks - 1 {
|
||||
plan.predecessor_begin[block + 1] += plan.predecessor_begin[block]
|
||||
plan.cursor[block] = plan.predecessor_begin[block]
|
||||
plan.position[block] = MachineNoId
|
||||
plan.dominator[block] = MachineNoId
|
||||
}
|
||||
for block: cast(s32)0..cast(s32)blocks - 1 {
|
||||
for edge: plan.successor_begin[block]..plan.successor_begin[block + 1] - 1 {
|
||||
successor := plan.successors[edge]
|
||||
plan.predecessors[plan.cursor[successor]] = block
|
||||
plan.cursor[successor] += 1
|
||||
}
|
||||
}
|
||||
// Iterative depth-first postorder from the entry, then reversed.
|
||||
for block: cast(s64)0..blocks - 1 { plan.cursor[block] = plan.successor_begin[block] }
|
||||
entry := function.entry
|
||||
plan.position[entry] = 0
|
||||
if !VecPush(plan.pending, entry) { return Fail(context, .Allocation) }
|
||||
while plan.pending.count > 0 {
|
||||
block := plan.pending[plan.pending.count - 1]
|
||||
if plan.cursor[block] < plan.successor_begin[block + 1] {
|
||||
successor := plan.successors[plan.cursor[block]]
|
||||
plan.cursor[block] += 1
|
||||
if plan.position[successor] == MachineNoId {
|
||||
plan.position[successor] = 0
|
||||
if !VecPush(plan.pending, successor) { return Fail(context, .Allocation) }
|
||||
}
|
||||
} else {
|
||||
if !VecResize(plan.pending, plan.pending.count - 1) || !VecPush(plan.order, block) {
|
||||
return Fail(context, .Allocation)
|
||||
}
|
||||
}
|
||||
}
|
||||
reached := plan.order.count
|
||||
for low: cast(s64)0..reached / 2 - 1 {
|
||||
high := reached - 1 - low
|
||||
swap := plan.order[low]
|
||||
plan.order[low] = plan.order[high]
|
||||
plan.order[high] = swap
|
||||
}
|
||||
for index: cast(s64)0..reached - 1 { plan.position[plan.order[index]] = cast(s32)index }
|
||||
return true
|
||||
}
|
||||
|
||||
Intersect :: (plan: *MachineAggregatePlan, left: s32, right: s32) -> s32 {
|
||||
while left != right {
|
||||
while plan.position[left] > plan.position[right] { left = plan.dominator[left] }
|
||||
while plan.position[right] > plan.position[left] { right = plan.dominator[right] }
|
||||
}
|
||||
return left
|
||||
}
|
||||
|
||||
Dominators :: (context: *Context) -> bool {
|
||||
plan := context.plan
|
||||
entry := context.function.entry
|
||||
plan.dominator[entry] = entry
|
||||
changed := true
|
||||
while changed {
|
||||
changed = false
|
||||
if !Spend(context, plan.order.count + plan.predecessors.count) { return false }
|
||||
for index: cast(s64)1..plan.order.count - 1 {
|
||||
block := plan.order[index]
|
||||
found: s32 = MachineNoId
|
||||
for edge: plan.predecessor_begin[block]..plan.predecessor_begin[block + 1] - 1 {
|
||||
predecessor := plan.predecessors[edge]
|
||||
if plan.dominator[predecessor] == MachineNoId { continue }
|
||||
found = ifx found == MachineNoId then predecessor else Intersect(plan, found, predecessor)
|
||||
}
|
||||
if plan.dominator[block] != found {
|
||||
plan.dominator[block] = found
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
Dominates :: (plan: *MachineAggregatePlan, upper: s32, lower: s32) -> bool {
|
||||
if plan.position[upper] < 0 || plan.position[lower] < 0 { return false }
|
||||
while plan.position[lower] > plan.position[upper] { lower = plan.dominator[lower] }
|
||||
return lower == upper
|
||||
}
|
||||
|
||||
// The view an extract VALUE in BLOCK shares its address with: an earlier view
|
||||
// of the same root, parent address and member whose block dominates BLOCK.
|
||||
ShareAddress :: (context: *Context, instruction: LirInstruction, block: s32) -> bool {
|
||||
plan := context.plan
|
||||
value := instruction.result
|
||||
source := instruction.operands[0]
|
||||
root := plan.root[value]
|
||||
parent := ifx MachineAggregateViewed(plan.view[source]) then plan.address[source] else MachineNoId
|
||||
dynamic := instruction.operands.count == 2
|
||||
member := ifx dynamic then cast(u64)instruction.operands[1] else instruction.immediate
|
||||
candidate := plan.chain_head[root]
|
||||
while candidate != MachineNoId {
|
||||
if !Spend(context, 1) { return false }
|
||||
if plan.key_parent[candidate] == parent && plan.key_dynamic[candidate] == dynamic &&
|
||||
plan.key_member[candidate] == member && Dominates(plan, plan.block_of[candidate], block) {
|
||||
plan.address[value] = candidate
|
||||
return true
|
||||
}
|
||||
candidate = plan.chain_next[candidate]
|
||||
}
|
||||
plan.block_of[value] = block
|
||||
plan.key_parent[value] = parent
|
||||
plan.key_dynamic[value] = dynamic
|
||||
plan.key_member[value] = member
|
||||
plan.chain_next[value] = plan.chain_head[root]
|
||||
plan.chain_head[root] = value
|
||||
return true
|
||||
}
|
||||
|
||||
Addresses :: (context: *Context) -> bool {
|
||||
plan := context.plan
|
||||
function := context.function
|
||||
count := function.values.count
|
||||
bound := context.bytes
|
||||
if !VecResizeBounded(plan.block_of, count, bound) || !VecResizeBounded(plan.key_parent, count, bound) ||
|
||||
!VecResizeBounded(plan.key_member, count, bound) || !VecResizeBounded(plan.key_dynamic, count, bound) ||
|
||||
!VecResizeBounded(plan.chain_head, count, bound) || !VecResizeBounded(plan.chain_next, count, bound) {
|
||||
return Fail(context, .Allocation)
|
||||
}
|
||||
for value: cast(s64)0..count - 1 { plan.chain_head[value] = MachineNoId; plan.chain_next[value] = MachineNoId }
|
||||
if !Order(context) || !Dominators(context) { return false }
|
||||
for block: plan.order {
|
||||
instructions := function.blocks[block].instructions
|
||||
if !Spend(context, instructions.count) { return false }
|
||||
for instruction: instructions {
|
||||
result := instruction.result
|
||||
if result < 0 { continue }
|
||||
if plan.view[result] == .Read {
|
||||
if !ShareAddress(context, instruction, block) { return false }
|
||||
} else if plan.view[result] == .Changed {
|
||||
plan.address[result] = plan.address[instruction.operands[0]]
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
#scope_export
|
||||
|
||||
// Plans FUNCTION of PROGRAM into PLAN. STACK_SIZE gives the size of each
|
||||
// stack-class type and -1 for the others; VIEWS also plans views. BUDGET bounds the work,
|
||||
// recorded in plan.work, and BYTES the element capacity of each scratch
|
||||
// vector.
|
||||
MachineAggregatePlanBuild :: (plan: *MachineAggregatePlan, program: LirProgram, function: LirFunction,
|
||||
stack_size: []s64, views: bool, budget: s64, bytes: s64) -> MachineProblem {
|
||||
plan.work = 0
|
||||
context := Context.{plan = plan, function = function, program = program, stack_size = stack_size,
|
||||
budget = budget, bytes = bytes, problem = .None}
|
||||
count := function.values.count
|
||||
if !VecResizeBounded(plan.slot, count, bytes) || !VecResizeBounded(plan.view, count, bytes) ||
|
||||
!VecResizeBounded(plan.root, count, bytes) || !VecResizeBounded(plan.address, count, bytes) ||
|
||||
!VecResizeBounded(plan.storage, count, bytes) || !VecResizeBounded(plan.index, count, bytes) ||
|
||||
!VecResizeBounded(plan.home, count, bytes) || !VecResizeBounded(plan.read, count, bytes) ||
|
||||
!VecResizeBounded(plan.update, count, bytes) || !VecResizeBounded(plan.other, count, bytes) ||
|
||||
!VecResizeBounded(plan.uses, count, bytes) { return .Allocation }
|
||||
if !Spend(*context, count) { return context.problem }
|
||||
for value: cast(s32)0..cast(s32)count - 1 {
|
||||
plan.slot[value] = value
|
||||
plan.view[value] = .None
|
||||
plan.root[value] = MachineNoId
|
||||
plan.address[value] = value
|
||||
plan.storage[value] = false
|
||||
plan.home[value] = -1
|
||||
plan.read[value] = -1
|
||||
plan.update[value] = -1
|
||||
plan.other[value] = -1
|
||||
plan.uses[value] = 0
|
||||
}
|
||||
if !Storage(*context) || views && (!Views(*context) || !Addresses(*context)) { return context.problem }
|
||||
for value: cast(s32)0..cast(s32)count - 1 {
|
||||
if Aggregate(*context, value) && (plan.view[value] == .None || plan.view[value] == .PutBack) {
|
||||
plan.storage[plan.slot[value]] = true
|
||||
}
|
||||
}
|
||||
return .None
|
||||
}
|
||||
|
||||
MachineAggregatePlanFree :: (plan: *MachineAggregatePlan) {
|
||||
VecFree(plan.slot)
|
||||
VecFree(plan.view)
|
||||
VecFree(plan.root)
|
||||
VecFree(plan.address)
|
||||
VecFree(plan.storage)
|
||||
VecFree(plan.index)
|
||||
VecFree(plan.parent)
|
||||
VecFree(plan.representative)
|
||||
VecFree(plan.live)
|
||||
VecFree(plan.live_in)
|
||||
VecFree(plan.live_out)
|
||||
VecFree(plan.interfere)
|
||||
VecFree(plan.members)
|
||||
VecFree(plan.home)
|
||||
VecFree(plan.read)
|
||||
VecFree(plan.update)
|
||||
VecFree(plan.other)
|
||||
VecFree(plan.uses)
|
||||
VecFree(plan.successor_begin)
|
||||
VecFree(plan.successors)
|
||||
VecFree(plan.predecessor_begin)
|
||||
VecFree(plan.predecessors)
|
||||
VecFree(plan.cursor)
|
||||
VecFree(plan.pending)
|
||||
VecFree(plan.order)
|
||||
VecFree(plan.position)
|
||||
VecFree(plan.dominator)
|
||||
VecFree(plan.block_of)
|
||||
VecFree(plan.key_parent)
|
||||
VecFree(plan.key_member)
|
||||
VecFree(plan.key_dynamic)
|
||||
VecFree(plan.chain_head)
|
||||
VecFree(plan.chain_next)
|
||||
}
|
||||
+193
-16
@@ -1,4 +1,5 @@
|
||||
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"
|
||||
@@ -26,6 +27,24 @@ LowerState :: struct {
|
||||
// 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 {
|
||||
@@ -355,18 +374,29 @@ CreateVirtuals :: (state: *LowerState, function_id: s32) -> bool {
|
||||
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
|
||||
if class == .Stack {
|
||||
// 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,
|
||||
@@ -707,17 +737,7 @@ LowerMemory :: (state: *LowerState, function: *MachineFunction, source: LirInstr
|
||||
value := ifx at == 0 && resolved != MachineNoId then resolved else GlobalVirtual(state, function, operand)
|
||||
if VirtualOperand(state, value, .Use) == MachineNoId { return false }
|
||||
}
|
||||
dynamic_member := source.op == .Extract && source.operands.count == 2 ||
|
||||
source.op == .Insert && source.operands.count == 3
|
||||
if dynamic_member {
|
||||
// R10 holds the computed member address; R11 is the byte-copy scratch.
|
||||
if PhysicalOperand(state, MachineAbiAddressScratchRegister(state.target), .Define) == MachineNoId ||
|
||||
PhysicalOperand(state, MachineAbiScratchRegister(state.target), .Define) == MachineNoId {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if (source.op == .FieldAddress || source.op == .Extract || source.op == .Insert) &&
|
||||
ImmediateOperand(state, source.immediate) == MachineNoId { return false }
|
||||
if source.op == .FieldAddress && ImmediateOperand(state, source.immediate) == MachineNoId { return false }
|
||||
return FinishInstruction(state, instruction) != MachineNoId
|
||||
}
|
||||
|
||||
@@ -954,6 +974,154 @@ LowerControl :: (state: *LowerState, function: *MachineFunction, source: LirInst
|
||||
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 }
|
||||
@@ -980,8 +1148,8 @@ LowerInstruction :: (state: *LowerState, function: *MachineFunction,
|
||||
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 LowerMemory(state, function, source, .AggregateExtract) }
|
||||
if source.op == .Insert { return LowerMemory(state, function, source, .AggregateInsert) }
|
||||
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) }
|
||||
@@ -1007,8 +1175,14 @@ LowerFunction :: (state: *LowerState, function_id: s32) -> bool {
|
||||
source := state.lir.functions[function_id]
|
||||
if source.external { return true }
|
||||
function := state.owner.functions[function_id]
|
||||
if !CreateVirtuals(state, function_id) { return false }
|
||||
// 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
|
||||
@@ -1143,7 +1317,10 @@ MachineLower :: (owner: *MachineOwner, program: LirProgram, target: TargetDescri
|
||||
frame_raw: Vec(s32)
|
||||
defer VecFree(frame_raw)
|
||||
state.frame_raw = *frame_raw
|
||||
if !CopyMetadata(*state) || !CopyTypes(*state) || !AddFunctionRecords(*state) {
|
||||
aggregates: AggregateLowering
|
||||
defer AggregateLoweringFree(*aggregates)
|
||||
state.aggregates = *aggregates
|
||||
if !CopyMetadata(*state) || !CopyTypes(*state) || !AggregateTypes(*state) || !AddFunctionRecords(*state) {
|
||||
result := Result(state)
|
||||
MachineFree(owner)
|
||||
return result
|
||||
|
||||
@@ -1418,13 +1418,16 @@ CollectBoundaries :: (state: *Alloc) -> bool {
|
||||
return true
|
||||
}
|
||||
|
||||
Temporary :: (state: *Alloc, index: s64, type: s32, size: s64, alignment: s32) -> s32 {
|
||||
// Cycle temporary INDEX: a pooled 16-byte slot for a register value, or a
|
||||
// slot of an aggregate's own size, since aggregate moves copy whole objects
|
||||
// of one size.
|
||||
Temporary :: (state: *Alloc, index: s64, type: s32, size: s64, alignment: s32, aggregate: bool) -> s32 {
|
||||
while state.temps.count <= index {
|
||||
slot := OutStack(state, .{function = state.function_id, kind = .Temporary, size = 16, alignment = 16,
|
||||
type = type, origin = MachineNoId, offset = 0, value = MachineNoId})
|
||||
if slot == MachineNoId || !VecPush(state.temps, slot) { unused Fail(state, .Allocation); return MachineNoId }
|
||||
}
|
||||
if size > 16 || alignment > 16 {
|
||||
if aggregate || size > 16 || alignment > 16 {
|
||||
return OutStack(state, .{function = state.function_id, kind = .Temporary, size = size,
|
||||
alignment = alignment, type = type, origin = MachineNoId, offset = 0, value = MachineNoId})
|
||||
}
|
||||
@@ -1564,7 +1567,7 @@ ResolveCopies :: (state: *Alloc) -> bool {
|
||||
size = object.size
|
||||
alignment = object.alignment
|
||||
}
|
||||
temporary := Temporary(state, temporaries, candidate.type, size, alignment)
|
||||
temporary := Temporary(state, temporaries, candidate.type, size, alignment, candidate.class == .Stack)
|
||||
if temporary == MachineNoId { return false }
|
||||
temporaries += 1
|
||||
if candidate.source_register >= 0 {
|
||||
|
||||
+146
-106
@@ -221,8 +221,39 @@ AtOffset :: (memory: X86Operand, offset: s64) -> X86Operand {
|
||||
return memory
|
||||
}
|
||||
|
||||
// Copies and zeroing of at least LoopBytes run a loop over 16-byte chunks
|
||||
// through the float scratch xmm15, with r11 counting up to zero, then finish
|
||||
// the tail through r11; shorter ones move 8/4/2/1-byte pieces through r11.
|
||||
LoopBytes :: 64
|
||||
|
||||
Looped :: (size: s64, first: X86Operand, second: X86Operand) -> bool {
|
||||
return size >= LoopBytes && first.kind == .Base && second.kind == .Base &&
|
||||
first.register != X86R11 && second.register != X86R11
|
||||
}
|
||||
|
||||
// r11 = -(whole chunks of SIZE); returns the chunk bytes and the loop start.
|
||||
LoopBegin :: (state: *State, size: s64, begin: *s64) -> s64 {
|
||||
chunks := size & ~cast(s64)15
|
||||
X86MoveImmediate(*state.writer, X86R11, cast(u64)(-chunks))
|
||||
<<begin = state.writer.at
|
||||
return chunks
|
||||
}
|
||||
|
||||
LoopEnd :: (state: *State, begin: s64) {
|
||||
X86SubtractImmediate(*state.writer, X86Direct(X86R11), -16)
|
||||
X86JumpCondition32(*state.writer, X86NotEqual, begin)
|
||||
}
|
||||
|
||||
CopyMemory :: (state: *State, destination: X86Operand, source: X86Operand, size: s64) -> bool {
|
||||
offset: s64
|
||||
if Looped(size, destination, source) {
|
||||
scratch := MachineAbiScratchFloatRegister(state.program.target)
|
||||
begin: s64
|
||||
offset = LoopBegin(state, size, *begin)
|
||||
X86VectorLoad(*state.writer, scratch, X86Indexed(source.register, X86R11, source.displacement + offset))
|
||||
X86VectorStore(*state.writer, X86Indexed(destination.register, X86R11, destination.displacement + offset), scratch)
|
||||
LoopEnd(state, begin)
|
||||
}
|
||||
while offset < size {
|
||||
remaining := size - offset
|
||||
width: s64 = 1
|
||||
@@ -237,8 +268,17 @@ CopyMemory :: (state: *State, destination: X86Operand, source: X86Operand, size:
|
||||
}
|
||||
|
||||
ZeroMemory :: (state: *State, destination: X86Operand, size: s64) -> bool {
|
||||
X86MoveImmediate(*state.writer, X86R11, 0)
|
||||
offset: s64
|
||||
if Looped(size, destination, destination) {
|
||||
scratch := MachineAbiScratchFloatRegister(state.program.target)
|
||||
X86VectorZero(*state.writer, scratch)
|
||||
begin: s64
|
||||
offset = LoopBegin(state, size, *begin)
|
||||
X86VectorStore(*state.writer, X86Indexed(destination.register, X86R11, destination.displacement + offset), scratch)
|
||||
LoopEnd(state, begin)
|
||||
}
|
||||
// The loop leaves r11 at zero.
|
||||
if offset == 0 && size > 0 { X86MoveImmediate(*state.writer, X86R11, 0) }
|
||||
while offset < size {
|
||||
remaining := size - offset
|
||||
width: s64 = 1
|
||||
@@ -1015,118 +1055,119 @@ AggregateBuild :: (state: *State) -> bool {
|
||||
return instruction.operand_count - 1 == member_count
|
||||
}
|
||||
|
||||
AggregateExtract :: (state: *State) -> bool {
|
||||
instruction := Current(state)
|
||||
if instruction.operand_count != 3 && instruction.operand_count != 6 {
|
||||
return Fail(state, .Unsupported)
|
||||
// The memory and type of the aggregate operand LOCAL names: its frame object,
|
||||
// or the pointee of a view's address held in a pointer register.
|
||||
AggregateAt :: (state: *State, local: s32, memory: *X86Operand, type: *s32) -> bool {
|
||||
operand := OperandAt(state, local)
|
||||
if operand.class == .General {
|
||||
base := Register(state, local, .Use)
|
||||
if base == MachineNoId { return false }
|
||||
pointer := TypeOf(state, operand)
|
||||
if pointer.kind != .Pointer || pointer.element < 0 { return Fail(state, .Unsupported, OperandId(state, local)) }
|
||||
<<memory = X86At(base, 0)
|
||||
<<type = pointer.element
|
||||
return true
|
||||
}
|
||||
destination := OperandAt(state, 0)
|
||||
source := OperandAt(state, 1)
|
||||
if source.kind != .StackObject || source.class != .Stack {
|
||||
return Fail(state, .Unsupported)
|
||||
}
|
||||
member: s32
|
||||
offset: s64
|
||||
source_memory := StackMemory(state, source.id, OperandId(state, 1))
|
||||
if state.diagnostic.problem != .None { return false }
|
||||
if instruction.operand_count == 3 {
|
||||
index := OperandAt(state, 2)
|
||||
if index.kind != .Immediate ||
|
||||
!Member(state, TypeIdOf(state, source), index.immediate, *member, *offset) {
|
||||
return Fail(state, .Unsupported, OperandId(state, 2))
|
||||
}
|
||||
source_memory = AtOffset(source_memory, offset)
|
||||
} else {
|
||||
index := Register(state, 2, .Use)
|
||||
scratch_address := OperandAt(state, 3)
|
||||
scratch_copy := OperandAt(state, 4)
|
||||
immediate := OperandAt(state, 5)
|
||||
aggregate := state.program.types[TypeIdOf(state, source)]
|
||||
if index == MachineNoId || aggregate.kind != .Array || aggregate.element < 0 ||
|
||||
scratch_address.kind != .Physical || scratch_address.role != .Define ||
|
||||
scratch_address.id != MachineAbiAddressScratchRegister(state.program.target) ||
|
||||
scratch_copy.kind != .Physical || scratch_copy.role != .Define ||
|
||||
scratch_copy.id != MachineAbiScratchRegister(state.program.target) ||
|
||||
immediate.kind != .Immediate || immediate.immediate != 0 {
|
||||
return Fail(state, .Unsupported)
|
||||
}
|
||||
member = aggregate.element
|
||||
size := state.program.types[member].size
|
||||
X86CompareImmediate(*state.writer, index, aggregate.count)
|
||||
TrapUnless(state, X86Below, MachineX64TrapReserved - 1)
|
||||
if size == 1 { X86Move(*state.writer, X86R11, index) }
|
||||
else { X86MultiplyImmediate(*state.writer, X86R11, index, size) }
|
||||
X86Lea(*state.writer, 10, source_memory)
|
||||
X86Arithmetic(*state.writer, X86Add, 10, X86R11)
|
||||
source_memory = X86At(10, 0)
|
||||
}
|
||||
size := state.program.types[member].size
|
||||
if destination.class == .Stack {
|
||||
if destination.kind != .StackObject { return Fail(state, .Unsupported, OperandId(state, 0)) }
|
||||
return CopyMemory(state, StackMemory(state, destination.id, OperandId(state, 0)), source_memory, size)
|
||||
}
|
||||
return MemoryToScalar(state, destination, OperandId(state, 0), source_memory,
|
||||
state.program.types[member])
|
||||
if operand.kind != .StackObject || operand.class != .Stack { return Fail(state, .Unsupported, OperandId(state, local)) }
|
||||
<<memory = StackMemory(state, operand.id, OperandId(state, local))
|
||||
<<type = TypeIdOf(state, operand)
|
||||
return state.diagnostic.problem == .None
|
||||
}
|
||||
|
||||
AggregateInsert :: (state: *State) -> bool {
|
||||
instruction := Current(state)
|
||||
if instruction.operand_count != 4 && instruction.operand_count != 7 {
|
||||
return Fail(state, .Unsupported)
|
||||
}
|
||||
destination := OperandAt(state, 0)
|
||||
aggregate := OperandAt(state, 1)
|
||||
value := OperandAt(state, 2)
|
||||
index := OperandAt(state, instruction.operand_count - 1)
|
||||
if destination.kind != .StackObject || aggregate.kind != .StackObject ||
|
||||
destination.class != .Stack || aggregate.class != .Stack || index.kind != .Immediate {
|
||||
return Fail(state, .Unsupported)
|
||||
}
|
||||
destination_memory := StackMemory(state, destination.id, OperandId(state, 0))
|
||||
aggregate_memory := StackMemory(state, aggregate.id, OperandId(state, 1))
|
||||
size := state.program.stack_objects[destination.id].size
|
||||
if state.diagnostic.problem != .None || state.program.stack_objects[aggregate.id].size != size ||
|
||||
!CopyMemory(state, destination_memory, aggregate_memory, size) { return false }
|
||||
member: s32
|
||||
// The memory and type of the member the current instruction names in the
|
||||
// aggregate of TYPE at MEMORY: its last operand, an immediate member, or
|
||||
// with operands INDEX, r10, r11 before it, an array element: bounds-checked
|
||||
// when that immediate is 0, else the bound the shared facts prove the index
|
||||
// below. Its address is then in r11, or in r10 when the access itself copies
|
||||
// through r11 (COPIES).
|
||||
MemberMemory :: (state: *State, memory: X86Operand, type: s32, index: s32, copies: bool,
|
||||
member: *s32, result: *X86Operand) -> bool {
|
||||
count := Current(state).operand_count
|
||||
immediate := OperandAt(state, count - 1)
|
||||
if immediate.kind != .Immediate { return Fail(state, .Unsupported) }
|
||||
offset: s64
|
||||
member_memory := destination_memory
|
||||
if instruction.operand_count == 4 {
|
||||
if index.kind != .Immediate ||
|
||||
!Member(state, TypeIdOf(state, aggregate), index.immediate, *member, *offset) {
|
||||
return Fail(state, .Unsupported, OperandId(state, 3))
|
||||
if count == index + 1 {
|
||||
if !Member(state, type, immediate.immediate, member, *offset) {
|
||||
return Fail(state, .Unsupported, OperandId(state, count - 1))
|
||||
}
|
||||
member_memory = AtOffset(member_memory, offset)
|
||||
} else {
|
||||
dynamic_index := Register(state, 3, .Use)
|
||||
scratch_address := OperandAt(state, 4)
|
||||
scratch_copy := OperandAt(state, 5)
|
||||
aggregate_type := state.program.types[TypeIdOf(state, aggregate)]
|
||||
if dynamic_index == MachineNoId || aggregate_type.kind != .Array || aggregate_type.element < 0 ||
|
||||
scratch_address.kind != .Physical || scratch_address.role != .Define ||
|
||||
scratch_address.id != MachineAbiAddressScratchRegister(state.program.target) ||
|
||||
scratch_copy.kind != .Physical || scratch_copy.role != .Define ||
|
||||
scratch_copy.id != MachineAbiScratchRegister(state.program.target) ||
|
||||
index.kind != .Immediate || index.immediate != 0 {
|
||||
return Fail(state, .Unsupported)
|
||||
}
|
||||
member = aggregate_type.element
|
||||
element_size := state.program.types[member].size
|
||||
X86CompareImmediate(*state.writer, dynamic_index, aggregate_type.count)
|
||||
<<result = AtOffset(memory, offset)
|
||||
return true
|
||||
}
|
||||
dynamic := Register(state, index, .Use)
|
||||
scratch_address := OperandAt(state, index + 1)
|
||||
scratch_copy := OperandAt(state, index + 2)
|
||||
aggregate := state.program.types[type]
|
||||
if count != index + 4 || dynamic == MachineNoId || aggregate.kind != .Array || aggregate.element < 0 ||
|
||||
memory.kind != .Base || immediate.immediate > cast(u64)aggregate.count ||
|
||||
scratch_address.kind != .Physical || scratch_address.role != .Define ||
|
||||
scratch_address.id != MachineAbiAddressScratchRegister(state.program.target) ||
|
||||
scratch_copy.kind != .Physical || scratch_copy.role != .Define ||
|
||||
scratch_copy.id != MachineAbiScratchRegister(state.program.target) {
|
||||
return Fail(state, .Unsupported)
|
||||
}
|
||||
<<member = aggregate.element
|
||||
size := state.program.types[aggregate.element].size
|
||||
if immediate.immediate == 0 {
|
||||
X86CompareImmediate(*state.writer, dynamic, aggregate.count)
|
||||
TrapUnless(state, X86Below, MachineX64TrapReserved - 1)
|
||||
if element_size == 1 { X86Move(*state.writer, X86R11, dynamic_index) }
|
||||
else { X86MultiplyImmediate(*state.writer, X86R11, dynamic_index, element_size) }
|
||||
X86Lea(*state.writer, 10, destination_memory)
|
||||
X86Arithmetic(*state.writer, X86Add, 10, X86R11)
|
||||
member_memory = X86At(10, 0)
|
||||
}
|
||||
member_size := state.program.types[member].size
|
||||
if size == 1 { X86Move(*state.writer, X86R11, dynamic) }
|
||||
else { X86MultiplyImmediate(*state.writer, X86R11, dynamic, size) }
|
||||
address := ifx copies then cast(s32)10 else X86R11
|
||||
X86Lea(*state.writer, address, X86Indexed(memory.register, X86R11, memory.displacement))
|
||||
<<result = X86At(address, 0)
|
||||
return true
|
||||
}
|
||||
|
||||
// destination = a member of an aggregate in a frame object or at a view's
|
||||
// address: destination, aggregate[, index, r10, r11], member.
|
||||
AggregateExtract :: (state: *State) -> bool {
|
||||
destination := OperandAt(state, 0)
|
||||
memory: X86Operand
|
||||
type: s32
|
||||
member: s32
|
||||
if !AggregateAt(state, 1, *memory, *type) ||
|
||||
!MemberMemory(state, memory, type, 2, destination.kind == .StackObject, *member, *memory) { return false }
|
||||
if destination.class == .Stack {
|
||||
if destination.kind != .StackObject { return Fail(state, .Unsupported, OperandId(state, 0)) }
|
||||
return CopyMemory(state, StackMemory(state, destination.id, OperandId(state, 0)), memory,
|
||||
state.program.types[member].size)
|
||||
}
|
||||
return MemoryToScalar(state, destination, OperandId(state, 0), memory, state.program.types[member])
|
||||
}
|
||||
|
||||
// destination = aggregate with one member replaced: destination, aggregate,
|
||||
// value[, index, r10, r11], member. An insert stored in its source's object
|
||||
// changes only that member. Through a view's address the member is replaced
|
||||
// in place: address, value[, index, r10, r11], member.
|
||||
AggregateInsert :: (state: *State) -> bool {
|
||||
first := OperandAt(state, 0)
|
||||
value_local: s32 = 2
|
||||
memory: X86Operand
|
||||
type: s32
|
||||
if first.class == .General {
|
||||
value_local = 1
|
||||
if !AggregateAt(state, 0, *memory, *type) { return false }
|
||||
} else {
|
||||
source: X86Operand
|
||||
if first.kind != .StackObject || first.class != .Stack || first.role != .Define ||
|
||||
!AggregateAt(state, 1, *source, *type) { return Fail(state, .Unsupported) }
|
||||
aggregate := OperandAt(state, 1)
|
||||
memory = StackMemory(state, first.id, OperandId(state, 0))
|
||||
size := state.program.stack_objects[first.id].size
|
||||
if state.diagnostic.problem != .None { return false }
|
||||
if state.program.stack_objects[aggregate.id].size != size { return Fail(state, .Unsupported, OperandId(state, 1)) }
|
||||
if first.id != aggregate.id && !CopyMemory(state, memory, source, size) { return false }
|
||||
}
|
||||
value := OperandAt(state, value_local)
|
||||
member: s32
|
||||
if !MemberMemory(state, memory, type, value_local + 1, value.kind == .StackObject, *member, *memory) { return false }
|
||||
size := state.program.types[member].size
|
||||
if value.class == .Stack {
|
||||
if value.kind != .StackObject { return Fail(state, .Unsupported, OperandId(state, 2)) }
|
||||
return CopyMemory(state, member_memory,
|
||||
StackMemory(state, value.id, OperandId(state, 2)), member_size)
|
||||
if value.kind != .StackObject { return Fail(state, .Unsupported, OperandId(state, value_local)) }
|
||||
return CopyMemory(state, memory, StackMemory(state, value.id, OperandId(state, value_local)), size)
|
||||
}
|
||||
return ScalarToMemory(state, value, OperandId(state, 2),
|
||||
member_memory, member_size)
|
||||
return ScalarToMemory(state, value, OperandId(state, value_local), memory, size)
|
||||
}
|
||||
|
||||
FieldAddress :: (state: *State) -> bool {
|
||||
@@ -1183,8 +1224,7 @@ ElementAddress :: (state: *State) -> bool {
|
||||
}
|
||||
if size == 1 { X86Move(*state.writer, X86R11, low) }
|
||||
else { X86MultiplyImmediate(*state.writer, X86R11, low, size) }
|
||||
X86Arithmetic(*state.writer, X86Add, X86R11, base)
|
||||
if destination != X86R11 { X86Move(*state.writer, destination, X86R11) }
|
||||
X86Lea(*state.writer, destination, X86Indexed(base, X86R11, 0))
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -31,15 +31,17 @@ X86GreaterEqual :: 13
|
||||
X86LessEqual :: 14
|
||||
X86Greater :: 15
|
||||
|
||||
X86OperandKind :: enum s32 { Register; Base; Rip; Relocated }
|
||||
X86OperandKind :: enum s32 { Register; Base; Rip; Relocated; Indexed }
|
||||
|
||||
// A ModRM r/m operand: a register, [base + displacement], [rip + field] whose
|
||||
// field reaches code offset `displacement`, or [rip + field] whose field a
|
||||
// relocation supplies (encoded as zero).
|
||||
// A ModRM r/m operand: a register, [base + displacement], [base + index +
|
||||
// displacement], [rip + field] whose field reaches code offset
|
||||
// `displacement`, or [rip + field] whose field a relocation supplies
|
||||
// (encoded as zero). `index` is read only for Indexed.
|
||||
X86Operand :: struct {
|
||||
kind: X86OperandKind
|
||||
register: s32
|
||||
displacement: s64
|
||||
index: s32
|
||||
}
|
||||
|
||||
X86Writer :: struct {
|
||||
@@ -57,6 +59,10 @@ X86At :: (base: s32, displacement: s64) -> X86Operand {
|
||||
return .{kind = .Base, register = base, displacement = displacement}
|
||||
}
|
||||
|
||||
X86Indexed :: (base: s32, index: s32, displacement: s64) -> X86Operand {
|
||||
return .{kind = .Indexed, register = base, displacement = displacement, index = index}
|
||||
}
|
||||
|
||||
X86RipTarget :: (target: s64) -> X86Operand {
|
||||
return .{kind = .Rip, register = -1, displacement = target}
|
||||
}
|
||||
@@ -114,11 +120,14 @@ X86Opcode :: (writer: *X86Writer, opcode: u32, count: s32) {
|
||||
X86Encode :: (writer: *X86Writer, prefix: u8, wide: bool, opcode: u32, count: s32,
|
||||
reg: s32, rm: X86Operand, reg_byte: bool = false, rm_byte: bool = false, trailing: s64 = 0) {
|
||||
memory := rm.kind == .Rip || rm.kind == .Relocated
|
||||
if !X86Register(reg) || !memory && !X86Register(rm.register) { writer.failed = true; return }
|
||||
indexed := rm.kind == .Indexed
|
||||
if !X86Register(reg) || !memory && !X86Register(rm.register) ||
|
||||
indexed && (!X86Register(rm.index) || rm.index == X86Rsp) { writer.failed = true; return }
|
||||
if prefix != 0 { X86Byte(writer, prefix) }
|
||||
rex: u8 = 0
|
||||
if wide { rex = rex | 8 }
|
||||
if reg >= 8 { rex = rex | 4 }
|
||||
if indexed && rm.index >= 8 { rex = rex | 2 }
|
||||
if !memory && rm.register >= 8 { rex = rex | 1 }
|
||||
needs := rex != 0 || reg_byte && reg >= 4 && reg < 8 ||
|
||||
rm_byte && rm.kind == .Register && rm.register >= 4 && rm.register < 8
|
||||
@@ -140,8 +149,13 @@ X86Encode :: (writer: *X86Writer, prefix: u8, wide: bool, opcode: u32, count: s3
|
||||
if rm.displacement == 0 && low != 5 { mode = 0 }
|
||||
else if X86Fits8(rm.displacement) { mode = 1 }
|
||||
else if !X86Fits32(rm.displacement) { writer.failed = true; return }
|
||||
X86Byte(writer, (mode << 6) | field | low)
|
||||
if low == 4 { X86Byte(writer, 36) }
|
||||
if indexed {
|
||||
X86Byte(writer, (mode << 6) | field | 4)
|
||||
X86Byte(writer, cast(u8)((rm.index & 7) << 3) | low)
|
||||
} else {
|
||||
X86Byte(writer, (mode << 6) | field | low)
|
||||
if low == 4 { X86Byte(writer, 36) }
|
||||
}
|
||||
if mode == 1 { X86Little(writer, cast(u64)rm.displacement, 1) }
|
||||
if mode == 2 { X86Little(writer, cast(u64)rm.displacement, 4) }
|
||||
}
|
||||
@@ -231,6 +245,20 @@ X86Store :: (writer: *X86Writer, destination: X86Operand, source: s32, size: s64
|
||||
writer.failed = true
|
||||
}
|
||||
|
||||
// Unaligned 16-byte moves between an XMM register and memory (movups), and
|
||||
// zeroing a whole XMM register (xorps).
|
||||
X86VectorLoad :: (writer: *X86Writer, destination: s32, source: X86Operand) {
|
||||
X86Encode(writer, 0, false, 0x0f10, 2, destination, source)
|
||||
}
|
||||
|
||||
X86VectorStore :: (writer: *X86Writer, destination: X86Operand, source: s32) {
|
||||
X86Encode(writer, 0, false, 0x0f11, 2, source, destination)
|
||||
}
|
||||
|
||||
X86VectorZero :: (writer: *X86Writer, register: s32) {
|
||||
X86Encode(writer, 0, false, 0x0f57, 2, register, X86Direct(register))
|
||||
}
|
||||
|
||||
// Scalar SSE2 moves and arithmetic. Float registers use their XMM encoding
|
||||
// number in the separate float-register namespace.
|
||||
X86FloatLoad :: (writer: *X86Writer, destination: s32, source: X86Operand, size: s64) {
|
||||
|
||||
@@ -344,6 +344,45 @@ facts. A Step-1 implementation limited to constant pointers will not reach the
|
||||
Vectors range by itself. Call throughput needs a new runtime-input experiment,
|
||||
not a target inferred from this folded fixture.
|
||||
|
||||
## Status: fixes 1 and 5 for Records (2026-11-15, Omega)
|
||||
|
||||
Implemented in `cmd/compiler_machine_aggregate.zi` (planning) and
|
||||
`cmd/compiler_machine_lower.zi`, `cmd/compiler_x86_64.zi`,
|
||||
`cmd/compiler_x86_bytes.zi`. Owner direction for fix 1: speed first, keep only
|
||||
the guardrails correctness needs, so no new verifier obligations were added.
|
||||
|
||||
- Storage: aggregate values with non-overlapping lifetimes share one frame
|
||||
object (the zx2wasm `coalesce_aggregates` rule), so an insert whose source
|
||||
dies writes only its member and block parameters reuse their arguments'
|
||||
object. Real copy cycles keep a temporary, now of the aggregate's own size.
|
||||
- Views (x86-64): an extract read only by extracts in its block is read in
|
||||
place through an address computed by `StackAddress` and
|
||||
`FieldAddress`/`ElementAddress`; a dominating view with the same storage
|
||||
and member shares that address. A changed view is stored in place and its
|
||||
put-back emits nothing. Dynamic indices use the shared LIR facts' proven
|
||||
bound (no check) or keep one check per address.
|
||||
- Copies and zeroing of 64 bytes or more run a 16-byte `movups` loop with an
|
||||
indexed operand; Records keeps no copy that large, Sieve's image falls from
|
||||
94,336 to 8,320 bytes.
|
||||
|
||||
Receipts: `bench/results/wasm-tier-omega-2026-11-15-records-before.json`
|
||||
(revision 7ac6643d, load 16.2/16.8) and `...-records-after.json` (revision
|
||||
c0efdfd5 plus this change, load 11.5/11.9), 11 samples, both on Omega with
|
||||
other lanes' uncommitted work in the tree.
|
||||
|
||||
| Records | C µs | zx engine µs | native µs | Wasm µs | native image |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| before | 9.38 | 1858.32 | 1951.25 | 18.48 | 69,760 B |
|
||||
| after | 8.66 | 29.20 | 32.18 | 17.00 | 12,416 B |
|
||||
|
||||
Direct repeated runs after the receipt measured native 25.4 µs (32 calls per
|
||||
process, start included) and the zx engine 28.9 µs, about 2.9× and 3.4× C.
|
||||
The update loop is now C-shaped for memory: one proven address per particle,
|
||||
then load/add/store of x and y. The rest of the gap to Wasm is scalar code
|
||||
outside fix 1: each compare becomes `cmp; setcc; movzx; test; jcc`, constants
|
||||
are moved into registers before use, jumps to the next block remain, and the
|
||||
per-iteration fuel decrement in memory stays enforced. Those belong to fix 6.
|
||||
|
||||
## Document verification and publication
|
||||
|
||||
Only this document is in scope for writes. Static inspection used receipt hash
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
// Aggregate storage and views on native code (compiler_machine_aggregate):
|
||||
// values that share a frame object, members read and changed in place
|
||||
// through one address, and the copies that remain. Every read must see the
|
||||
// value as it was when read.
|
||||
|
||||
Particle :: struct { x: s64; y: s64; dx: s64; dy: s64 }
|
||||
// Packed members of odd sizes, so copies end in 4-, 2- and 1-byte pieces.
|
||||
Cell :: struct { tag: s8; weight: s32; count: s16 }
|
||||
Grid :: struct { cells: [5]Cell; total: s64 }
|
||||
|
||||
// The Records kernel of bench/wasm_tier.zi: 64 records changed in place by
|
||||
// member for 200 steps, with branches between the changes.
|
||||
Records :: () -> s64 {
|
||||
particles: [64]Particle
|
||||
for i: 0..63 { particles[i] = Particle.{x = i, y = 2 * i, dx = i % 5 + 1, dy = i % 3 + 1} }
|
||||
for step: 0..199 {
|
||||
for i: 0..63 {
|
||||
particles[i].x += particles[i].dx
|
||||
particles[i].y += particles[i].dy
|
||||
if particles[i].x > 1000 || particles[i].x < 0 { particles[i].dx = -particles[i].dx }
|
||||
if particles[i].y > 1000 || particles[i].y < 0 { particles[i].dy = -particles[i].dy }
|
||||
}
|
||||
}
|
||||
total: s64
|
||||
for i: 0..63 { total += particles[i].x + particles[i].y }
|
||||
return total
|
||||
}
|
||||
|
||||
// A whole-array snapshot keeps its values after the array changes.
|
||||
Snapshot :: () -> s64 {
|
||||
values: [64]Particle
|
||||
for i: 0..63 { values[i].x = i; values[i].dy = 2 * i }
|
||||
old := values
|
||||
values[3].x = 1000
|
||||
values[60] = Particle.{x = -1, y = 2, dx = 3, dy = 4}
|
||||
old_total: s64
|
||||
for i: 0..63 { old_total += old[i].x + old[i].dy }
|
||||
return old_total * 100 + old[3].x + old[60].x + values[3].x + values[60].dy
|
||||
}
|
||||
|
||||
// Two arrays swapped every round: the loop's block parameters form a copy
|
||||
// cycle, and the member changed afterwards lands in only one of them.
|
||||
Rotate :: (rounds: s64) -> s64 {
|
||||
a: [16]s64
|
||||
b: [16]s64
|
||||
for i: 0..15 { a[i] = i; b[i] = 100 + i }
|
||||
for round: 0..rounds - 1 {
|
||||
t := a
|
||||
a = b
|
||||
b = t
|
||||
a[round % 16] += 1
|
||||
}
|
||||
return a[0] + a[15] * 3 + b[1] * 5 + b[14] * 7
|
||||
}
|
||||
|
||||
// Two small record parameters swapped at a join: a copy cycle of records
|
||||
// smaller than a register-sized temporary.
|
||||
Vector :: struct { x: s32; y: s32 }
|
||||
Ordered :: (first: Vector, second: Vector) -> s64 {
|
||||
from := first
|
||||
to := second
|
||||
if to.x < from.x {
|
||||
from = second
|
||||
to = first
|
||||
}
|
||||
return cast(s64)from.x * 100 + cast(s64)to.x * 10 + cast(s64)(to.y - from.y)
|
||||
}
|
||||
|
||||
// Members of one element changed in place on either branch, the element
|
||||
// read again after the branches join.
|
||||
Branches :: (rounds: s64) -> s64 {
|
||||
grid: Grid
|
||||
for i: 0..4 {
|
||||
grid.cells[i] = Cell.{tag = cast(s8)i, weight = cast(s32)(i * 3), count = cast(s16)(i + 1)}
|
||||
}
|
||||
for round: 0..rounds - 1 {
|
||||
k := round % 5
|
||||
if grid.cells[k].weight > 6 { grid.cells[k].weight -= 5 } else { grid.cells[k].count += 2 }
|
||||
grid.total += cast(s64)grid.cells[k].weight + cast(s64)grid.cells[k].tag
|
||||
}
|
||||
sum := grid.total
|
||||
for i: 0..4 { sum += cast(s64)grid.cells[i].weight * 10 + cast(s64)grid.cells[i].count }
|
||||
return sum
|
||||
}
|
||||
|
||||
// A record parameter changed in place; the caller's value is unchanged.
|
||||
Bump :: (particle: Particle, by: s64) -> Particle {
|
||||
particle.x += by
|
||||
particle.dy -= by
|
||||
return particle
|
||||
}
|
||||
|
||||
// A record carried around a loop, with a snapshot taken inside it.
|
||||
Carried :: () -> s64 {
|
||||
p := Particle.{x = 1, y = 2, dx = 3, dy = 4}
|
||||
first: Particle
|
||||
for step: 0..9 {
|
||||
if step == 3 { first = p }
|
||||
p.x += p.dx
|
||||
p.y += step
|
||||
}
|
||||
return first.x * 1000 + p.x * 10 + p.y
|
||||
}
|
||||
|
||||
// A record taken out of a call's record result and carried to the next
|
||||
// iteration only through the loop edge.
|
||||
Moved :: struct { particle: Particle; done: bool }
|
||||
Advance :: (particle: Particle) -> Moved {
|
||||
particle.x += particle.dx
|
||||
return Moved.{particle = particle, done = particle.x > 20}
|
||||
}
|
||||
Walk :: () -> s64 {
|
||||
p := Particle.{x = 1, y = 0, dx = 3, dy = 0}
|
||||
steps: s64
|
||||
while steps < 100 {
|
||||
moved := Advance(p)
|
||||
if moved.done { return steps * 100 + moved.particle.x }
|
||||
p = moved.particle
|
||||
steps += 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// Scalars stored at runtime indices, each value dying at its store.
|
||||
Scatter :: (seed: s64) -> s64 {
|
||||
slots: [32]s64
|
||||
for i: 0..31 { slots[(i * 7 + seed) % 32] = i * i + seed }
|
||||
total: s64
|
||||
for i: 0..31 { total += slots[i] * (i + 1) }
|
||||
return total
|
||||
}
|
||||
|
||||
main :: () -> s32 {
|
||||
print("records %\n", Records())
|
||||
print("snapshot %\n", Snapshot())
|
||||
print("rotate % %\n", Rotate(5), Rotate(37))
|
||||
print("branches %\n", Branches(23))
|
||||
print("ordered % %\n", Ordered(Vector.{5, 1}, Vector.{2, 7}), Ordered(Vector.{1, 1}, Vector.{2, 7}))
|
||||
start := Particle.{x = 4, y = 5, dx = 6, dy = 7}
|
||||
bumped := Bump(start, 30)
|
||||
print("bump % % % %\n", start.x, start.dy, bumped.x, bumped.dy)
|
||||
print("carried %\n", Carried())
|
||||
print("scatter %\n", Scatter(3))
|
||||
print("walk %\n", Walk())
|
||||
return 0
|
||||
}
|
||||
@@ -166,6 +166,7 @@ main :: (argc: s32, argv: **u8) -> s32 {
|
||||
ParityAdd(*cases, spec_root, "zx_lowered_using:main", CheckPath(spec_root, "zx_lowered_using.zi"))
|
||||
ParityAdd(*cases, spec_root, "zx_lowered_tables:main", CheckPath(spec_root, "zx_lowered_tables.zi"))
|
||||
ParityAdd(*cases, spec_root, "zx_lowered_records:main", CheckPath(spec_root, "zx_lowered_records.zi"))
|
||||
ParityAdd(*cases, spec_root, "zx_lowered_aggregates:main", CheckPath(spec_root, "zx_lowered_aggregates.zi"))
|
||||
for entry: spec {
|
||||
at: s64
|
||||
while entry[at] != cast(u8)58 { at += 1 }
|
||||
|
||||
Reference in new issue
Block a user