One commit, because the parts below only build together. Allocator: an interval needed at the current instruction is never evicted, and the allocated-program verifier checks that every operand sits where the allocation says. AArch64 encoder: compiler_aarch64.zi encodes allocated machine IR with the shared ARM byte helpers, maps the function-address relocation, sign-extends signed 8- and 16-bit loads and rejects what it cannot encode with a named diagnostic. It has no AOT ELF writer yet. Native default with checked pointers and no fallback: on linux-x86_64, `ziran run app.zx`, `zi2zx run`, the embedding API's Auto and the Kryon players run a bundle's verified program as native code in W^X memory. Stray and freed pointers, double free, bounds and read-only stores trap. A native gap is a named preflight error, nothing falls back to the engine, and `--backend engine` picks it explicitly. zx2native uses the same preflight. Native code exchanges module state for hot reload, checks the stack, zeroes fresh locals, spends fuel at the engine's checkpoints and returns records, arrays and strings from host calls. `zi2zx --debug` source origins name lines in native traps and `zx2native --emit map`. The host value API drops its VM prefix (HostValue, HOST_*). A call with a record result loads the hidden result address into rax only after its stack arguments are stored, and an indirect target stays in r10: rax could hold a stack argument (Kryon's text-field clip guard arrived as an address) or the target (indirect calls returning records crashed). Self-hosting ports: compiler_backend_process, compiler_backend_cache, compiler_native_names and compiler_runtime_emit replace the zir_c_build, zir_c_cache and zir_c_process C, with checked bootstrap C and Makefile rules. zir_c.toolchain again reports "compiling OUT failed:" with the head of the compiler output and a truncation marker. The parallel scheduler no longer stalls on a held compiler after reaping a finished job, and poll or read errors now fail the build. A fresh BUILD_DIR (Kryon's runtime build) builds: generated files have pattern rules, objects wait for the headers they include, and engine flags are per object instead of leaking into zi2c. Legacy removals F1-F10 and N1-N4: the duplicate LirX64 encoder and its spec test, zir_c_*, zir_runtime and zir_native, nine zero-reference spec tests, vec_capacity, the zx_metadata and native_cache_names benchmarks, build-android-host.sh and two shell wrappers are deleted; zx2native is machine-only; `zi2zx` rejects `--opt` on ZX input; the bootstrap is regenerated. ASSEMBLY docs, the legacy-removal plan, the milestones and the remaining-work plan record the current position. Co-Authored-By: Claude Opus 5.5 <[email protected]>
5242 lines
240 KiB
Ziran
5242 lines
240 KiB
Ziran
using IR :: #import "compiler_lowered_ir"
|
|
using Verify :: #import "compiler_lowered_verify"
|
|
using Binary :: #import "std/binary"
|
|
using Math :: #import "std/math"
|
|
using Vectors :: #import "std/vec"
|
|
#import "std/option"
|
|
|
|
LirExecProblem :: enum s32 {
|
|
None; InvalidProgram; NotReady; Busy; Allocation
|
|
WorkLimit; FuelLimit; FrameLimit; ValueLimit; AddressLimit; ValueBytes
|
|
Type; Pointer; Calling; DivideByZero; InvalidShift; InvalidConversion
|
|
Trap; Unreachable; Unsupported; Host
|
|
}
|
|
|
|
LirExecLimits :: struct {
|
|
work: s64
|
|
fuel: s64
|
|
frames: s64
|
|
values: s64
|
|
addresses: s64
|
|
value_bytes: s64
|
|
}
|
|
|
|
LirExecValue :: struct { type: s32; bits: u64; bytes: s64 }
|
|
// Arguments and the result use the canonical bits of their LIR scalar types:
|
|
// zero-extended integers, 0/1 bools and IEEE float32/float64 patterns.
|
|
LirExecHostCall :: #type (context: *void, function: s32, arguments: []u64, result: *u64) -> bool;
|
|
// A host may change the elements of an argument bound as a mutable view
|
|
// (LirExecHostMutableView): it sets `changed` and puts the argument's new
|
|
// image in `bytes`, with the same element count. After the call the engine
|
|
// copies those elements back into the view's storage.
|
|
LirExecArgument :: struct { type: s32; bits: u64; bytes: []u8; changed: bool }
|
|
LirExecTypedHostCall :: #type (context: *void, function: s32,
|
|
arguments: []LirExecArgument, result: *LirExecArgument) -> bool;
|
|
// The platform byte-output service `(descriptor: u64, data: *u8, count: u64)`,
|
|
// such as ziran.platform.write_all. The engine resolves the checked data
|
|
// pointer and its extent itself; the embedder sees only the borrowed bytes,
|
|
// which stay valid for the duration of the call.
|
|
LirExecPlatformWrite :: #type (context: *void, descriptor: u64, bytes: []u8) -> bool;
|
|
LirExecHostBinding :: struct {
|
|
function: s32
|
|
call: LirExecHostCall
|
|
typed: LirExecTypedHostCall
|
|
write: LirExecPlatformWrite
|
|
context: *void
|
|
// Bit p: parameter p is a mutable view.
|
|
views: u64
|
|
}
|
|
|
|
LirExecResult :: struct {
|
|
problem: LirExecProblem
|
|
verification: LirDiagnostic
|
|
function: s32
|
|
block: s32
|
|
instruction: s32
|
|
origin: s32
|
|
trap: u64
|
|
value: LirExecValue
|
|
work_remaining: s64
|
|
fuel_remaining: s64
|
|
}
|
|
|
|
LirExecFunctionPlan :: struct {
|
|
value_base: s64
|
|
block_base: s64
|
|
frame_bytes: s64
|
|
word_count: s64
|
|
scratch_offset: s64
|
|
scratch_bytes: s64
|
|
// The constant words a new frame starts with (LirExecConstantWord).
|
|
constants: s64
|
|
constant_count: s64
|
|
}
|
|
|
|
// The run loop's compact code (ExecPlanCode). Each verified instruction the
|
|
// loop runs itself is translated once into one LirExecCode: a handler
|
|
// specialized by operation and width, with its operands' frame words and
|
|
// storage offsets resolved ahead. Constants, null, function addresses and
|
|
// fuel have no code: a new frame starts with their words written, and their
|
|
// work and fuel are charged with their segment's. A Slow instruction runs
|
|
// through ExecStep, the reference implementation.
|
|
LirExecHandler :: enum s32 {
|
|
Slow; GlobalAddress
|
|
Add; Subtract; Multiply; BitAnd; BitOr; BitXor
|
|
DivideUnsigned; DivideSigned; RemainderUnsigned; RemainderSigned
|
|
ShiftLeft; ShiftRightUnsigned; ShiftRightSigned
|
|
Negate; BitNot; FloatNegate
|
|
FloatAdd32; FloatSubtract32; FloatMultiply32; FloatDivide32
|
|
FloatAdd64; FloatSubtract64; FloatMultiply64; FloatDivide64
|
|
Equal; NotEqual; Less; LessEqual; Greater; GreaterEqual
|
|
SignedLess; SignedLessEqual; SignedGreater; SignedGreaterEqual
|
|
FloatCompare32; FloatCompare64
|
|
ConvertInteger; ConvertBoolInteger; ConvertIntegerBool; ConvertIntegerFloat
|
|
ConvertFloatFloat; ConvertFloatInteger; Bitcast
|
|
ExtractWord; ExtractBytes; ExtractWordIndexed; ExtractBytesIndexed
|
|
InsertWord; InsertBytes; InsertWordIndexed; InsertBytesIndexed
|
|
Aggregate; Load; Store; FieldAddress; ElementIndex; ElementView
|
|
Jump; Branch
|
|
// A compare whose only use is the Branch right after it: one dispatch.
|
|
BranchEqual; BranchNotEqual; BranchLess; BranchLessEqual; BranchGreater; BranchGreaterEqual
|
|
BranchSignedLess; BranchSignedLessEqual; BranchSignedGreater; BranchSignedGreaterEqual
|
|
// Calls and returns between frames of the program (ExecFastCall,
|
|
// ExecFastReturn). Each ends its segment and charges its own work.
|
|
Call; Return
|
|
// An address derivation whose only use is the Load or Store right after
|
|
// it: the two run as one, with no table entry for the address.
|
|
LoadField; LoadIndex; LoadView; StoreField; StoreIndex; StoreView
|
|
// Two Extracts of words in a row, and an Add before the block's Jump.
|
|
ExtractWordPair; AddJump
|
|
HostWrite
|
|
// A generic host call whose arguments are frame words and whose result,
|
|
// if any, is a scalar word: it runs in the fast loop like HostWrite.
|
|
HostCall
|
|
// A slice whose bounds hold: the ElementView of its element `low`, with
|
|
// `b` low, `value` high and `c` the view's count; `sign_b`, `extra` and
|
|
// `sign_c` are their sign bits.
|
|
ElementSlice
|
|
// Frame storage at the end of the frame's bytes, made by the run loop
|
|
// (ExecFastAllocate) like a Call.
|
|
Allocate
|
|
}
|
|
|
|
LirExecCode :: struct {
|
|
handler: LirExecHandler
|
|
// Load, Extract: 1 for a bool result. Address derivations: 1 for a
|
|
// transient one. Integer conversions: 1 for a signed source or result.
|
|
flag: s32
|
|
// Frame words, relative to the frame's first word.
|
|
result: s32
|
|
a: s32
|
|
b: s32
|
|
c: s32
|
|
// The type a pointer operand must name (Load, Store, derivations), or
|
|
// a derivation's target type in `target`.
|
|
type: s32
|
|
target: s32
|
|
// Where the instruction came from, for the reference path.
|
|
block: s32
|
|
index: s32
|
|
// The edge plans of a terminator.
|
|
edge: s32
|
|
// A Call's result value, which the callee's frame fills.
|
|
result_value: s32
|
|
// A fused Store's value word, or -1 with the value's bytes at `w`.
|
|
value: s32
|
|
// 1 when a FieldAddress whose only use is this derivation's base runs
|
|
// first, inside it: the type it checks, and the field's offset and size.
|
|
prefix: s32
|
|
prefix_type: s32
|
|
// A derivation that makes a table entry: its slot in the instance's
|
|
// derived_tokens, or -1.
|
|
memo: s32
|
|
prefix_offset: s64
|
|
prefix_size: s64
|
|
// Byte sizes, bit widths and frame storage offsets (relative to the
|
|
// frame's storage), as each handler uses them.
|
|
size: s64
|
|
x: s64
|
|
y: s64
|
|
z: s64
|
|
w: s64
|
|
// The plan instruction that starts this instruction's block.
|
|
base: s64
|
|
// Result masks, sign bits of index operands and other constants.
|
|
immediate: u64
|
|
extra: u64
|
|
sign_b: u64
|
|
sign_c: u64
|
|
// This instruction's own work, and the work and fuel from it to the end
|
|
// of its segment, given back when the reference path takes over here.
|
|
cost: s64
|
|
rest_work: s64
|
|
rest_fuel: s64
|
|
}
|
|
|
|
// One value an edge or an Aggregate copies: a frame word, or bytes of frame
|
|
// storage. `scratch` is where a two-phase edge parks it.
|
|
LirExecMove :: struct { word: bool; from: s64; to: s64; size: s64; scratch: s64 }
|
|
|
|
LirExecEdgePlan :: struct {
|
|
moves: s64
|
|
count: s64
|
|
// The arguments cannot overwrite each other: copy them in order.
|
|
direct: bool
|
|
// Two copies of each argument, as ExecEdge charges them.
|
|
work: s64
|
|
target_block: s32
|
|
target_base: s64
|
|
// The code, work and fuel of the target block's first segment.
|
|
target_code: s64
|
|
target_work: s64
|
|
target_fuel: s64
|
|
}
|
|
|
|
LirExecConstantWord :: struct { word: s64; bits: u64 }
|
|
|
|
LirExecPlan :: struct {
|
|
program: LirProgram
|
|
type_sizes: Vec(s64)
|
|
value_offsets: Vec(s64)
|
|
value_words: Vec(s64)
|
|
value_sizes: Vec(s64)
|
|
value_types: Vec(s32)
|
|
value_canonical: Vec(u8)
|
|
value_masks: Vec(u64)
|
|
// One byte per type, as LirHostShapes gives it.
|
|
host_shapes: Vec(u8)
|
|
functions: Vec(LirExecFunctionPlan)
|
|
block_edge_bases: Vec(s64)
|
|
block_instruction_bases: Vec(s64)
|
|
edge_direct: Vec(u8)
|
|
instructions: Vec(LirInstruction)
|
|
// 1 for an address derivation that needs no table entry (ExecPlanTransients).
|
|
transient: Vec(u8)
|
|
global_offsets: Vec(s64)
|
|
global_bytes: s64
|
|
code: Vec(LirExecCode)
|
|
// How many codes have a `memo` slot.
|
|
derived_count: s64
|
|
moves: Vec(LirExecMove)
|
|
edge_plans: Vec(LirExecEdgePlan)
|
|
constant_words: Vec(LirExecConstantWord)
|
|
// Per plan instruction: the code of the segment that starts there, or
|
|
// -1 where none starts, and the work and fuel it charges on entry. A
|
|
// segment is a block's run of instructions up to the next Slow one.
|
|
segment_code: Vec(s64)
|
|
segment_work: Vec(s64)
|
|
segment_fuel: Vec(s64)
|
|
// 2^k for k from -1074 to 1023, for float operands.
|
|
powers: Vec(float64)
|
|
ready: bool
|
|
}
|
|
|
|
LirExecAddress :: struct {
|
|
token: u64
|
|
global: s32
|
|
frame: s64
|
|
generation: u64
|
|
offset: s64
|
|
extent: s64
|
|
type: s32
|
|
owned: bool
|
|
writable: bool
|
|
// One more than the heap block this address lies in; 0 for none.
|
|
heap: s64
|
|
// How many times this table slot has been given back and reused. It is
|
|
// part of the token, so no older pointer to the slot is valid again.
|
|
version: u64
|
|
// One more than the next entry made for the same frame or heap block.
|
|
next: s64
|
|
}
|
|
|
|
// A heap block is a range of the owned bytes. Resizing or freeing it ends
|
|
// its generation, so addresses derived from it stop being valid.
|
|
LirExecHeapBlock :: struct {
|
|
offset: s64
|
|
size: s64
|
|
count: u64
|
|
generation: u64
|
|
live: bool
|
|
// One more than the block that ended the owned bytes when this one was
|
|
// put after it; 0 for none. Freed storage is given back down this chain.
|
|
below: s64
|
|
// One more than the newest address entry made for this block.
|
|
addresses: s64
|
|
// Holds a value a host returned. The program never frees it; it lives
|
|
// while something the program can reach names it (ExecHostCollect).
|
|
host: bool
|
|
}
|
|
|
|
LirExecFrame :: struct {
|
|
function: s32
|
|
block: s32
|
|
instruction: s32
|
|
return_value: s32
|
|
base: s64
|
|
word_base: s64
|
|
value_base: s64
|
|
instruction_base: s64
|
|
generation: u64
|
|
// One more than the newest address entry made for this frame's storage.
|
|
addresses: s64
|
|
}
|
|
|
|
// The token a derivation code last made, and the operand words it made it
|
|
// from. The same words derive the same address, so while the token is
|
|
// still a live table entry it is the one the table lookup would find.
|
|
LirExecDerivedToken :: struct { base: u64; index: u64; count: u64; token: u64 }
|
|
|
|
LirExecInstance :: struct {
|
|
plan: *LirExecPlan
|
|
limits: LirExecLimits
|
|
identity: u32
|
|
globals: Vec(u8)
|
|
addresses: Vec(LirExecAddress)
|
|
// Open-addressed index of `addresses` by the fields that make two
|
|
// addresses the same one: each slot is zero, -1 for a removed entry, or
|
|
// one more than an entry. `address_used` counts the nonzero slots.
|
|
address_slots: Vec(s32)
|
|
address_used: s64
|
|
// Table slots given back by frames that returned and heap blocks that died.
|
|
address_free: Vec(s64)
|
|
// One per derivation code with a `memo` slot (ExecFastDerive).
|
|
derived_tokens: Vec(LirExecDerivedToken)
|
|
// The table entries transient derivations take in turn (ExecTransient):
|
|
// ExecTransientSlots of them from transient_base, never indexed.
|
|
transient_base: s64
|
|
transient_count: s64
|
|
transient_next: s64
|
|
storage: Vec(u8)
|
|
words: Vec(u64)
|
|
frames: Vec(LirExecFrame)
|
|
result_bytes: Vec(u8)
|
|
result_value: LirExecValue
|
|
hosts: Vec(LirExecHostBinding)
|
|
// Per program function: one more than its binding's index, or 0 while
|
|
// not yet looked up (ExecFastHostBinding). Bindings never change once made.
|
|
host_lookup: Vec(s32)
|
|
// Every external function has a binding. Bindings are only ever added,
|
|
// so once a run has found them all they stay complete.
|
|
hosts_bound: bool
|
|
host_arguments: Vec(u64)
|
|
typed_arguments: Vec(LirExecArgument)
|
|
host_bytes: Vec(u8)
|
|
owned: Vec(u8)
|
|
heap_blocks: Vec(LirExecHeapBlock)
|
|
// One more than the block that ends the owned bytes; 0 for none.
|
|
heap_tail: s64
|
|
// Records of freed blocks whose bytes were given back, for reuse.
|
|
heap_free: Vec(s64)
|
|
// Dead host blocks whose bytes are still in the owned region, for the
|
|
// next host values to reuse.
|
|
host_free: Vec(s64)
|
|
heap_epoch: u64
|
|
// Bytes of host blocks made since the last collection, and the bytes
|
|
// that collection scanned: the next one waits until both are passed.
|
|
host_since: s64
|
|
host_scanned: s64
|
|
live_values: s64
|
|
frame_epoch: u64
|
|
current_value_base: s64
|
|
current_word_base: s64
|
|
work_remaining: s64
|
|
fuel_remaining: s64
|
|
failure: LirExecResult
|
|
initializer_failure: LirExecResult
|
|
initialized: bool
|
|
initializer_failed: bool
|
|
ready: bool
|
|
running: bool
|
|
// Run every instruction through ExecStep (LirExecRunReference).
|
|
reference: bool
|
|
}
|
|
|
|
#scope_file
|
|
|
|
ExecNoDiagnostic :: () -> LirDiagnostic {
|
|
return .{.problem = .None, .function = LirNoId, .block = LirNoId,
|
|
.instruction = LirNoId, .value = LirNoId, .origin = LirNoId}
|
|
}
|
|
|
|
ExecResult :: (problem: LirExecProblem) -> LirExecResult {
|
|
return .{.problem = problem, .verification = ExecNoDiagnostic(),
|
|
.function = LirNoId, .block = LirNoId, .instruction = LirNoId,
|
|
.origin = LirNoId}
|
|
}
|
|
|
|
ExecMask :: (bits: s32) -> u64 {
|
|
if bits == 64 { return ~cast(u64)0 }
|
|
return (cast(u64)1 << cast(u64)bits) - cast(u64)1
|
|
}
|
|
|
|
ExecSigned :: (value: u64, bits: s32) -> s64 {
|
|
value &= ExecMask(bits)
|
|
if bits < 64 && (value & (cast(u64)1 << cast(u64)(bits - 1))) != 0 {
|
|
value |= ~ExecMask(bits)
|
|
}
|
|
return cast(s64)value
|
|
}
|
|
|
|
ExecReadBits :: (bytes: []u8, at: s64, count: s64) -> u64 {
|
|
result: u64
|
|
for index: cast(s64)0..count - 1 {
|
|
result |= cast(u64)bytes[at + index] << cast(u64)(index * 8)
|
|
}
|
|
return result
|
|
}
|
|
|
|
ExecWriteBits :: (bytes: []u8, at: s64, count: s64, value: u64) {
|
|
for index: cast(s64)0..count - 1 {
|
|
bytes[at + index] = cast(u8)(value >> cast(u64)(index * 8))
|
|
}
|
|
}
|
|
|
|
// A finite positive value as `value` in [1, 2) times 2^exponent, in exact
|
|
// steps by powers of two.
|
|
ExecNormalize :: (input: float64, exponent: *s32) -> float64 #inline {
|
|
value := input
|
|
power: s32
|
|
step: float64 = 18446744073709551616.0
|
|
back: float64 = 5.42101086242752217003726400434970855712890625e-20
|
|
while value >= step { value *= back; power += 64 }
|
|
while value < 1.0 { value *= step; power -= 64 }
|
|
if value >= 4294967296.0 { value *= 2.3283064365386962890625e-10; power += 32 }
|
|
if value >= 65536.0 { value *= 0.0000152587890625; power += 16 }
|
|
if value >= 256.0 { value *= 0.00390625; power += 8 }
|
|
if value >= 16.0 { value *= 0.0625; power += 4 }
|
|
if value >= 4.0 { value *= 0.25; power += 2 }
|
|
if value >= 2.0 { value *= 0.5; power += 1 }
|
|
<<exponent = power
|
|
return value
|
|
}
|
|
|
|
ExecFloat64Bits :: (input: float64) -> u64 {
|
|
negative := input < 0.0 || input == 0.0 && 1.0 / input < 0.0
|
|
value := ifx negative then 0.0 - input else input
|
|
sign := ifx negative then cast(u64)1 << cast(u64)63 else cast(u64)0
|
|
if value != value { return sign | cast(u64)0x7ff8000000000000 }
|
|
if value == 0.0 { return sign }
|
|
if !Finite64(value) { return sign | cast(u64)0x7ff0000000000000 }
|
|
exponent: s32
|
|
value = ExecNormalize(value, *exponent)
|
|
if exponent >= -1022 {
|
|
fraction := cast(u64)((value - 1.0) * 4503599627370496.0)
|
|
return sign | (cast(u64)(exponent + 1023) << cast(u64)52) | fraction
|
|
}
|
|
fraction := cast(u64)ScaleByPowerOfTwo(value, exponent + 1074)
|
|
return sign | fraction
|
|
}
|
|
|
|
ExecFloat32Bits :: (input: float32) -> u64 {
|
|
original := cast(float64)input
|
|
negative := original < 0.0 || original == 0.0 && 1.0 / original < 0.0
|
|
value := ifx negative then 0.0 - original else original
|
|
sign := ifx negative then cast(u64)1 << cast(u64)31 else cast(u64)0
|
|
if value != value { return sign | cast(u64)0x7fc00000 }
|
|
if value == 0.0 { return sign }
|
|
if !Finite64(value) { return sign | cast(u64)0x7f800000 }
|
|
exponent: s32
|
|
value = ExecNormalize(value, *exponent)
|
|
if exponent >= -126 {
|
|
fraction := cast(u64)((value - 1.0) * 8388608.0)
|
|
return sign | (cast(u64)(exponent + 127) << cast(u64)23) | fraction
|
|
}
|
|
fraction := cast(u64)ScaleByPowerOfTwo(value, exponent + 149)
|
|
return sign | fraction
|
|
}
|
|
|
|
// The value of IEEE bits, exactly as Float32FromBits and Float64FromBits
|
|
// give it, scaled by the plan's table of powers of two instead of loops.
|
|
ExecBitsFloat :: (plan: *LirExecPlan, input: u64, single: bool) -> float64 #inline {
|
|
exponent: s64
|
|
mantissa: u64
|
|
negative: bool
|
|
value: float64
|
|
if single {
|
|
bits := input & cast(u64)4294967295
|
|
exponent = cast(s64)((bits >> cast(u64)23) & cast(u64)255)
|
|
mantissa = bits & cast(u64)8388607
|
|
negative = (bits & cast(u64)2147483648) != cast(u64)0
|
|
if exponent == 255 {
|
|
value = ifx mantissa == 0 then Infinity() else NotANumber()
|
|
} else if exponent == 0 {
|
|
value = cast(float64)mantissa * plan.powers[925]
|
|
} else {
|
|
value = cast(float64)(mantissa + cast(u64)8388608) * plan.powers[exponent + 924]
|
|
}
|
|
} else {
|
|
exponent = cast(s64)((input >> cast(u64)52) & cast(u64)2047)
|
|
mantissa = input & cast(u64)4503599627370495
|
|
negative = (input >> cast(u64)63) != cast(u64)0
|
|
if exponent == 2047 {
|
|
value = ifx mantissa == 0 then Infinity() else NotANumber()
|
|
} else if exponent == 0 {
|
|
value = cast(float64)mantissa * plan.powers[0]
|
|
} else {
|
|
value = cast(float64)(mantissa + cast(u64)4503599627370496) * plan.powers[exponent - 1]
|
|
}
|
|
}
|
|
if negative { return -value }
|
|
return value
|
|
}
|
|
|
|
ExecFloat :: (plan: *LirExecPlan, type: LirType, bits: u64) -> float64 #inline {
|
|
return ExecBitsFloat(plan, bits, type.bits == 32)
|
|
}
|
|
|
|
ExecTypeChildren :: (type: LirType) -> s64 {
|
|
if type.kind == .Record { return type.fields.count }
|
|
if type.kind == .Array { return 1 }
|
|
return 0
|
|
}
|
|
|
|
ExecTypeChild :: (type: LirType, index: s64) -> s32 {
|
|
if type.kind == .Record { return type.fields[index] }
|
|
return type.element
|
|
}
|
|
|
|
ExecPlanLayouts :: (program: LirProgram, plan: *LirExecPlan, maximum: s64) -> LirExecProblem {
|
|
colors: Vec(u8)
|
|
stack: Vec(s32)
|
|
next: Vec(s64)
|
|
count := program.types.count
|
|
if !VecResizeBounded(plan.type_sizes, count, count) ||
|
|
!VecResizeBounded(colors, count, count) || !VecResizeBounded(stack, count, count) ||
|
|
!VecResizeBounded(next, count, count) { return .Allocation }
|
|
if count == 0 { return .None }
|
|
for index: cast(s64)0..count - 1 { plan.type_sizes[index] = -1 }
|
|
for root: cast(s32)0..cast(s32)count - 1 {
|
|
if colors[root] == 2 { continue }
|
|
depth: s64
|
|
stack[0] = root
|
|
while depth >= 0 {
|
|
id := stack[depth]
|
|
type := program.types[id]
|
|
colors[id] = 1
|
|
children := ExecTypeChildren(type)
|
|
if next[id] < children {
|
|
child := ExecTypeChild(type, next[id])
|
|
next[id] += 1
|
|
if colors[child] == 1 { return .InvalidProgram }
|
|
if colors[child] == 0 { depth += 1; stack[depth] = child }
|
|
continue
|
|
}
|
|
size: s64
|
|
if type.kind == .Bool { size = 1 }
|
|
else if type.kind == .Integer || type.kind == .Float { size = type.bits / 8 }
|
|
else if type.kind == .Pointer || type.kind == .Function { size = 8 }
|
|
else if type.kind == .Array {
|
|
child := plan.type_sizes[type.element]
|
|
if type.count != 0 && child > maximum / type.count { return .ValueBytes }
|
|
size = child * type.count
|
|
} else if type.kind == .Record {
|
|
for field: type.fields {
|
|
field_size := plan.type_sizes[field]
|
|
if field_size > maximum - size { return .ValueBytes }
|
|
size += field_size
|
|
}
|
|
}
|
|
if size < 0 || size > maximum { return .ValueBytes }
|
|
plan.type_sizes[id] = size
|
|
colors[id] = 2
|
|
depth -= 1
|
|
}
|
|
}
|
|
return .None
|
|
}
|
|
|
|
ExecPlanValuesOverlap :: (plan: *LirExecPlan, base: s64, left: s32, right: s32) -> bool {
|
|
left_word := plan.value_words[base + left]
|
|
right_word := plan.value_words[base + right]
|
|
if (left_word >= 0) != (right_word >= 0) { return false }
|
|
if left_word >= 0 { return left_word == right_word }
|
|
left_at := plan.value_offsets[base + left]
|
|
right_at := plan.value_offsets[base + right]
|
|
left_size := plan.value_sizes[base + left]
|
|
right_size := plan.value_sizes[base + right]
|
|
return left_at < right_at + right_size && right_at < left_at + left_size
|
|
}
|
|
|
|
ExecPlanValuesSameLocation :: (plan: *LirExecPlan, base: s64,
|
|
left: s32, right: s32) -> bool {
|
|
left_word := plan.value_words[base + left]
|
|
right_word := plan.value_words[base + right]
|
|
if (left_word >= 0) != (right_word >= 0) { return false }
|
|
if left_word >= 0 { return left_word == right_word }
|
|
return plan.value_offsets[base + left] == plan.value_offsets[base + right] &&
|
|
plan.value_sizes[base + left] == plan.value_sizes[base + right]
|
|
}
|
|
|
|
// Edge locations are immutable after plan construction. Prove direct-copy
|
|
// safety once instead of repeating this quadratic overlap check on every loop
|
|
// back-edge. Cycles and destructive aliases retain the scratch path.
|
|
ExecPlanEdgeDirectSafe :: (plan: *LirExecPlan, base: s64,
|
|
edge: LirEdge, target: LirBlock) -> bool {
|
|
if edge.arguments.count != target.parameters.count { return false }
|
|
for destination_index: cast(s64)0..target.parameters.count - 1 {
|
|
destination := target.parameters[destination_index]
|
|
for source_index: cast(s64)0..edge.arguments.count - 1 {
|
|
source := edge.arguments[source_index]
|
|
if !ExecPlanValuesOverlap(plan, base, destination, source) { continue }
|
|
if destination_index == source_index &&
|
|
ExecPlanValuesSameLocation(plan, base, destination, source) { continue }
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// Records and arrays that are never needed at the same time share one frame
|
|
// slot: an Insert's result with its aggregate, and a block parameter with
|
|
// the arguments its edges pass, unless some value of one is live where a
|
|
// value of the other is defined. An in-place Insert and an edge between
|
|
// values of one slot then move no bytes (their work is charged as before).
|
|
// Liveness is exact over the function's blocks. A function with more
|
|
// composite values than ExecCoalesceLimit keeps the local rules alone.
|
|
ExecCoalesceLimit :: 4096
|
|
|
|
ExecPlanCoalesce :: (program: LirProgram, function: LirFunction, aliases: *Vec(s32)) -> bool {
|
|
count := function.values.count
|
|
index: Vec(s64)
|
|
values: Vec(s32)
|
|
defer VecFree(index)
|
|
defer VecFree(values)
|
|
if !VecResize(index, count) { return false }
|
|
for value: cast(s64)0..count - 1 {
|
|
index[value] = -1
|
|
kind := program.types[function.values[value]].kind
|
|
if kind == .Record || kind == .Array {
|
|
index[value] = values.count
|
|
if !VecPush(values, cast(s32)value) { return false }
|
|
}
|
|
}
|
|
total := values.count
|
|
if total == 0 || total > ExecCoalesceLimit { return true }
|
|
words := (total + 63) / 64
|
|
blocks := function.blocks.count
|
|
live_in: Vec(u64)
|
|
live_out: Vec(u64)
|
|
live: Vec(u64)
|
|
conflicts: Vec(u64)
|
|
members: Vec(u64)
|
|
parent: Vec(s64)
|
|
defer VecFree(live_in)
|
|
defer VecFree(live_out)
|
|
defer VecFree(live)
|
|
defer VecFree(conflicts)
|
|
defer VecFree(members)
|
|
defer VecFree(parent)
|
|
if !VecResize(live_in, blocks * words) || !VecResize(live_out, blocks * words) || !VecResize(live, words) ||
|
|
!VecResize(conflicts, total * words) || !VecResize(members, total * words) || !VecResize(parent, total) {
|
|
return false
|
|
}
|
|
// Live sets at block entry and exit, to a fixed point.
|
|
changed := true
|
|
while changed {
|
|
changed = false
|
|
block_at := blocks - 1
|
|
while block_at >= 0 {
|
|
block := function.blocks[block_at]
|
|
out := block_at * words
|
|
for instruction: block.instructions {
|
|
for edge: instruction.edges {
|
|
successor := cast(s64)edge.block * words
|
|
for word: 0..words - 1 { live_out[out + word] |= live_in[successor + word] }
|
|
}
|
|
}
|
|
for word: 0..words - 1 { live[word] = live_out[out + word] }
|
|
ExecLiveBlock(block, index[:], live[:], conflicts[:], words, false)
|
|
for word: 0..words - 1 {
|
|
if live_in[out + word] != live[word] { live_in[out + word] = live[word]; changed = true }
|
|
}
|
|
block_at -= 1
|
|
}
|
|
}
|
|
// Which composite values are live where each one is defined.
|
|
for block_at: cast(s64)0..blocks - 1 {
|
|
for word: 0..words - 1 { live[word] = live_out[block_at * words + word] }
|
|
ExecLiveBlock(function.blocks[block_at], index[:], live[:], conflicts[:], words, true)
|
|
}
|
|
for at: cast(s64)0..total - 1 {
|
|
parent[at] = at
|
|
members[at * words + at / 64] |= cast(u64)1 << cast(u64)(at % 64)
|
|
}
|
|
// In-place Inserts first, then edges.
|
|
for pass: 0..1 {
|
|
for block: function.blocks {
|
|
for instruction: block.instructions {
|
|
if pass == 0 && instruction.op == .Insert && instruction.result != LirNoId &&
|
|
instruction.operands.count >= 2 {
|
|
ExecCoalescePair(function, index[:], values[:], parent[:], conflicts[:], members[:], words,
|
|
instruction.result, instruction.operands[0])
|
|
}
|
|
if pass == 1 {
|
|
for edge: instruction.edges {
|
|
target := function.blocks[edge.block]
|
|
for at: cast(s64)0..edge.arguments.count - 1 {
|
|
if at >= target.parameters.count { break }
|
|
ExecCoalescePair(function, index[:], values[:], parent[:], conflicts[:], members[:],
|
|
words, target.parameters[at], edge.arguments[at])
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
for at: cast(s64)0..total - 1 {
|
|
root := ExecCoalesceRoot(parent[:], at)
|
|
(<<aliases)[values[at]] = ifx root == at then LirNoId else values[root]
|
|
}
|
|
return true
|
|
}
|
|
|
|
// Walks a block backward from the live set at its end to the one at its
|
|
// start. With `record`, every composite value a block defines conflicts
|
|
// with each composite value live just after its definition.
|
|
ExecLiveBlock :: (block: LirBlock, index: []s64, live: []u64, conflicts: []u64, words: s64, record: bool) {
|
|
at := block.instructions.count - 1
|
|
while at >= 0 {
|
|
instruction := block.instructions[at]
|
|
for edge: instruction.edges {
|
|
for argument: edge.arguments { ExecLiveSet(live, index[argument], true) }
|
|
}
|
|
if instruction.result != LirNoId && index[instruction.result] >= 0 {
|
|
defined := index[instruction.result]
|
|
ExecLiveSet(live, defined, false)
|
|
if record { ExecLiveConflicts(live, conflicts, words, defined) }
|
|
}
|
|
for operand: instruction.operands { ExecLiveSet(live, index[operand], true) }
|
|
at -= 1
|
|
}
|
|
for parameter: block.parameters {
|
|
if index[parameter] < 0 { continue }
|
|
ExecLiveSet(live, index[parameter], false)
|
|
if record { ExecLiveConflicts(live, conflicts, words, index[parameter]) }
|
|
}
|
|
// Parameters are defined together: each conflicts with the others.
|
|
if record {
|
|
for left: block.parameters {
|
|
if index[left] < 0 { continue }
|
|
for right: block.parameters {
|
|
if index[right] >= 0 && right != left { ExecConflict(conflicts, words, index[left], index[right]) }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
ExecLiveSet :: (live: []u64, value: s64, on: bool) #inline {
|
|
if value < 0 { return }
|
|
bit := cast(u64)1 << cast(u64)(value % 64)
|
|
if on { live[value / 64] |= bit } else { live[value / 64] &= ~bit }
|
|
}
|
|
|
|
ExecConflict :: (conflicts: []u64, words: s64, left: s64, right: s64) #inline {
|
|
conflicts[left * words + right / 64] |= cast(u64)1 << cast(u64)(right % 64)
|
|
conflicts[right * words + left / 64] |= cast(u64)1 << cast(u64)(left % 64)
|
|
}
|
|
|
|
ExecLiveConflicts :: (live: []u64, conflicts: []u64, words: s64, defined: s64) {
|
|
for word: cast(s64)0..words - 1 {
|
|
bits := live[word]
|
|
while bits != 0 {
|
|
low := bits & (cast(u64)0 - bits)
|
|
bit: s64
|
|
probe := low
|
|
while probe > 1 { probe >>= cast(u64)1; bit += 1 }
|
|
other := word * 64 + bit
|
|
if other != defined { ExecConflict(conflicts, words, defined, other) }
|
|
bits ^= low
|
|
}
|
|
}
|
|
}
|
|
|
|
ExecCoalesceRoot :: (parent: []s64, at: s64) -> s64 {
|
|
root := at
|
|
while parent[root] != root { root = parent[root] }
|
|
step := at
|
|
while parent[step] != root {
|
|
next := parent[step]
|
|
parent[step] = root
|
|
step = next
|
|
}
|
|
return root
|
|
}
|
|
|
|
// Puts two values of one type in one slot unless their groups conflict.
|
|
// A group's root is its lowest-numbered value, which is laid out first.
|
|
ExecCoalescePair :: (function: LirFunction, index: []s64, values: []s32, parent: []s64,
|
|
conflicts: []u64, members: []u64, words: s64, left: s32, right: s32) {
|
|
if left == LirNoId || right == LirNoId || index[left] < 0 || index[right] < 0 ||
|
|
function.values[left] != function.values[right] { return }
|
|
a := ExecCoalesceRoot(parent, index[left])
|
|
b := ExecCoalesceRoot(parent, index[right])
|
|
if a == b { return }
|
|
for word: cast(s64)0..words - 1 {
|
|
if (conflicts[a * words + word] & members[b * words + word]) != 0 { return }
|
|
}
|
|
root := ifx values[a] < values[b] then a else b
|
|
other := ifx root == a then b else a
|
|
for word: cast(s64)0..words - 1 {
|
|
conflicts[root * words + word] |= conflicts[other * words + word]
|
|
members[root * words + word] |= members[other * words + word]
|
|
}
|
|
parent[other] = root
|
|
}
|
|
|
|
ExecPlanFunctions :: (program: LirProgram, plan: *LirExecPlan, maximum: s64) -> LirExecProblem {
|
|
values: s64
|
|
blocks: s64
|
|
edges: s64
|
|
instructions: s64
|
|
for function: program.functions {
|
|
if function.values.count > 9223372036854775807 - values { return .ValueLimit }
|
|
values += function.values.count
|
|
if function.blocks.count > 9223372036854775807 - blocks { return .ValueLimit }
|
|
blocks += function.blocks.count
|
|
for block: function.blocks {
|
|
if block.instructions.count > 9223372036854775807 - instructions {
|
|
return .ValueLimit
|
|
}
|
|
instructions += block.instructions.count
|
|
for instruction: block.instructions {
|
|
if instruction.edges.count > 9223372036854775807 - edges { return .ValueLimit }
|
|
edges += instruction.edges.count
|
|
}
|
|
}
|
|
}
|
|
if !VecResizeBounded(plan.value_offsets, values, values) ||
|
|
!VecResizeBounded(plan.value_words, values, values) ||
|
|
!VecResizeBounded(plan.value_sizes, values, values) ||
|
|
!VecResizeBounded(plan.value_types, values, values) ||
|
|
!VecResizeBounded(plan.value_canonical, values, values) ||
|
|
!VecResizeBounded(plan.value_masks, values, values) ||
|
|
!VecResizeBounded(plan.functions, program.functions.count, program.functions.count) ||
|
|
!VecResizeBounded(plan.block_edge_bases, blocks, blocks) ||
|
|
!VecResizeBounded(plan.block_instruction_bases, blocks, blocks) ||
|
|
!VecResizeBounded(plan.edge_direct, edges, edges) ||
|
|
!VecResizeBounded(plan.instructions, instructions, instructions) ||
|
|
!VecResizeBounded(plan.transient, instructions, instructions) ||
|
|
!VecResizeBounded(plan.global_offsets, program.globals.count, program.globals.count) { return .Allocation }
|
|
value_at: s64
|
|
block_at: s64
|
|
edge_at: s64
|
|
instruction_at: s64
|
|
for function_index: cast(s64)0..program.functions.count - 1 {
|
|
function := program.functions[function_index]
|
|
uses: Vec(s64)
|
|
aliases: Vec(s32)
|
|
predecessors: Vec(s64)
|
|
defer VecFree(uses)
|
|
defer VecFree(aliases)
|
|
defer VecFree(predecessors)
|
|
if !VecResizeBounded(uses, function.values.count, function.values.count) ||
|
|
!VecResizeBounded(aliases, function.values.count, function.values.count) ||
|
|
!VecResizeBounded(predecessors, function.blocks.count, function.blocks.count) {
|
|
return .Allocation
|
|
}
|
|
for value_index: cast(s64)0..function.values.count - 1 { aliases[value_index] = LirNoId }
|
|
for block: function.blocks {
|
|
for instruction: block.instructions {
|
|
for operand: instruction.operands { uses[operand] += 1 }
|
|
for edge: instruction.edges {
|
|
predecessors[edge.block] += 1
|
|
for argument: edge.arguments { uses[argument] += 1 }
|
|
}
|
|
}
|
|
}
|
|
// A dead Extract still executes (and therefore retains its trap
|
|
// behavior), but the bytes it reads cannot keep a prior aggregate
|
|
// version live. Discount only that content use for slot coalescing.
|
|
for block: function.blocks {
|
|
for instruction: block.instructions {
|
|
if instruction.op == .Extract && instruction.result != LirNoId &&
|
|
uses[instruction.result] == 0 && instruction.operands.count != 0 {
|
|
uses[instruction.operands[0]] -= 1
|
|
}
|
|
}
|
|
}
|
|
// A parameter of a single-predecessor block may share its incoming
|
|
// value's slot. The edge is the incoming value's last dynamic use;
|
|
// require a unique occurrence on that edge so two live parameters can
|
|
// never observe an Insert updating their shared aggregate bytes.
|
|
for block: function.blocks {
|
|
for instruction: block.instructions {
|
|
for edge: instruction.edges {
|
|
if predecessors[edge.block] != 1 { continue }
|
|
target := function.blocks[edge.block]
|
|
for index: cast(s64)0..target.parameters.count - 1 {
|
|
source := edge.arguments[index]
|
|
destination := target.parameters[index]
|
|
if source >= destination ||
|
|
function.values[source] != function.values[destination] { continue }
|
|
source_root := source
|
|
while aliases[source_root] != LirNoId { source_root = aliases[source_root] }
|
|
unique := true
|
|
for other: cast(s64)0..edge.arguments.count - 1 {
|
|
other_root := edge.arguments[other]
|
|
while aliases[other_root] != LirNoId { other_root = aliases[other_root] }
|
|
if other != index && other_root == source_root { unique = false; break }
|
|
}
|
|
if unique { aliases[destination] = source_root }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// Join parameters may coalesce too when every predecessor already
|
|
// carries the same proven location (for example, both arms of a branch
|
|
// forwarding an unchanged array). Different incoming roots stay apart.
|
|
for target_index: cast(s64)0..function.blocks.count - 1 {
|
|
if predecessors[target_index] <= 1 { continue }
|
|
target := function.blocks[target_index]
|
|
for parameter_index: cast(s64)0..target.parameters.count - 1 {
|
|
candidate: s32 = LirNoId
|
|
consistent := true
|
|
for source_block: function.blocks {
|
|
for instruction: source_block.instructions {
|
|
for edge: instruction.edges {
|
|
if edge.block != target_index { continue }
|
|
source := edge.arguments[parameter_index]
|
|
root := source
|
|
while aliases[root] != LirNoId { root = aliases[root] }
|
|
for other: cast(s64)0..edge.arguments.count - 1 {
|
|
other_root := edge.arguments[other]
|
|
while aliases[other_root] != LirNoId { other_root = aliases[other_root] }
|
|
if other != parameter_index && other_root == root {
|
|
consistent = false; break
|
|
}
|
|
}
|
|
if !consistent { break }
|
|
if candidate == LirNoId { candidate = root }
|
|
else if candidate != root { consistent = false; break }
|
|
}
|
|
if !consistent { break }
|
|
}
|
|
if !consistent { break }
|
|
}
|
|
destination := target.parameters[parameter_index]
|
|
if consistent && candidate != LirNoId && candidate < destination &&
|
|
function.values[candidate] == function.values[destination] {
|
|
aliases[destination] = candidate
|
|
}
|
|
}
|
|
}
|
|
for block: function.blocks {
|
|
for instruction: block.instructions {
|
|
if instruction.op != .Insert || instruction.result == LirNoId ||
|
|
instruction.operands.count < 2 { continue }
|
|
source := instruction.operands[0]
|
|
if source < instruction.result && uses[source] == 1 &&
|
|
function.values[source] == function.values[instruction.result] {
|
|
aliases[instruction.result] = source
|
|
}
|
|
}
|
|
}
|
|
if !ExecPlanCoalesce(program, function, *aliases) { return .Allocation }
|
|
base := value_at
|
|
offset: s64
|
|
words: s64
|
|
for value_index: cast(s64)0..function.values.count - 1 {
|
|
value := function.values[value_index]
|
|
type := program.types[value]
|
|
plan.value_sizes[value_at] = plan.type_sizes[value]
|
|
plan.value_types[value_at] = value
|
|
if type.kind == .Bool { plan.value_canonical[value_at] = 1; plan.value_masks[value_at] = 1 }
|
|
else if type.kind == .Integer {
|
|
plan.value_canonical[value_at] = 2
|
|
plan.value_masks[value_at] = ExecMask(type.bits)
|
|
}
|
|
scalar := type.kind == .Bool || type.kind == .Integer || type.kind == .Float ||
|
|
type.kind == .Pointer || type.kind == .Function
|
|
alias := aliases[value_index]
|
|
if alias != LirNoId {
|
|
plan.value_offsets[value_at] = plan.value_offsets[base + alias]
|
|
plan.value_words[value_at] = plan.value_words[base + alias]
|
|
} else if scalar {
|
|
plan.value_offsets[value_at] = -1
|
|
plan.value_words[value_at] = words
|
|
words += 1
|
|
} else {
|
|
plan.value_words[value_at] = -1
|
|
plan.value_offsets[value_at] = offset
|
|
size := plan.type_sizes[value]
|
|
if size > maximum - offset { return .ValueBytes }
|
|
offset += size
|
|
}
|
|
value_at += 1
|
|
}
|
|
scratch: s64
|
|
for block: function.blocks {
|
|
size: s64
|
|
for parameter: block.parameters {
|
|
part := plan.type_sizes[function.values[parameter]]
|
|
if part > maximum - size { return .ValueBytes }
|
|
size += part
|
|
}
|
|
if size > scratch { scratch = size }
|
|
}
|
|
if scratch > maximum - offset { return .ValueBytes }
|
|
if words > (maximum - offset - scratch) / 8 { return .ValueBytes }
|
|
function_base := value_at - function.values.count
|
|
plan.functions[function_index] = .{.value_base = function_base, .block_base = block_at,
|
|
.frame_bytes = offset + scratch, .word_count = words,
|
|
.scratch_offset = offset, .scratch_bytes = scratch}
|
|
function_first := instruction_at
|
|
for block: function.blocks {
|
|
plan.block_edge_bases[block_at] = edge_at
|
|
plan.block_instruction_bases[block_at] = instruction_at
|
|
for instruction: block.instructions {
|
|
plan.instructions[instruction_at] = instruction
|
|
instruction_at += 1
|
|
for edge: instruction.edges {
|
|
target := function.blocks[edge.block]
|
|
plan.edge_direct[edge_at] = cast(u8)ExecPlanEdgeDirectSafe(
|
|
plan, function_base, edge, target)
|
|
edge_at += 1
|
|
}
|
|
}
|
|
block_at += 1
|
|
}
|
|
if !ExecPlanTransients(plan, function, function_first) { return .Allocation }
|
|
}
|
|
offset: s64
|
|
for global_index: cast(s64)0..program.globals.count - 1 {
|
|
plan.global_offsets[global_index] = offset
|
|
size := plan.type_sizes[program.globals[global_index].type]
|
|
if size > maximum - offset { return .ValueBytes }
|
|
offset += size
|
|
}
|
|
plan.global_bytes = offset
|
|
return .None
|
|
}
|
|
|
|
// ---- Compact code --------------------------------------------------------
|
|
|
|
ExecPlanCodeKind :: enum s32 {
|
|
// Runs through ExecStep; it ends the segment before it.
|
|
Slow
|
|
// Has a LirExecCode the run loop executes.
|
|
Fast
|
|
// A word that holds one value from the frame's start (constant words).
|
|
Constant
|
|
// Charged with its segment but runs no code: fuel, and a compare that
|
|
// the Branch after it carries out.
|
|
Folded
|
|
}
|
|
|
|
ExecPlanWord :: (plan: *LirExecPlan, base: s64, value: s32) -> s32 {
|
|
return cast(s32)plan.value_words[base + value]
|
|
}
|
|
|
|
ExecPlanMask :: (plan: *LirExecPlan, base: s64, value: s32) -> u64 {
|
|
if plan.value_canonical[base + value] == 2 { return plan.value_masks[base + value] }
|
|
return ~cast(u64)0
|
|
}
|
|
|
|
// The sign bit an index operand must not have (ExecIndexBits), or 0.
|
|
// k when `size` is 2^k, else -1.
|
|
ExecPlanShift :: (size: s64) -> s64 {
|
|
if size <= 0 { return -1 }
|
|
shift: u64 = 0
|
|
while shift < 62 && (cast(u64)1 << shift) < cast(u64)size { shift += 1 }
|
|
if (cast(u64)1 << shift) == cast(u64)size { return cast(s64)shift }
|
|
return -1
|
|
}
|
|
|
|
ExecPlanSign :: (program: LirProgram, plan: *LirExecPlan, base: s64, value: s32) -> u64 {
|
|
type := program.types[plan.value_types[base + value]]
|
|
if type.kind != .Integer || !type.is_signed { return 0 }
|
|
return cast(u64)1 << cast(u64)(type.bits - 1)
|
|
}
|
|
|
|
// ExecMember at plan time: the member's offset and the work ExecMember
|
|
// charges for it.
|
|
ExecPlanMember :: (program: LirProgram, plan: *LirExecPlan, type_id: s32, member: u64,
|
|
offset: *s64, cost: *s64) -> bool {
|
|
type := program.types[type_id]
|
|
if type.kind == .Array {
|
|
if member >= cast(u64)type.count { return false }
|
|
<<offset = cast(s64)member * plan.type_sizes[type.element]
|
|
<<cost = 0
|
|
return true
|
|
}
|
|
if type.kind != .Record || member >= cast(u64)type.fields.count { return false }
|
|
result: s64
|
|
for index: cast(s64)0..cast(s64)member - 1 { result += plan.type_sizes[type.fields[index]] }
|
|
<<offset = result
|
|
<<cost = cast(s64)member
|
|
return true
|
|
}
|
|
|
|
ExecPlanBinary :: (op: LirOp, type: LirType) -> LirExecHandler {
|
|
if type.kind == .Float {
|
|
if type.bits == 32 {
|
|
if op == .Add { return .FloatAdd32 }
|
|
if op == .Subtract { return .FloatSubtract32 }
|
|
if op == .Multiply { return .FloatMultiply32 }
|
|
if op == .Divide { return .FloatDivide32 }
|
|
} else if type.bits == 64 {
|
|
if op == .Add { return .FloatAdd64 }
|
|
if op == .Subtract { return .FloatSubtract64 }
|
|
if op == .Multiply { return .FloatMultiply64 }
|
|
if op == .Divide { return .FloatDivide64 }
|
|
}
|
|
return .Slow
|
|
}
|
|
if type.kind != .Integer { return .Slow }
|
|
if op == .Add { return .Add }
|
|
if op == .Subtract { return .Subtract }
|
|
if op == .Multiply { return .Multiply }
|
|
if op == .BitAnd { return .BitAnd }
|
|
if op == .BitOr { return .BitOr }
|
|
if op == .BitXor { return .BitXor }
|
|
if op == .Divide { return ifx type.is_signed then .DivideSigned else .DivideUnsigned }
|
|
if op == .Remainder { return ifx type.is_signed then .RemainderSigned else .RemainderUnsigned }
|
|
if op == .ShiftLeft { return .ShiftLeft }
|
|
if op == .ShiftRight { return ifx type.is_signed then .ShiftRightSigned else .ShiftRightUnsigned }
|
|
return .Slow
|
|
}
|
|
|
|
ExecPlanCompare :: (op: LirOp, type: LirType) -> LirExecHandler {
|
|
if type.kind == .Float { return ifx type.bits == 32 then .FloatCompare32 else .FloatCompare64 }
|
|
if op == .Equal { return .Equal }
|
|
if op == .NotEqual { return .NotEqual }
|
|
if type.kind == .Integer && type.is_signed {
|
|
if op == .Less { return .SignedLess }
|
|
if op == .LessEqual { return .SignedLessEqual }
|
|
if op == .Greater { return .SignedGreater }
|
|
return .SignedGreaterEqual
|
|
}
|
|
if op == .Less { return .Less }
|
|
if op == .LessEqual { return .LessEqual }
|
|
if op == .Greater { return .Greater }
|
|
return .GreaterEqual
|
|
}
|
|
|
|
// A handler that derives an address from operand 0, alone or with its use.
|
|
ExecPlanDerivation :: (handler: LirExecHandler) -> bool {
|
|
return handler == .FieldAddress || handler == .ElementIndex || handler == .ElementView ||
|
|
handler == .LoadField || handler == .LoadIndex || handler == .LoadView ||
|
|
handler == .StoreField || handler == .StoreIndex || handler == .StoreView
|
|
}
|
|
|
|
// The handler of a derivation and the Load or Store after it, or Slow.
|
|
ExecPlanFusedMemory :: (derivation: LirExecHandler, memory: LirExecHandler) -> LirExecHandler {
|
|
if memory == .Load {
|
|
if derivation == .FieldAddress { return .LoadField }
|
|
if derivation == .ElementIndex { return .LoadIndex }
|
|
if derivation == .ElementView { return .LoadView }
|
|
} else if memory == .Store {
|
|
if derivation == .FieldAddress { return .StoreField }
|
|
if derivation == .ElementIndex { return .StoreIndex }
|
|
if derivation == .ElementView { return .StoreView }
|
|
}
|
|
return .Slow
|
|
}
|
|
|
|
// The Branch handler that also does compare `handler`, or Slow.
|
|
ExecPlanFused :: (handler: LirExecHandler) -> LirExecHandler {
|
|
if handler == .Equal { return .BranchEqual }
|
|
if handler == .NotEqual { return .BranchNotEqual }
|
|
if handler == .Less { return .BranchLess }
|
|
if handler == .LessEqual { return .BranchLessEqual }
|
|
if handler == .Greater { return .BranchGreater }
|
|
if handler == .GreaterEqual { return .BranchGreaterEqual }
|
|
if handler == .SignedLess { return .BranchSignedLess }
|
|
if handler == .SignedLessEqual { return .BranchSignedLessEqual }
|
|
if handler == .SignedGreater { return .BranchSignedGreater }
|
|
if handler == .SignedGreaterEqual { return .BranchSignedGreaterEqual }
|
|
return .Slow
|
|
}
|
|
|
|
// Translates one instruction. `work` and `fuel` are what ExecStep charges
|
|
// for it, apart from the copies of a terminator's edge (ExecPlanEdges).
|
|
ExecPlanInstruction :: (program: LirProgram, plan: *LirExecPlan, base: s64,
|
|
instruction: LirInstruction, transient: bool, out: *LirExecCode, work: *s64,
|
|
fuel: *s64, bits: *u64) -> ExecPlanCodeKind {
|
|
op := instruction.op
|
|
count := instruction.operands.count
|
|
<<work = 1
|
|
<<fuel = 0
|
|
out.handler = .Slow
|
|
out.result = -1
|
|
out.a = -1
|
|
out.b = -1
|
|
out.c = -1
|
|
out.flag = 0
|
|
out.edge = -1
|
|
out.result_value = instruction.result
|
|
out.value = -1
|
|
out.prefix = 0
|
|
out.memo = -1
|
|
if instruction.result != LirNoId { out.result = ExecPlanWord(plan, base, instruction.result) }
|
|
if count > 0 { out.a = ExecPlanWord(plan, base, instruction.operands[0]) }
|
|
if count > 1 { out.b = ExecPlanWord(plan, base, instruction.operands[1]) }
|
|
if count > 2 { out.c = ExecPlanWord(plan, base, instruction.operands[2]) }
|
|
if op == .Constant || op == .Null || op == .FunctionAddress {
|
|
if out.result < 0 { return .Slow }
|
|
value: u64
|
|
if op == .Constant { value = program.constants[instruction.symbol].bits }
|
|
if op == .FunctionAddress { value = cast(u64)(instruction.symbol + 1) }
|
|
canonical := plan.value_canonical[base + instruction.result]
|
|
if canonical == 1 { value = cast(u64)(value != 0) }
|
|
else if canonical == 2 { value &= plan.value_masks[base + instruction.result] }
|
|
<<bits = value
|
|
return .Constant
|
|
}
|
|
if op == .Fuel {
|
|
<<fuel = cast(s64)instruction.immediate
|
|
return .Folded
|
|
}
|
|
if op == .GlobalAddress {
|
|
if out.result < 0 { return .Slow }
|
|
out.handler = .GlobalAddress
|
|
out.x = instruction.symbol
|
|
return .Fast
|
|
}
|
|
if op == .Jump {
|
|
out.handler = .Jump
|
|
return .Fast
|
|
}
|
|
if op == .Branch {
|
|
if out.a < 0 { return .Slow }
|
|
out.handler = .Branch
|
|
return .Fast
|
|
}
|
|
code := cast(s32)op
|
|
if op == .Negate || op == .BitNot {
|
|
if out.result < 0 || out.a < 0 { return .Slow }
|
|
type := program.types[plan.value_types[base + instruction.operands[0]]]
|
|
if type.kind == .Integer {
|
|
out.handler = ifx op == .Negate then .Negate else .BitNot
|
|
out.immediate = ExecPlanMask(plan, base, instruction.result)
|
|
} else if type.kind == .Float && op == .Negate {
|
|
out.handler = .FloatNegate
|
|
out.immediate = ifx type.bits == 32 then cast(u64)0x80000000 else cast(u64)0x8000000000000000
|
|
} else { return .Slow }
|
|
return .Fast
|
|
}
|
|
if code >= cast(s32)LirOp.Add && code <= cast(s32)LirOp.Remainder ||
|
|
code >= cast(s32)LirOp.BitAnd && code <= cast(s32)LirOp.ShiftRight {
|
|
if count != 2 || out.result < 0 || out.a < 0 || out.b < 0 { return .Slow }
|
|
type := program.types[plan.value_types[base + instruction.operands[0]]]
|
|
out.handler = ExecPlanBinary(op, type)
|
|
if out.handler == .Slow { return .Slow }
|
|
out.size = type.bits
|
|
out.immediate = ExecPlanMask(plan, base, instruction.result)
|
|
return .Fast
|
|
}
|
|
if code >= cast(s32)LirOp.Equal && code <= cast(s32)LirOp.GreaterEqual {
|
|
if count != 2 || out.result < 0 || out.a < 0 || out.b < 0 { return .Slow }
|
|
type := program.types[plan.value_types[base + instruction.operands[0]]]
|
|
out.handler = ExecPlanCompare(op, type)
|
|
out.size = type.bits
|
|
out.extra = cast(u64)code
|
|
return .Fast
|
|
}
|
|
if op == .Convert || op == .Bitcast {
|
|
if count != 1 || out.result < 0 || out.a < 0 { return .Slow }
|
|
source := program.types[plan.value_types[base + instruction.operands[0]]]
|
|
destination := program.types[plan.value_types[base + instruction.result]]
|
|
out.size = source.bits
|
|
out.y = destination.bits
|
|
out.immediate = ExecPlanMask(plan, base, instruction.result)
|
|
if op == .Bitcast {
|
|
if destination.kind == .Bool { return .Slow }
|
|
out.handler = .Bitcast
|
|
return .Fast
|
|
}
|
|
if source.kind == .Bool && destination.kind == .Integer { out.handler = .ConvertBoolInteger }
|
|
else if source.kind == .Integer && destination.kind == .Bool {
|
|
out.handler = .ConvertIntegerBool
|
|
out.extra = ExecMask(source.bits)
|
|
} else if source.kind == .Integer && destination.kind == .Integer {
|
|
out.handler = .ConvertInteger
|
|
out.extra = ExecMask(source.bits)
|
|
out.flag = cast(s32)source.is_signed
|
|
} else if source.kind == .Integer && destination.kind == .Float {
|
|
out.handler = .ConvertIntegerFloat
|
|
out.extra = ExecMask(source.bits)
|
|
out.flag = cast(s32)source.is_signed
|
|
} else if source.kind == .Float && destination.kind == .Float {
|
|
out.handler = .ConvertFloatFloat
|
|
} else if source.kind == .Float && destination.kind == .Integer {
|
|
out.handler = .ConvertFloatInteger
|
|
out.flag = cast(s32)destination.is_signed
|
|
} else { return .Slow }
|
|
return .Fast
|
|
}
|
|
if op == .Extract || op == .Insert {
|
|
expected := ifx op == .Extract then 1 else 2
|
|
aggregate := instruction.operands[0]
|
|
aggregate_type := plan.value_types[base + aggregate]
|
|
aggregate_at := plan.value_offsets[base + aggregate]
|
|
if plan.value_words[base + aggregate] >= 0 || aggregate_at < 0 { return .Slow }
|
|
indexed := count == expected + 1
|
|
member_offset: s64
|
|
member_cost: s64
|
|
if indexed {
|
|
type := program.types[aggregate_type]
|
|
if type.kind != .Array { return .Slow }
|
|
index := instruction.operands[expected]
|
|
if plan.value_words[base + index] < 0 { return .Slow }
|
|
out.extra = cast(u64)type.count
|
|
out.sign_c = ExecPlanSign(program, plan, base, index)
|
|
out.c = ExecPlanWord(plan, base, index)
|
|
} else if count != expected ||
|
|
!ExecPlanMember(program, plan, aggregate_type, instruction.immediate, *member_offset, *member_cost) {
|
|
return .Slow
|
|
}
|
|
out.x = aggregate_at
|
|
if op == .Extract {
|
|
result := instruction.result
|
|
size := plan.value_sizes[base + result]
|
|
out.size = size
|
|
<<work = 1 + member_cost + ExecCopyCost(size)
|
|
if out.result >= 0 {
|
|
out.handler = ifx indexed then .ExtractWordIndexed else .ExtractWord
|
|
out.flag = cast(s32)(plan.value_canonical[base + result] == 1)
|
|
out.immediate = ExecPlanMask(plan, base, result)
|
|
} else {
|
|
out.handler = ifx indexed then .ExtractBytesIndexed else .ExtractBytes
|
|
out.y = plan.value_offsets[base + result]
|
|
}
|
|
if !indexed { out.x += member_offset }
|
|
return .Fast
|
|
}
|
|
if out.result >= 0 { return .Slow }
|
|
replacement := instruction.operands[1]
|
|
out.y = plan.value_offsets[base + instruction.result]
|
|
out.size = plan.value_sizes[base + aggregate]
|
|
out.z = plan.value_sizes[base + replacement]
|
|
if !indexed { out.immediate = cast(u64)member_offset }
|
|
<<work = 1 + member_cost + ExecCopyCost(out.size) + ExecCopyCost(out.z)
|
|
if out.b >= 0 {
|
|
out.handler = ifx indexed then .InsertWordIndexed else .InsertWord
|
|
} else {
|
|
out.handler = ifx indexed then .InsertBytesIndexed else .InsertBytes
|
|
out.w = plan.value_offsets[base + replacement]
|
|
}
|
|
return .Fast
|
|
}
|
|
if op == .Aggregate {
|
|
if out.result >= 0 { return .Slow }
|
|
destination := plan.value_offsets[base + instruction.result]
|
|
out.x = plan.moves.count
|
|
out.y = count
|
|
at: s64
|
|
cost: s64 = 1
|
|
for operand: instruction.operands {
|
|
size := plan.value_sizes[base + operand]
|
|
word := plan.value_words[base + operand]
|
|
from := ifx word >= 0 then word else plan.value_offsets[base + operand]
|
|
if !VecPush(plan.moves, LirExecMove.{.word = word >= 0, .from = from,
|
|
.to = destination + at, .size = size}) { return .Slow }
|
|
cost += ExecCopyCost(size)
|
|
at += size
|
|
}
|
|
<<work = cost
|
|
out.handler = .Aggregate
|
|
return .Fast
|
|
}
|
|
if op == .Load || op == .Store {
|
|
if out.a < 0 { return .Slow }
|
|
value := ifx op == .Load then instruction.result else instruction.operands[1]
|
|
if value == LirNoId { return .Slow }
|
|
size := plan.value_sizes[base + value]
|
|
out.size = size
|
|
out.type = plan.value_types[base + value]
|
|
<<work = 1 + ExecCopyCost(size)
|
|
word := plan.value_words[base + value]
|
|
if word < 0 { out.x = plan.value_offsets[base + value] }
|
|
if op == .Load {
|
|
out.handler = .Load
|
|
out.flag = cast(s32)(plan.value_canonical[base + value] == 1)
|
|
out.immediate = ExecPlanMask(plan, base, value)
|
|
} else { out.handler = .Store }
|
|
return .Fast
|
|
}
|
|
if op == .FieldAddress || op == .ElementAddress {
|
|
if out.result < 0 || out.a < 0 || count > 4 { return .Slow }
|
|
expected := program.types[plan.value_types[base + instruction.operands[0]]].element
|
|
target := program.types[plan.value_types[base + instruction.result]].element
|
|
out.type = expected
|
|
out.target = target
|
|
out.size = plan.type_sizes[target]
|
|
out.flag = cast(s32)transient
|
|
// Views check their count against the extent per element: by a
|
|
// shift when the size is a power of two (ExecFastPerElement).
|
|
out.z = ExecPlanShift(out.size)
|
|
if count == 4 {
|
|
// A slice of `low`, `high` and the view's count: the view of its
|
|
// element `low` (ElementSlice).
|
|
out.value = out.c
|
|
out.c = ExecPlanWord(plan, base, instruction.operands[3])
|
|
if expected != target || out.size <= 0 || out.b < 0 || out.c < 0 || out.value < 0 { return .Slow }
|
|
out.sign_b = ExecPlanSign(program, plan, base, instruction.operands[1])
|
|
out.extra = ExecPlanSign(program, plan, base, instruction.operands[2])
|
|
out.sign_c = ExecPlanSign(program, plan, base, instruction.operands[3])
|
|
out.handler = .ElementSlice
|
|
<<work = 2
|
|
return .Fast
|
|
}
|
|
if op == .FieldAddress {
|
|
member_offset: s64
|
|
member_cost: s64
|
|
if !ExecPlanMember(program, plan, expected, instruction.immediate, *member_offset, *member_cost) ||
|
|
program.types[expected].kind != .Record { return .Slow }
|
|
out.handler = .FieldAddress
|
|
out.x = member_offset
|
|
<<work = 2 + member_cost
|
|
return .Fast
|
|
}
|
|
if out.b < 0 { return .Slow }
|
|
out.sign_b = ExecPlanSign(program, plan, base, instruction.operands[1])
|
|
if count == 2 {
|
|
parent := program.types[expected]
|
|
if parent.kind != .Array { return .Slow }
|
|
out.handler = .ElementIndex
|
|
out.extra = cast(u64)parent.count
|
|
} else {
|
|
if out.c < 0 { return .Slow }
|
|
out.sign_c = ExecPlanSign(program, plan, base, instruction.operands[2])
|
|
out.handler = .ElementView
|
|
}
|
|
<<work = 2
|
|
return .Fast
|
|
}
|
|
if op == .Allocate {
|
|
// Frame storage and its table entry, with the first value copied in
|
|
// when there is one (ExecAllocate). `y` is that copy's work.
|
|
if out.result < 0 || count > 1 { return .Slow }
|
|
pointee := program.types[plan.value_types[base + instruction.result]].element
|
|
out.type = pointee
|
|
out.size = plan.type_sizes[pointee]
|
|
out.x = 0
|
|
out.y = 0
|
|
if count == 1 {
|
|
value := instruction.operands[0]
|
|
if plan.value_types[base + value] != pointee || plan.value_sizes[base + value] != out.size { return .Slow }
|
|
if out.a < 0 { out.x = plan.value_offsets[base + value] }
|
|
out.y = ExecCopyCost(out.size)
|
|
}
|
|
// It grows the frame's storage, so it ends its segment: the run loop
|
|
// makes it (ExecFastAllocate) and charges its work.
|
|
out.handler = .Allocate
|
|
<<work = 1 + out.y
|
|
return .Slow
|
|
}
|
|
if op == .Call {
|
|
// The callee's entry parameters take the arguments in order.
|
|
target := program.functions[instruction.symbol]
|
|
if target.external || target.parameters.count != count { return .Slow }
|
|
target_plan := plan.functions[instruction.symbol]
|
|
entry := target.blocks[target.entry]
|
|
out.x = plan.moves.count
|
|
out.y = count
|
|
cost: s64 = 1
|
|
for index: cast(s64)0..count - 1 {
|
|
source := instruction.operands[index]
|
|
destination := entry.parameters[index]
|
|
size := plan.value_sizes[base + source]
|
|
source_word := plan.value_words[base + source]
|
|
destination_word := plan.value_words[target_plan.value_base + destination]
|
|
if (source_word >= 0) != (destination_word >= 0) { return .Slow }
|
|
word := source_word >= 0
|
|
if !VecPush(plan.moves, LirExecMove.{.word = word, .size = size,
|
|
.from = ifx word then source_word else plan.value_offsets[base + source],
|
|
.to = ifx word then destination_word else plan.value_offsets[target_plan.value_base + destination]}) {
|
|
return .Slow
|
|
}
|
|
cost += ExecCopyCost(size)
|
|
}
|
|
out.handler = .Call
|
|
out.target = instruction.symbol
|
|
<<work = cost
|
|
return .Slow
|
|
}
|
|
if op == .Return {
|
|
out.handler = .Return
|
|
// The code record is reused from block to block: nothing returned
|
|
// has no size.
|
|
out.size = 0
|
|
out.x = 0
|
|
if count == 1 {
|
|
value := instruction.operands[0]
|
|
out.size = plan.value_sizes[base + value]
|
|
if plan.value_words[base + value] < 0 { out.x = plan.value_offsets[base + value] }
|
|
}
|
|
return .Slow
|
|
}
|
|
if op == .HostCall {
|
|
if count != 3 || !ExecPlatformWriteSignature(program, instruction.symbol) {
|
|
// A generic host call whose arguments all live in frame words and
|
|
// whose result, if any, is a scalar word stays in the fast loop;
|
|
// anything else runs on ExecStep.
|
|
target := program.functions[instruction.symbol]
|
|
if count > 3 { return .Slow }
|
|
if count >= 1 && out.a < 0 { return .Slow }
|
|
if count >= 2 && out.b < 0 { return .Slow }
|
|
if count >= 3 && out.c < 0 { return .Slow }
|
|
if out.result >= 0 && !ExecHostScalarType(program.types[target.result]) { return .Slow }
|
|
out.handler = .HostCall
|
|
out.target = instruction.symbol
|
|
out.type = target.result
|
|
out.x = count
|
|
<<work = 1 + count
|
|
return .Fast
|
|
}
|
|
if out.a < 0 || out.b < 0 || out.c < 0 { return .Slow }
|
|
target := program.functions[instruction.symbol]
|
|
out.handler = .HostWrite
|
|
out.target = instruction.symbol
|
|
out.type = program.types[target.parameters[1]].element
|
|
<<work = 1 + count
|
|
return .Fast
|
|
}
|
|
return .Slow
|
|
}
|
|
|
|
// The edge plans of one block's instructions, from plan edge `edge_at`.
|
|
ExecPlanEdges :: (plan: *LirExecPlan, function: LirFunction, function_plan: LirExecFunctionPlan,
|
|
block: LirBlock, edge_at: s64) -> bool {
|
|
base := function_plan.value_base
|
|
at := edge_at
|
|
for instruction: block.instructions {
|
|
for edge: instruction.edges {
|
|
target := function.blocks[edge.block]
|
|
target_base := plan.block_instruction_bases[function_plan.block_base + edge.block]
|
|
direct := plan.edge_direct[at] != 0
|
|
first := plan.moves.count
|
|
work: s64
|
|
scratch: s64
|
|
if edge.arguments.count != target.parameters.count { return false }
|
|
for index: cast(s64)0..target.parameters.count - 1 {
|
|
source := edge.arguments[index]
|
|
destination := target.parameters[index]
|
|
size := plan.value_sizes[base + source]
|
|
work += 2 * ExecCopyCost(size)
|
|
if direct && ExecPlanValuesSameLocation(plan, base, source, destination) { continue }
|
|
source_word := plan.value_words[base + source]
|
|
destination_word := plan.value_words[base + destination]
|
|
if (source_word >= 0) != (destination_word >= 0) { return false }
|
|
word := source_word >= 0
|
|
move := LirExecMove.{.word = word, .size = size,
|
|
.from = ifx word then source_word else plan.value_offsets[base + source],
|
|
.to = ifx word then destination_word else plan.value_offsets[base + destination],
|
|
.scratch = function_plan.scratch_offset + scratch}
|
|
scratch += size
|
|
if !VecPush(plan.moves, move) { return false }
|
|
}
|
|
plan.edge_plans[at] = .{.moves = first, .count = plan.moves.count - first,
|
|
.direct = direct, .work = work, .target_block = edge.block,
|
|
.target_base = target_base, .target_code = plan.segment_code[target_base],
|
|
.target_work = plan.segment_work[target_base], .target_fuel = plan.segment_fuel[target_base]}
|
|
at += 1
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// Translates every function into the plan's compact code (LirExecCode).
|
|
ExecPlanCode :: (program: LirProgram, plan: *LirExecPlan) -> LirExecProblem {
|
|
total := plan.instructions.count
|
|
if !VecResizeBounded(plan.powers, 2098, 2098) ||
|
|
!VecResizeBounded(plan.segment_code, total, total) ||
|
|
!VecResizeBounded(plan.segment_work, total, total) ||
|
|
!VecResizeBounded(plan.segment_fuel, total, total) ||
|
|
!VecResizeBounded(plan.edge_plans, plan.edge_direct.count, plan.edge_direct.count) ||
|
|
!VecReserve(plan.code, total) { return .Allocation }
|
|
plan.powers[0] = ScaleByPowerOfTwo(1.0, -1074)
|
|
for index: cast(s64)1..2097 { plan.powers[index] = plan.powers[index - 1] * 2.0 }
|
|
for index: cast(s64)0..total - 1 { plan.segment_code[index] = -1 }
|
|
// Neither total may come near the limits of the work and fuel counters.
|
|
ceiling: s64 = 4611686018427387904
|
|
kinds: Vec(ExecPlanCodeKind)
|
|
works: Vec(s64)
|
|
fuels: Vec(s64)
|
|
codes: Vec(LirExecCode)
|
|
entries: Vec(s64)
|
|
uses: Vec(s64)
|
|
defer VecFree(uses)
|
|
defer VecFree(kinds)
|
|
defer VecFree(works)
|
|
defer VecFree(fuels)
|
|
defer VecFree(codes)
|
|
defer VecFree(entries)
|
|
for function_index: cast(s64)0..program.functions.count - 1 {
|
|
function := program.functions[function_index]
|
|
function_plan := plan.functions[function_index]
|
|
base := function_plan.value_base
|
|
plan.functions[function_index].constants = plan.constant_words.count
|
|
if !VecResize(uses, function.values.count) { return .Allocation }
|
|
for value: cast(s64)0..function.values.count - 1 { uses[value] = 0 }
|
|
for block: function.blocks {
|
|
for instruction: block.instructions {
|
|
for operand: instruction.operands { uses[operand] += 1 }
|
|
for edge: instruction.edges { for argument: edge.arguments { uses[argument] += 1 } }
|
|
}
|
|
}
|
|
for block_index: cast(s32)0..cast(s32)function.blocks.count - 1 {
|
|
block := function.blocks[block_index]
|
|
first := plan.block_instruction_bases[function_plan.block_base + block_index]
|
|
count := block.instructions.count
|
|
if !VecResize(kinds, count) || !VecResize(works, count) || !VecResize(fuels, count) ||
|
|
!VecResize(codes, count) || !VecResize(entries, count) { return .Allocation }
|
|
edges := plan.block_edge_bases[function_plan.block_base + block_index]
|
|
for index: cast(s64)0..count - 1 {
|
|
bits: u64
|
|
kind := ExecPlanInstruction(program, plan, base, block.instructions[index],
|
|
plan.transient[first + index] != 0, *codes[index], *works[index], *fuels[index], *bits)
|
|
codes[index].block = block_index
|
|
codes[index].index = cast(s32)index
|
|
codes[index].base = first
|
|
codes[index].cost = works[index]
|
|
if block.instructions[index].edges.count != 0 { codes[index].edge = cast(s32)edges }
|
|
edges += block.instructions[index].edges.count
|
|
if kind == .Constant {
|
|
if !VecPush(plan.constant_words, LirExecConstantWord.{.word = cast(s64)codes[index].result,
|
|
.bits = bits}) { return .Allocation }
|
|
}
|
|
kinds[index] = kind
|
|
}
|
|
// A derivation used only by the Load or Store right after it runs
|
|
// inside that instruction's code.
|
|
for index: cast(s64)0..count - 2 {
|
|
if kinds[index] != .Fast || kinds[index + 1] != .Fast { continue }
|
|
fused := ExecPlanFusedMemory(codes[index].handler, codes[index + 1].handler)
|
|
derived := block.instructions[index].result
|
|
user := block.instructions[index + 1]
|
|
if fused == .Slow || codes[index].flag == 0 || derived == LirNoId ||
|
|
user.operands[0] != derived || uses[derived] != 1 { continue }
|
|
memory := codes[index + 1]
|
|
codes[index].handler = fused
|
|
codes[index].result = memory.result
|
|
codes[index].value = memory.b
|
|
codes[index].w = memory.x
|
|
codes[index].immediate = memory.immediate
|
|
codes[index].flag = memory.flag
|
|
kinds[index + 1] = .Folded
|
|
}
|
|
// A FieldAddress used only as the base of the derivation right
|
|
// after it runs inside that derivation's code.
|
|
for index: cast(s64)0..count - 2 {
|
|
if kinds[index] != .Fast || codes[index].handler != .FieldAddress || codes[index].flag == 0 ||
|
|
kinds[index + 1] != .Fast || codes[index + 1].prefix != 0 { continue }
|
|
next := codes[index + 1].handler
|
|
if !ExecPlanDerivation(next) { continue }
|
|
derived := block.instructions[index].result
|
|
if derived == LirNoId || block.instructions[index + 1].operands[0] != derived ||
|
|
uses[derived] != 1 { continue }
|
|
field := codes[index]
|
|
fused := codes[index + 1]
|
|
fused.prefix = 1
|
|
fused.prefix_type = field.type
|
|
fused.prefix_offset = field.x
|
|
fused.prefix_size = field.size
|
|
fused.a = field.a
|
|
fused.block = field.block
|
|
fused.index = field.index
|
|
fused.cost = field.cost + fused.cost
|
|
codes[index] = fused
|
|
kinds[index + 1] = .Folded
|
|
}
|
|
// Two word Extracts in a row run as one.
|
|
index: s64
|
|
while index + 1 < count {
|
|
if kinds[index] == .Fast && kinds[index + 1] == .Fast &&
|
|
codes[index].handler == .ExtractWord && codes[index + 1].handler == .ExtractWord {
|
|
second := codes[index + 1]
|
|
codes[index].handler = .ExtractWordPair
|
|
codes[index].b = second.result
|
|
codes[index].y = second.x
|
|
codes[index].z = second.size
|
|
codes[index].c = second.flag
|
|
codes[index].extra = second.immediate
|
|
kinds[index + 1] = .Folded
|
|
index += 2
|
|
} else { index += 1 }
|
|
}
|
|
// An Add right before the block's Jump runs inside it.
|
|
if count >= 2 && codes[count - 1].handler == .Jump && kinds[count - 2] == .Fast &&
|
|
codes[count - 2].handler == .Add {
|
|
add := codes[count - 2]
|
|
codes[count - 1].handler = .AddJump
|
|
codes[count - 1].result = add.result
|
|
codes[count - 1].a = add.a
|
|
codes[count - 1].b = add.b
|
|
codes[count - 1].immediate = add.immediate
|
|
kinds[count - 2] = .Folded
|
|
}
|
|
// A compare right before the Branch on its result runs inside it.
|
|
if count >= 2 && codes[count - 1].handler == .Branch && kinds[count - 2] == .Fast {
|
|
compare := block.instructions[count - 2]
|
|
fused := ExecPlanFused(codes[count - 2].handler)
|
|
if fused != .Slow && compare.result != LirNoId &&
|
|
block.instructions[count - 1].operands[0] == compare.result {
|
|
codes[count - 1].handler = fused
|
|
codes[count - 1].result = codes[count - 2].result
|
|
codes[count - 1].a = codes[count - 2].a
|
|
codes[count - 1].b = codes[count - 2].b
|
|
codes[count - 1].size = codes[count - 2].size
|
|
kinds[count - 2] = .Folded
|
|
}
|
|
}
|
|
// Keep each segment's totals far from overflow.
|
|
running_work: s64
|
|
running_fuel: s64
|
|
for index: cast(s64)0..count - 1 {
|
|
if kinds[index] != .Slow &&
|
|
(works[index] > ceiling - running_work || fuels[index] > ceiling - running_fuel) {
|
|
kinds[index] = .Slow
|
|
codes[index].handler = .Slow
|
|
}
|
|
if kinds[index] == .Slow { running_work = 0; running_fuel = 0 }
|
|
else { running_work += works[index]; running_fuel += fuels[index] }
|
|
}
|
|
for index: cast(s64)0..count - 1 {
|
|
entries[index] = -1
|
|
if kinds[index] == .Fast || kinds[index] == .Slow {
|
|
entries[index] = plan.code.count
|
|
handler := codes[index].handler
|
|
if kinds[index] == .Fast && codes[index].flag == 0 && (handler == .FieldAddress ||
|
|
handler == .ElementIndex || handler == .ElementView || handler == .ElementSlice) {
|
|
codes[index].memo = cast(s32)plan.derived_count
|
|
plan.derived_count += 1
|
|
}
|
|
if !VecPush(plan.code, codes[index]) { return .Allocation }
|
|
}
|
|
}
|
|
at: s64
|
|
while at < count {
|
|
if kinds[at] == .Slow {
|
|
plan.segment_code[first + at] = entries[at]
|
|
plan.segment_work[first + at] = 0
|
|
plan.segment_fuel[first + at] = 0
|
|
at += 1
|
|
continue
|
|
}
|
|
end := at
|
|
work: s64
|
|
fuel: s64
|
|
while end < count && kinds[end] != .Slow {
|
|
work += works[end]
|
|
fuel += fuels[end]
|
|
end += 1
|
|
}
|
|
next := at
|
|
while next < count && entries[next] < 0 { next += 1 }
|
|
if next >= count { return .InvalidProgram }
|
|
plan.segment_code[first + at] = entries[next]
|
|
plan.segment_work[first + at] = work
|
|
plan.segment_fuel[first + at] = fuel
|
|
for index: at..end - 1 {
|
|
if entries[index] >= 0 {
|
|
plan.code[entries[index]].rest_work = work
|
|
plan.code[entries[index]].rest_fuel = fuel
|
|
}
|
|
work -= works[index]
|
|
fuel -= fuels[index]
|
|
}
|
|
at = end
|
|
}
|
|
}
|
|
plan.functions[function_index].constant_count =
|
|
plan.constant_words.count - plan.functions[function_index].constants
|
|
for block_index: cast(s64)0..function.blocks.count - 1 {
|
|
block_at := function_plan.block_base + block_index
|
|
if !ExecPlanEdges(plan, function, plan.functions[function_index], function.blocks[block_index],
|
|
plan.block_edge_bases[block_at]) { return .InvalidProgram }
|
|
}
|
|
}
|
|
return .None
|
|
}
|
|
|
|
ExecInstructionOrigin :: (instance: *LirExecInstance, frame: LirExecFrame) -> s32 {
|
|
function := instance.plan.program.functions[frame.function]
|
|
if frame.block < 0 || frame.block >= function.blocks.count { return function.origin }
|
|
block := function.blocks[frame.block]
|
|
if frame.instruction < 0 || frame.instruction >= block.instructions.count { return function.origin }
|
|
origin := block.instructions[frame.instruction].origin
|
|
return ifx origin != LirNoId then origin else function.origin
|
|
}
|
|
|
|
ExecFail :: (instance: *LirExecInstance, problem: LirExecProblem, trap: u64 = 0) -> bool #cold {
|
|
if instance.failure.problem != .None { return false }
|
|
result := ExecResult(problem)
|
|
result.trap = trap
|
|
result.work_remaining = instance.work_remaining
|
|
result.fuel_remaining = instance.fuel_remaining
|
|
if instance.frames.count != 0 {
|
|
frame := instance.frames[instance.frames.count - 1]
|
|
result.function = frame.function
|
|
result.block = frame.block
|
|
result.instruction = frame.instruction
|
|
result.origin = ExecInstructionOrigin(instance, frame)
|
|
}
|
|
instance.failure = result
|
|
return false
|
|
}
|
|
|
|
ExecInitialLocation :: (instance: *LirExecInstance, function_id: s32) {
|
|
if instance.failure.problem == .None || instance.failure.function != LirNoId ||
|
|
function_id < 0 || function_id >= instance.plan.program.functions.count { return }
|
|
function := instance.plan.program.functions[function_id]
|
|
instance.failure.function = function_id
|
|
instance.failure.block = function.entry
|
|
instance.failure.instruction = 0
|
|
instruction := function.blocks[function.entry].instructions[0]
|
|
instance.failure.origin = ifx instruction.origin != LirNoId then instruction.origin else function.origin
|
|
}
|
|
|
|
ExecSpend :: (instance: *LirExecInstance, count: s64) -> bool #inline {
|
|
if count < 0 || count > instance.work_remaining { return ExecFail(instance, .WorkLimit) }
|
|
instance.work_remaining -= count
|
|
return true
|
|
}
|
|
|
|
ExecCopyCost :: (count: s64) -> s64 {
|
|
// A shift rather than a checked division for the sizes copies have.
|
|
if count >= 0 { return 1 + ((count + 7) >> 3) }
|
|
return 1 + (count + 7) / 8
|
|
}
|
|
|
|
ExecFrameValueOffset :: (instance: *LirExecInstance, frame_index: s64, value: s32) -> s64 {
|
|
frame := instance.frames[frame_index]
|
|
return frame.base + instance.plan.value_offsets[frame.value_base + value]
|
|
}
|
|
|
|
ExecFrameValueWord :: (instance: *LirExecInstance, frame_index: s64, value: s32) -> s64 {
|
|
frame := instance.frames[frame_index]
|
|
return frame.word_base + instance.plan.value_words[frame.value_base + value]
|
|
}
|
|
|
|
ExecValueIsWord :: (instance: *LirExecInstance, frame_index: s64, value: s32) -> bool {
|
|
frame := instance.frames[frame_index]
|
|
return instance.plan.value_words[frame.value_base + value] >= 0
|
|
}
|
|
|
|
ExecValueSize :: (instance: *LirExecInstance, frame_index: s64, value: s32) -> s64 {
|
|
frame := instance.frames[frame_index]
|
|
return instance.plan.value_sizes[frame.value_base + value]
|
|
}
|
|
|
|
ExecValueType :: (instance: *LirExecInstance, value: s32) -> LirType #inline {
|
|
return instance.plan.program.types[
|
|
instance.plan.value_types[instance.current_value_base + value]]
|
|
}
|
|
|
|
// Values are read without a definedness check: the verifier proves every
|
|
// use is dominated by its definition and has the operand type it needs.
|
|
// Values from outside the plan (arguments, host results, global images)
|
|
// are checked where they come in.
|
|
ExecSlotBits :: (instance: *LirExecInstance, value: s32) -> u64 #inline {
|
|
word := instance.plan.value_words[instance.current_value_base + value]
|
|
if word < 0 {
|
|
unused ExecFail(instance, .Type)
|
|
return 0
|
|
}
|
|
return instance.words[instance.current_word_base + word]
|
|
}
|
|
|
|
ExecIndexBits :: (instance: *LirExecInstance, value: s32) -> u64 {
|
|
bits := ExecSlotBits(instance, value)
|
|
type := ExecValueType(instance, value)
|
|
if type.is_signed && ExecSigned(bits, type.bits) < 0 { unused ExecFail(instance, .Type) }
|
|
return bits
|
|
}
|
|
|
|
ExecWriteSlotBits :: (instance: *LirExecInstance, value: s32, bits: u64) #inline {
|
|
at := instance.current_value_base + value
|
|
word := instance.plan.value_words[at]
|
|
if word < 0 {
|
|
unused ExecFail(instance, .Type)
|
|
return
|
|
}
|
|
canonical := instance.plan.value_canonical[at]
|
|
if canonical == 1 { bits = cast(u64)(bits != 0) }
|
|
else if canonical == 2 { bits &= instance.plan.value_masks[at] }
|
|
instance.words[instance.current_word_base + word] = bits
|
|
}
|
|
|
|
ExecCopyStorage :: (instance: *LirExecInstance, source: s64, destination: s64, count: s64) -> bool {
|
|
if !ExecSpend(instance, ExecCopyCost(count)) { return false }
|
|
if source == destination { return true }
|
|
for index: cast(s64)0..count - 1 { instance.storage[destination + index] = instance.storage[source + index] }
|
|
return true
|
|
}
|
|
|
|
ExecCopyValueToStorage :: (instance: *LirExecInstance, frame_index: s64,
|
|
source: s32, destination: s64) -> bool {
|
|
size := ExecValueSize(instance, frame_index, source)
|
|
if ExecValueIsWord(instance, frame_index, source) {
|
|
if !ExecSpend(instance, ExecCopyCost(size)) { return false }
|
|
ExecWriteBits(instance.storage[:], destination, size,
|
|
instance.words[ExecFrameValueWord(instance, frame_index, source)])
|
|
return true
|
|
}
|
|
return ExecCopyStorage(instance, ExecFrameValueOffset(instance, frame_index, source),
|
|
destination, size)
|
|
}
|
|
|
|
ExecCopyStorageToValue :: (instance: *LirExecInstance, source: s64,
|
|
frame_index: s64, destination: s32) -> bool {
|
|
size := ExecValueSize(instance, frame_index, destination)
|
|
if ExecValueIsWord(instance, frame_index, destination) {
|
|
if !ExecSpend(instance, ExecCopyCost(size)) { return false }
|
|
ExecWriteSlotBits(instance, destination,
|
|
ExecReadBits(instance.storage[:], source, size))
|
|
return instance.failure.problem == .None
|
|
}
|
|
if !ExecCopyStorage(instance, source,
|
|
ExecFrameValueOffset(instance, frame_index, destination), size) { return false }
|
|
return true
|
|
}
|
|
|
|
ExecCopyValue :: (instance: *LirExecInstance, source_frame: s64, source: s32,
|
|
destination_frame: s64, destination: s32) -> bool {
|
|
size := ExecValueSize(instance, source_frame, source)
|
|
source_word := ExecValueIsWord(instance, source_frame, source)
|
|
if source_word != ExecValueIsWord(instance, destination_frame, destination) {
|
|
return ExecFail(instance, .Type)
|
|
}
|
|
if source_word {
|
|
if !ExecSpend(instance, ExecCopyCost(size)) { return false }
|
|
instance.words[ExecFrameValueWord(instance, destination_frame, destination)] =
|
|
instance.words[ExecFrameValueWord(instance, source_frame, source)]
|
|
} else if !ExecCopyStorage(instance, ExecFrameValueOffset(instance, source_frame, source),
|
|
ExecFrameValueOffset(instance, destination_frame, destination), size) { return false }
|
|
return true
|
|
}
|
|
|
|
ExecCopySlot :: (instance: *LirExecInstance, frame_index: s64, source: s32, destination: s32) -> bool {
|
|
return ExecCopyValue(instance, frame_index, source, frame_index, destination)
|
|
}
|
|
|
|
ExecMember :: (instance: *LirExecInstance, type_id: s32, member: u64, offset: *s64, member_type: *s32) -> bool {
|
|
type := instance.plan.program.types[type_id]
|
|
if type.kind == .Array {
|
|
if member >= cast(u64)type.count { return ExecFail(instance, .Type) }
|
|
<<member_type = type.element
|
|
<<offset = cast(s64)member * instance.plan.type_sizes[type.element]
|
|
return true
|
|
}
|
|
if type.kind != .Record || member >= cast(u64)type.fields.count { return ExecFail(instance, .Type) }
|
|
result: s64
|
|
for index: cast(s64)0..cast(s64)member - 1 {
|
|
if !ExecSpend(instance, 1) { return false }
|
|
result += instance.plan.type_sizes[type.fields[index]]
|
|
}
|
|
<<member_type = type.fields[cast(s64)member]
|
|
<<offset = result
|
|
return true
|
|
}
|
|
|
|
// A table holds at most this many entries, and a slot is reused at most
|
|
// ExecAddressVersions times before it is retired.
|
|
ExecAddressSlots :: 2097151
|
|
ExecAddressVersions :: 268435455
|
|
|
|
// A pointer's bits: the instance's identity (its low 16 bits), the slot's
|
|
// version, and one more than the slot. Zero is the null pointer.
|
|
ExecAddressToken :: (identity: u32, index: s64, version: u64 = 0) -> u64 {
|
|
return (cast(u64)(identity & 65535) << cast(u64)48) | (version << cast(u64)22) | cast(u64)(index + 1)
|
|
}
|
|
|
|
ExecFindAddress :: (instance: *LirExecInstance, token: u64) -> s32 {
|
|
if token == 0 { return -1 }
|
|
low := token & cast(u64)4194303
|
|
if low == 0 { return -1 }
|
|
index := cast(s64)(low - cast(u64)1)
|
|
if index >= instance.addresses.count || instance.addresses[index].token != token { return -1 }
|
|
return cast(s32)index
|
|
}
|
|
|
|
ExecAddressHash :: (address: LirExecAddress) -> u64 {
|
|
hash := cast(u64)address.offset * cast(u64)0x9E3779B97F4A7C15
|
|
hash = (hash ^ cast(u64)address.extent) * cast(u64)0xC2B2AE3D27D4EB4F
|
|
hash = (hash ^ cast(u64)(address.frame + 1)) * cast(u64)0x9E3779B97F4A7C15
|
|
hash = (hash ^ address.generation) * cast(u64)0xC2B2AE3D27D4EB4F
|
|
hash = (hash ^ cast(u64)(address.global + 1)) * cast(u64)0x9E3779B97F4A7C15
|
|
hash = (hash ^ cast(u64)address.type) * cast(u64)0xC2B2AE3D27D4EB4F
|
|
if address.owned { hash = ~hash }
|
|
return hash ^ (hash >> cast(u64)29)
|
|
}
|
|
|
|
// Two addresses are one when they name the same bytes as the same type.
|
|
ExecAddressSame :: (left: LirExecAddress, right: LirExecAddress) -> bool {
|
|
return left.frame == right.frame && left.generation == right.generation &&
|
|
left.global == right.global && left.offset == right.offset && left.extent == right.extent &&
|
|
left.type == right.type && left.owned == right.owned
|
|
}
|
|
|
|
// The table entry equal to `address`, or -1.
|
|
ExecAddressLookup :: (instance: *LirExecInstance, address: LirExecAddress) -> s64 {
|
|
if instance.address_slots.count == 0 { return -1 }
|
|
mask := instance.address_slots.count - 1
|
|
slot := cast(s64)(ExecAddressHash(address) & cast(u64)mask)
|
|
entry := instance.address_slots[slot]
|
|
while entry != 0 {
|
|
if entry > 0 && ExecAddressSame(instance.addresses[entry - 1], address) { return cast(s64)entry - 1 }
|
|
slot = (slot + 1) & mask
|
|
entry = instance.address_slots[slot]
|
|
}
|
|
return -1
|
|
}
|
|
|
|
// Rebuilds the index from the live entries, at most a quarter full.
|
|
ExecAddressReindex :: (instance: *LirExecInstance) -> bool {
|
|
live: s64
|
|
for index: cast(s64)0..instance.addresses.count - 1 {
|
|
if instance.addresses[index].token != 0 && !ExecTransientIndex(instance, index) { live += 1 }
|
|
}
|
|
// The table never shrinks: a rebuild in place only drops removed entries.
|
|
capacity: s64 = 64
|
|
while capacity < (live + 1) * 4 { capacity *= 2 }
|
|
if capacity < instance.address_slots.count { capacity = instance.address_slots.count }
|
|
if !VecResizeBounded(instance.address_slots, capacity, capacity) { return false }
|
|
for index: cast(s64)0..capacity - 1 { instance.address_slots[index] = 0 }
|
|
mask := capacity - 1
|
|
for index: cast(s64)0..instance.addresses.count - 1 {
|
|
if instance.addresses[index].token == 0 || ExecTransientIndex(instance, index) { continue }
|
|
slot := cast(s64)(ExecAddressHash(instance.addresses[index]) & cast(u64)mask)
|
|
while instance.address_slots[slot] != 0 { slot = (slot + 1) & mask }
|
|
instance.address_slots[slot] = cast(s32)(index + 1)
|
|
}
|
|
instance.address_used = live
|
|
return true
|
|
}
|
|
|
|
ExecAddressIndexAdd :: (instance: *LirExecInstance, index: s64) -> bool {
|
|
// Removed entries count as used until a rebuild drops them.
|
|
if (instance.address_used + 1) * 2 > instance.address_slots.count { return ExecAddressReindex(instance) }
|
|
mask := instance.address_slots.count - 1
|
|
slot := cast(s64)(ExecAddressHash(instance.addresses[index]) & cast(u64)mask)
|
|
while instance.address_slots[slot] > 0 { slot = (slot + 1) & mask }
|
|
if instance.address_slots[slot] == 0 { instance.address_used += 1 }
|
|
instance.address_slots[slot] = cast(s32)(index + 1)
|
|
return true
|
|
}
|
|
|
|
ExecAddressIndexRemove :: (instance: *LirExecInstance, index: s64) {
|
|
if instance.address_slots.count == 0 { return }
|
|
mask := instance.address_slots.count - 1
|
|
slot := cast(s64)(ExecAddressHash(instance.addresses[index]) & cast(u64)mask)
|
|
entry := instance.address_slots[slot]
|
|
while entry != 0 {
|
|
if cast(s64)entry == index + 1 {
|
|
instance.address_slots[slot] = -1
|
|
// A removed slot right before an empty one ends no probe, so it
|
|
// and the removed slots before it are empty again: frames that
|
|
// come and go leave no trail for lookups to walk.
|
|
while instance.address_slots[slot] == -1 && instance.address_slots[(slot + 1) & mask] == 0 {
|
|
instance.address_slots[slot] = 0
|
|
instance.address_used -= 1
|
|
slot = (slot - 1) & mask
|
|
}
|
|
return
|
|
}
|
|
slot = (slot + 1) & mask
|
|
entry = instance.address_slots[slot]
|
|
}
|
|
}
|
|
|
|
// Makes a table entry for `address`: a slot that was given back, under its
|
|
// next version, or a new slot. An address into a frame or a heap block joins
|
|
// that frame's or block's chain and is given back when the frame returns or
|
|
// the block dies. Returns the entry's index, or -1 with the failure recorded.
|
|
ExecNewAddress :: (instance: *LirExecInstance, address: LirExecAddress) -> s64 {
|
|
index: s64
|
|
version: u64
|
|
if instance.address_free.count > 0 {
|
|
index = instance.address_free[instance.address_free.count - 1]
|
|
unused VecResize(instance.address_free, instance.address_free.count - 1)
|
|
version = instance.addresses[index].version + 1
|
|
} else {
|
|
index = instance.addresses.count
|
|
if index >= instance.limits.addresses || index >= ExecAddressSlots {
|
|
unused ExecFail(instance, .AddressLimit)
|
|
return -1
|
|
}
|
|
if !VecPush(instance.addresses, LirExecAddress.{}) { unused ExecFail(instance, .Allocation); return -1 }
|
|
}
|
|
added := address
|
|
added.version = version
|
|
added.token = ExecAddressToken(instance.identity, index, version)
|
|
added.next = 0
|
|
if added.frame >= 0 {
|
|
added.next = instance.frames[added.frame].addresses
|
|
instance.frames[added.frame].addresses = index + 1
|
|
} else if added.heap != 0 {
|
|
added.next = instance.heap_blocks[added.heap - 1].addresses
|
|
instance.heap_blocks[added.heap - 1].addresses = index + 1
|
|
}
|
|
instance.addresses[index] = added
|
|
if !ExecAddressIndexAdd(instance, index) { unused ExecFail(instance, .Allocation); return -1 }
|
|
return index
|
|
}
|
|
|
|
// Gives back every entry of a chain. Its frame returned or its heap block
|
|
// died, so no valid pointer names these entries any more.
|
|
ExecReleaseAddresses :: (instance: *LirExecInstance, head: s64) {
|
|
at := head
|
|
while at != 0 {
|
|
index := at - 1
|
|
at = instance.addresses[index].next
|
|
ExecAddressIndexRemove(instance, index)
|
|
instance.addresses[index].token = 0
|
|
instance.addresses[index].next = 0
|
|
if instance.addresses[index].version < ExecAddressVersions { unused VecPush(instance.address_free, index) }
|
|
}
|
|
}
|
|
|
|
// The token of the table entry equal to `address`, made when it is new.
|
|
// Deriving the same address again gives the same token, so pointers compare
|
|
// equal exactly when they name the same bytes as the same type.
|
|
ExecInternAddress :: (instance: *LirExecInstance, address: LirExecAddress) -> u64 {
|
|
if !ExecSpend(instance, 1) { return 0 }
|
|
index := ExecAddressLookup(instance, address)
|
|
if index < 0 { index = ExecNewAddress(instance, address) }
|
|
if index < 0 { return 0 }
|
|
return instance.addresses[index].token
|
|
}
|
|
|
|
// Transient addresses. A derivation whose result is only the address of a
|
|
// Load or Store, or the base of another derivation, later in its own block,
|
|
// with no call or resize between, makes no lasting table entry: it takes the
|
|
// next of a few entries kept for this, in turn, with a new version, so its
|
|
// token lives until that entry is taken again. The plan proves the uses come
|
|
// first. Its checks and its work charge are an interned address's.
|
|
ExecTransientSlots :: 256;
|
|
|
|
ExecTransientIndex :: (instance: *LirExecInstance, index: s64) -> bool {
|
|
return instance.transient_count != 0 && index >= instance.transient_base &&
|
|
index < instance.transient_base + instance.transient_count
|
|
}
|
|
|
|
ExecTransient :: (instance: *LirExecInstance, address: LirExecAddress) -> u64 {
|
|
if !ExecSpend(instance, 1) { return 0 }
|
|
if instance.transient_count == 0 {
|
|
base := instance.addresses.count
|
|
if base + ExecTransientSlots > instance.limits.addresses || base + ExecTransientSlots > ExecAddressSlots {
|
|
unused ExecFail(instance, .AddressLimit)
|
|
return 0
|
|
}
|
|
for at: 1..ExecTransientSlots {
|
|
if !VecPush(instance.addresses, LirExecAddress.{}) { unused ExecFail(instance, .Allocation); return 0 }
|
|
}
|
|
instance.transient_base = base
|
|
instance.transient_count = ExecTransientSlots
|
|
}
|
|
index := instance.transient_base + instance.transient_next
|
|
instance.transient_next += 1
|
|
if instance.transient_next == ExecTransientSlots { instance.transient_next = 0 }
|
|
entry := address
|
|
entry.version = (instance.addresses[index].version + 1) & cast(u64)268435455
|
|
entry.token = ExecAddressToken(instance.identity, index, entry.version)
|
|
entry.next = 0
|
|
instance.addresses[index] = entry
|
|
return entry.token
|
|
}
|
|
|
|
ExecDeriveToken :: (instance: *LirExecInstance, address: LirExecAddress, transient: bool) -> u64 {
|
|
if transient { return ExecTransient(instance, address) }
|
|
return ExecInternAddress(instance, address)
|
|
}
|
|
|
|
ExecTransientBarrier :: (op: LirOp) -> bool {
|
|
return op == .Call || op == .CallIndirect || op == .HostCall || op == .Resize
|
|
}
|
|
|
|
// Marks the transient derivations of `function`, whose instructions start at
|
|
// plan instruction `first`.
|
|
ExecPlanTransients :: (plan: *LirExecPlan, function: LirFunction, first: s64) -> bool {
|
|
count := function.values.count
|
|
defined_in: Vec(s32)
|
|
defined_at: Vec(s64)
|
|
last_use: Vec(s64)
|
|
usable: Vec(u8)
|
|
defer VecFree(defined_in)
|
|
defer VecFree(defined_at)
|
|
defer VecFree(last_use)
|
|
defer VecFree(usable)
|
|
if !VecResizeBounded(defined_in, count, count) || !VecResizeBounded(defined_at, count, count) ||
|
|
!VecResizeBounded(last_use, count, count) || !VecResizeBounded(usable, count, count) { return false }
|
|
for value: cast(s64)0..count - 1 { defined_in[value] = -1 }
|
|
at := first
|
|
for block_index: cast(s32)0..cast(s32)function.blocks.count - 1 {
|
|
block := function.blocks[block_index]
|
|
for index: cast(s64)0..block.instructions.count - 1 {
|
|
instruction := block.instructions[index]
|
|
plan.transient[at + index] = 0
|
|
if (instruction.op == .FieldAddress || instruction.op == .ElementAddress) && instruction.result != LirNoId {
|
|
defined_in[instruction.result] = block_index
|
|
defined_at[instruction.result] = at + index
|
|
last_use[instruction.result] = at + index
|
|
usable[instruction.result] = 1
|
|
}
|
|
}
|
|
at += block.instructions.count
|
|
}
|
|
at = first
|
|
for block_index: cast(s32)0..cast(s32)function.blocks.count - 1 {
|
|
block := function.blocks[block_index]
|
|
for index: cast(s64)0..block.instructions.count - 1 {
|
|
instruction := block.instructions[index]
|
|
for operand: cast(s64)0..instruction.operands.count - 1 {
|
|
value := instruction.operands[operand]
|
|
if defined_in[value] < 0 { continue }
|
|
// An empty slice is its base's own token, so a slice may keep it.
|
|
address_use := operand == 0 && (instruction.op == .Load || instruction.op == .Store ||
|
|
instruction.op == .FieldAddress ||
|
|
instruction.op == .ElementAddress && instruction.operands.count != 4)
|
|
if defined_in[value] != block_index || defined_at[value] >= at + index || !address_use {
|
|
usable[value] = 0
|
|
}
|
|
if at + index > last_use[value] { last_use[value] = at + index }
|
|
}
|
|
for edge: instruction.edges {
|
|
for value: edge.arguments { if defined_in[value] >= 0 { usable[value] = 0 } }
|
|
}
|
|
}
|
|
at += block.instructions.count
|
|
}
|
|
for value: cast(s64)0..count - 1 {
|
|
if defined_in[value] < 0 || usable[value] == 0 { continue }
|
|
from := defined_at[value]
|
|
to := last_use[value]
|
|
// Every derivation between takes an entry too; the uses must come
|
|
// before the entry comes round again.
|
|
if to - from >= ExecTransientSlots { continue }
|
|
clear := true
|
|
for between: from + 1..to - 1 {
|
|
if ExecTransientBarrier(plan.instructions[between].op) { clear = false; break }
|
|
}
|
|
if clear { plan.transient[from] = 1 }
|
|
}
|
|
return true
|
|
}
|
|
|
|
ExecFieldAddress :: (instance: *LirExecInstance, parent: s32, member: u64, target_type: s32,
|
|
transient: bool) -> u64 {
|
|
base := instance.addresses[parent]
|
|
member_offset: s64
|
|
member_type: s32
|
|
if !ExecMember(instance, base.type, member, *member_offset, *member_type) ||
|
|
member_type != target_type { unused ExecFail(instance, .Type); return 0 }
|
|
offset := base.offset + member_offset
|
|
parent_type := instance.plan.program.types[base.type]
|
|
extent := ifx parent_type.kind == .Array then base.extent - member_offset else instance.plan.type_sizes[target_type]
|
|
if extent < instance.plan.type_sizes[target_type] { unused ExecFail(instance, .Pointer); return 0 }
|
|
child_frame := cast(s64)-1
|
|
child_generation: u64
|
|
child_global := base.global
|
|
if base.frame >= 0 {
|
|
if base.frame >= instance.frames.count ||
|
|
instance.frames[base.frame].generation != base.generation {
|
|
unused ExecFail(instance, .Pointer); return 0
|
|
}
|
|
child_frame = base.frame
|
|
child_generation = base.generation
|
|
child_global = -1
|
|
} else if base.heap != 0 {
|
|
child_generation = base.generation
|
|
}
|
|
return ExecDeriveToken(instance, .{.global = child_global, .frame = child_frame,
|
|
.generation = child_generation, .offset = offset, .extent = extent, .type = target_type,
|
|
.owned = base.owned, .writable = base.writable, .heap = base.heap}, transient)
|
|
}
|
|
|
|
ExecElementAddress :: (instance: *LirExecInstance, parent: s32, index: u64,
|
|
count: u64, target_type: s32, transient: bool) -> u64 {
|
|
base := instance.addresses[parent]
|
|
size := instance.plan.type_sizes[target_type]
|
|
if base.type != target_type || index >= count ||
|
|
count > cast(u64)9223372036854775807 || size < 0 ||
|
|
size != 0 && count > cast(u64)(base.extent / size) {
|
|
unused ExecFail(instance, .Pointer)
|
|
return 0
|
|
}
|
|
member_offset := cast(s64)index * size
|
|
offset := base.offset + member_offset
|
|
extent := base.extent - member_offset
|
|
return ExecDeriveToken(instance, .{.global = base.global, .frame = base.frame,
|
|
.generation = base.generation, .offset = offset, .extent = extent, .type = target_type,
|
|
.owned = base.owned, .writable = base.writable, .heap = base.heap}, transient)
|
|
}
|
|
|
|
ExecSliceAddress :: (instance: *LirExecInstance, parent: s32, low: u64,
|
|
high: u64, count: u64, target_type: s32, transient: bool) -> u64 {
|
|
base := instance.addresses[parent]
|
|
size := instance.plan.type_sizes[target_type]
|
|
if base.type != target_type || low > high || high > count ||
|
|
count > cast(u64)9223372036854775807 || size <= 0 ||
|
|
count > cast(u64)(base.extent / size) {
|
|
unused ExecFail(instance, .Pointer)
|
|
return 0
|
|
}
|
|
if low == high { return base.token }
|
|
return ExecElementAddress(instance, parent, low, count, target_type, transient)
|
|
}
|
|
|
|
ExecResizeStorage :: (instance: *LirExecInstance, count: s64) -> bool {
|
|
word_bytes := instance.words.count * 8
|
|
available := instance.limits.value_bytes - instance.globals.count -
|
|
instance.result_bytes.count - instance.owned.count - word_bytes
|
|
if count < 0 || available < 0 || count > available { return ExecFail(instance, .ValueBytes) }
|
|
if !VecResizeBounded(instance.storage, count, available) { return ExecFail(instance, .Allocation) }
|
|
return true
|
|
}
|
|
|
|
ExecResizeWords :: (instance: *LirExecInstance, count: s64) -> bool {
|
|
available := instance.limits.value_bytes - instance.globals.count -
|
|
instance.result_bytes.count - instance.storage.count - instance.owned.count
|
|
if count < 0 || available < 0 || count > available / 8 {
|
|
return ExecFail(instance, .ValueBytes)
|
|
}
|
|
if !VecResizeBounded(instance.words, count, available / 8) {
|
|
return ExecFail(instance, .Allocation)
|
|
}
|
|
return true
|
|
}
|
|
|
|
ExecPushFrame :: (instance: *LirExecInstance, function_id: s32, caller: s64,
|
|
operands: []s32, return_value: s32, arguments: []LirExecArgument) -> bool {
|
|
if function_id < 0 || function_id >= instance.plan.program.functions.count { return ExecFail(instance, .Calling) }
|
|
function := *instance.plan.program.functions[function_id]
|
|
if operands.count != 0 && arguments.count != 0 ||
|
|
operands.count == 0 && arguments.count != function.parameters.count ||
|
|
operands.count != 0 && operands.count != function.parameters.count { return ExecFail(instance, .Calling) }
|
|
if instance.frames.count >= instance.limits.frames {
|
|
unused ExecFail(instance, .FrameLimit)
|
|
if caller < 0 { ExecInitialLocation(instance, function_id) }
|
|
return false
|
|
}
|
|
if function.values.count > instance.limits.values - instance.live_values {
|
|
unused ExecFail(instance, .ValueLimit)
|
|
if caller < 0 { ExecInitialLocation(instance, function_id) }
|
|
return false
|
|
}
|
|
plan := *instance.plan.functions[function_id]
|
|
base := instance.storage.count
|
|
word_base := instance.words.count
|
|
if !ExecResizeStorage(instance, base + plan.frame_bytes) {
|
|
if caller < 0 { ExecInitialLocation(instance, function_id) }
|
|
return false
|
|
}
|
|
if !ExecResizeWords(instance, word_base + plan.word_count) {
|
|
if caller < 0 { ExecInitialLocation(instance, function_id) }
|
|
return false
|
|
}
|
|
instance.frame_epoch += 1
|
|
frame := LirExecFrame.{.function = function_id, .block = function.entry,
|
|
.return_value = return_value, .base = base, .word_base = word_base,
|
|
.value_base = plan.value_base,
|
|
.instruction_base = instance.plan.block_instruction_bases[plan.block_base + function.entry],
|
|
.generation = instance.frame_epoch}
|
|
if !VecPush(instance.frames, frame) {
|
|
unused ExecFail(instance, .Allocation)
|
|
if caller < 0 { ExecInitialLocation(instance, function_id) }
|
|
return false
|
|
}
|
|
instance.current_value_base = frame.value_base
|
|
instance.current_word_base = frame.word_base
|
|
instance.live_values += function.values.count
|
|
frame_index := instance.frames.count - 1
|
|
// The words of constants, null and function addresses hold their values
|
|
// from the start: those instructions have no code (ExecPlanCode).
|
|
for at: plan.constants..plan.constants + plan.constant_count - 1 {
|
|
constant := instance.plan.constant_words[at]
|
|
instance.words[word_base + constant.word] = constant.bits
|
|
}
|
|
entry := *function.blocks[function.entry]
|
|
for index: cast(s64)0..function.parameters.count - 1 {
|
|
destination := entry.parameters[index]
|
|
type_id := function.parameters[index]
|
|
size := instance.plan.type_sizes[type_id]
|
|
if operands.count != 0 {
|
|
source := operands[index]
|
|
if !ExecCopyValue(instance, caller, source, frame_index, destination) { return false }
|
|
} else {
|
|
argument := arguments[index]
|
|
if argument.type != type_id { return ExecFail(instance, .Type) }
|
|
type := instance.plan.program.types[type_id]
|
|
composite := type.kind == .Record || type.kind == .Array
|
|
if composite {
|
|
destination_at := ExecFrameValueOffset(instance, frame_index, destination)
|
|
if argument.bytes.count != size || !ExecSpend(instance, ExecCopyCost(size)) { return false }
|
|
for byte: cast(s64)0..size - 1 { instance.storage[destination_at + byte] = argument.bytes[byte] }
|
|
} else {
|
|
if argument.bytes.count != 0 { return ExecFail(instance, .Type) }
|
|
ExecWriteSlotBits(instance, destination, argument.bits)
|
|
if instance.failure.problem != .None { return false }
|
|
}
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
ExecPopFrame :: (instance: *LirExecInstance) {
|
|
frame := *instance.frames[instance.frames.count - 1]
|
|
ExecReleaseAddresses(instance, frame.addresses)
|
|
instance.live_values -= instance.plan.program.functions[frame.function].values.count
|
|
unused VecResize(instance.storage, frame.base)
|
|
unused VecResize(instance.words, frame.word_base)
|
|
unused VecPop(instance.frames)
|
|
if instance.frames.count == 0 {
|
|
instance.current_value_base = 0
|
|
instance.current_word_base = 0
|
|
} else {
|
|
current := instance.frames[instance.frames.count - 1]
|
|
instance.current_value_base = current.value_base
|
|
instance.current_word_base = current.word_base
|
|
}
|
|
}
|
|
|
|
ExecValuesSameLocation :: (instance: *LirExecInstance, frame_index: s64,
|
|
left: s32, right: s32) -> bool {
|
|
left_word := ExecValueIsWord(instance, frame_index, left)
|
|
if left_word != ExecValueIsWord(instance, frame_index, right) { return false }
|
|
if left_word {
|
|
return ExecFrameValueWord(instance, frame_index, left) ==
|
|
ExecFrameValueWord(instance, frame_index, right)
|
|
}
|
|
return ExecFrameValueOffset(instance, frame_index, left) ==
|
|
ExecFrameValueOffset(instance, frame_index, right) &&
|
|
ExecValueSize(instance, frame_index, left) == ExecValueSize(instance, frame_index, right)
|
|
}
|
|
|
|
ExecEdge :: (instance: *LirExecInstance, frame_index: s64,
|
|
edge: *LirEdge, direct_safe: bool) -> bool {
|
|
frame := *instance.frames[frame_index]
|
|
plan := *instance.plan.functions[frame.function]
|
|
target := *instance.plan.program.functions[frame.function].blocks[edge.block]
|
|
if direct_safe {
|
|
for index: cast(s64)0..target.parameters.count - 1 {
|
|
source := edge.arguments[index]
|
|
destination := target.parameters[index]
|
|
size := ExecValueSize(instance, frame_index, source)
|
|
// Preserve the canonical two-copy work charge even though the
|
|
// proven-safe implementation moves the value only once.
|
|
if ExecValuesSameLocation(instance, frame_index, source, destination) {
|
|
if !ExecSpend(instance, ExecCopyCost(size)) ||
|
|
!ExecSpend(instance, ExecCopyCost(size)) { return false }
|
|
} else if !ExecSpend(instance, ExecCopyCost(size)) ||
|
|
!ExecCopyValue(instance, frame_index, source, frame_index, destination) { return false }
|
|
}
|
|
instance.frames[frame_index].block = edge.block
|
|
instance.frames[frame_index].instruction = 0
|
|
instance.frames[frame_index].instruction_base =
|
|
instance.plan.block_instruction_bases[plan.block_base + edge.block]
|
|
return true
|
|
}
|
|
scratch := frame.base + plan.scratch_offset
|
|
at: s64
|
|
for index: cast(s64)0..edge.arguments.count - 1 {
|
|
source := edge.arguments[index]
|
|
size := ExecValueSize(instance, frame_index, source)
|
|
if !ExecCopyValueToStorage(instance, frame_index, source, scratch + at) { return false }
|
|
at += size
|
|
}
|
|
at = 0
|
|
for index: cast(s64)0..target.parameters.count - 1 {
|
|
destination := target.parameters[index]
|
|
size := ExecValueSize(instance, frame_index, destination)
|
|
if !ExecCopyStorageToValue(instance, scratch + at, frame_index, destination) { return false }
|
|
at += size
|
|
}
|
|
instance.frames[frame_index].block = edge.block
|
|
instance.frames[frame_index].instruction = 0
|
|
instance.frames[frame_index].instruction_base =
|
|
instance.plan.block_instruction_bases[plan.block_base + edge.block]
|
|
return true
|
|
}
|
|
|
|
ExecIntegerBinary :: (instance: *LirExecInstance, frame_index: s64,
|
|
instruction: *LirInstruction, type: LirType) -> bool {
|
|
left := ExecSlotBits(instance, instruction.operands[0]) & ExecMask(type.bits)
|
|
right := ExecSlotBits(instance, instruction.operands[1])
|
|
if instance.failure.problem != .None { return false }
|
|
if instruction.op == .ShiftLeft || instruction.op == .ShiftRight {
|
|
count_type := ExecValueType(instance, instruction.operands[1])
|
|
right &= ExecMask(count_type.bits)
|
|
} else { right &= ExecMask(type.bits) }
|
|
result: u64
|
|
if instruction.op == .Add { result = left + right }
|
|
else if instruction.op == .Subtract { result = left - right }
|
|
else if instruction.op == .Multiply { result = left * right }
|
|
else if instruction.op == .BitAnd { result = left & right }
|
|
else if instruction.op == .BitOr { result = left | right }
|
|
else if instruction.op == .BitXor { result = left ^ right }
|
|
else if instruction.op == .Divide || instruction.op == .Remainder {
|
|
if right == 0 { return ExecFail(instance, .DivideByZero) }
|
|
if type.is_signed {
|
|
signed_left := ExecSigned(left, type.bits)
|
|
signed_right := ExecSigned(right, type.bits)
|
|
minimum := cast(u64)1 << cast(u64)(type.bits - 1)
|
|
if left == minimum && signed_right == -1 {
|
|
result = ifx instruction.op == .Divide then minimum else 0
|
|
} else if instruction.op == .Divide { result = cast(u64)(signed_left / signed_right) }
|
|
else { result = cast(u64)(signed_left % signed_right) }
|
|
} else if instruction.op == .Divide { result = left / right }
|
|
else { result = left % right }
|
|
} else if instruction.op == .ShiftLeft || instruction.op == .ShiftRight {
|
|
count := right
|
|
if count >= cast(u64)type.bits { return ExecFail(instance, .InvalidShift) }
|
|
if instruction.op == .ShiftLeft { result = left << count }
|
|
else {
|
|
result = left >> count
|
|
if type.is_signed && count != 0 && (left & (cast(u64)1 << cast(u64)(type.bits - 1))) != 0 {
|
|
result |= ExecMask(type.bits) ^ (ExecMask(type.bits) >> count)
|
|
}
|
|
}
|
|
} else { return ExecFail(instance, .Unsupported) }
|
|
ExecWriteSlotBits(instance, instruction.result, result)
|
|
return true
|
|
}
|
|
|
|
ExecFloatBinary :: (instance: *LirExecInstance, frame_index: s64,
|
|
instruction: *LirInstruction, type: LirType) -> bool {
|
|
left := ExecFloat(instance.plan, type, ExecSlotBits(instance, instruction.operands[0]))
|
|
right := ExecFloat(instance.plan, type, ExecSlotBits(instance, instruction.operands[1]))
|
|
if instance.failure.problem != .None { return false }
|
|
bits: u64
|
|
if type.bits == 32 {
|
|
a := cast(float32)left
|
|
b := cast(float32)right
|
|
value: float32
|
|
if instruction.op == .Add { value = a + b }
|
|
else if instruction.op == .Subtract { value = a - b }
|
|
else if instruction.op == .Multiply { value = a * b }
|
|
else if instruction.op == .Divide { value = a / b }
|
|
else { return ExecFail(instance, .Unsupported) }
|
|
bits = ExecFloat32Bits(value)
|
|
} else {
|
|
value: float64
|
|
if instruction.op == .Add { value = left + right }
|
|
else if instruction.op == .Subtract { value = left - right }
|
|
else if instruction.op == .Multiply { value = left * right }
|
|
else if instruction.op == .Divide { value = left / right }
|
|
else { return ExecFail(instance, .Unsupported) }
|
|
bits = ExecFloat64Bits(value)
|
|
}
|
|
ExecWriteSlotBits(instance, instruction.result, bits)
|
|
return true
|
|
}
|
|
|
|
ExecCompare :: (instance: *LirExecInstance, frame_index: s64,
|
|
instruction: *LirInstruction, type: LirType) -> bool {
|
|
left := ExecSlotBits(instance, instruction.operands[0])
|
|
right := ExecSlotBits(instance, instruction.operands[1])
|
|
if instance.failure.problem != .None { return false }
|
|
answer: bool
|
|
if type.kind == .Float {
|
|
a := ExecFloat(instance.plan, type, left)
|
|
b := ExecFloat(instance.plan, type, right)
|
|
if instruction.op == .Equal { answer = a == b }
|
|
if instruction.op == .NotEqual { answer = a != b }
|
|
if instruction.op == .Less { answer = a < b }
|
|
if instruction.op == .LessEqual { answer = a <= b }
|
|
if instruction.op == .Greater { answer = a > b }
|
|
if instruction.op == .GreaterEqual { answer = a >= b }
|
|
} else if type.kind == .Integer && type.is_signed {
|
|
a := ExecSigned(left, type.bits)
|
|
b := ExecSigned(right, type.bits)
|
|
if instruction.op == .Equal { answer = a == b }
|
|
if instruction.op == .NotEqual { answer = a != b }
|
|
if instruction.op == .Less { answer = a < b }
|
|
if instruction.op == .LessEqual { answer = a <= b }
|
|
if instruction.op == .Greater { answer = a > b }
|
|
if instruction.op == .GreaterEqual { answer = a >= b }
|
|
} else {
|
|
if type.kind == .Integer { left &= ExecMask(type.bits); right &= ExecMask(type.bits) }
|
|
if instruction.op == .Equal { answer = left == right }
|
|
if instruction.op == .NotEqual { answer = left != right }
|
|
if instruction.op == .Less { answer = left < right }
|
|
if instruction.op == .LessEqual { answer = left <= right }
|
|
if instruction.op == .Greater { answer = left > right }
|
|
if instruction.op == .GreaterEqual { answer = left >= right }
|
|
}
|
|
ExecWriteSlotBits(instance, instruction.result, cast(u64)answer)
|
|
return true
|
|
}
|
|
|
|
ExecConvert :: (instance: *LirExecInstance, frame_index: s64, instruction: *LirInstruction,
|
|
source: LirType, destination: LirType) -> bool {
|
|
bits := ExecSlotBits(instance, instruction.operands[0])
|
|
if instance.failure.problem != .None { return false }
|
|
if instruction.op == .Bitcast {
|
|
ExecWriteSlotBits(instance, instruction.result, bits)
|
|
return true
|
|
}
|
|
result: u64
|
|
if source.kind == .Bool && destination.kind == .Integer { result = cast(u64)(bits != 0) }
|
|
else if source.kind == .Integer && destination.kind == .Bool { result = cast(u64)((bits & ExecMask(source.bits)) != 0) }
|
|
else if source.kind == .Integer && destination.kind == .Integer {
|
|
result = bits & ExecMask(source.bits)
|
|
if source.is_signed && source.bits < 64 && (result & (cast(u64)1 << cast(u64)(source.bits - 1))) != 0 {
|
|
result |= ~ExecMask(source.bits)
|
|
}
|
|
} else if source.kind == .Integer && destination.kind == .Float {
|
|
if destination.bits == 32 {
|
|
value := ifx source.is_signed then cast(float32)ExecSigned(bits, source.bits) else cast(float32)(bits & ExecMask(source.bits))
|
|
result = ExecFloat32Bits(value)
|
|
} else {
|
|
value := ifx source.is_signed then cast(float64)ExecSigned(bits, source.bits) else cast(float64)(bits & ExecMask(source.bits))
|
|
result = ExecFloat64Bits(value)
|
|
}
|
|
} else if source.kind == .Float && destination.kind == .Float {
|
|
value := ExecFloat(instance.plan, source, bits)
|
|
result = ifx destination.bits == 32 then ExecFloat32Bits(cast(float32)value) else ExecFloat64Bits(value)
|
|
} else if source.kind == .Float && destination.kind == .Integer {
|
|
value := ExecFloat(instance.plan, source, bits)
|
|
if !Finite64(value) { return ExecFail(instance, .InvalidConversion) }
|
|
if destination.is_signed {
|
|
bound := ScaleByPowerOfTwo(1.0, destination.bits - 1)
|
|
if value < 0.0 - bound || value >= bound { return ExecFail(instance, .InvalidConversion) }
|
|
result = cast(u64)cast(s64)value
|
|
} else {
|
|
bound := ScaleByPowerOfTwo(1.0, destination.bits)
|
|
if value < 0.0 || value >= bound { return ExecFail(instance, .InvalidConversion) }
|
|
result = cast(u64)value
|
|
}
|
|
} else { return ExecFail(instance, .Unsupported) }
|
|
ExecWriteSlotBits(instance, instruction.result, result)
|
|
return true
|
|
}
|
|
|
|
ExecAggregate :: (instance: *LirExecInstance, frame_index: s64, instruction: *LirInstruction) -> bool {
|
|
destination := ExecFrameValueOffset(instance, frame_index, instruction.result)
|
|
at: s64
|
|
for operand: instruction.operands {
|
|
size := ExecValueSize(instance, frame_index, operand)
|
|
if !ExecCopyValueToStorage(instance, frame_index, operand, destination + at) { return false }
|
|
at += size
|
|
}
|
|
return true
|
|
}
|
|
|
|
ExecExtractInsert :: (instance: *LirExecInstance, frame_index: s64, instruction: *LirInstruction) -> bool {
|
|
frame := instance.frames[frame_index]
|
|
function := instance.plan.program.functions[frame.function]
|
|
aggregate := instruction.operands[0]
|
|
aggregate_type := function.values[aggregate]
|
|
offset: s64
|
|
member_type: s32
|
|
member := instruction.immediate
|
|
expected := ifx instruction.op == .Extract then 1 else 2
|
|
if instruction.operands.count == expected + 1 {
|
|
member = ExecIndexBits(instance, instruction.operands[expected])
|
|
if instance.failure.problem != .None { return false }
|
|
}
|
|
if !ExecMember(instance, aggregate_type, member, *offset, *member_type) { return false }
|
|
if instruction.op == .Extract {
|
|
if !ExecCopyStorageToValue(instance,
|
|
ExecFrameValueOffset(instance, frame_index, aggregate) + offset,
|
|
frame_index, instruction.result) { return false }
|
|
} else {
|
|
if !ExecCopySlot(instance, frame_index, aggregate, instruction.result) { return false }
|
|
replacement := instruction.operands[1]
|
|
if !ExecCopyValueToStorage(instance, frame_index, replacement,
|
|
ExecFrameValueOffset(instance, frame_index, instruction.result) + offset) { return false }
|
|
}
|
|
return true
|
|
}
|
|
|
|
ExecFinishFrame :: (instance: *LirExecInstance, frame_index: s64, instruction: *LirInstruction) -> bool {
|
|
frame := instance.frames[frame_index]
|
|
function := instance.plan.program.functions[frame.function]
|
|
result_type := function.result
|
|
result_size := instance.plan.type_sizes[result_type]
|
|
if frame_index == 0 {
|
|
available := instance.limits.value_bytes - instance.globals.count -
|
|
instance.storage.count - instance.words.count * 8 - instance.owned.count
|
|
if result_size > available { return ExecFail(instance, .ValueBytes) }
|
|
if !VecResizeBounded(instance.result_bytes, result_size,
|
|
instance.limits.value_bytes - instance.globals.count) { return ExecFail(instance, .Allocation) }
|
|
bits: u64
|
|
if result_size != 0 {
|
|
source := instruction.operands[0]
|
|
if !ExecSpend(instance, ExecCopyCost(result_size)) { return false }
|
|
type := instance.plan.program.types[result_type]
|
|
if type.kind == .Record || type.kind == .Array {
|
|
source_at := ExecFrameValueOffset(instance, frame_index, source)
|
|
for index: cast(s64)0..result_size - 1 {
|
|
instance.result_bytes[index] = instance.storage[source_at + index]
|
|
}
|
|
} else {
|
|
bits = instance.words[ExecFrameValueWord(instance, frame_index, source)]
|
|
ExecWriteBits(instance.result_bytes[:], 0, result_size, bits)
|
|
}
|
|
}
|
|
instance.result_value = .{.type = result_type, .bits = bits, .bytes = result_size}
|
|
ExecPopFrame(instance)
|
|
return true
|
|
}
|
|
caller := frame_index - 1
|
|
if result_size != 0 {
|
|
if frame.return_value == LirNoId { return ExecFail(instance, .Calling) }
|
|
if !ExecCopyValue(instance, frame_index, instruction.operands[0],
|
|
caller, frame.return_value) { return false }
|
|
} else if frame.return_value != LirNoId {
|
|
// A zero-sized result, such as [0]s32, has no bytes to copy; only a
|
|
// void procedure cannot fill the caller's result.
|
|
if instance.plan.program.types[result_type].kind == .Void { return ExecFail(instance, .Calling) }
|
|
}
|
|
ExecPopFrame(instance)
|
|
return true
|
|
}
|
|
|
|
ExecCallInstruction :: (instance: *LirExecInstance, frame_index: s64,
|
|
instruction: *LirInstruction) -> bool {
|
|
target := instruction.symbol
|
|
skip: s64
|
|
if instruction.op == .CallIndirect {
|
|
bits := ExecSlotBits(instance, instruction.operands[0])
|
|
if instance.failure.problem != .None || bits == 0 ||
|
|
bits > cast(u64)instance.plan.program.functions.count { return ExecFail(instance, .Calling) }
|
|
target = cast(s32)(bits - 1)
|
|
skip = 1
|
|
signature := instance.plan.program.types[
|
|
instance.plan.value_types[instance.current_value_base + instruction.operands[0]]]
|
|
actual := instance.plan.program.functions[target]
|
|
if signature.result != actual.result || signature.parameters.count != actual.parameters.count {
|
|
return ExecFail(instance, .Calling)
|
|
}
|
|
for index: cast(s64)0..signature.parameters.count - 1 {
|
|
if signature.parameters[index] != actual.parameters[index] { return ExecFail(instance, .Calling) }
|
|
}
|
|
}
|
|
arguments := instruction.operands[skip:]
|
|
no_arguments: [0]LirExecArgument
|
|
if !ExecPushFrame(instance, target, frame_index, arguments, instruction.result, no_arguments[:]) { return false }
|
|
instance.frames[frame_index].instruction += 1
|
|
return true
|
|
}
|
|
|
|
ExecAddressValid :: (instance: *LirExecInstance, address_index: s64) -> bool {
|
|
address := instance.addresses[address_index]
|
|
if address.owned {
|
|
if address.heap != 0 {
|
|
block := instance.heap_blocks[address.heap - 1]
|
|
if !block.live || block.generation != address.generation { return false }
|
|
}
|
|
return address.offset >= 0 && address.extent >= 0 &&
|
|
address.offset <= instance.owned.count && address.extent <= instance.owned.count - address.offset
|
|
}
|
|
if address.frame < 0 { return true }
|
|
return address.frame < instance.frames.count &&
|
|
instance.frames[address.frame].generation == address.generation
|
|
}
|
|
|
|
ExecAddressOffset :: (instance: *LirExecInstance, address_index: s64) -> s64 {
|
|
if !ExecAddressValid(instance, address_index) { unused ExecFail(instance, .Pointer); return -1 }
|
|
address := instance.addresses[address_index]
|
|
if address.owned { return address.offset }
|
|
if address.frame < 0 { return address.offset }
|
|
return instance.frames[address.frame].base + address.offset
|
|
}
|
|
|
|
ExecCopyAddressToValue :: (instance: *LirExecInstance, address_index: s64,
|
|
frame_index: s64, destination: s32) -> bool {
|
|
source := ExecAddressOffset(instance, address_index)
|
|
if instance.failure.problem != .None || source < 0 { return false }
|
|
address := instance.addresses[address_index]
|
|
size := ExecValueSize(instance, frame_index, destination)
|
|
if size < 0 || size > instance.addresses[address_index].extent { return ExecFail(instance, .Pointer) }
|
|
if !ExecSpend(instance, ExecCopyCost(size)) { return false }
|
|
if ExecValueIsWord(instance, frame_index, destination) {
|
|
bits: u64
|
|
if address.owned { bits = ExecReadBits(instance.owned[:], source, size) }
|
|
else if address.frame < 0 { bits = ExecReadBits(instance.globals[:], source, size) }
|
|
else { bits = ExecReadBits(instance.storage[:], source, size) }
|
|
ExecWriteSlotBits(instance, destination, bits)
|
|
return instance.failure.problem == .None
|
|
}
|
|
destination_at := ExecFrameValueOffset(instance, frame_index, destination)
|
|
if address.owned {
|
|
for index: cast(s64)0..size - 1 {
|
|
instance.storage[destination_at + index] = instance.owned[source + index]
|
|
}
|
|
} else if address.frame < 0 {
|
|
for index: cast(s64)0..size - 1 {
|
|
instance.storage[destination_at + index] = instance.globals[source + index]
|
|
}
|
|
} else {
|
|
for index: cast(s64)0..size - 1 {
|
|
instance.storage[destination_at + index] = instance.storage[source + index]
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
ExecCopyValueToAddress :: (instance: *LirExecInstance, frame_index: s64,
|
|
source: s32, address_index: s64) -> bool {
|
|
destination := ExecAddressOffset(instance, address_index)
|
|
if instance.failure.problem != .None || destination < 0 { return false }
|
|
address := instance.addresses[address_index]
|
|
if !address.writable { return ExecFail(instance, .Pointer) }
|
|
size := ExecValueSize(instance, frame_index, source)
|
|
if size < 0 || size > instance.addresses[address_index].extent { return ExecFail(instance, .Pointer) }
|
|
if !ExecSpend(instance, ExecCopyCost(size)) { return false }
|
|
if ExecValueIsWord(instance, frame_index, source) {
|
|
bits := instance.words[ExecFrameValueWord(instance, frame_index, source)]
|
|
if address.owned { ExecWriteBits(instance.owned[:], destination, size, bits) }
|
|
else if address.frame < 0 { ExecWriteBits(instance.globals[:], destination, size, bits) }
|
|
else { ExecWriteBits(instance.storage[:], destination, size, bits) }
|
|
return true
|
|
}
|
|
source_at := ExecFrameValueOffset(instance, frame_index, source)
|
|
if address.owned {
|
|
for index: cast(s64)0..size - 1 {
|
|
instance.owned[destination + index] = instance.storage[source_at + index]
|
|
}
|
|
} else if address.frame < 0 {
|
|
for index: cast(s64)0..size - 1 {
|
|
instance.globals[destination + index] = instance.storage[source_at + index]
|
|
}
|
|
} else {
|
|
for index: cast(s64)0..size - 1 {
|
|
instance.storage[destination + index] = instance.storage[source_at + index]
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
ExecAllocate :: (instance: *LirExecInstance, frame_index: s64,
|
|
instruction: *LirInstruction, result_type: s32) -> bool {
|
|
pointee := instance.plan.program.types[result_type].element
|
|
size := instance.plan.type_sizes[pointee]
|
|
base := instance.storage.count
|
|
if !ExecResizeStorage(instance, base + size) { return false }
|
|
index := ExecNewAddress(instance, .{.global = -1, .frame = frame_index,
|
|
.generation = instance.frames[frame_index].generation,
|
|
.offset = base - instance.frames[frame_index].base, .extent = size, .type = pointee,
|
|
.writable = true})
|
|
if index < 0 { return false }
|
|
address := instance.addresses[index]
|
|
if instruction.operands.count != 0 {
|
|
value := instruction.operands[0]
|
|
if instance.plan.value_types[instance.current_value_base + value] != pointee {
|
|
return ExecFail(instance, .Type)
|
|
}
|
|
if !ExecCopyValueToStorage(instance, frame_index, value, base) { return false }
|
|
}
|
|
ExecWriteSlotBits(instance, instruction.result, address.token)
|
|
return true
|
|
}
|
|
|
|
// Give back the owned bytes of dead heap blocks that end the owned region.
|
|
ExecHeapTrim :: (instance: *LirExecInstance) -> bool {
|
|
while instance.heap_tail != 0 {
|
|
if !ExecSpend(instance, 1) { return false }
|
|
index := instance.heap_tail - 1
|
|
block := instance.heap_blocks[index]
|
|
if block.live { return true }
|
|
if block.offset + block.size != instance.owned.count { instance.heap_tail = 0; return true }
|
|
unused VecResize(instance.owned, block.offset)
|
|
instance.heap_blocks[index].size = 0
|
|
instance.heap_tail = block.below
|
|
if !VecPush(instance.heap_free, index) { return ExecFail(instance, .Allocation) }
|
|
}
|
|
return true
|
|
}
|
|
|
|
// A read-only block of BYTES owned bytes for a value a host gave, and the
|
|
// index of its address, or -1 after a failure.
|
|
ExecHostBlock :: (instance: *LirExecInstance, bytes: s64, element: s32) -> s64 {
|
|
available := instance.limits.value_bytes - instance.globals.count - instance.storage.count -
|
|
instance.words.count * 8 - instance.result_bytes.count
|
|
instance.host_since += bytes
|
|
instance.heap_epoch += 1
|
|
// A dead host block of room enough lends its bytes and its place.
|
|
tries: s64 = 0
|
|
while tries < 8 && tries < instance.host_free.count {
|
|
at := instance.host_free.count - 1 - tries
|
|
record := instance.host_free[at]
|
|
block := instance.heap_blocks[record]
|
|
usable := !block.live && block.host && block.size > 0
|
|
if usable && block.size < bytes { tries += 1; continue }
|
|
instance.host_free[at] = instance.host_free[instance.host_free.count - 1]
|
|
unused VecResize(instance.host_free, instance.host_free.count - 1)
|
|
if !usable { continue }
|
|
instance.heap_blocks[record].live = true
|
|
instance.heap_blocks[record].count = cast(u64)bytes
|
|
instance.heap_blocks[record].generation = instance.heap_epoch
|
|
return ExecNewAddress(instance, .{.global = -1, .frame = -1, .generation = instance.heap_epoch,
|
|
.offset = block.offset, .extent = bytes, .type = element, .owned = true, .writable = false,
|
|
.heap = record + 1})
|
|
}
|
|
base := instance.owned.count
|
|
if bytes > available - base { unused ExecFail(instance, .ValueBytes); return -1 }
|
|
if !VecResizeBounded(instance.owned, base + bytes, available) { unused ExecFail(instance, .Allocation); return -1 }
|
|
record: s64
|
|
if instance.heap_free.count > 0 {
|
|
record = instance.heap_free[instance.heap_free.count - 1]
|
|
unused VecResize(instance.heap_free, instance.heap_free.count - 1)
|
|
} else {
|
|
record = instance.heap_blocks.count
|
|
if !VecPush(instance.heap_blocks, LirExecHeapBlock.{}) { unused ExecFail(instance, .Allocation); return -1 }
|
|
}
|
|
instance.heap_blocks[record] = .{.offset = base, .size = bytes, .count = cast(u64)bytes,
|
|
.generation = instance.heap_epoch, .live = true, .below = instance.heap_tail, .host = true}
|
|
instance.heap_tail = record + 1
|
|
return ExecNewAddress(instance, .{.global = -1, .frame = -1, .generation = instance.heap_epoch,
|
|
.offset = base, .extent = bytes, .type = element, .owned = true, .writable = false,
|
|
.heap = record + 1})
|
|
}
|
|
|
|
ExecHostEnd :: (instance: *LirExecInstance, index: s64) -> bool {
|
|
instance.heap_blocks[index].live = false
|
|
ExecReleaseAddresses(instance, instance.heap_blocks[index].addresses)
|
|
instance.heap_blocks[index].addresses = 0
|
|
return VecPush(instance.host_free, index) || ExecFail(instance, .Allocation)
|
|
}
|
|
|
|
// Ends every host block made after EPOCH: a rejected image leaves no
|
|
// storage behind.
|
|
ExecHostRollback :: (instance: *LirExecInstance, epoch: u64) {
|
|
for index: cast(s64)0..instance.heap_blocks.count - 1 {
|
|
block := instance.heap_blocks[index]
|
|
if block.live && block.host && block.generation > epoch { unused ExecHostEnd(instance, index) }
|
|
}
|
|
unused ExecHeapTrim(instance)
|
|
}
|
|
|
|
// Marks the live host block that TOKEN names, if any, to be scanned.
|
|
ExecHostMarkToken :: (instance: *LirExecInstance, token: u64, marks: *Vec(u8), pending: *Vec(s64)) -> bool {
|
|
found := ExecFindAddress(instance, token)
|
|
if found < 0 || instance.addresses[found].heap == 0 { return true }
|
|
block := instance.addresses[found].heap - 1
|
|
if !instance.heap_blocks[block].live || !instance.heap_blocks[block].host || (<<marks)[block] != 0 { return true }
|
|
(<<marks)[block] = 1
|
|
return VecPush(<<pending, block) || ExecFail(instance, .Allocation)
|
|
}
|
|
|
|
// Every eight bytes of BYTES[from:from + count] that could be a token of
|
|
// this instance, at any offset since values are packed.
|
|
ExecHostMarkBytes :: (instance: *LirExecInstance, bytes: []u8, from: s64, count: s64,
|
|
marks: *Vec(u8), pending: *Vec(s64)) -> bool {
|
|
if count < 8 { return true }
|
|
if !ExecSpend(instance, ExecCopyCost(count)) { return false }
|
|
low := cast(u8)(instance.identity & cast(u32)255)
|
|
high := cast(u8)((instance.identity >> cast(u32)8) & cast(u32)255)
|
|
for at: from..from + count - 8 {
|
|
if bytes[at + 7] != high || bytes[at + 6] != low { continue }
|
|
if !ExecHostMarkToken(instance, ExecReadBits(bytes, at, 8), marks, pending) { return false }
|
|
}
|
|
return true
|
|
}
|
|
|
|
// Gives back the host blocks the program can no longer reach. It reaches
|
|
// the globals, the frames' storage and words, the result bytes and its own
|
|
// heap blocks, and every host block those name. A name is any eight bytes
|
|
// equal to a valid token of a block's address, so a reachable block is
|
|
// never freed; bytes that only look like a token keep a block a little
|
|
// longer. A dead block's addresses end, and its bytes go back down the
|
|
// owned region's chain like a freed heap block's.
|
|
ExecHostCollect :: (instance: *LirExecInstance) -> bool {
|
|
count := instance.heap_blocks.count
|
|
marks: Vec(u8)
|
|
pending: Vec(s64)
|
|
defer VecFree(marks)
|
|
defer VecFree(pending)
|
|
if !VecResize(marks, count) { return ExecFail(instance, .Allocation) }
|
|
scanned := instance.globals.count + instance.storage.count + instance.result_bytes.count + instance.words.count * 8
|
|
if !ExecHostMarkBytes(instance, instance.globals[:], 0, instance.globals.count, *marks, *pending) ||
|
|
!ExecHostMarkBytes(instance, instance.storage[:], 0, instance.storage.count, *marks, *pending) ||
|
|
!ExecHostMarkBytes(instance, instance.result_bytes[:], 0, instance.result_bytes.count, *marks, *pending) { return false }
|
|
if !ExecSpend(instance, instance.words.count) { return false }
|
|
for word: instance.words {
|
|
if !ExecHostMarkToken(instance, word, *marks, *pending) { return false }
|
|
}
|
|
for index: cast(s64)0..count - 1 {
|
|
block := instance.heap_blocks[index]
|
|
if !block.live || block.host { continue }
|
|
scanned += block.size
|
|
if !ExecHostMarkBytes(instance, instance.owned[:], block.offset, block.size, *marks, *pending) { return false }
|
|
}
|
|
while pending.count > 0 {
|
|
block := instance.heap_blocks[pending[pending.count - 1]]
|
|
unused VecResize(pending, pending.count - 1)
|
|
scanned += block.size
|
|
if !ExecHostMarkBytes(instance, instance.owned[:], block.offset, block.size, *marks, *pending) { return false }
|
|
}
|
|
for index: cast(s64)0..count - 1 {
|
|
block := instance.heap_blocks[index]
|
|
if block.live && block.host && marks[index] == 0 && !ExecHostEnd(instance, index) { return false }
|
|
}
|
|
instance.host_since = 0
|
|
instance.host_scanned = scanned
|
|
return ExecHeapTrim(instance)
|
|
}
|
|
|
|
// resize(pointer: *T, old_count, new_count) -> *T. A null pointer with
|
|
// old_count 0 allocates; new_count 0 frees and gives null. The new block
|
|
// keeps the first min(old_count, new_count) elements and zero-fills the
|
|
// rest. When the value-byte budget cannot hold the request the result is
|
|
// null and the old block stays valid. Only a block's own base pointer,
|
|
// with its exact element count, may be resized or freed.
|
|
ExecResize :: (instance: *LirExecInstance, instruction: *LirInstruction, result_type: s32) -> bool {
|
|
token := ExecSlotBits(instance, instruction.operands[0])
|
|
old_count := ExecIndexBits(instance, instruction.operands[1])
|
|
new_count := ExecIndexBits(instance, instruction.operands[2])
|
|
if instance.failure.problem != .None { return false }
|
|
element := instance.plan.program.types[result_type].element
|
|
size := instance.plan.type_sizes[element]
|
|
if size < 0 { return ExecFail(instance, .Type) }
|
|
previous: s64 = -1
|
|
if token == 0 {
|
|
if old_count != 0 { return ExecFail(instance, .Pointer) }
|
|
} else {
|
|
found := ExecFindAddress(instance, token)
|
|
if found < 0 || !ExecAddressValid(instance, found) { return ExecFail(instance, .Pointer) }
|
|
address := instance.addresses[found]
|
|
if address.heap == 0 || address.type != element { return ExecFail(instance, .Pointer) }
|
|
previous = address.heap - 1
|
|
if address.offset != instance.heap_blocks[previous].offset ||
|
|
old_count != instance.heap_blocks[previous].count { return ExecFail(instance, .Pointer) }
|
|
}
|
|
if new_count == 0 {
|
|
if previous >= 0 {
|
|
instance.heap_blocks[previous].live = false
|
|
ExecReleaseAddresses(instance, instance.heap_blocks[previous].addresses)
|
|
instance.heap_blocks[previous].addresses = 0
|
|
if !ExecHeapTrim(instance) { return false }
|
|
}
|
|
ExecWriteSlotBits(instance, instruction.result, 0)
|
|
return true
|
|
}
|
|
available := instance.limits.value_bytes - instance.globals.count - instance.storage.count -
|
|
instance.words.count * 8 - instance.result_bytes.count
|
|
if available < 0 || new_count > cast(u64)9223372036854775807 ||
|
|
size != 0 && new_count > cast(u64)(available / size) {
|
|
ExecWriteSlotBits(instance, instruction.result, 0)
|
|
return true
|
|
}
|
|
bytes := cast(s64)new_count * size
|
|
if !ExecSpend(instance, ExecCopyCost(bytes)) { return false }
|
|
base := instance.owned.count
|
|
kept: s64
|
|
if previous >= 0 {
|
|
kept = instance.heap_blocks[previous].size
|
|
if kept > bytes { kept = bytes }
|
|
// The last block of the owned bytes grows or shrinks in place.
|
|
if instance.heap_blocks[previous].offset + instance.heap_blocks[previous].size == instance.owned.count {
|
|
base = instance.heap_blocks[previous].offset
|
|
}
|
|
}
|
|
if base + bytes > available || !VecResizeBounded(instance.owned, base + bytes, available) {
|
|
ExecWriteSlotBits(instance, instruction.result, 0)
|
|
return true
|
|
}
|
|
if previous >= 0 && base != instance.heap_blocks[previous].offset {
|
|
source := instance.heap_blocks[previous].offset
|
|
for index: cast(s64)0..kept - 1 { instance.owned[base + index] = instance.owned[source + index] }
|
|
}
|
|
for index: kept..bytes - 1 { instance.owned[base + index] = 0 }
|
|
// The block keeps its record when it grows or shrinks where it is;
|
|
// otherwise it takes a freed record or a new one, above the old tail.
|
|
record := previous
|
|
below := instance.heap_tail
|
|
// The old block's generation ends here, and its addresses with it.
|
|
if previous >= 0 {
|
|
ExecReleaseAddresses(instance, instance.heap_blocks[previous].addresses)
|
|
instance.heap_blocks[previous].addresses = 0
|
|
}
|
|
if previous >= 0 && base == instance.heap_blocks[previous].offset {
|
|
below = instance.heap_blocks[previous].below
|
|
} else {
|
|
if previous >= 0 { instance.heap_blocks[previous].live = false }
|
|
if instance.heap_free.count > 0 {
|
|
record = instance.heap_free[instance.heap_free.count - 1]
|
|
unused VecResize(instance.heap_free, instance.heap_free.count - 1)
|
|
} else {
|
|
record = instance.heap_blocks.count
|
|
if !VecPush(instance.heap_blocks, LirExecHeapBlock.{}) { return ExecFail(instance, .Allocation) }
|
|
}
|
|
}
|
|
instance.heap_epoch += 1
|
|
block := LirExecHeapBlock.{.offset = base, .size = bytes, .count = new_count,
|
|
.generation = instance.heap_epoch, .live = true, .below = below}
|
|
instance.heap_blocks[record] = block
|
|
instance.heap_tail = record + 1
|
|
index := ExecNewAddress(instance, .{.global = -1, .frame = -1, .generation = block.generation,
|
|
.offset = base, .extent = bytes, .type = element, .owned = true, .writable = true,
|
|
.heap = record + 1})
|
|
if index < 0 { return false }
|
|
address := instance.addresses[index]
|
|
ExecWriteSlotBits(instance, instruction.result, address.token)
|
|
return true
|
|
}
|
|
|
|
ExecMemoryInstruction :: (instance: *LirExecInstance, frame_index: s64,
|
|
instruction: *LirInstruction, result_type: s32) -> bool {
|
|
if instruction.op == .FieldAddress || instruction.op == .ElementAddress {
|
|
token := ExecSlotBits(instance, instruction.operands[0])
|
|
low: u64
|
|
high: u64
|
|
count: u64
|
|
if instruction.op == .ElementAddress && instruction.operands.count == 4 {
|
|
low = ExecIndexBits(instance, instruction.operands[1])
|
|
high = ExecIndexBits(instance, instruction.operands[2])
|
|
count = ExecIndexBits(instance, instruction.operands[3])
|
|
if instance.failure.problem != .None { return false }
|
|
if token == 0 {
|
|
if low != 0 || high != 0 || count != 0 { return ExecFail(instance, .Pointer) }
|
|
ExecWriteSlotBits(instance, instruction.result, 0)
|
|
return true
|
|
}
|
|
}
|
|
address := ExecFindAddress(instance, token)
|
|
if address < 0 { return ExecFail(instance, .Pointer) }
|
|
expected := instance.plan.program.types[instance.plan.value_types[
|
|
instance.current_value_base + instruction.operands[0]]].element
|
|
if instance.addresses[address].type != expected { return ExecFail(instance, .Type) }
|
|
target := instance.plan.program.types[result_type].element
|
|
member := instruction.immediate
|
|
transient := instance.plan.transient[instance.frames[frame_index].instruction_base +
|
|
instance.frames[frame_index].instruction] != 0
|
|
child: u64
|
|
if instruction.op == .ElementAddress && instruction.operands.count == 4 {
|
|
child = ExecSliceAddress(instance, address, low, high, count, target, transient)
|
|
} else if instruction.op == .ElementAddress && instruction.operands.count == 3 {
|
|
index := ExecIndexBits(instance, instruction.operands[1])
|
|
count := ExecIndexBits(instance, instruction.operands[2])
|
|
if instance.failure.problem != .None { return false }
|
|
child = ExecElementAddress(instance, address, index, count, target, transient)
|
|
} else {
|
|
if instruction.op == .ElementAddress {
|
|
member = ExecIndexBits(instance, instruction.operands[1])
|
|
if instance.failure.problem != .None { return false }
|
|
}
|
|
child = ExecFieldAddress(instance, address, member, target, transient)
|
|
}
|
|
if instance.failure.problem != .None { return false }
|
|
ExecWriteSlotBits(instance, instruction.result, child)
|
|
return true
|
|
}
|
|
token := ExecSlotBits(instance, instruction.operands[0])
|
|
address_index := ExecFindAddress(instance, token)
|
|
if address_index < 0 { return ExecFail(instance, .Pointer) }
|
|
if instruction.op == .Load {
|
|
if instance.addresses[address_index].type != result_type { return ExecFail(instance, .Type) }
|
|
return ExecCopyAddressToValue(instance, address_index, frame_index, instruction.result)
|
|
}
|
|
value := instruction.operands[1]
|
|
if instance.plan.value_types[instance.current_value_base + value] !=
|
|
instance.addresses[address_index].type {
|
|
return ExecFail(instance, .Type)
|
|
}
|
|
// Read-only globals hold string literal bytes; no address can write them.
|
|
if !instance.addresses[address_index].writable { return ExecFail(instance, .Pointer) }
|
|
return ExecCopyValueToAddress(instance, frame_index, value, address_index)
|
|
}
|
|
|
|
ExecBytesMatchSame :: (bytes: []u8, left: s64, right: s64, count: s64) -> bool {
|
|
for index: cast(s64)0..count - 1 {
|
|
if bytes[left + index] != bytes[right + index] { return false }
|
|
}
|
|
return true
|
|
}
|
|
|
|
ExecBytesMatchAcross :: (left: []u8, left_at: s64, right: []u8,
|
|
right_at: s64, count: s64) -> bool {
|
|
for index: cast(s64)0..count - 1 {
|
|
if left[left_at + index] != right[right_at + index] { return false }
|
|
}
|
|
return true
|
|
}
|
|
|
|
ExecBytesEqual :: (instance: *LirExecInstance, instruction: *LirInstruction) -> bool {
|
|
left_token := ExecSlotBits(instance, instruction.operands[0])
|
|
left_count := ExecIndexBits(instance, instruction.operands[1])
|
|
right_token := ExecSlotBits(instance, instruction.operands[2])
|
|
right_count := ExecIndexBits(instance, instruction.operands[3])
|
|
if instance.failure.problem != .None || left_count > cast(u64)9223372036854775807 ||
|
|
right_count > cast(u64)9223372036854775807 { return ExecFail(instance, .Pointer) }
|
|
left_address: s64 = -1
|
|
right_address: s64 = -1
|
|
if left_token != 0 { left_address = ExecFindAddress(instance, left_token) }
|
|
if right_token != 0 { right_address = ExecFindAddress(instance, right_token) }
|
|
if (left_token != 0 && left_address < 0) || (right_token != 0 && right_address < 0) ||
|
|
(left_token == 0 && left_count != 0) || (right_token == 0 && right_count != 0) {
|
|
return ExecFail(instance, .Pointer)
|
|
}
|
|
left_pointer := instance.plan.program.types[instance.plan.value_types[
|
|
instance.current_value_base + instruction.operands[0]]]
|
|
right_pointer := instance.plan.program.types[instance.plan.value_types[
|
|
instance.current_value_base + instruction.operands[2]]]
|
|
if (left_address >= 0 && instance.addresses[left_address].type != left_pointer.element) ||
|
|
(right_address >= 0 && instance.addresses[right_address].type != right_pointer.element) {
|
|
return ExecFail(instance, .Type)
|
|
}
|
|
if (left_address >= 0 && instance.addresses[left_address].extent < cast(s64)left_count) ||
|
|
(right_address >= 0 && instance.addresses[right_address].extent < cast(s64)right_count) {
|
|
return ExecFail(instance, .Pointer)
|
|
}
|
|
if left_count != right_count {
|
|
ExecWriteSlotBits(instance, instruction.result, 0)
|
|
return true
|
|
}
|
|
if left_count == 0 {
|
|
ExecWriteSlotBits(instance, instruction.result, 1)
|
|
return true
|
|
}
|
|
left_at := ExecAddressOffset(instance, left_address)
|
|
right_at := ExecAddressOffset(instance, right_address)
|
|
if instance.failure.problem != .None { return false }
|
|
left := instance.addresses[left_address]
|
|
right := instance.addresses[right_address]
|
|
if !ExecSpend(instance, ExecCopyCost(cast(s64)left_count)) { return false }
|
|
count := cast(s64)left_count
|
|
equal: bool
|
|
if left.owned {
|
|
if right.owned {
|
|
equal = ExecBytesMatchSame(instance.owned[:], left_at, right_at, count)
|
|
} else if right.frame < 0 {
|
|
equal = ExecBytesMatchAcross(instance.owned[:], left_at,
|
|
instance.globals[:], right_at, count)
|
|
} else {
|
|
equal = ExecBytesMatchAcross(instance.owned[:], left_at,
|
|
instance.storage[:], right_at, count)
|
|
}
|
|
} else if left.frame < 0 {
|
|
if right.owned {
|
|
equal = ExecBytesMatchAcross(instance.globals[:], left_at,
|
|
instance.owned[:], right_at, count)
|
|
} else if right.frame < 0 {
|
|
equal = ExecBytesMatchSame(instance.globals[:], left_at, right_at, count)
|
|
} else {
|
|
equal = ExecBytesMatchAcross(instance.globals[:], left_at,
|
|
instance.storage[:], right_at, count)
|
|
}
|
|
} else if right.owned {
|
|
equal = ExecBytesMatchAcross(instance.storage[:], left_at,
|
|
instance.owned[:], right_at, count)
|
|
} else if right.frame < 0 {
|
|
equal = ExecBytesMatchAcross(instance.storage[:], left_at,
|
|
instance.globals[:], right_at, count)
|
|
} else {
|
|
equal = ExecBytesMatchSame(instance.storage[:], left_at, right_at, count)
|
|
}
|
|
if !equal {
|
|
ExecWriteSlotBits(instance, instruction.result, 0)
|
|
return true
|
|
}
|
|
ExecWriteSlotBits(instance, instruction.result, 1)
|
|
return true
|
|
}
|
|
|
|
ExecUnaryInstruction :: (instance: *LirExecInstance, frame_index: s64,
|
|
instruction: *LirInstruction) -> bool {
|
|
source_type := ExecValueType(instance, instruction.operands[0])
|
|
bits := ExecSlotBits(instance, instruction.operands[0])
|
|
if instance.failure.problem != .None { return false }
|
|
if source_type.kind == .Integer {
|
|
ExecWriteSlotBits(instance, instruction.result,
|
|
ifx instruction.op == .Negate then cast(u64)0 - bits else ~bits)
|
|
} else {
|
|
sign := ifx source_type.bits == 32 then cast(u64)0x80000000 else cast(u64)0x8000000000000000
|
|
ExecWriteSlotBits(instance, instruction.result, bits ^ sign)
|
|
}
|
|
return true
|
|
}
|
|
|
|
ExecNumericInstruction :: (instance: *LirExecInstance, frame_index: s64,
|
|
instruction: *LirInstruction, result_type: s32) -> bool {
|
|
op := instruction.op
|
|
opcode := cast(s32)op
|
|
if opcode >= cast(s32)LirOp.Add && opcode <= cast(s32)LirOp.Remainder ||
|
|
opcode >= cast(s32)LirOp.BitAnd && opcode <= cast(s32)LirOp.ShiftRight {
|
|
type := ExecValueType(instance, instruction.operands[0])
|
|
if type.kind == .Integer { return ExecIntegerBinary(instance, frame_index, instruction, type) }
|
|
return ExecFloatBinary(instance, frame_index, instruction, type)
|
|
}
|
|
if opcode >= cast(s32)LirOp.Equal && opcode <= cast(s32)LirOp.GreaterEqual {
|
|
type := ExecValueType(instance, instruction.operands[0])
|
|
return ExecCompare(instance, frame_index, instruction, type)
|
|
}
|
|
if op == .Convert || op == .Bitcast {
|
|
source := ExecValueType(instance, instruction.operands[0])
|
|
destination := instance.plan.program.types[result_type]
|
|
return ExecConvert(instance, frame_index, instruction, source, destination)
|
|
}
|
|
return ExecFail(instance, .Unsupported)
|
|
}
|
|
|
|
ExecValueInstruction :: (instance: *LirExecInstance, frame_index: s64,
|
|
instruction: *LirInstruction) -> bool {
|
|
op := instruction.op
|
|
result_type: s32 = LirNoId
|
|
if instruction.result != LirNoId {
|
|
result_type = instance.plan.value_types[instance.current_value_base + instruction.result]
|
|
}
|
|
if op == .Constant {
|
|
constant := instance.plan.program.constants[instruction.symbol]
|
|
ExecWriteSlotBits(instance, instruction.result, constant.bits)
|
|
} else if op == .Null { ExecWriteSlotBits(instance, instruction.result, 0) }
|
|
else if op == .GlobalAddress {
|
|
ExecWriteSlotBits(instance, instruction.result, instance.addresses[instruction.symbol].token)
|
|
} else if op == .FunctionAddress {
|
|
ExecWriteSlotBits(instance, instruction.result, cast(u64)(instruction.symbol + 1))
|
|
} else if op == .Aggregate {
|
|
if !ExecAggregate(instance, frame_index, instruction) { return false }
|
|
} else if op == .Extract || op == .Insert {
|
|
if !ExecExtractInsert(instance, frame_index, instruction) { return false }
|
|
} else if op == .FieldAddress || op == .ElementAddress || op == .Load || op == .Store {
|
|
if !ExecMemoryInstruction(instance, frame_index, instruction, result_type) { return false }
|
|
} else if op == .BytesEqual {
|
|
if !ExecBytesEqual(instance, instruction) { return false }
|
|
} else if op == .Allocate {
|
|
if !ExecAllocate(instance, frame_index, instruction, result_type) { return false }
|
|
} else if op == .Resize {
|
|
if !ExecResize(instance, instruction, result_type) { return false }
|
|
} else if op == .Negate || op == .BitNot {
|
|
if !ExecUnaryInstruction(instance, frame_index, instruction) { return false }
|
|
} else if !ExecNumericInstruction(instance, frame_index, instruction, result_type) { return false }
|
|
instance.frames[frame_index].instruction += 1
|
|
return true
|
|
}
|
|
|
|
ExecHostCanonical :: (type: LirType, bits: u64) -> bool {
|
|
if type.kind == .Bool { return bits <= cast(u64)1 }
|
|
if type.kind == .Integer { return (bits & ~ExecMask(type.bits)) == cast(u64)0 }
|
|
if type.kind == .Float && type.bits == 32 { return bits <= cast(u64)4294967295 }
|
|
return type.kind == .Float && type.bits == 64
|
|
}
|
|
|
|
ExecHostScalarType :: (type: LirType) -> bool {
|
|
return type.kind == .Bool || type.kind == .Integer || type.kind == .Float
|
|
}
|
|
|
|
ExecHostHandleType :: (program: LirProgram, type: s32) -> bool {
|
|
return program.types[type].kind == .Pointer
|
|
}
|
|
|
|
// Scalars and opaque handles cross a typed host boundary in `bits`; every
|
|
// other host shape crosses as an image in `bytes`.
|
|
ExecHostBitsType :: (program: LirProgram, type: s32) -> bool {
|
|
return ExecHostScalarType(program.types[type]) || ExecHostHandleType(program, type)
|
|
}
|
|
|
|
ExecHostSignature :: (plan: *LirExecPlan, function: s32, typed: bool) -> bool {
|
|
program := plan.program
|
|
fn := program.functions[function]
|
|
for parameter: fn.parameters {
|
|
if typed {
|
|
if plan.host_shapes[parameter] == 0 { return false }
|
|
} else if !ExecHostScalarType(program.types[parameter]) { return false }
|
|
}
|
|
if program.types[fn.result].kind == .Void { return true }
|
|
if typed { return plan.host_shapes[fn.result] != 0 }
|
|
return ExecHostScalarType(program.types[fn.result])
|
|
}
|
|
|
|
// Where decoded host bytes go: a frame's storage, the instance-owned bytes
|
|
// or the globals.
|
|
ExecStore :: enum u8 { Frame; Owned; Globals }
|
|
|
|
ExecStoreBits :: (instance: *LirExecInstance, store: ExecStore, at: s64, count: s64, bits: u64) {
|
|
if store == .Owned { ExecWriteBits(instance.owned[:], at, count, bits) }
|
|
else if store == .Globals { ExecWriteBits(instance.globals[:], at, count, bits) }
|
|
else { ExecWriteBits(instance.storage[:], at, count, bits) }
|
|
}
|
|
|
|
ExecHostAvailable :: (instance: *LirExecInstance) -> s64 {
|
|
return instance.limits.value_bytes - instance.globals.count - instance.storage.count -
|
|
instance.words.count * 8 - instance.result_bytes.count - instance.owned.count
|
|
}
|
|
|
|
// A host image is the value's own bytes followed by the elements of every
|
|
// view inside it. In the image a view's two words are the byte offset of its
|
|
// first element from the start of the image and its element count; an empty
|
|
// view is two zero words. Elements are images themselves, so views nest.
|
|
// Handles keep their bits.
|
|
//
|
|
// Writes the image of the `type` value at `source[from]` to the host bytes at
|
|
// `to` and appends its view elements. `base` is where the whole image starts
|
|
// and `limit` bounds the host bytes. A type may hold itself through a view, so
|
|
// `depth` counts the levels a value nests and stops past LirHostShapeDepth.
|
|
ExecHostEncode :: (instance: *LirExecInstance, type: s32, source: []u8, from: s64,
|
|
base: s64, to: s64, limit: s64, depth: s64) -> bool {
|
|
plan := instance.plan
|
|
program := plan.program
|
|
size := plan.type_sizes[type]
|
|
if depth > LirHostShapeDepth { return ExecFail(instance, .Host) }
|
|
if plan.host_shapes[type] < LirHostShapeViews {
|
|
if !ExecSpend(instance, ExecCopyCost(size)) { return false }
|
|
for byte: cast(s64)0..size - 1 { instance.host_bytes[to + byte] = source[from + byte] }
|
|
return true
|
|
}
|
|
value := program.types[type]
|
|
if LirHostView(program, type) {
|
|
token := ExecReadBits(source, from, 8)
|
|
count := ExecReadBits(source, from + 8, 8)
|
|
if !ExecSpend(instance, 1) { return false }
|
|
if count == 0 {
|
|
ExecWriteBits(instance.host_bytes[:], to, 8, 0)
|
|
ExecWriteBits(instance.host_bytes[:], to + 8, 8, 0)
|
|
return true
|
|
}
|
|
element := program.types[value.fields[0]].element
|
|
width := plan.type_sizes[element]
|
|
found := ExecFindAddress(instance, token)
|
|
if found < 0 || width <= 0 || count > cast(u64)9223372036854775807 ||
|
|
instance.addresses[found].type != element || !ExecAddressValid(instance, found) ||
|
|
count > cast(u64)(instance.addresses[found].extent / width) { return ExecFail(instance, .Host) }
|
|
bytes := cast(s64)count * width
|
|
at := instance.host_bytes.count
|
|
if bytes > limit - at { return ExecFail(instance, .ValueBytes) }
|
|
if !VecResizeBounded(instance.host_bytes, at + bytes, limit) { return ExecFail(instance, .Allocation) }
|
|
ExecWriteBits(instance.host_bytes[:], to, 8, cast(u64)(at - base))
|
|
ExecWriteBits(instance.host_bytes[:], to + 8, 8, count)
|
|
// The elements live wherever the address was made: owned bytes,
|
|
// globals or a frame.
|
|
entry := instance.addresses[found]
|
|
elements := instance.storage[:]
|
|
if entry.owned { elements = instance.owned[:] }
|
|
else if entry.frame < 0 { elements = instance.globals[:] }
|
|
offset := ExecAddressOffset(instance, found)
|
|
if instance.failure.problem != .None { return false }
|
|
if plan.host_shapes[element] < LirHostShapeViews {
|
|
if !ExecSpend(instance, ExecCopyCost(bytes)) { return false }
|
|
for byte: cast(s64)0..bytes - 1 { instance.host_bytes[at + byte] = elements[offset + byte] }
|
|
return true
|
|
}
|
|
for index: cast(s64)0..cast(s64)count - 1 {
|
|
if !ExecHostEncode(instance, element, elements, offset + index * width,
|
|
base, at + index * width, limit, depth + 1) { return false }
|
|
}
|
|
return true
|
|
}
|
|
if value.kind == .Array {
|
|
width := plan.type_sizes[value.element]
|
|
for index: cast(s64)0..value.count - 1 {
|
|
if !ExecHostEncode(instance, value.element, source, from + index * width,
|
|
base, to + index * width, limit, depth + 1) { return false }
|
|
}
|
|
return true
|
|
}
|
|
offset: s64
|
|
for field: value.fields {
|
|
if !ExecHostEncode(instance, field, source, from + offset, base, to + offset, limit, depth + 1) { return false }
|
|
offset += plan.type_sizes[field]
|
|
}
|
|
return true
|
|
}
|
|
|
|
ExecTypedHostArguments :: (instance: *LirExecInstance, frame_index: s64,
|
|
instruction: *LirInstruction) -> bool {
|
|
program := instance.plan.program
|
|
count := instruction.operands.count
|
|
available := ExecHostAvailable(instance)
|
|
if available < 0 { return ExecFail(instance, .ValueBytes) }
|
|
unused VecResize(instance.host_bytes, 0)
|
|
// Earlier calls may have left more room than this one needs.
|
|
if !VecResize(instance.typed_arguments, count) ||
|
|
!VecResize(instance.host_arguments, count) { return ExecFail(instance, .Allocation) }
|
|
for index: cast(s64)0..count - 1 {
|
|
operand := instruction.operands[index]
|
|
type := instance.plan.value_types[instance.current_value_base + operand]
|
|
value := LirExecArgument.{.type = type}
|
|
if ExecHostBitsType(program, type) {
|
|
value.bits = ExecSlotBits(instance, operand)
|
|
if instance.failure.problem != .None { return false }
|
|
} else {
|
|
size := instance.plan.type_sizes[type]
|
|
at := instance.host_bytes.count
|
|
if size > available - at { return ExecFail(instance, .ValueBytes) }
|
|
if !VecResizeBounded(instance.host_bytes, at + size, available) { return ExecFail(instance, .Allocation) }
|
|
source := ExecFrameValueOffset(instance, frame_index, operand)
|
|
if !ExecHostEncode(instance, type, instance.storage[:], source, at, at, available, 0) { return false }
|
|
// The image is sliced below, once the host bytes have stopped growing.
|
|
instance.host_arguments[index] = cast(u64)at
|
|
value.bits = cast(u64)(instance.host_bytes.count - at)
|
|
}
|
|
instance.typed_arguments[index] = value
|
|
}
|
|
for index: cast(s64)0..count - 1 {
|
|
if ExecHostBitsType(program, instance.typed_arguments[index].type) { continue }
|
|
start := cast(s64)instance.host_arguments[index]
|
|
end := start + cast(s64)instance.typed_arguments[index].bits
|
|
instance.typed_arguments[index].bits = 0
|
|
instance.typed_arguments[index].bytes = VecSlice(instance.host_bytes, start, end)
|
|
}
|
|
return true
|
|
}
|
|
|
|
// Reads the `type` value at `image[from]` of a host image into `store` at
|
|
// `to`. Each view's elements become read-only instance-owned storage that
|
|
// stays valid for globals and later calls. `depth` is as for ExecHostEncode.
|
|
ExecHostDecode :: (instance: *LirExecInstance, type: s32, image: []u8, from: s64,
|
|
store: ExecStore, to: s64, depth: s64) -> bool {
|
|
plan := instance.plan
|
|
program := plan.program
|
|
value := program.types[type]
|
|
size := plan.type_sizes[type]
|
|
if depth > LirHostShapeDepth || from < 0 || size > image.count - from { return ExecFail(instance, .Host) }
|
|
if !ExecSpend(instance, 1) { return false }
|
|
if value.kind == .Array {
|
|
width := plan.type_sizes[value.element]
|
|
for index: cast(s64)0..value.count - 1 {
|
|
if !ExecHostDecode(instance, value.element, image, from + index * width,
|
|
store, to + index * width, depth + 1) { return false }
|
|
}
|
|
return true
|
|
}
|
|
if value.kind == .Record && !LirHostView(program, type) {
|
|
offset: s64
|
|
for field: value.fields {
|
|
if !ExecHostDecode(instance, field, image, from + offset, store, to + offset, depth + 1) { return false }
|
|
offset += plan.type_sizes[field]
|
|
}
|
|
return true
|
|
}
|
|
if value.kind != .Record {
|
|
bits := ExecReadBits(image, from, size)
|
|
if value.kind == .Bool && bits > cast(u64)1 { return ExecFail(instance, .Host) }
|
|
ExecStoreBits(instance, store, to, size, bits)
|
|
return true
|
|
}
|
|
start := ExecReadBits(image, from, 8)
|
|
count := ExecReadBits(image, from + 8, 8)
|
|
token: u64
|
|
if count == 0 {
|
|
if start != 0 { return ExecFail(instance, .Host) }
|
|
} else {
|
|
element := program.types[value.fields[0]].element
|
|
width := plan.type_sizes[element]
|
|
if width <= 0 || start > cast(u64)image.count ||
|
|
count > cast(u64)((image.count - cast(s64)start) / width) { return ExecFail(instance, .Host) }
|
|
bytes := cast(s64)count * width
|
|
index := ExecHostBlock(instance, bytes, element)
|
|
if index < 0 { return false }
|
|
base := instance.addresses[index].offset
|
|
token = instance.addresses[index].token
|
|
kind := program.types[element].kind
|
|
if kind == .Integer || kind == .Float {
|
|
if !ExecSpend(instance, ExecCopyCost(bytes)) { return false }
|
|
for byte: cast(s64)0..bytes - 1 { instance.owned[base + byte] = image[cast(s64)start + byte] }
|
|
} else {
|
|
for index: cast(s64)0..cast(s64)count - 1 {
|
|
if !ExecHostDecode(instance, element, image, cast(s64)start + index * width,
|
|
.Owned, base + index * width, depth + 1) { return false }
|
|
}
|
|
}
|
|
}
|
|
ExecStoreBits(instance, store, to, 8, token)
|
|
ExecStoreBits(instance, store, to + 8, 8, count)
|
|
return true
|
|
}
|
|
|
|
ExecTypedHostResult :: (instance: *LirExecInstance, frame_index: s64,
|
|
instruction: *LirInstruction, result: LirExecArgument) -> bool {
|
|
program := instance.plan.program
|
|
expected := program.functions[instruction.symbol].result
|
|
if result.type != expected { return ExecFail(instance, .Host) }
|
|
type := program.types[expected]
|
|
if type.kind == .Void { return result.bytes.count == 0 || ExecFail(instance, .Host) }
|
|
if instruction.result == LirNoId { return ExecFail(instance, .Host) }
|
|
if ExecHostBitsType(program, expected) {
|
|
if result.bytes.count != 0 ||
|
|
ExecHostScalarType(type) && !ExecHostCanonical(type, result.bits) { return ExecFail(instance, .Host) }
|
|
ExecWriteSlotBits(instance, instruction.result, result.bits)
|
|
return instance.failure.problem == .None
|
|
}
|
|
// A value without views is exactly its own bytes.
|
|
if instance.plan.host_shapes[expected] < LirHostShapeViews &&
|
|
result.bytes.count != instance.plan.type_sizes[expected] { return ExecFail(instance, .Host) }
|
|
destination := ExecFrameValueOffset(instance, frame_index, instruction.result)
|
|
epoch := instance.heap_epoch
|
|
if !ExecHostDecode(instance, expected, result.bytes, 0, .Frame, destination, 0) {
|
|
ExecHostRollback(instance, epoch)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
ExecHostViewParameter :: (host: LirExecHostBinding, index: s64) -> bool {
|
|
return index < 64 && ((host.views >> cast(u64)index) & cast(u64)1) != cast(u64)0
|
|
}
|
|
|
|
// Where the elements of the view argument `index` lie: their store and byte
|
|
// range. Returns the view's address, or -1 when it is empty. Encoding the
|
|
// argument checked the address.
|
|
ExecViewSpan :: (instance: *LirExecInstance, frame_index: s64, instruction: *LirInstruction,
|
|
index: s64, store: *ExecStore, start: *s64, end: *s64) -> s32 {
|
|
program := instance.plan.program
|
|
source := ExecFrameValueOffset(instance, frame_index, instruction.operands[index])
|
|
count := cast(s64)ExecReadBits(instance.storage[:], source + 8, 8)
|
|
found := ExecFindAddress(instance, ExecReadBits(instance.storage[:], source, 8))
|
|
if count == 0 || found < 0 { return -1 }
|
|
view := program.types[instance.typed_arguments[index].type]
|
|
width := instance.plan.type_sizes[program.types[view.fields[0]].element]
|
|
entry := instance.addresses[found]
|
|
<<store = .Frame
|
|
if entry.owned { <<store = .Owned } else if entry.frame < 0 { <<store = .Globals }
|
|
<<start = ExecAddressOffset(instance, found)
|
|
<<end = <<start + count * width
|
|
return found
|
|
}
|
|
|
|
// Two mutable view arguments of one call may not share elements: the host
|
|
// would see one change through the other and one copy-back would be lost.
|
|
ExecHostViewsApart :: (instance: *LirExecInstance, frame_index: s64,
|
|
instruction: *LirInstruction, host: LirExecHostBinding) -> bool {
|
|
count := instruction.operands.count
|
|
if host.views == cast(u64)0 { return true }
|
|
for left: cast(s64)0..count - 1 {
|
|
left_store: ExecStore
|
|
left_start: s64
|
|
left_end: s64
|
|
if !ExecHostViewParameter(host, left) ||
|
|
ExecViewSpan(instance, frame_index, instruction, left, *left_store, *left_start, *left_end) < 0 { continue }
|
|
for right: left + 1..count - 1 {
|
|
right_store: ExecStore
|
|
right_start: s64
|
|
right_end: s64
|
|
if !ExecHostViewParameter(host, right) ||
|
|
ExecViewSpan(instance, frame_index, instruction, right, *right_store, *right_start, *right_end) < 0 { continue }
|
|
if left_store == right_store && left_start < right_end && right_start < left_end {
|
|
return ExecFail(instance, .Host)
|
|
}
|
|
}
|
|
}
|
|
return instance.failure.problem == .None
|
|
}
|
|
|
|
// Copies the elements of each mutable view argument the host changed back
|
|
// into the view's storage. An element whose own image bytes are the ones
|
|
// the host was given is left as it is, so an unchanged string in it takes
|
|
// no new bytes and read-only storage passes when nothing in it changed.
|
|
ExecTypedHostCopyBack :: (instance: *LirExecInstance, frame_index: s64,
|
|
instruction: *LirInstruction, host: LirExecHostBinding) -> bool {
|
|
plan := instance.plan
|
|
program := plan.program
|
|
for index: cast(s64)0..instruction.operands.count - 1 {
|
|
argument := instance.typed_arguments[index]
|
|
if !argument.changed { continue }
|
|
if !ExecHostViewParameter(host, index) { return ExecFail(instance, .Host) }
|
|
source := ExecFrameValueOffset(instance, frame_index, instruction.operands[index])
|
|
count := ExecReadBits(instance.storage[:], source + 8, 8)
|
|
image := argument.bytes
|
|
if image.count < 16 || ExecReadBits(image, 8, 8) != count { return ExecFail(instance, .Host) }
|
|
if count == 0 { continue }
|
|
store: ExecStore
|
|
at: s64
|
|
end: s64
|
|
found := ExecViewSpan(instance, frame_index, instruction, index, *store, *at, *end)
|
|
if found < 0 { return ExecFail(instance, .Host) }
|
|
writable := instance.addresses[found].writable
|
|
element := program.types[program.types[argument.type].fields[0]].element
|
|
width := plan.type_sizes[element]
|
|
start := ExecReadBits(image, 0, 8)
|
|
if start > cast(u64)image.count ||
|
|
count > cast(u64)((image.count - cast(s64)start) / width) { return ExecFail(instance, .Host) }
|
|
// The elements of the image the host was given.
|
|
given := cast(s64)instance.host_arguments[index]
|
|
given += cast(s64)ExecReadBits(instance.host_bytes[:], given, 8)
|
|
kind := program.types[element].kind
|
|
if kind == .Integer || kind == .Float {
|
|
bytes := cast(s64)count * width
|
|
if ExecBytesMatchAcross(image, cast(s64)start, instance.host_bytes[:], given, bytes) { continue }
|
|
if !writable { return ExecFail(instance, .Pointer) }
|
|
if !ExecSpend(instance, ExecCopyCost(bytes)) { return false }
|
|
for byte: cast(s64)0..bytes - 1 {
|
|
ExecStoreBits(instance, store, at + byte, 1, cast(u64)image[cast(s64)start + byte])
|
|
}
|
|
continue
|
|
}
|
|
for item: cast(s64)0..cast(s64)count - 1 {
|
|
from := cast(s64)start + item * width
|
|
if ExecBytesMatchAcross(image, from, instance.host_bytes[:], given + item * width, width) { continue }
|
|
if !writable { return ExecFail(instance, .Pointer) }
|
|
if !ExecHostDecode(instance, element, image, from, store, at + item * width, 1) { return false }
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
ExecHostBinding :: (instance: *LirExecInstance, function: s32) -> s64 {
|
|
for index: cast(s64)0..instance.hosts.count - 1 {
|
|
if instance.hosts[index].function == function { return index }
|
|
}
|
|
return -1
|
|
}
|
|
|
|
// ExecHostBinding, remembered per function in host_lookup (one entry per
|
|
// program function, sized when the instance opens). A function with no
|
|
// binding yet is not remembered: one can still be bound before a run.
|
|
ExecFastHostBinding :: (instance: *LirExecInstance, function: s32) -> s64 #inline {
|
|
known := instance.host_lookup[function]
|
|
if known > 0 { return cast(s64)known - 1 }
|
|
resolved := ExecHostBinding(instance, function)
|
|
if resolved >= 0 { instance.host_lookup[function] = cast(s32)(resolved + 1) }
|
|
return resolved
|
|
}
|
|
|
|
ExecPlatformWriteSignature :: (program: LirProgram, function: s32) -> bool {
|
|
fn := program.functions[function]
|
|
if fn.parameters.count != 3 || program.types[fn.result].kind != .Void { return false }
|
|
descriptor := program.types[fn.parameters[0]]
|
|
pointer := program.types[fn.parameters[1]]
|
|
count := program.types[fn.parameters[2]]
|
|
if descriptor.kind != .Integer || descriptor.bits != 64 || descriptor.is_signed ||
|
|
pointer.kind != .Pointer || count.kind != .Integer || count.bits != 64 || count.is_signed { return false }
|
|
element := program.types[pointer.element]
|
|
return element.kind == .Integer && element.bits == 8 && !element.is_signed
|
|
}
|
|
|
|
ExecPlatformWriteCall :: (instance: *LirExecInstance, frame_index: s64,
|
|
instruction: *LirInstruction, host: LirExecHostBinding) -> bool {
|
|
descriptor := ExecSlotBits(instance, instruction.operands[0])
|
|
token := ExecSlotBits(instance, instruction.operands[1])
|
|
count := ExecSlotBits(instance, instruction.operands[2])
|
|
if instance.failure.problem != .None { return false }
|
|
if count > cast(u64)9223372036854775807 { return ExecFail(instance, .Pointer) }
|
|
size := cast(s64)count
|
|
empty: [0]u8
|
|
bytes: []u8 = empty[:]
|
|
if size != 0 {
|
|
found := ExecFindAddress(instance, token)
|
|
if found < 0 || instance.addresses[found].extent < size || !ExecAddressValid(instance, found) {
|
|
return ExecFail(instance, .Pointer)
|
|
}
|
|
entry := instance.addresses[found]
|
|
pointee := instance.plan.program.types[entry.type]
|
|
if pointee.kind != .Integer || pointee.bits != 8 || pointee.is_signed { return ExecFail(instance, .Pointer) }
|
|
at := ExecAddressOffset(instance, found)
|
|
if instance.failure.problem != .None { return false }
|
|
if !ExecSpend(instance, ExecCopyCost(size)) { return false }
|
|
if entry.owned { bytes = instance.owned[at:at + size] }
|
|
else if entry.frame < 0 { bytes = instance.globals[at:at + size] }
|
|
else { bytes = instance.storage[at:at + size] }
|
|
}
|
|
if !host.write(host.context, descriptor, bytes) { return ExecFail(instance, .Host) }
|
|
instance.frames[frame_index].instruction += 1
|
|
return true
|
|
}
|
|
|
|
ExecHostCall :: (instance: *LirExecInstance, frame_index: s64, instruction: *LirInstruction) -> bool {
|
|
program := instance.plan.program
|
|
binding := ExecHostBinding(instance, instruction.symbol)
|
|
if binding < 0 { return ExecFail(instance, .Host) }
|
|
count := instruction.operands.count
|
|
if !ExecSpend(instance, count) { return false }
|
|
host := instance.hosts[binding]
|
|
if host.write != null { return ExecPlatformWriteCall(instance, frame_index, instruction, host) }
|
|
if host.typed != null {
|
|
// Host values the program dropped give their storage back once a
|
|
// collection's worth of new ones has come in.
|
|
if instance.host_since >= 65536 && instance.host_since >= instance.host_scanned &&
|
|
!ExecHostCollect(instance) { return false }
|
|
if !ExecTypedHostArguments(instance, frame_index, instruction) ||
|
|
!ExecHostViewsApart(instance, frame_index, instruction, host) { return false }
|
|
result := LirExecArgument.{.type = LirNoId}
|
|
if !host.typed(host.context, instruction.symbol,
|
|
VecSlice(instance.typed_arguments, 0, count), *result) ||
|
|
!ExecTypedHostCopyBack(instance, frame_index, instruction, host) ||
|
|
!ExecTypedHostResult(instance, frame_index, instruction, result) {
|
|
if instance.failure.problem == .None { return ExecFail(instance, .Host) }
|
|
return false
|
|
}
|
|
instance.frames[frame_index].instruction += 1
|
|
return true
|
|
}
|
|
if !VecResize(instance.host_arguments, count) { return ExecFail(instance, .Allocation) }
|
|
for at: cast(s64)0..count - 1 {
|
|
instance.host_arguments[at] = ExecSlotBits(instance, instruction.operands[at])
|
|
if instance.failure.problem != .None { return false }
|
|
}
|
|
result: u64
|
|
if !host.call(host.context, instruction.symbol, VecSlice(instance.host_arguments, 0, count), *result) {
|
|
return ExecFail(instance, .Host)
|
|
}
|
|
if instruction.result != LirNoId {
|
|
if !ExecHostCanonical(program.types[program.functions[instruction.symbol].result], result) {
|
|
return ExecFail(instance, .Host)
|
|
}
|
|
ExecWriteSlotBits(instance, instruction.result, result)
|
|
}
|
|
instance.frames[frame_index].instruction += 1
|
|
return true
|
|
}
|
|
|
|
ExecStep :: (instance: *LirExecInstance) -> bool {
|
|
frame_index := instance.frames.count - 1
|
|
// Read in place: the step runs for every instruction, and a copy of the
|
|
// frame record cost more than the step's own work.
|
|
frame := *instance.frames[frame_index]
|
|
instruction := *instance.plan.instructions[frame.instruction_base + frame.instruction]
|
|
if !ExecSpend(instance, 1) { return false }
|
|
op := instruction.op
|
|
if op == .Fuel {
|
|
amount := cast(s64)instruction.immediate
|
|
if amount > instance.fuel_remaining { return ExecFail(instance, .FuelLimit) }
|
|
instance.fuel_remaining -= amount
|
|
instance.frames[frame_index].instruction += 1
|
|
return true
|
|
}
|
|
if op == .Trap { return ExecFail(instance, .Trap, instruction.immediate) }
|
|
if op == .Unreachable { return ExecFail(instance, .Unreachable) }
|
|
edge_base := instance.plan.block_edge_bases[instance.plan.functions[frame.function].block_base + frame.block]
|
|
if op == .Jump {
|
|
return ExecEdge(instance, frame_index, *instruction.edges[0],
|
|
instance.plan.edge_direct[edge_base] != 0)
|
|
}
|
|
if op == .Branch {
|
|
condition := ExecSlotBits(instance, instruction.operands[0]) != 0
|
|
if instance.failure.problem != .None { return false }
|
|
edge_index: s64 = ifx condition then 0 else 1
|
|
return ExecEdge(instance, frame_index, *instruction.edges[edge_index],
|
|
instance.plan.edge_direct[edge_base + edge_index] != 0)
|
|
}
|
|
if op == .Return { return ExecFinishFrame(instance, frame_index, instruction) }
|
|
if op == .HostCall { return ExecHostCall(instance, frame_index, instruction) }
|
|
if op == .Call || op == .CallIndirect {
|
|
return ExecCallInstruction(instance, frame_index, instruction)
|
|
}
|
|
return ExecValueInstruction(instance, frame_index, instruction)
|
|
}
|
|
|
|
// ---- The run loop --------------------------------------------------------
|
|
//
|
|
// The loop runs a frame's compact code. A segment's work and fuel are
|
|
// charged when it is entered; when they do not fit, or anything unusual
|
|
// happens (a failure, a call, a host value, a new table entry it cannot
|
|
// make), the loop gives back the work and fuel of the instructions it has
|
|
// not run, puts the frame at the instruction it stopped on, and lets
|
|
// ExecStep run from there to the next segment. A run therefore charges
|
|
// and fails exactly where ExecStep alone would.
|
|
|
|
ExecSetPosition :: (instance: *LirExecInstance, frame_index: s64, block: s32, index: s32, base: s64) #inline {
|
|
instance.frames[frame_index].block = block
|
|
instance.frames[frame_index].instruction = index
|
|
instance.frames[frame_index].instruction_base = base
|
|
}
|
|
|
|
// Runs instructions through ExecStep, at least one, until the top frame
|
|
// stands at the start of a segment.
|
|
ExecRunSlow :: (instance: *LirExecInstance) -> bool {
|
|
while true {
|
|
if !ExecStep(instance) || instance.failure.problem != .None { return false }
|
|
if instance.frames.count == 0 { return true }
|
|
frame := *instance.frames[instance.frames.count - 1]
|
|
if instance.plan.segment_code[frame.instruction_base + frame.instruction] >= 0 { return true }
|
|
}
|
|
return true
|
|
}
|
|
|
|
// The table entry `token` names, or -1 (ExecFindAddress).
|
|
ExecFastFind :: (instance: *LirExecInstance, token: u64) -> s64 #inline {
|
|
low := token & cast(u64)1048575
|
|
if low == 0 { return -1 }
|
|
index := cast(s64)low - 1
|
|
if index >= instance.addresses.count || instance.addresses[index].token != token { return -1 }
|
|
return index
|
|
}
|
|
|
|
// Where a valid address's bytes start in its store, or -1 (ExecAddressOffset).
|
|
ExecFastLocate :: (instance: *LirExecInstance, address: *LirExecAddress) -> s64 #inline {
|
|
if address.owned {
|
|
if address.heap != 0 {
|
|
block := *instance.heap_blocks[address.heap - 1]
|
|
if !block.live || block.generation != address.generation { return -1 }
|
|
}
|
|
if address.offset < 0 || address.extent < 0 || address.offset > instance.owned.count ||
|
|
address.extent > instance.owned.count - address.offset { return -1 }
|
|
return address.offset
|
|
}
|
|
if address.frame < 0 { return address.offset }
|
|
if address.frame >= instance.frames.count ||
|
|
instance.frames[address.frame].generation != address.generation { return -1 }
|
|
return instance.frames[address.frame].base + address.offset
|
|
}
|
|
|
|
ExecGetBits :: (bytes: []u8, at: s64, size: s64) -> u64 #inline {
|
|
if size == 8 {
|
|
b := bytes[at:at + 8]
|
|
return cast(u64)b[0] | (cast(u64)b[1] << cast(u64)8) | (cast(u64)b[2] << cast(u64)16) |
|
|
(cast(u64)b[3] << cast(u64)24) | (cast(u64)b[4] << cast(u64)32) | (cast(u64)b[5] << cast(u64)40) |
|
|
(cast(u64)b[6] << cast(u64)48) | (cast(u64)b[7] << cast(u64)56)
|
|
}
|
|
if size == 4 {
|
|
b := bytes[at:at + 4]
|
|
return cast(u64)b[0] | (cast(u64)b[1] << cast(u64)8) | (cast(u64)b[2] << cast(u64)16) |
|
|
(cast(u64)b[3] << cast(u64)24)
|
|
}
|
|
if size == 1 { return cast(u64)bytes[at] }
|
|
return ExecReadBits(bytes, at, size)
|
|
}
|
|
|
|
ExecPutBits :: (bytes: []u8, at: s64, size: s64, value: u64) #inline {
|
|
if size == 8 {
|
|
b := bytes[at:at + 8]
|
|
b[0] = cast(u8)value
|
|
b[1] = cast(u8)(value >> cast(u64)8)
|
|
b[2] = cast(u8)(value >> cast(u64)16)
|
|
b[3] = cast(u8)(value >> cast(u64)24)
|
|
b[4] = cast(u8)(value >> cast(u64)32)
|
|
b[5] = cast(u8)(value >> cast(u64)40)
|
|
b[6] = cast(u8)(value >> cast(u64)48)
|
|
b[7] = cast(u8)(value >> cast(u64)56)
|
|
return
|
|
}
|
|
if size == 1 { bytes[at] = cast(u8)value; return }
|
|
ExecWriteBits(bytes, at, size, value)
|
|
}
|
|
|
|
ExecCopyBytes :: (bytes: []u8, from: s64, to: s64, count: s64) #inline {
|
|
if from == to { return }
|
|
// Apart, eight bytes at a time give the same bytes as one at a time.
|
|
if count >= 8 && (to + count <= from || from + count <= to) {
|
|
source := bytes[from:from + count]
|
|
target := bytes[to:to + count]
|
|
at: s64
|
|
while at + 8 <= count {
|
|
ExecPutBits(target, at, 8, ExecGetBits(source, at, 8))
|
|
at += 8
|
|
}
|
|
while at < count { target[at] = source[at]; at += 1 }
|
|
return
|
|
}
|
|
for index: cast(s64)0..count - 1 { bytes[to + index] = bytes[from + index] }
|
|
}
|
|
|
|
// How many of a view code's elements `extent` bytes hold, as `extent /
|
|
// code.size` gives it: a shift by `code.z` when the size is a power of two.
|
|
ExecFastPerElement :: (extent: s64, code: *LirExecCode) -> u64 #inline {
|
|
if code.z >= 0 && extent >= 0 { return cast(u64)extent >> cast(u64)code.z }
|
|
return cast(u64)(extent / code.size)
|
|
}
|
|
|
|
// A derivation's token, made as ExecDeriveToken would without its work
|
|
// charge (the segment paid it): a transient one takes the next of its
|
|
// entries. 0 hands the instruction to ExecStep;
|
|
// ExecFailedToken: failed, with the failure recorded.
|
|
ExecFailedToken :: () -> u64 #inline { return ~cast(u64)0 }
|
|
|
|
ExecFastDerive :: (instance: *LirExecInstance, words: []u64, frame_index: s64, code: *LirExecCode,
|
|
word_base: s64, view: bool, indexed: bool) -> u64 #inline {
|
|
base_token := words[word_base + code.a]
|
|
index_word: u64
|
|
count_word: u64
|
|
if view || indexed { index_word = words[word_base + code.b] }
|
|
if view { count_word = words[word_base + code.c] }
|
|
if code.memo >= 0 {
|
|
memo := *instance.derived_tokens[code.memo]
|
|
if memo.token != 0 && memo.base == base_token && memo.index == index_word &&
|
|
memo.count == count_word && ExecFastFind(instance, memo.token) >= 0 { return memo.token }
|
|
}
|
|
derived: LirExecAddress
|
|
if !ExecFastAddress(instance, words, code, word_base, view, indexed, *derived) { return 0 }
|
|
if code.flag != 0 {
|
|
if instance.transient_count == 0 { return 0 }
|
|
index := instance.transient_base + instance.transient_next
|
|
instance.transient_next += 1
|
|
if instance.transient_next == ExecTransientSlots { instance.transient_next = 0 }
|
|
entry := *instance.addresses[index]
|
|
version := (entry.version + 1) & cast(u64)268435455
|
|
<<entry = derived
|
|
entry.version = version
|
|
entry.token = ExecAddressToken(instance.identity, index, version)
|
|
entry.next = 0
|
|
return entry.token
|
|
}
|
|
token: u64
|
|
made := ExecFastIntern(instance, frame_index, code, *derived, *token)
|
|
if made < 0 { return ExecFailedToken() }
|
|
if made == 0 { return 0 }
|
|
if code.memo >= 0 {
|
|
instance.derived_tokens[code.memo] = .{.base = base_token, .index = index_word,
|
|
.count = count_word, .token = token}
|
|
}
|
|
return token
|
|
}
|
|
|
|
// Stands where ExecStep would once `code` has run and charged its own
|
|
// work: for a failure it reports after its host was called.
|
|
ExecFastStand :: (instance: *LirExecInstance, frame_index: s64, code: *LirExecCode) #cold {
|
|
instance.work_remaining += code.rest_work - code.cost
|
|
instance.fuel_remaining += code.rest_fuel
|
|
ExecSetPosition(instance, frame_index, code.block, code.index, code.base)
|
|
}
|
|
|
|
// A HostWrite from the fast loop, as ExecPlatformWriteCall makes it:
|
|
// `count` bytes of `element` at `pointer` to `descriptor`. 1 when written;
|
|
// 0 hands the instruction to ExecStep with nothing done; -1 when the host
|
|
// failed, standing on the instruction.
|
|
ExecFastWrite :: (instance: *LirExecInstance, frame_index: s64, code: *LirExecCode,
|
|
function: s32, element: s32, descriptor: u64, pointer: u64, count: u64) -> s32 #inline {
|
|
binding := ExecFastHostBinding(instance, function)
|
|
if binding < 0 || count > cast(u64)9223372036854775807 { return 0 }
|
|
host := instance.hosts[binding]
|
|
if host.write == null { return 0 }
|
|
size := cast(s64)count
|
|
no_bytes: [0]u8
|
|
bytes: []u8 = no_bytes[:]
|
|
copy: s64 = 0
|
|
if size != 0 {
|
|
index := ExecFastFind(instance, pointer)
|
|
if index < 0 { return 0 }
|
|
address := *instance.addresses[index]
|
|
if address.type != element || address.extent < size { return 0 }
|
|
at := ExecFastLocate(instance, address)
|
|
if at < 0 { return 0 }
|
|
if address.owned { bytes = instance.owned[at:at + size] }
|
|
else if address.frame < 0 { bytes = instance.globals[at:at + size] }
|
|
else { bytes = instance.storage[at:at + size] }
|
|
copy = ExecCopyCost(size)
|
|
if copy > instance.work_remaining { return 0 }
|
|
}
|
|
instance.work_remaining -= copy
|
|
if !host.write(host.context, descriptor, bytes) {
|
|
ExecFastStand(instance, frame_index, code)
|
|
unused ExecFail(instance, .Host)
|
|
return -1
|
|
}
|
|
return 1
|
|
}
|
|
|
|
ExecFastIntern :: (instance: *LirExecInstance, frame_index: s64, code: *LirExecCode,
|
|
pointer: *LirExecAddress, token: *u64) -> s32 {
|
|
address := <<pointer
|
|
found := ExecAddressLookup(instance, address)
|
|
if found >= 0 {
|
|
<<token = instance.addresses[found].token
|
|
return 1
|
|
}
|
|
if instance.address_free.count == 0 && (instance.addresses.count >= instance.limits.addresses ||
|
|
instance.addresses.count >= ExecAddressSlots) { return 0 }
|
|
// ExecNewAddress records its own failures: stand where ExecStep would.
|
|
rest_work := code.rest_work - code.cost
|
|
instance.work_remaining += rest_work
|
|
instance.fuel_remaining += code.rest_fuel
|
|
ExecSetPosition(instance, frame_index, code.block, code.index, code.base)
|
|
index := ExecNewAddress(instance, address)
|
|
if index < 0 { return -1 }
|
|
instance.work_remaining -= rest_work
|
|
instance.fuel_remaining -= code.rest_fuel
|
|
<<token = instance.addresses[index].token
|
|
return 1
|
|
}
|
|
|
|
// Takes edge `edge`. The next code to run, ExecHandOver when the run goes
|
|
// on at a segment the outer loop enters, or ExecBail when the edge's
|
|
// copies do not fit and the terminator goes to ExecStep.
|
|
ExecFastEdge :: (instance: *LirExecInstance, words: []u64, storage: []u8, frame_index: s64,
|
|
edge: s64, word_base: s64, storage_base: s64) -> s64 #inline {
|
|
plan := instance.plan
|
|
target := *plan.edge_plans[edge]
|
|
if target.work > instance.work_remaining { return ExecBail }
|
|
instance.work_remaining -= target.work
|
|
if target.direct {
|
|
for at: target.moves..target.moves + target.count - 1 {
|
|
move := *plan.moves[at]
|
|
if move.word { words[word_base + move.to] = words[word_base + move.from] }
|
|
else { ExecCopyBytes(storage, storage_base + move.from, storage_base + move.to, move.size) }
|
|
}
|
|
} else {
|
|
for at: target.moves..target.moves + target.count - 1 {
|
|
move := *plan.moves[at]
|
|
if move.word {
|
|
ExecWriteBits(storage, storage_base + move.scratch, move.size, words[word_base + move.from])
|
|
} else { ExecCopyBytes(storage, storage_base + move.from, storage_base + move.scratch, move.size) }
|
|
}
|
|
for at: target.moves..target.moves + target.count - 1 {
|
|
move := *plan.moves[at]
|
|
if move.word {
|
|
words[word_base + move.to] = ExecReadBits(storage, storage_base + move.scratch, move.size)
|
|
} else { ExecCopyBytes(storage, storage_base + move.scratch, storage_base + move.to, move.size) }
|
|
}
|
|
}
|
|
if target.target_work > instance.work_remaining || target.target_fuel > instance.fuel_remaining {
|
|
ExecSetPosition(instance, frame_index, target.target_block, 0, target.target_base)
|
|
return ExecHandOver
|
|
}
|
|
instance.work_remaining -= target.target_work
|
|
instance.fuel_remaining -= target.target_fuel
|
|
return target.target_code
|
|
}
|
|
|
|
// Statuses of the run loop, beside the index of code to hand to ExecStep.
|
|
ExecFailed :: -1
|
|
ExecHandOver :: -2
|
|
ExecBail :: -3
|
|
|
|
// The bits of a word a Load or Extract reads: bools as 0 or 1, integers masked.
|
|
ExecFastCanonical :: (code: *LirExecCode, bits: u64) -> u64 #inline {
|
|
if code.flag != 0 { return cast(u64)(bits != 0) }
|
|
return bits & code.immediate
|
|
}
|
|
|
|
// Load and Store through a pointer word; false hands the instruction over.
|
|
ExecFastMemory :: (instance: *LirExecInstance, words: []u64, storage: []u8, owned: []u8, globals: []u8,
|
|
code: *LirExecCode, word_base: s64, storage_base: s64, store: bool) -> bool #inline {
|
|
index := ExecFastFind(instance, words[word_base + code.a])
|
|
if index < 0 { return false }
|
|
address := *instance.addresses[index]
|
|
if address.type != code.type || code.size > address.extent || store && !address.writable { return false }
|
|
at := ExecFastLocate(instance, address)
|
|
if at < 0 { return false }
|
|
size := code.size
|
|
if !store {
|
|
if code.result >= 0 {
|
|
bits: u64
|
|
if address.owned { bits = ExecGetBits(owned, at, size) }
|
|
else if address.frame < 0 { bits = ExecGetBits(globals, at, size) }
|
|
else { bits = ExecGetBits(storage, at, size) }
|
|
words[word_base + code.result] = ExecFastCanonical(code, bits)
|
|
return true
|
|
}
|
|
to := storage_base + code.x
|
|
if address.owned { for byte: cast(s64)0..size - 1 { storage[to + byte] = owned[at + byte] } }
|
|
else if address.frame < 0 { for byte: cast(s64)0..size - 1 { storage[to + byte] = globals[at + byte] } }
|
|
else { ExecCopyBytes(storage, at, to, size) }
|
|
return true
|
|
}
|
|
if code.b >= 0 {
|
|
bits := words[word_base + code.b]
|
|
if address.owned { ExecPutBits(owned, at, size, bits) }
|
|
else if address.frame < 0 { ExecPutBits(globals, at, size, bits) }
|
|
else { ExecPutBits(storage, at, size, bits) }
|
|
return true
|
|
}
|
|
from := storage_base + code.x
|
|
if address.owned { for byte: cast(s64)0..size - 1 { owned[at + byte] = storage[from + byte] } }
|
|
else if address.frame < 0 { for byte: cast(s64)0..size - 1 { globals[at + byte] = storage[from + byte] } }
|
|
else { for byte: cast(s64)0..size - 1 { storage[at + byte] = storage[from + byte] } }
|
|
return true
|
|
}
|
|
|
|
// The address a FieldAddress, ElementIndex or ElementView derives, as
|
|
// ExecFieldAddress and ExecElementAddress make it; false hands it over.
|
|
ExecFastAddress :: (instance: *LirExecInstance, words: []u64, code: *LirExecCode, word_base: s64,
|
|
view: bool, indexed: bool, derived: *LirExecAddress) -> bool #inline {
|
|
index := ExecFastFind(instance, words[word_base + code.a])
|
|
if index < 0 { return false }
|
|
base := *instance.addresses[index]
|
|
// A FieldAddress first: its address, a transient one, is this one's base.
|
|
field: LirExecAddress
|
|
if code.prefix != 0 {
|
|
if instance.transient_count == 0 || base.type != code.prefix_type { return false }
|
|
frame: s64 = -1
|
|
generation: u64
|
|
global := base.global
|
|
if base.frame >= 0 {
|
|
if base.frame >= instance.frames.count ||
|
|
instance.frames[base.frame].generation != base.generation { return false }
|
|
frame = base.frame
|
|
generation = base.generation
|
|
global = -1
|
|
} else if base.heap != 0 { generation = base.generation }
|
|
field = .{.global = global, .frame = frame, .generation = generation,
|
|
.offset = base.offset + code.prefix_offset, .extent = code.prefix_size, .type = code.type,
|
|
.owned = base.owned, .writable = base.writable, .heap = base.heap}
|
|
base = *field
|
|
}
|
|
if base.type != code.type { return false }
|
|
if view {
|
|
element := words[word_base + code.b]
|
|
count := words[word_base + code.c]
|
|
if (element & code.sign_b) != 0 || (count & code.sign_c) != 0 || element >= count ||
|
|
count > cast(u64)9223372036854775807 ||
|
|
code.size != 0 && count > ExecFastPerElement(base.extent, code) { return false }
|
|
offset := cast(s64)element * code.size
|
|
<<derived = .{.global = base.global, .frame = base.frame, .generation = base.generation,
|
|
.offset = base.offset + offset, .extent = base.extent - offset, .type = code.target,
|
|
.owned = base.owned, .writable = base.writable, .heap = base.heap}
|
|
return true
|
|
}
|
|
offset := code.x
|
|
extent := code.size
|
|
if indexed {
|
|
member := words[word_base + code.b]
|
|
if (member & code.sign_b) != 0 || member >= code.extra { return false }
|
|
offset = cast(s64)member * code.size
|
|
extent = base.extent - offset
|
|
if extent < code.size { return false }
|
|
}
|
|
frame: s64 = -1
|
|
generation: u64
|
|
global := base.global
|
|
if base.frame >= 0 {
|
|
if base.frame >= instance.frames.count ||
|
|
instance.frames[base.frame].generation != base.generation { return false }
|
|
frame = base.frame
|
|
generation = base.generation
|
|
global = -1
|
|
} else if base.heap != 0 { generation = base.generation }
|
|
<<derived = .{.global = global, .frame = frame, .generation = generation,
|
|
.offset = base.offset + offset, .extent = extent, .type = code.target,
|
|
.owned = base.owned, .writable = base.writable, .heap = base.heap}
|
|
return true
|
|
}
|
|
|
|
// A derivation and the Load or Store that uses it, as one: the address is
|
|
// derived as ExecFastAddress derives it and used where it lies, with the
|
|
// checks ExecAddressValid and ExecCopyAddressToValue make. false hands the
|
|
// derivation, and so the pair, to ExecStep.
|
|
ExecFastFusedMemory :: (instance: *LirExecInstance, words: []u64, storage: []u8, owned: []u8, globals: []u8,
|
|
code: *LirExecCode, word_base: s64, storage_base: s64, view: bool, indexed: bool, store: bool) -> bool #inline {
|
|
// The derivation is a transient one; its entries are made by ExecStep
|
|
// the first time, and with them any address-limit failure.
|
|
if instance.transient_count == 0 { return false }
|
|
address: LirExecAddress
|
|
if !ExecFastAddress(instance, words, code, word_base, view, indexed, *address) { return false }
|
|
size := code.size
|
|
if size > address.extent || store && !address.writable { return false }
|
|
at := ExecFastLocate(instance, *address)
|
|
if at < 0 { return false }
|
|
if !store {
|
|
if code.result >= 0 {
|
|
bits: u64
|
|
if address.owned { bits = ExecGetBits(owned, at, size) }
|
|
else if address.frame < 0 { bits = ExecGetBits(globals, at, size) }
|
|
else { bits = ExecGetBits(storage, at, size) }
|
|
words[word_base + code.result] = ExecFastCanonical(code, bits)
|
|
return true
|
|
}
|
|
to := storage_base + code.w
|
|
if address.owned { for byte: cast(s64)0..size - 1 { storage[to + byte] = owned[at + byte] } }
|
|
else if address.frame < 0 { for byte: cast(s64)0..size - 1 { storage[to + byte] = globals[at + byte] } }
|
|
else { ExecCopyBytes(storage, at, to, size) }
|
|
return true
|
|
}
|
|
if code.value >= 0 {
|
|
bits := words[word_base + code.value]
|
|
if address.owned { ExecPutBits(owned, at, size, bits) }
|
|
else if address.frame < 0 { ExecPutBits(globals, at, size, bits) }
|
|
else { ExecPutBits(storage, at, size, bits) }
|
|
return true
|
|
}
|
|
from := storage_base + code.w
|
|
if address.owned { for byte: cast(s64)0..size - 1 { owned[at + byte] = storage[from + byte] } }
|
|
else if address.frame < 0 { for byte: cast(s64)0..size - 1 { globals[at + byte] = storage[from + byte] } }
|
|
else { for byte: cast(s64)0..size - 1 { storage[at + byte] = storage[from + byte] } }
|
|
return true
|
|
}
|
|
|
|
// Insert into a copy of the aggregate; false hands the instruction over.
|
|
ExecFastInsert :: (words: []u64, storage: []u8, code: *LirExecCode, word_base: s64,
|
|
storage_base: s64, indexed: bool, word: bool) -> bool #inline {
|
|
offset := cast(s64)code.immediate
|
|
if indexed {
|
|
member := words[word_base + code.c]
|
|
if (member & code.sign_c) != 0 || member >= code.extra { return false }
|
|
offset = cast(s64)member * code.z
|
|
}
|
|
ExecCopyBytes(storage, storage_base + code.x, storage_base + code.y, code.size)
|
|
if word { ExecPutBits(storage, storage_base + code.y + offset, code.z, words[word_base + code.b]) }
|
|
else { ExecCopyBytes(storage, storage_base + code.w, storage_base + code.y + offset, code.z) }
|
|
return true
|
|
}
|
|
|
|
ExecFastFloat64 :: (plan: *LirExecPlan, handler: LirExecHandler, left: u64, right: u64) -> u64 #inline {
|
|
a := ExecBitsFloat(plan, left, false)
|
|
b := ExecBitsFloat(plan, right, false)
|
|
value: float64
|
|
if handler == .FloatAdd64 { value = a + b }
|
|
else if handler == .FloatSubtract64 { value = a - b }
|
|
else if handler == .FloatMultiply64 { value = a * b }
|
|
else { value = a / b }
|
|
return ExecFloat64Bits(value)
|
|
}
|
|
|
|
ExecFastFloat32 :: (plan: *LirExecPlan, handler: LirExecHandler, left: u64, right: u64) -> u64 #inline {
|
|
a := cast(float32)ExecBitsFloat(plan, left, true)
|
|
b := cast(float32)ExecBitsFloat(plan, right, true)
|
|
value: float32
|
|
if handler == .FloatAdd32 { value = a + b }
|
|
else if handler == .FloatSubtract32 { value = a - b }
|
|
else if handler == .FloatMultiply32 { value = a * b }
|
|
else { value = a / b }
|
|
return ExecFloat32Bits(value)
|
|
}
|
|
|
|
ExecFastFloatCompare :: (plan: *LirExecPlan, code: *LirExecCode, left: u64, right: u64, single: bool) -> u64 #inline {
|
|
a := ExecBitsFloat(plan, left, single)
|
|
b := ExecBitsFloat(plan, right, single)
|
|
op := cast(LirOp)cast(s32)code.extra
|
|
answer: bool
|
|
if op == .Equal { answer = a == b }
|
|
else if op == .NotEqual { answer = a != b }
|
|
else if op == .Less { answer = a < b }
|
|
else if op == .LessEqual { answer = a <= b }
|
|
else if op == .Greater { answer = a > b }
|
|
else { answer = a >= b }
|
|
return cast(u64)answer
|
|
}
|
|
|
|
// Divide and Remainder; false (a zero divisor) hands the instruction over.
|
|
ExecFastDivide :: (code: *LirExecCode, left: u64, right: u64, signed: bool, remainder: bool, result: *u64) -> bool #inline {
|
|
if right == 0 { return false }
|
|
if !signed {
|
|
<<result = ifx remainder then left % right else left / right
|
|
return true
|
|
}
|
|
bits := cast(s32)code.size
|
|
signed_right := ExecSigned(right, bits)
|
|
minimum := cast(u64)1 << cast(u64)(bits - 1)
|
|
if left == minimum && signed_right == -1 { <<result = ifx remainder then cast(u64)0 else minimum }
|
|
else if remainder { <<result = cast(u64)(ExecSigned(left, bits) % signed_right) & code.immediate }
|
|
else { <<result = cast(u64)(ExecSigned(left, bits) / signed_right) & code.immediate }
|
|
return true
|
|
}
|
|
|
|
// Shifts; false (a count of the width or more) hands the instruction over.
|
|
ExecFastShift :: (code: *LirExecCode, left: u64, count: u64, right: bool, signed: bool, result: *u64) -> bool #inline {
|
|
if count >= cast(u64)code.size { return false }
|
|
if !right { <<result = (left << count) & code.immediate; return true }
|
|
value := left >> count
|
|
if signed && count != 0 && (left & (cast(u64)1 << cast(u64)(code.size - 1))) != 0 {
|
|
value |= code.immediate ^ (code.immediate >> count)
|
|
}
|
|
<<result = value
|
|
return true
|
|
}
|
|
|
|
ExecFastFloatInteger :: (plan: *LirExecPlan, code: *LirExecCode, bits: u64, result: *u64) -> bool #inline {
|
|
value := ExecBitsFloat(plan, bits, code.size == 32)
|
|
if !Finite64(value) { return false }
|
|
if code.flag != 0 {
|
|
bound := plan.powers[1073 + code.y]
|
|
if value < 0.0 - bound || value >= bound { return false }
|
|
<<result = cast(u64)cast(s64)value & code.immediate
|
|
return true
|
|
}
|
|
bound := plan.powers[1074 + code.y]
|
|
if value < 0.0 || value >= bound { return false }
|
|
<<result = cast(u64)value & code.immediate
|
|
return true
|
|
}
|
|
|
|
ExecFastIntegerFloat :: (code: *LirExecCode, bits: u64) -> u64 #inline {
|
|
source := cast(s32)code.size
|
|
if code.y == 32 {
|
|
value := ifx code.flag != 0 then cast(float32)ExecSigned(bits, source) else cast(float32)(bits & code.extra)
|
|
return ExecFloat32Bits(value)
|
|
}
|
|
value := ifx code.flag != 0 then cast(float64)ExecSigned(bits, source) else cast(float64)(bits & code.extra)
|
|
return ExecFloat64Bits(value)
|
|
}
|
|
|
|
ExecFastConvertInteger :: (code: *LirExecCode, bits: u64) -> u64 #inline {
|
|
value := bits & code.extra
|
|
if code.flag != 0 && code.size < 64 && (value & (cast(u64)1 << cast(u64)(code.size - 1))) != 0 { value |= ~code.extra }
|
|
return value & code.immediate
|
|
}
|
|
|
|
// Runs the top frame's code from `start`. Returns the code to hand to
|
|
// ExecStep (a Slow instruction, or one this loop gives back), ExecHandOver
|
|
// when the frame stands at a segment the outer loop enters, or ExecFailed.
|
|
// It reaches the frame's words and storage through views: nothing it calls
|
|
// resizes them, and whatever would goes through ExecStep after it returns.
|
|
ExecRunCode :: (instance: *LirExecInstance, frame_index: s64, start: s64) -> s64 {
|
|
plan := instance.plan
|
|
wb := instance.frames[frame_index].word_base
|
|
sb := instance.frames[frame_index].base
|
|
words := instance.words[:]
|
|
storage := instance.storage[:]
|
|
owned := instance.owned[:]
|
|
globals := instance.globals[:]
|
|
pc := start
|
|
while true {
|
|
c := *plan.code[pc]
|
|
h := c.handler
|
|
next := pc + 1
|
|
if h == .Add {
|
|
words[wb + c.result] = (words[wb + c.a] + words[wb + c.b]) & c.immediate
|
|
} else if h == .Subtract {
|
|
words[wb + c.result] = (words[wb + c.a] - words[wb + c.b]) & c.immediate
|
|
} else if h == .Multiply {
|
|
words[wb + c.result] = (words[wb + c.a] * words[wb + c.b]) & c.immediate
|
|
} else if h == .BitAnd {
|
|
words[wb + c.result] = words[wb + c.a] & words[wb + c.b]
|
|
} else if h == .BitOr {
|
|
words[wb + c.result] = words[wb + c.a] | words[wb + c.b]
|
|
} else if h == .BitXor {
|
|
words[wb + c.result] = words[wb + c.a] ^ words[wb + c.b]
|
|
} else if h == .Equal {
|
|
words[wb + c.result] = cast(u64)(words[wb + c.a] == words[wb + c.b])
|
|
} else if h == .NotEqual {
|
|
words[wb + c.result] = cast(u64)(words[wb + c.a] != words[wb + c.b])
|
|
} else if h == .Less {
|
|
words[wb + c.result] = cast(u64)(words[wb + c.a] < words[wb + c.b])
|
|
} else if h == .LessEqual {
|
|
words[wb + c.result] = cast(u64)(words[wb + c.a] <= words[wb + c.b])
|
|
} else if h == .Greater {
|
|
words[wb + c.result] = cast(u64)(words[wb + c.a] > words[wb + c.b])
|
|
} else if h == .GreaterEqual {
|
|
words[wb + c.result] = cast(u64)(words[wb + c.a] >= words[wb + c.b])
|
|
} else if h == .SignedLess {
|
|
words[wb + c.result] = cast(u64)(ExecSigned(words[wb + c.a], cast(s32)c.size) <
|
|
ExecSigned(words[wb + c.b], cast(s32)c.size))
|
|
} else if h == .SignedLessEqual {
|
|
words[wb + c.result] = cast(u64)(ExecSigned(words[wb + c.a], cast(s32)c.size) <=
|
|
ExecSigned(words[wb + c.b], cast(s32)c.size))
|
|
} else if h == .SignedGreater {
|
|
words[wb + c.result] = cast(u64)(ExecSigned(words[wb + c.a], cast(s32)c.size) >
|
|
ExecSigned(words[wb + c.b], cast(s32)c.size))
|
|
} else if h == .SignedGreaterEqual {
|
|
words[wb + c.result] = cast(u64)(ExecSigned(words[wb + c.a], cast(s32)c.size) >=
|
|
ExecSigned(words[wb + c.b], cast(s32)c.size))
|
|
} else if h == .Jump {
|
|
next = ExecFastEdge(instance, words, storage, frame_index, c.edge, wb, sb)
|
|
} else if h == .Branch {
|
|
next = ExecFastEdge(instance, words, storage, frame_index,
|
|
c.edge + cast(s64)(words[wb + c.a] == 0), wb, sb)
|
|
} else if h == .BranchEqual {
|
|
condition := words[wb + c.a] == words[wb + c.b]
|
|
words[wb + c.result] = cast(u64)condition
|
|
next = ExecFastEdge(instance, words, storage, frame_index, c.edge + cast(s64)!condition, wb, sb)
|
|
} else if h == .BranchNotEqual {
|
|
condition := words[wb + c.a] != words[wb + c.b]
|
|
words[wb + c.result] = cast(u64)condition
|
|
next = ExecFastEdge(instance, words, storage, frame_index, c.edge + cast(s64)!condition, wb, sb)
|
|
} else if h == .BranchLess {
|
|
condition := words[wb + c.a] < words[wb + c.b]
|
|
words[wb + c.result] = cast(u64)condition
|
|
next = ExecFastEdge(instance, words, storage, frame_index, c.edge + cast(s64)!condition, wb, sb)
|
|
} else if h == .BranchLessEqual {
|
|
condition := words[wb + c.a] <= words[wb + c.b]
|
|
words[wb + c.result] = cast(u64)condition
|
|
next = ExecFastEdge(instance, words, storage, frame_index, c.edge + cast(s64)!condition, wb, sb)
|
|
} else if h == .BranchGreater {
|
|
condition := words[wb + c.a] > words[wb + c.b]
|
|
words[wb + c.result] = cast(u64)condition
|
|
next = ExecFastEdge(instance, words, storage, frame_index, c.edge + cast(s64)!condition, wb, sb)
|
|
} else if h == .BranchGreaterEqual {
|
|
condition := words[wb + c.a] >= words[wb + c.b]
|
|
words[wb + c.result] = cast(u64)condition
|
|
next = ExecFastEdge(instance, words, storage, frame_index, c.edge + cast(s64)!condition, wb, sb)
|
|
} else if h == .BranchSignedLess {
|
|
condition := ExecSigned(words[wb + c.a], cast(s32)c.size) < ExecSigned(words[wb + c.b], cast(s32)c.size)
|
|
words[wb + c.result] = cast(u64)condition
|
|
next = ExecFastEdge(instance, words, storage, frame_index, c.edge + cast(s64)!condition, wb, sb)
|
|
} else if h == .BranchSignedLessEqual {
|
|
condition := ExecSigned(words[wb + c.a], cast(s32)c.size) <= ExecSigned(words[wb + c.b], cast(s32)c.size)
|
|
words[wb + c.result] = cast(u64)condition
|
|
next = ExecFastEdge(instance, words, storage, frame_index, c.edge + cast(s64)!condition, wb, sb)
|
|
} else if h == .BranchSignedGreater {
|
|
condition := ExecSigned(words[wb + c.a], cast(s32)c.size) > ExecSigned(words[wb + c.b], cast(s32)c.size)
|
|
words[wb + c.result] = cast(u64)condition
|
|
next = ExecFastEdge(instance, words, storage, frame_index, c.edge + cast(s64)!condition, wb, sb)
|
|
} else if h == .BranchSignedGreaterEqual {
|
|
condition := ExecSigned(words[wb + c.a], cast(s32)c.size) >= ExecSigned(words[wb + c.b], cast(s32)c.size)
|
|
words[wb + c.result] = cast(u64)condition
|
|
next = ExecFastEdge(instance, words, storage, frame_index, c.edge + cast(s64)!condition, wb, sb)
|
|
} else if h == .ExtractWord {
|
|
words[wb + c.result] = ExecFastCanonical(c, ExecGetBits(storage, sb + c.x, c.size))
|
|
} else if h == .ExtractBytes {
|
|
ExecCopyBytes(storage, sb + c.x, sb + c.y, c.size)
|
|
} else if h == .ExtractWordPair {
|
|
words[wb + c.result] = ExecFastCanonical(c, ExecGetBits(storage, sb + c.x, c.size))
|
|
bits := ExecGetBits(storage, sb + c.y, c.z)
|
|
if c.c != 0 { bits = cast(u64)(bits != 0) } else { bits &= c.extra }
|
|
words[wb + c.b] = bits
|
|
} else if h == .AddJump {
|
|
words[wb + c.result] = (words[wb + c.a] + words[wb + c.b]) & c.immediate
|
|
next = ExecFastEdge(instance, words, storage, frame_index, c.edge, wb, sb)
|
|
} else if h == .ExtractWordIndexed {
|
|
member := words[wb + c.c]
|
|
if (member & c.sign_c) != 0 || member >= c.extra { return pc }
|
|
words[wb + c.result] = ExecFastCanonical(c, ExecGetBits(storage, sb + c.x + cast(s64)member * c.size, c.size))
|
|
} else if h == .ExtractBytesIndexed {
|
|
member := words[wb + c.c]
|
|
if (member & c.sign_c) != 0 || member >= c.extra { return pc }
|
|
ExecCopyBytes(storage, sb + c.x + cast(s64)member * c.size, sb + c.y, c.size)
|
|
} else if h == .InsertWord {
|
|
if !ExecFastInsert(words, storage, c, wb, sb, false, true) { return pc }
|
|
} else if h == .InsertBytes {
|
|
if !ExecFastInsert(words, storage, c, wb, sb, false, false) { return pc }
|
|
} else if h == .InsertWordIndexed {
|
|
if !ExecFastInsert(words, storage, c, wb, sb, true, true) { return pc }
|
|
} else if h == .InsertBytesIndexed {
|
|
if !ExecFastInsert(words, storage, c, wb, sb, true, false) { return pc }
|
|
} else if h == .Load {
|
|
if !ExecFastMemory(instance, words, storage, owned, globals, c, wb, sb, false) { return pc }
|
|
} else if h == .Store {
|
|
if !ExecFastMemory(instance, words, storage, owned, globals, c, wb, sb, true) { return pc }
|
|
} else if h == .LoadField {
|
|
if !ExecFastFusedMemory(instance, words, storage, owned, globals, c, wb, sb, false, false, false) { return pc }
|
|
} else if h == .LoadIndex {
|
|
if !ExecFastFusedMemory(instance, words, storage, owned, globals, c, wb, sb, false, true, false) { return pc }
|
|
} else if h == .LoadView {
|
|
if !ExecFastFusedMemory(instance, words, storage, owned, globals, c, wb, sb, true, false, false) { return pc }
|
|
} else if h == .StoreField {
|
|
if !ExecFastFusedMemory(instance, words, storage, owned, globals, c, wb, sb, false, false, true) { return pc }
|
|
} else if h == .StoreIndex {
|
|
if !ExecFastFusedMemory(instance, words, storage, owned, globals, c, wb, sb, false, true, true) { return pc }
|
|
} else if h == .StoreView {
|
|
if !ExecFastFusedMemory(instance, words, storage, owned, globals, c, wb, sb, true, false, true) { return pc }
|
|
} else if h == .FieldAddress {
|
|
token := ExecFastDerive(instance, words, frame_index, c, wb, false, false)
|
|
if token == 0 { return pc }
|
|
if token == ExecFailedToken() { return ExecFailed }
|
|
words[wb + c.result] = token
|
|
} else if h == .ElementIndex {
|
|
token := ExecFastDerive(instance, words, frame_index, c, wb, false, true)
|
|
if token == 0 { return pc }
|
|
if token == ExecFailedToken() { return ExecFailed }
|
|
words[wb + c.result] = token
|
|
} else if h == .ElementView {
|
|
token := ExecFastDerive(instance, words, frame_index, c, wb, true, false)
|
|
if token == 0 { return pc }
|
|
if token == ExecFailedToken() { return ExecFailed }
|
|
words[wb + c.result] = token
|
|
} else if h == .ElementSlice {
|
|
// Bounds that do not hold, and an empty slice (its base's own
|
|
// token), run on ExecStep.
|
|
high := words[wb + c.value]
|
|
if (high & c.extra) != 0 || words[wb + c.b] >= high || high > words[wb + c.c] { return pc }
|
|
token := ExecFastDerive(instance, words, frame_index, c, wb, true, false)
|
|
if token == 0 { return pc }
|
|
if token == ExecFailedToken() { return ExecFailed }
|
|
words[wb + c.result] = token
|
|
} else if h == .Negate {
|
|
words[wb + c.result] = (cast(u64)0 - words[wb + c.a]) & c.immediate
|
|
} else if h == .BitNot {
|
|
words[wb + c.result] = ~words[wb + c.a] & c.immediate
|
|
} else if h == .FloatNegate {
|
|
words[wb + c.result] = words[wb + c.a] ^ c.immediate
|
|
} else if h == .ConvertInteger {
|
|
words[wb + c.result] = ExecFastConvertInteger(c, words[wb + c.a])
|
|
} else if h == .ConvertBoolInteger {
|
|
words[wb + c.result] = cast(u64)(words[wb + c.a] != 0) & c.immediate
|
|
} else if h == .ConvertIntegerBool {
|
|
words[wb + c.result] = cast(u64)((words[wb + c.a] & c.extra) != 0)
|
|
} else if h == .Bitcast {
|
|
words[wb + c.result] = words[wb + c.a] & c.immediate
|
|
} else if h == .FloatAdd64 {
|
|
words[wb + c.result] = ExecFastFloat64(plan, .FloatAdd64, words[wb + c.a], words[wb + c.b])
|
|
} else if h == .FloatSubtract64 {
|
|
words[wb + c.result] = ExecFastFloat64(plan, .FloatSubtract64, words[wb + c.a], words[wb + c.b])
|
|
} else if h == .FloatMultiply64 {
|
|
words[wb + c.result] = ExecFastFloat64(plan, .FloatMultiply64, words[wb + c.a], words[wb + c.b])
|
|
} else if h == .FloatDivide64 {
|
|
words[wb + c.result] = ExecFastFloat64(plan, .FloatDivide64, words[wb + c.a], words[wb + c.b])
|
|
} else if h == .FloatAdd32 {
|
|
words[wb + c.result] = ExecFastFloat32(plan, .FloatAdd32, words[wb + c.a], words[wb + c.b])
|
|
} else if h == .FloatSubtract32 {
|
|
words[wb + c.result] = ExecFastFloat32(plan, .FloatSubtract32, words[wb + c.a], words[wb + c.b])
|
|
} else if h == .FloatMultiply32 {
|
|
words[wb + c.result] = ExecFastFloat32(plan, .FloatMultiply32, words[wb + c.a], words[wb + c.b])
|
|
} else if h == .FloatDivide32 {
|
|
words[wb + c.result] = ExecFastFloat32(plan, .FloatDivide32, words[wb + c.a], words[wb + c.b])
|
|
} else if h == .FloatCompare32 {
|
|
words[wb + c.result] = ExecFastFloatCompare(plan, c, words[wb + c.a], words[wb + c.b], true)
|
|
} else if h == .FloatCompare64 {
|
|
words[wb + c.result] = ExecFastFloatCompare(plan, c, words[wb + c.a], words[wb + c.b], false)
|
|
} else if h == .ConvertIntegerFloat {
|
|
words[wb + c.result] = ExecFastIntegerFloat(c, words[wb + c.a])
|
|
} else if h == .ConvertFloatFloat {
|
|
value := ExecBitsFloat(plan, words[wb + c.a], c.size == 32)
|
|
words[wb + c.result] = ifx c.y == 32 then ExecFloat32Bits(cast(float32)value) else ExecFloat64Bits(value)
|
|
} else if h == .ConvertFloatInteger {
|
|
result: u64
|
|
if !ExecFastFloatInteger(plan, c, words[wb + c.a], *result) { return pc }
|
|
words[wb + c.result] = result
|
|
} else if h == .DivideUnsigned {
|
|
result: u64
|
|
if !ExecFastDivide(c, words[wb + c.a], words[wb + c.b], false, false, *result) { return pc }
|
|
words[wb + c.result] = result
|
|
} else if h == .RemainderUnsigned {
|
|
result: u64
|
|
if !ExecFastDivide(c, words[wb + c.a], words[wb + c.b], false, true, *result) { return pc }
|
|
words[wb + c.result] = result
|
|
} else if h == .DivideSigned {
|
|
result: u64
|
|
if !ExecFastDivide(c, words[wb + c.a], words[wb + c.b], true, false, *result) { return pc }
|
|
words[wb + c.result] = result
|
|
} else if h == .RemainderSigned {
|
|
result: u64
|
|
if !ExecFastDivide(c, words[wb + c.a], words[wb + c.b], true, true, *result) { return pc }
|
|
words[wb + c.result] = result
|
|
} else if h == .ShiftLeft {
|
|
result: u64
|
|
if !ExecFastShift(c, words[wb + c.a], words[wb + c.b], false, false, *result) { return pc }
|
|
words[wb + c.result] = result
|
|
} else if h == .ShiftRightUnsigned {
|
|
result: u64
|
|
if !ExecFastShift(c, words[wb + c.a], words[wb + c.b], true, false, *result) { return pc }
|
|
words[wb + c.result] = result
|
|
} else if h == .ShiftRightSigned {
|
|
result: u64
|
|
if !ExecFastShift(c, words[wb + c.a], words[wb + c.b], true, true, *result) { return pc }
|
|
words[wb + c.result] = result
|
|
} else if h == .Aggregate {
|
|
for at: c.x..c.x + c.y - 1 {
|
|
move := *plan.moves[at]
|
|
if move.word { ExecPutBits(storage, sb + move.to, move.size, words[wb + move.from]) }
|
|
else { ExecCopyBytes(storage, sb + move.from, sb + move.to, move.size) }
|
|
}
|
|
} else if h == .GlobalAddress {
|
|
words[wb + c.result] = instance.addresses[c.x].token
|
|
} else if h == .HostWrite {
|
|
written := ExecFastWrite(instance, frame_index, c, c.target, c.type,
|
|
words[wb + c.a], words[wb + c.b], words[wb + c.c])
|
|
if written == 0 { return pc }
|
|
if written < 0 { return ExecFailed }
|
|
} else if h == .HostCall {
|
|
// The planner only sends calls whose arguments are frame words;
|
|
// anything the host binds as a write or a typed image still runs
|
|
// on ExecStep.
|
|
host_binding := ExecFastHostBinding(instance, c.target)
|
|
if host_binding < 0 { return pc }
|
|
host := instance.hosts[host_binding]
|
|
if host.write != null || host.typed != null { return pc }
|
|
host_arguments: [3]u64
|
|
if c.x >= 1 { host_arguments[0] = words[wb + c.a] }
|
|
if c.x >= 2 { host_arguments[1] = words[wb + c.b] }
|
|
if c.x >= 3 { host_arguments[2] = words[wb + c.c] }
|
|
host_result: u64
|
|
if !host.call(host.context, c.target, host_arguments[:c.x], *host_result) {
|
|
ExecFastStand(instance, frame_index, c)
|
|
unused ExecFail(instance, .Host)
|
|
return ExecFailed
|
|
}
|
|
if c.result >= 0 {
|
|
if !ExecHostCanonical(plan.program.types[c.type], host_result) {
|
|
ExecFastStand(instance, frame_index, c)
|
|
unused ExecFail(instance, .Host)
|
|
return ExecFailed
|
|
}
|
|
words[wb + c.result] = host_result
|
|
}
|
|
} else { return pc }
|
|
if next < 0 {
|
|
if next == ExecBail { return pc }
|
|
return next
|
|
}
|
|
pc = next
|
|
}
|
|
return ExecFailed
|
|
}
|
|
|
|
// A Call between program frames, as ExecCallInstruction and ExecPushFrame
|
|
// make it, when nothing about it can fail. false: ExecStep makes it.
|
|
ExecFastCall :: (instance: *LirExecInstance, frame_index: s64, code: *LirExecCode) -> bool {
|
|
plan := instance.plan
|
|
target := code.target
|
|
function := *plan.program.functions[target]
|
|
target_plan := *plan.functions[target]
|
|
if code.cost > instance.work_remaining || instance.frames.count >= instance.limits.frames ||
|
|
function.values.count > instance.limits.values - instance.live_values { return false }
|
|
// The same bounded growth as ExecResizeStorage and ExecResizeWords; a
|
|
// refusal leaves both as they were for ExecStep to report.
|
|
base := instance.storage.count
|
|
word_base := instance.words.count
|
|
outside := instance.limits.value_bytes - instance.globals.count - instance.result_bytes.count -
|
|
instance.owned.count
|
|
storage_room := outside - word_base * 8
|
|
if storage_room < 0 || target_plan.frame_bytes > storage_room - base ||
|
|
!VecResizeBounded(instance.storage, base + target_plan.frame_bytes, storage_room) { return false }
|
|
word_room := outside - instance.storage.count
|
|
if word_room < 0 || word_base + target_plan.word_count > word_room / 8 ||
|
|
!VecResizeBounded(instance.words, word_base + target_plan.word_count, word_room / 8) {
|
|
unused VecResize(instance.storage, base)
|
|
return false
|
|
}
|
|
caller := *instance.frames[frame_index]
|
|
caller_words := caller.word_base
|
|
caller_storage := caller.base
|
|
instance.frame_epoch += 1
|
|
frame := LirExecFrame.{.function = target, .block = function.entry, .return_value = code.result_value,
|
|
.base = base, .word_base = word_base, .value_base = target_plan.value_base,
|
|
.instruction_base = plan.block_instruction_bases[target_plan.block_base + function.entry],
|
|
.generation = instance.frame_epoch}
|
|
if !VecPush(instance.frames, frame) {
|
|
unused VecResize(instance.words, word_base)
|
|
unused VecResize(instance.storage, base)
|
|
instance.frame_epoch -= 1
|
|
return false
|
|
}
|
|
instance.work_remaining -= code.cost
|
|
instance.current_value_base = frame.value_base
|
|
instance.current_word_base = word_base
|
|
instance.live_values += function.values.count
|
|
for at: target_plan.constants..target_plan.constants + target_plan.constant_count - 1 {
|
|
constant := *plan.constant_words[at]
|
|
instance.words[word_base + constant.word] = constant.bits
|
|
}
|
|
for at: code.x..code.x + code.y - 1 {
|
|
move := *plan.moves[at]
|
|
if move.word { instance.words[word_base + move.to] = instance.words[caller_words + move.from] }
|
|
// The callee's storage lies past the caller's: the two never overlap.
|
|
else { ExecCopyBytes(instance.storage[:], caller_storage + move.from, base + move.to, move.size) }
|
|
}
|
|
ExecSetPosition(instance, frame_index, code.block, code.index + 1, code.base)
|
|
return true
|
|
}
|
|
|
|
// A Return to a calling program frame, as ExecFinishFrame makes it, when it
|
|
// cannot fail. false: ExecStep makes it.
|
|
ExecFastReturn :: (instance: *LirExecInstance, frame_index: s64, code: *LirExecCode) -> bool {
|
|
if frame_index == 0 { return ExecFastRootReturn(instance, code) }
|
|
frame := *instance.frames[frame_index]
|
|
caller := *instance.frames[frame_index - 1]
|
|
cost: s64 = 1
|
|
if code.size != 0 {
|
|
if frame.return_value == LirNoId { return false }
|
|
cost += ExecCopyCost(code.size)
|
|
} else if frame.return_value != LirNoId { return false }
|
|
if cost > instance.work_remaining { return false }
|
|
plan := instance.plan
|
|
if code.size != 0 {
|
|
destination := caller.value_base + frame.return_value
|
|
if code.a >= 0 {
|
|
instance.words[caller.word_base + plan.value_words[destination]] = instance.words[frame.word_base + code.a]
|
|
} else {
|
|
to := caller.base + plan.value_offsets[destination]
|
|
from := frame.base + code.x
|
|
for byte: cast(s64)0..code.size - 1 { instance.storage[to + byte] = instance.storage[from + byte] }
|
|
}
|
|
}
|
|
instance.work_remaining -= cost
|
|
ExecPopFrame(instance)
|
|
return true
|
|
}
|
|
|
|
// An Allocate, as ExecStep and ExecAllocate make it, standing on the
|
|
// instruction. false, with nothing done, hands it to ExecStep when the work,
|
|
// the storage or a table entry might not be there; a table that cannot grow
|
|
// leaves its failure recorded, as ExecAllocate would.
|
|
ExecFastAllocate :: (instance: *LirExecInstance, frame_index: s64, code: *LirExecCode) -> bool {
|
|
at := instance.storage.count
|
|
available := instance.limits.value_bytes - instance.globals.count -
|
|
instance.result_bytes.count - instance.owned.count - instance.words.count * 8
|
|
if code.cost > instance.work_remaining || available < 0 || code.size > available - at ||
|
|
instance.address_free.count == 0 && (instance.addresses.count >= instance.limits.addresses ||
|
|
instance.addresses.count >= ExecAddressSlots) ||
|
|
!VecResizeBounded(instance.storage, at + code.size, available) { return false }
|
|
frame_base := instance.frames[frame_index].base
|
|
word_base := instance.frames[frame_index].word_base
|
|
// ExecStep's own work comes first; the first value's copy after the entry.
|
|
instance.work_remaining -= 1
|
|
made := ExecNewAddress(instance, .{.global = -1, .frame = frame_index,
|
|
.generation = instance.frames[frame_index].generation, .offset = at - frame_base,
|
|
.extent = code.size, .type = code.type, .writable = true})
|
|
if made < 0 { return false }
|
|
if code.y != 0 {
|
|
instance.work_remaining -= code.y
|
|
if code.a >= 0 { ExecPutBits(instance.storage[:], at, code.size, instance.words[word_base + code.a]) }
|
|
else { ExecCopyBytes(instance.storage[:], frame_base + code.x, at, code.size) }
|
|
}
|
|
instance.words[word_base + code.result] = instance.addresses[made].token
|
|
ExecSetPosition(instance, frame_index, code.block, code.index + 1, code.base)
|
|
return true
|
|
}
|
|
|
|
// The root call's Return of a word or of nothing, as ExecFinishFrame makes
|
|
// it; false hands anything else to ExecStep.
|
|
ExecFastRootReturn :: (instance: *LirExecInstance, code: *LirExecCode) -> bool {
|
|
frame := *instance.frames[0]
|
|
result_type := instance.plan.program.functions[frame.function].result
|
|
result_size := instance.plan.type_sizes[result_type]
|
|
if code.size != result_size || result_size != 0 && code.a < 0 { return false }
|
|
cost: s64 = 1
|
|
if result_size != 0 { cost += ExecCopyCost(result_size) }
|
|
available := instance.limits.value_bytes - instance.globals.count -
|
|
instance.storage.count - instance.words.count * 8 - instance.owned.count
|
|
if cost > instance.work_remaining || result_size > available ||
|
|
!VecResizeBounded(instance.result_bytes, result_size,
|
|
instance.limits.value_bytes - instance.globals.count) { return false }
|
|
bits: u64
|
|
if result_size != 0 {
|
|
bits = instance.words[frame.word_base + code.a]
|
|
ExecPutBits(instance.result_bytes[:], 0, result_size, bits)
|
|
}
|
|
instance.result_value = .{.type = result_type, .bits = bits, .bytes = result_size}
|
|
instance.work_remaining -= cost
|
|
ExecPopFrame(instance)
|
|
return true
|
|
}
|
|
|
|
// Runs the instance's frames to the end of the root call.
|
|
ExecRunFast :: (instance: *LirExecInstance) -> bool {
|
|
plan := instance.plan
|
|
while instance.frames.count != 0 {
|
|
frame_index := instance.frames.count - 1
|
|
position := instance.frames[frame_index].instruction_base + instance.frames[frame_index].instruction
|
|
pc := plan.segment_code[position]
|
|
work := plan.segment_work[position]
|
|
fuel := plan.segment_fuel[position]
|
|
if pc < 0 || work > instance.work_remaining || fuel > instance.fuel_remaining {
|
|
if !ExecRunSlow(instance) { return false }
|
|
continue
|
|
}
|
|
instance.work_remaining -= work
|
|
instance.fuel_remaining -= fuel
|
|
stopped := ExecRunCode(instance, frame_index, pc)
|
|
if stopped == ExecFailed { return false }
|
|
if stopped >= 0 {
|
|
code := *plan.code[stopped]
|
|
if code.handler == .Call && ExecFastCall(instance, frame_index, code) ||
|
|
code.handler == .Return && ExecFastReturn(instance, frame_index, code) { continue }
|
|
if code.handler == .Allocate {
|
|
allocated := ExecFastAllocate(instance, frame_index, code)
|
|
if instance.failure.problem != .None { return false }
|
|
if allocated { continue }
|
|
}
|
|
// The rest of the segment from here goes to ExecStep: give back
|
|
// what it was charged and stand on the instruction.
|
|
instance.work_remaining += code.rest_work
|
|
instance.fuel_remaining += code.rest_fuel
|
|
ExecSetPosition(instance, frame_index, code.block, code.index, code.base)
|
|
if !ExecRunSlow(instance) { return false }
|
|
}
|
|
}
|
|
return instance.failure.problem == .None
|
|
}
|
|
|
|
ExecResetRun :: (instance: *LirExecInstance) -> bool {
|
|
// Frames a failed run left behind give their addresses back too.
|
|
for frame: instance.frames { ExecReleaseAddresses(instance, frame.addresses) }
|
|
if !VecResize(instance.frames, 0) || !VecResize(instance.storage, 0) ||
|
|
!VecResize(instance.words, 0) ||
|
|
!VecResize(instance.result_bytes, 0) { return false }
|
|
instance.live_values = 0
|
|
instance.current_value_base = 0
|
|
instance.current_word_base = 0
|
|
instance.result_value = .{.type = LirNoId}
|
|
// Only ExecFail sets a problem, so with none the record is already this.
|
|
if instance.failure.problem != .None { instance.failure = ExecResult(.None) }
|
|
instance.work_remaining = instance.limits.work
|
|
instance.fuel_remaining = instance.limits.fuel
|
|
return true
|
|
}
|
|
|
|
ExecRunRoot :: (instance: *LirExecInstance, function: s32, arguments: []LirExecArgument) -> bool {
|
|
no_operands: [0]s32
|
|
if !ExecPushFrame(instance, function, -1, no_operands[:], LirNoId, arguments) { return false }
|
|
if !instance.reference { return ExecRunFast(instance) }
|
|
while instance.frames.count != 0 && instance.failure.problem == .None {
|
|
if !ExecStep(instance) { break }
|
|
}
|
|
return instance.failure.problem == .None
|
|
}
|
|
|
|
ExecRunFunction :: (instance: *LirExecInstance, function: s32, arguments: []LirExecArgument) -> LirExecResult {
|
|
if instance == null || !instance.ready || instance.plan == null || !instance.plan.ready {
|
|
return ExecResult(.NotReady)
|
|
}
|
|
if instance.running { return ExecResult(.Busy) }
|
|
if instance.initializer_failed { return instance.initializer_failure }
|
|
program := *instance.plan.program
|
|
// LirNoId runs only the initializers that have not run yet.
|
|
if function != LirNoId && (function < 0 || function >= program.functions.count ||
|
|
program.functions[function].external) {
|
|
return ExecResult(.Calling)
|
|
}
|
|
if !instance.hosts_bound {
|
|
for index: cast(s32)0..cast(s32)program.functions.count - 1 {
|
|
if program.functions[index].external && ExecHostBinding(instance, index) < 0 {
|
|
missing := ExecResult(.Host)
|
|
missing.function = index
|
|
return missing
|
|
}
|
|
}
|
|
instance.hosts_bound = true
|
|
}
|
|
if !ExecResetRun(instance) { return ExecResult(.Allocation) }
|
|
instance.running = true
|
|
no_arguments: [0]LirExecArgument
|
|
if !instance.initialized {
|
|
for initializer: program.initializers {
|
|
if !ExecRunRoot(instance, initializer, no_arguments[:]) { break }
|
|
}
|
|
if instance.failure.problem == .None {
|
|
instance.initialized = true
|
|
instance.result_value = .{.type = LirNoId}
|
|
unused VecResize(instance.result_bytes, 0)
|
|
} else {
|
|
instance.initializer_failed = true
|
|
instance.initializer_failure = instance.failure
|
|
}
|
|
}
|
|
if instance.failure.problem == .None && function != LirNoId && !ExecRunRoot(instance, function, arguments) {
|
|
// ExecRunRoot records the stable failure location in the instance.
|
|
}
|
|
if !ExecEndRun(instance) { return instance.failure }
|
|
result := ExecResult(.None)
|
|
result.value = instance.result_value
|
|
result.work_remaining = instance.work_remaining
|
|
result.fuel_remaining = instance.fuel_remaining
|
|
return result
|
|
}
|
|
|
|
// Ends a run: false when it failed, with the frames it left given up and
|
|
// the failure in instance.failure.
|
|
ExecEndRun :: (instance: *LirExecInstance) -> bool {
|
|
instance.running = false
|
|
if instance.failure.problem == .None { return true }
|
|
unused VecResize(instance.frames, 0)
|
|
unused VecResize(instance.storage, 0)
|
|
unused VecResize(instance.words, 0)
|
|
instance.live_values = 0
|
|
return false
|
|
}
|
|
|
|
ExecGlobalAccess :: (instance: *LirExecInstance, global: s32) -> LirExecProblem {
|
|
if instance == null || !instance.ready || instance.plan == null || !instance.initialized { return .NotReady }
|
|
if instance.running { return .Busy }
|
|
program := instance.plan.program
|
|
if global < 0 || global >= program.globals.count { return .Calling }
|
|
if instance.plan.host_shapes[program.globals[global].type] == 0 { return .Type }
|
|
instance.failure = ExecResult(.None)
|
|
instance.work_remaining = instance.limits.work
|
|
return .None
|
|
}
|
|
|
|
#scope_export
|
|
|
|
LirExecDefaultLimits :: () -> LirExecLimits {
|
|
return .{.work = 16000000, .fuel = 16000000, .frames = 128,
|
|
.values = 1048576, .addresses = ExecAddressSlots, .value_bytes = 268435456}
|
|
}
|
|
|
|
// Heap blocks the program allocated and still holds. A program that frees
|
|
// or drops every owned value ends with none.
|
|
LirExecHeapLive :: (instance: *LirExecInstance) -> s64 {
|
|
live: s64
|
|
if instance == null { return 0 }
|
|
for block: instance.heap_blocks { if block.live && !block.host { live += 1 } }
|
|
return live
|
|
}
|
|
|
|
LirExecPlanFree :: (plan: *LirExecPlan) {
|
|
if plan == null { return }
|
|
VecFree(plan.type_sizes)
|
|
VecFree(plan.value_offsets)
|
|
VecFree(plan.value_words)
|
|
VecFree(plan.value_sizes)
|
|
VecFree(plan.value_types)
|
|
VecFree(plan.value_canonical)
|
|
VecFree(plan.value_masks)
|
|
VecFree(plan.host_shapes)
|
|
VecFree(plan.functions)
|
|
VecFree(plan.block_edge_bases)
|
|
VecFree(plan.block_instruction_bases)
|
|
VecFree(plan.edge_direct)
|
|
VecFree(plan.instructions)
|
|
VecFree(plan.transient)
|
|
VecFree(plan.global_offsets)
|
|
VecFree(plan.code)
|
|
VecFree(plan.moves)
|
|
VecFree(plan.edge_plans)
|
|
VecFree(plan.constant_words)
|
|
VecFree(plan.segment_code)
|
|
VecFree(plan.segment_work)
|
|
VecFree(plan.segment_fuel)
|
|
VecFree(plan.powers)
|
|
plan.program = .{}
|
|
plan.global_bytes = 0
|
|
plan.derived_count = 0
|
|
plan.ready = false
|
|
}
|
|
|
|
LirExecInstanceClose :: (instance: *LirExecInstance) {
|
|
if instance == null { return }
|
|
VecFree(instance.globals)
|
|
VecFree(instance.addresses)
|
|
VecFree(instance.address_slots)
|
|
VecFree(instance.address_free)
|
|
VecFree(instance.derived_tokens)
|
|
instance.address_used = 0
|
|
VecFree(instance.storage)
|
|
VecFree(instance.words)
|
|
VecFree(instance.frames)
|
|
VecFree(instance.result_bytes)
|
|
VecFree(instance.hosts)
|
|
VecFree(instance.host_lookup)
|
|
VecFree(instance.host_arguments)
|
|
VecFree(instance.typed_arguments)
|
|
VecFree(instance.host_bytes)
|
|
VecFree(instance.owned)
|
|
VecFree(instance.heap_blocks)
|
|
VecFree(instance.heap_free)
|
|
VecFree(instance.host_free)
|
|
instance.heap_tail = 0
|
|
instance.heap_epoch = 0
|
|
instance.host_since = 0
|
|
instance.host_scanned = 0
|
|
instance.plan = null
|
|
instance.limits = .{}
|
|
instance.identity = 0
|
|
instance.result_value = .{.type = LirNoId}
|
|
instance.live_values = 0
|
|
instance.current_value_base = 0
|
|
instance.current_word_base = 0
|
|
instance.work_remaining = 0
|
|
instance.fuel_remaining = 0
|
|
instance.failure = ExecResult(.None)
|
|
instance.initializer_failure = ExecResult(.None)
|
|
instance.initialized = false
|
|
instance.initializer_failed = false
|
|
instance.hosts_bound = false
|
|
instance.ready = false
|
|
instance.running = false
|
|
}
|
|
|
|
LirExecPlanBuild :: (program: LirProgram, verify_limits: LirLimits, output: *LirExecPlan) -> LirExecResult {
|
|
if output == null { return ExecResult(.NotReady) }
|
|
LirExecPlanFree(output)
|
|
diagnostic := LirVerify(program, verify_limits)
|
|
if diagnostic.problem != .None {
|
|
result := ExecResult(.InvalidProgram)
|
|
result.verification = diagnostic
|
|
result.function = diagnostic.function
|
|
result.block = diagnostic.block
|
|
result.instruction = diagnostic.instruction
|
|
result.origin = diagnostic.origin
|
|
return result
|
|
}
|
|
output.program = program
|
|
problem := ExecPlanLayouts(program, output, verify_limits.bytes)
|
|
if problem == .None && !LirHostShapes(program, *output.host_shapes) { problem = .Allocation }
|
|
if problem == .None { problem = ExecPlanFunctions(program, output, verify_limits.bytes) }
|
|
if problem == .None { problem = ExecPlanCode(program, output) }
|
|
if problem != .None {
|
|
result := ExecResult(problem)
|
|
LirExecPlanFree(output)
|
|
return result
|
|
}
|
|
output.ready = true
|
|
return ExecResult(.None)
|
|
}
|
|
|
|
LirExecInstanceOpen :: (plan: *LirExecPlan, limits: LirExecLimits, identity: u32,
|
|
output: *LirExecInstance) -> LirExecResult {
|
|
if output == null { return ExecResult(.NotReady) }
|
|
LirExecInstanceClose(output)
|
|
if plan == null || !plan.ready || identity == 0 ||
|
|
limits.work < 0 || limits.fuel < 0 || limits.frames < 1 || limits.values < 0 ||
|
|
limits.addresses < 0 || limits.value_bytes < 0 {
|
|
return ExecResult(.NotReady)
|
|
}
|
|
if limits.addresses < plan.program.globals.count { return ExecResult(.AddressLimit) }
|
|
if plan.global_bytes > limits.value_bytes { return ExecResult(.ValueBytes) }
|
|
output.plan = plan
|
|
output.limits = limits
|
|
output.identity = identity
|
|
output.frame_epoch = 1
|
|
output.work_remaining = limits.work
|
|
output.fuel_remaining = limits.fuel
|
|
output.failure = ExecResult(.None)
|
|
if !VecResizeBounded(output.globals, plan.global_bytes, limits.value_bytes) ||
|
|
!VecResizeBounded(output.addresses, plan.program.globals.count, limits.addresses) ||
|
|
!VecResize(output.derived_tokens, plan.derived_count) ||
|
|
!VecResize(output.host_lookup, plan.program.functions.count) {
|
|
LirExecInstanceClose(output)
|
|
return ExecResult(.Allocation)
|
|
}
|
|
for global_index: cast(s64)0..plan.program.globals.count - 1 {
|
|
global := plan.program.globals[global_index]
|
|
offset := plan.global_offsets[global_index]
|
|
output.addresses[global_index] = .{.token = ExecAddressToken(identity, global_index),
|
|
.global = cast(s32)global_index, .frame = -1, .offset = offset,
|
|
.extent = plan.type_sizes[global.type], .type = global.type,
|
|
.writable = global.writable}
|
|
if global.constant != LirNoId {
|
|
constant := plan.program.constants[global.constant]
|
|
type := plan.program.types[global.type]
|
|
if type.kind == .Array {
|
|
for at: cast(s64)0..constant.bytes.count - 1 { output.globals[offset + at] = constant.bytes[at] }
|
|
} else {
|
|
bits := constant.bits
|
|
if type.kind == .Bool { bits = cast(u64)(bits != 0) }
|
|
if type.kind == .Integer { bits &= ExecMask(type.bits) }
|
|
ExecWriteBits(output.globals[:], offset, plan.type_sizes[global.type], bits)
|
|
}
|
|
}
|
|
}
|
|
output.ready = true
|
|
return ExecResult(.None)
|
|
}
|
|
|
|
LirExecRun :: (instance: *LirExecInstance) -> LirExecResult {
|
|
if instance == null || !instance.ready || instance.plan.program.entry == LirNoId {
|
|
return ExecResult(.NotReady)
|
|
}
|
|
no_arguments: [0]LirExecArgument
|
|
return ExecRunFunction(instance, instance.plan.program.entry, no_arguments[:])
|
|
}
|
|
|
|
// LirExecRun for a host that runs the entry again and again, without
|
|
// building a result: true when the run succeeded, with the result in
|
|
// instance.result_value and what is left in instance.work_remaining and
|
|
// instance.fuel_remaining; false with the result LirExecRun gives in
|
|
// `failed`. The first run takes LirExecRun's own path.
|
|
LirExecRunEntry :: (instance: *LirExecInstance, failed: *LirExecResult) -> bool {
|
|
if instance != null && instance.ready && instance.initialized && instance.hosts_bound &&
|
|
!instance.running && instance.plan != null && instance.plan.ready {
|
|
entry := instance.plan.program.entry
|
|
if entry != LirNoId && !instance.plan.program.functions[entry].external {
|
|
if !ExecResetRun(instance) {
|
|
<<failed = ExecResult(.Allocation)
|
|
return false
|
|
}
|
|
instance.running = true
|
|
no_arguments: [0]LirExecArgument
|
|
unused ExecRunRoot(instance, entry, no_arguments[:])
|
|
if ExecEndRun(instance) { return true }
|
|
<<failed = instance.failure
|
|
return false
|
|
}
|
|
}
|
|
<<failed = LirExecRun(instance)
|
|
return failed.problem == .None
|
|
}
|
|
|
|
// LirExecRun with every instruction run by the reference implementation,
|
|
// one at a time, instead of the compact code. Both give the same result,
|
|
// failure location and remaining work and fuel; tests compare them.
|
|
LirExecRunReference :: (instance: *LirExecInstance) -> LirExecResult {
|
|
if instance == null || !instance.ready || instance.plan.program.entry == LirNoId {
|
|
return ExecResult(.NotReady)
|
|
}
|
|
no_arguments: [0]LirExecArgument
|
|
instance.reference = true
|
|
result := ExecRunFunction(instance, instance.plan.program.entry, no_arguments[:])
|
|
instance.reference = false
|
|
return result
|
|
}
|
|
|
|
LirExecCall :: (instance: *LirExecInstance, function: s32, arguments: []LirExecArgument) -> LirExecResult {
|
|
return ExecRunFunction(instance, function, arguments)
|
|
}
|
|
|
|
// Runs the global initializers now, as the first run would. Every later
|
|
// run returns their failure.
|
|
LirExecInitialize :: (instance: *LirExecInstance) -> LirExecResult {
|
|
no_arguments: [0]LirExecArgument
|
|
return ExecRunFunction(instance, LirNoId, no_arguments[:])
|
|
}
|
|
|
|
// Puts the host image of global `global` in the instance's host bytes
|
|
// between runs, as a host call would be given it. They hold it until the
|
|
// next call into the instance.
|
|
LirExecGlobalImage :: (instance: *LirExecInstance, global: s32) -> LirExecProblem {
|
|
problem := ExecGlobalAccess(instance, global)
|
|
if problem != .None { return problem }
|
|
plan := instance.plan
|
|
type := plan.program.globals[global].type
|
|
size := plan.type_sizes[type]
|
|
available := ExecHostAvailable(instance)
|
|
unused VecResize(instance.host_bytes, 0)
|
|
if size > available { return .ValueBytes }
|
|
if !VecResizeBounded(instance.host_bytes, size, available) { return .Allocation }
|
|
if !ExecHostEncode(instance, type, instance.globals[:], plan.global_offsets[global], 0, 0, available, 0) {
|
|
return instance.failure.problem
|
|
}
|
|
return .None
|
|
}
|
|
|
|
// Gives global `global` the value of a host image of its type between runs.
|
|
// View elements become read-only instance-owned storage; a rejected image
|
|
// leaves none behind.
|
|
LirExecGlobalStore :: (instance: *LirExecInstance, global: s32, image: []u8) -> LirExecProblem {
|
|
problem := ExecGlobalAccess(instance, global)
|
|
if problem != .None { return problem }
|
|
plan := instance.plan
|
|
type := plan.program.globals[global].type
|
|
if !plan.program.globals[global].writable { return .Pointer }
|
|
if plan.host_shapes[type] < LirHostShapeViews && image.count != plan.type_sizes[type] { return .Host }
|
|
epoch := instance.heap_epoch
|
|
if !ExecHostDecode(instance, type, image, 0, .Globals, plan.global_offsets[global], 0) {
|
|
ExecHostRollback(instance, epoch)
|
|
return instance.failure.problem
|
|
}
|
|
return .None
|
|
}
|
|
|
|
LirExecResultCopy :: (instance: *LirExecInstance, output: []u8) -> bool {
|
|
if instance == null || !instance.ready || instance.result_value.type == LirNoId ||
|
|
output.count < instance.result_bytes.count { return false }
|
|
for index: cast(s64)0..instance.result_bytes.count - 1 { output[index] = instance.result_bytes[index] }
|
|
return true
|
|
}
|
|
|
|
LirExecBindHost :: (instance: *LirExecInstance, function: s32, call: LirExecHostCall, context: *void) -> LirExecProblem {
|
|
if instance == null || !instance.ready || instance.plan == null { return .NotReady }
|
|
if instance.running { return .Busy }
|
|
program := instance.plan.program
|
|
if call == null || function < 0 || function >= program.functions.count ||
|
|
!program.functions[function].external || program.functions[function].calling != .Host ||
|
|
ExecHostBinding(instance, function) >= 0 || !ExecHostSignature(instance.plan, function, false) { return .Calling }
|
|
if !VecPush(instance.hosts, LirExecHostBinding.{function = function, call = call, context = context}) { return .Allocation }
|
|
return .None
|
|
}
|
|
|
|
LirExecBindHostTyped :: (instance: *LirExecInstance, function: s32,
|
|
call: LirExecTypedHostCall, context: *void) -> LirExecProblem {
|
|
if instance == null || !instance.ready || instance.plan == null { return .NotReady }
|
|
if instance.running { return .Busy }
|
|
program := instance.plan.program
|
|
if call == null || function < 0 || function >= program.functions.count ||
|
|
!program.functions[function].external || program.functions[function].calling != .Host ||
|
|
ExecHostBinding(instance, function) >= 0 || !ExecHostSignature(instance.plan, function, true) { return .Calling }
|
|
if !VecPush(instance.hosts, LirExecHostBinding.{function = function, typed = call, context = context}) {
|
|
return .Allocation
|
|
}
|
|
return .None
|
|
}
|
|
|
|
// Binds parameter `parameter` of typed host function `function` as a
|
|
// mutable view (see LirExecArgument). The first 64 parameters can be.
|
|
LirExecHostMutableView :: (instance: *LirExecInstance, function: s32, parameter: s32) -> LirExecProblem {
|
|
if instance == null || !instance.ready || instance.plan == null { return .NotReady }
|
|
if instance.running { return .Busy }
|
|
binding := ExecHostBinding(instance, function)
|
|
if binding < 0 || instance.hosts[binding].typed == null { return .Calling }
|
|
program := instance.plan.program
|
|
parameters := program.functions[function].parameters
|
|
if parameter < 0 || parameter >= 64 || cast(s64)parameter >= parameters.count ||
|
|
!LirHostView(program, parameters[parameter]) { return .Calling }
|
|
instance.hosts[binding].views |= cast(u64)1 << cast(u64)parameter
|
|
return .None
|
|
}
|
|
|
|
// Bind a bodiless `(u64, *u8, u64) -> void` host function as checked
|
|
// platform byte output. Each call borrows exactly `count` bytes from the
|
|
// checked data pointer; a null pointer is valid only with count zero.
|
|
LirExecBindPlatformWrite :: (instance: *LirExecInstance, function: s32,
|
|
call: LirExecPlatformWrite, context: *void) -> LirExecProblem {
|
|
if instance == null || !instance.ready || instance.plan == null { return .NotReady }
|
|
if instance.running { return .Busy }
|
|
program := instance.plan.program
|
|
if call == null || function < 0 || function >= program.functions.count ||
|
|
!program.functions[function].external || program.functions[function].calling != .Host ||
|
|
ExecHostBinding(instance, function) >= 0 || !ExecPlatformWriteSignature(program, function) { return .Calling }
|
|
if !VecPush(instance.hosts, LirExecHostBinding.{function = function, write = call, context = context}) {
|
|
return .Allocation
|
|
}
|
|
return .None
|
|
}
|
|
|
|
LirExecProblemName :: (problem: LirExecProblem) -> string {
|
|
if problem == .None { return "none" }
|
|
if problem == .InvalidProgram { return "invalid-program" }
|
|
if problem == .NotReady { return "not-ready" }
|
|
if problem == .Busy { return "busy" }
|
|
if problem == .Allocation { return "allocation" }
|
|
if problem == .WorkLimit { return "work-limit" }
|
|
if problem == .FuelLimit { return "fuel-limit" }
|
|
if problem == .FrameLimit { return "frame-limit" }
|
|
if problem == .ValueLimit { return "value-limit" }
|
|
if problem == .AddressLimit { return "address-limit" }
|
|
if problem == .ValueBytes { return "value-bytes" }
|
|
if problem == .Type { return "type" }
|
|
if problem == .Pointer { return "pointer" }
|
|
if problem == .Calling { return "calling" }
|
|
if problem == .DivideByZero { return "divide-by-zero" }
|
|
if problem == .InvalidShift { return "invalid-shift" }
|
|
if problem == .InvalidConversion { return "invalid-conversion" }
|
|
if problem == .Trap { return "trap" }
|
|
if problem == .Unreachable { return "unreachable" }
|
|
if problem == .Host { return "host" }
|
|
return "unsupported"
|
|
}
|