module scheme import os import strings import dl import math import arena $if !macos || freestanding { $compile_error('native execution currently requires a hosted macOS C build') } // Graph inspection borrows live procedures only during compilation. Plans // retain code identities and selectors, never captured procedure environments. enum NativeProviderKind { root global argument capture } struct NativeProvider { kind NativeProviderKind parent int depth int slot int } struct NativeNode { provider NativeProvider procedure Value mut: function &Function = unsafe { nil } } struct NativeGraph { mut: nodes []NativeNode instructions int captures int uses_vectors bool uses_bytevectors bool uses_text bool uses_not bool writes_vectors bool writes_captures bool } fn native_graph(mut vm VM, root Value, arguments []Value) !NativeGraph { mut graph := NativeGraph{ nodes: [NativeNode{ procedure: root }] } for i, value in arguments { if value.tag == .procedure { graph.nodes << NativeNode{ provider: NativeProvider{kind: .argument, slot: i}, procedure: value } } } mut globals := map[int]bool{} mut index := 0 for index < graph.nodes.len { node := graph.nodes[index] if node.procedure.tag != .procedure { return error('non-procedure call') } vm.check_callable_owner(node.procedure)! p := node.procedure.procedure_pointer() if p.mode != .closure || isnil(p.function.code) || p.function.code.builtin_root || p.function.rest || !isnil(p.function.star) || p.function.goops_next_slot >= 0 { return error('unsupported callable protocol') } // A function-argument loop can instead enter through its existing VM // closure, where the callback becomes a guarded capture. Keep that // smaller loop entry rather than widening it with the caller's locals. allow_named_loops := index != 0 || !arguments.any(it.tag == .procedure) f := native_lower_bindings(mut vm, p.function, allow_named_loops)! graph.nodes[index].function = f graph.instructions += f.instructions.len if graph.instructions > 4096 || graph.nodes.len > 32 { return error('graph too large') } depths := native_stack_depths(f)! for pc, instruction in f.instructions { if depths[pc] < 0 { continue } match instruction.op { .constant { value := f.constants[int(instruction.a)] if value.tag !in [.integer, .real, .boolean, .nil, .unspecified, .uninitialized, .character] { return error('non-scalar constant') } } .global, .global_reference { mut slot := -1 if instruction.op == .global_reference { mut resolver := Machine{ function: f } resolved, _ := resolver.global_reference_slot(mut vm, int(instruction.a))! slot = resolved } else { slot = f.global_slots[int(instruction.a)] if slot < 0 { slot = vm.global_index_in(f.code.namespace, f.names[int(instruction.a)])! } } value := if slot >= 0 { vm.globals[slot] } else { vm.pristine_standard(-slot - 2) } if value.tag != .procedure { _ := native_input_scalar(value) or { return error('unsupported global value') } graph.captures++ if graph.captures > 1024 { return error('too many native captures') } continue } vm.check_callable_owner(value)! target := value.procedure_pointer() if instruction.b == native_control_guard { if native_control_operator(target) == 0 { return error('changed private control operator') } continue } if target.mode == .primitive { if !isnil(target.env) || target.primitive !in [.add, .subtract, .multiply, .num_eq, .less, .greater, .less_equal, .greater_equal, .cons, .car, .cdr, .nullp, .pairp, .quotient, .remainder, .modulo, .inexact_to_exact, .vector_ref, .vector_set, .vector_length, .bytevector_ref, .bytevector_set, .bytevector_length, .string_ref, .string_length, .char_to_integer, .not] { return error('unsupported primitive or extension') } if target.primitive in [.vector_ref, .vector_set, .vector_length] { graph.uses_vectors = true } if target.primitive in [.bytevector_ref, .bytevector_set, .bytevector_length] { graph.uses_bytevectors = true } if target.primitive in [.string_ref, .string_length] { graph.uses_text = true } if target.primitive == .not { graph.uses_not = true } if target.primitive in [.vector_set, .bytevector_set] { graph.writes_vectors = true } } else if target.mode == .closure { if slot !in globals { globals[slot] = true graph.nodes << NativeNode{ provider: NativeProvider{kind: .global, slot: slot}, procedure: value } } } else { return error('effectful or unsupported global') } } .local { if instruction.a > 0 { value := native_capture_value(p, int(instruction.a), int(instruction.b)) or { return error('missing captured slot') } if value.tag == .procedure { mut known := false for candidate in graph.nodes { if candidate.procedure.pointer() == value.pointer() { known = true; break } } if !known { graph.nodes << NativeNode{provider: NativeProvider{kind: .capture, parent: index, depth: int(instruction.a), slot: int(instruction.b)}, procedure: value} } } else { _ := native_input_scalar(value) or { return error('unsupported captured value') } } graph.captures++ if graph.captures > 1024 { return error('too many native captures') } } } .define_local { if instruction.a != 0 { return error('captured definition') } } .assign_local { if instruction.a > 0 { value := native_capture_value(p, int(instruction.a), int(instruction.b)) or { return error('missing capture assignment') } if value.tag !in [.integer, .real, .boolean, .nil, .unspecified] { return error('non-scalar capture assignment') } graph.captures++ if graph.captures > 1024 { return error('too many native captures') } graph.writes_captures = true } } .drop, .duplicate, .swap, .jump, .jump_false, .and_jump, .or_jump, .call, .tail_call, .implicit_call, .ret { } else { return error('unsupported instruction ${instruction.op}') } } } index++ } return graph } fn native_procedure_target(graph NativeGraph, node int, value Value) int { if value.pointer() == graph.nodes[node].procedure.pointer() { return node } for i, provider in graph.nodes { if provider.procedure.pointer() == value.pointer() { return i } } return -1 } fn native_capture_value(p &Procedure, depth int, slot int) ?Value { mut cursor := EnvironmentRef{ value: p.env } for _ in 1 .. depth { if isnil(cursor.value) { return none } cursor = EnvironmentRef{ value: cursor.value.parent } } if isnil(cursor.value) || slot < 0 || slot >= cursor.value.slots.len { return none } return cursor.value.slots[slot] } fn native_global_slot(mut vm VM, f &Function, instruction Instruction) !int { if instruction.op == .global_reference { mut resolver := Machine{ function: f } slot, _ := resolver.global_reference_slot(mut vm, int(instruction.a))! return slot } slot := f.global_slots[int(instruction.a)] if slot >= 0 { return slot } return vm.global_index_in(f.code.namespace, f.names[int(instruction.a)]) } fn native_stack_depths(f &Function) ![]int { mut depths := []int{len: f.instructions.len, init: -1} mut queue := [0] depths[0] = 0 for qi := 0; qi < queue.len; qi++ { pc := queue[qi] instruction := f.instructions[pc] before := depths[pc] need := match instruction.op { .drop, .duplicate, .jump_false, .and_jump, .or_jump, .ret, .define_local, .assign_local, .implicit_call { 1 } .swap { 2 } .call, .tail_call, .scope_call, .scope_tail { int(instruction.a) + 1 } else { 0 } } if need < 0 || before < need { return error('native stack underflow') } mut after := before match instruction.op { .constant, .global, .global_reference, .local, .duplicate, .closure, .scope_function { after++ } .drop, .jump_false { after-- } .call, .scope_call { after -= int(instruction.a) } .tail_call, .scope_tail, .ret { continue } else {} } if after < 0 || after > 256 { return error('invalid native stack depth') } mut successors := []int{} mut heights := []int{} match instruction.op { .jump { successors << int(instruction.a) heights << after } .jump_false { successors << [int(instruction.a), pc + 1] heights << [after, after] } .and_jump, .or_jump { successors << [int(instruction.a), pc + 1] heights << [before, before - 1] } else { successors << pc + 1 heights << after } } for i, next in successors { if next < 0 || next >= depths.len { return error('invalid native jump') } if depths[next] == -1 { depths[next] = heights[i] queue << next } else if depths[next] != heights[i] { return error('inconsistent native stack merge') } } } return depths } fn native_i64_literal(n i64) string { if n == exact_min { return '(-INT64_C(9223372036854775807)-1)' } return 'INT64_C(${n})' } fn native_emit(mut vm VM, graph NativeGraph, layout []NativeCapture) !string { mut code := strings.new_builder(8192) code.write_string($embed_file('native_abi.h').to_string()) for primitive in [Primitive.add, .subtract, .multiply, .num_eq, .less, .greater, .less_equal, .greater_equal, .cons, .car, .cdr, .nullp, .pairp, .quotient, .remainder, .modulo, .inexact_to_exact, .vector_ref, .vector_set, .vector_length, .bytevector_ref, .bytevector_set, .bytevector_length, .string_ref, .string_length, .char_to_integer] { code.writeln('#define P_${primitive.str().to_upper()} ${int(primitive)}') } if graph.uses_not { code.writeln('#define P_NOT ${int(Primitive.not)}') } if graph.uses_vectors || graph.uses_bytevectors || graph.uses_text { code.writeln('#define VILE_NATIVE_VECTORS 1') } if graph.writes_captures { code.writeln('#define VILE_NATIVE_CAPTURE_WRITES 1') } code.write_string($embed_file('native_runtime.h').to_string()) // Keep integer-only IR separate: merging real arithmetic into its loops // prevents the C optimizer from retaining proven integer result tags. mixed_required := native_real_literals(graph) || graph.uses_vectors params := graph.nodes[0].function.params floating_possible := mixed_required || params > 0 || graph.captures > 0 if !mixed_required { native_emit_functions(mut code, mut vm, graph, layout, false)! } if floating_possible { native_emit_functions(mut code, mut vm, graph, layout, true)! } code.writeln('void native_entry(V*caps,V*args,void*pool,int64_t pairs,const VileNativeHostApi*api,VileNativeVectorJournal*journal,V*out){') if graph.uses_vectors || graph.uses_bytevectors || graph.uses_text { code.writeln('Ctx c={.caps=caps,.next=(Pair*)pool,.end=pool?(Pair*)pool+pairs:0,.api=api,.journal=journal};') } else { code.writeln('Ctx c={.caps=caps,.next=(Pair*)pool,.end=pool?(Pair*)pool+pairs:0};') } arguments := native_arguments('args', 0, params) if mixed_required { code.writeln('*out=f0(&c,0${arguments});') } else if !floating_possible { code.writeln('*out=i0(&c,0${arguments});') } else { code.writeln('int floating=0;') code.writeln('for(int i=0;i<${params}&&!floating;i++)floating=args[i].k==REAL;') code.writeln('for(int i=0;i<${graph.captures}&&!floating;i++)floating=caps[i].k==REAL;') code.writeln('*out=floating?f0(&c,0${arguments}):i0(&c,0${arguments});') } code.writeln('}') return code.str() } fn native_real_literals(graph NativeGraph) bool { for node in graph.nodes { for value in node.function.constants { if value.tag == .real { return true } } } return false } fn native_emit_functions(mut code strings.Builder, mut vm VM, graph NativeGraph, layout []NativeCapture, floating bool) ! { prefix := if floating { 'f' } else { 'i' } apply_name := if floating { 'apply' } else { 'integer_apply' } primitive_name := if floating { 'prim' } else { 'integer_prim' } for i, node in graph.nodes { code.writeln('static V ${prefix}${i}(Ctx*,int${native_parameters(node.function.params)});') } code.writeln('static inline V ${apply_name}(Ctx*c,V p,int n,V*a,int d){if(p.k!=FN)return fail();if(p.x<0)return ${primitive_name}(c,(int)(-p.x-1),n,a);switch(p.x){') for i, node in graph.nodes { code.writeln('case ${i}:return n==${node.function.params}?${prefix}${i}(c,d+1${native_arguments('a', 0, node.function.params)}):fail();') } code.writeln('default:return fail();}}') mut captures := 0 for ni, node in graph.nodes { p := node.procedure.procedure_pointer() f := node.function if f.params > 8 || f.slot_count > 64 { return error('native function too wide') } depths := native_stack_depths(f)! callees := native_callees(mut vm, graph, ni)! argument_callees := native_argument_callees(graph, ni) code.writeln('static V ${prefix}${ni}(Ctx*c,int d${native_parameters(f.params)}){if(d>512)return fail();V in[8],s[256],v[64];') for i in 0 .. f.params { code.writeln('in[${i}]=arg${i};') } code.writeln('entry:;') // Internal calls and self tail jumps can supply other procedure IDs. // Check the specialization on every function entry, before using it. for i, target in argument_callees { if target != native_unknown_callee { code.writeln('if(in[${i}].k!=FN||in[${i}].x!=${target})return fail();') } } for i in 0 .. f.slot_count { code.writeln('v[${i}]=val(0,UNINIT);') } for i in 0 .. f.params { code.writeln('v[${i}]=in[${i}];') } for pc, instruction in f.instructions { h := depths[pc] if h < 0 { continue } a, b := int(instruction.a), int(instruction.b) known := callees[pc] code.writeln('L${pc}:;') match instruction.op { .constant { x := f.constants[a] literal := match x.tag { .integer { 'val(${native_i64_literal(x.whole())},INT)' } .real { 'val(${native_i64_literal(i64(math.f64_bits(x.floating())))},REAL)' } .character { 'val(${native_i64_literal(x.whole())},CHARACTER)' } .boolean { 'val(${if x.is_true() { 1 } else { 0 }},BOOL)' } .nil { 'val(0,LIST)' } .unspecified { 'val(0,UNSPEC)' } .uninitialized { 'val(0,UNINIT)' } else { return error('unsupported native literal') } } code.writeln('s[${h}]=${literal};') } .global, .global_reference { slot := native_global_slot(mut vm, f, instruction)! value := if slot >= 0 { vm.globals[slot] } else { vm.pristine_standard(-slot - 2) } if value.tag != .procedure { code.writeln('s[${h}]=c->caps[${captures}];') captures++ continue } target := value.procedure_pointer() if instruction.b == native_control_guard { code.writeln('s[${h}]=val(0,UNSPEC);') continue } mut id := -1 - int(target.primitive) if target.mode == .closure { id = -999 for j, n in graph.nodes { if n.provider.kind == .global && n.provider.slot == slot { id = j break } } if id == -999 { return error('missing native callee') } } code.writeln('s[${h}]=val(${id},FN);') } .local { if a == 0 { code.writeln('if(v[${b}].k==UNINIT)return fail();s[${h}]=v[${b}];') } else { mut cursor := EnvironmentRef{ value: p.env } for _ in 1 .. a { cursor = EnvironmentRef{ value: cursor.value.parent } } if captures >= 1024 { return error('too many captures') } ci := layout[captures].alias captures++ value := native_capture_value(p, a, b) or { return error('missing captured slot') } if value.tag == .procedure { target := native_procedure_target(graph, ni, value) if target < 0 { return error('missing captured procedure') } // The live identity is guarded before entry; only its code ID // is constant, while the provider's environment stays live. code.writeln('s[${h}]=val(${target},FN);') } else { code.writeln('s[${h}]=c->caps[${ci}];') } } } .define_local, .assign_local { if a == 0 { code.writeln('v[${b}]=s[${h - 1}];s[${h - 1}]=val(0,UNSPEC);') } else { ci := layout[captures].alias captures++ code.writeln('{V x=s[${h - 1}];if(!(x.k==INT||x.k==REAL||x.k==BOOL||x.k==UNSPEC||(x.k==LIST&&x.x==0)))return fail();c->caps[${ci}]=x;s[${h - 1}]=val(0,UNSPEC);}') } } .drop {} .duplicate { code.writeln('s[${h}]=s[${h - 1}];') } .swap { code.writeln('{V t=s[${h - 1}];s[${h - 1}]=s[${h - 2}];s[${h - 2}]=t;}') } .jump { code.writeln('goto L${a};') } .jump_false { code.writeln('if(!truth(s[${h - 1}]))goto L${a};') } .and_jump { code.writeln('if(!truth(s[${h - 1}]))goto L${a};') } .or_jump { code.writeln('if(truth(s[${h - 1}]))goto L${a};') } .implicit_call { code.writeln('if(s[${h - 1}].k==FN){') if a != 0 && f.params == 0 { code.writeln('if(s[${h - 1}].x==${ni})goto entry;') } expression := native_application(graph, known, 0, h, floating) if a != 0 { code.writeln('return ${expression};}') } else { code.writeln('s[${h - 1}]=${expression};if(s[${h - 1}].k==ERR)return fail();}') } } .call { if native_integer(mut code, known, a, h - a, false, floating) { continue } expression := native_application(graph, known, a, h - a, floating) code.writeln('s[${h - a - 1}]=${expression};if(s[${h - a - 1}].k==ERR)return fail();') } .tail_call { base := h - a - 1 if native_integer(mut code, known, a, base + 1, true, floating) { continue } if a == f.params { if known == ni { for i in 0 .. a { code.writeln('in[${i}]=s[${base + 1 + i}];') } code.writeln('goto entry;') continue } if known == native_unknown_callee { code.writeln('if(s[${base}].k==FN&&s[${base}].x==${ni}){') for i in 0 .. a { code.writeln('in[${i}]=s[${base + 1 + i}];') } code.writeln('goto entry;}') } } expression := native_application(graph, known, a, base + 1, floating) code.writeln('return ${expression};') } .ret { code.writeln('return s[${h - 1}];') } else { return error('unsupported emitted instruction') } } } code.writeln('return fail();}') } } #flag -I @VMODROOT/scheme #include "native_bridge.h" @[typedef] struct C.VileNativeValue { x i64 k i64 } @[typedef] struct C.VileNativeVectorWrite { vector voidptr index i64 original [2]u64 } @[typedef] struct C.VileNativeVectorJournal { mut: entries &C.VileNativeVectorWrite count i64 capacity i64 } @[typedef] struct C.VileNativeHostApi { context voidptr vector fn (voidptr, &C.VileNativeVectorJournal, i64, &C.VileNativeValue, i64, &C.VileNativeValue) finish fn (voidptr, &C.VileNativeVectorJournal, &C.VileNativeValue) } fn C.vile_native_invoke(voidptr, &C.VileNativeValue, &C.VileNativeValue, voidptr, i64, &C.VileNativeHostApi, i64, &C.VileNativeValue) fn C.mkdtemp(&char) &char struct NativeBinding { node int pc int slot int mode ProcedureKind primitive Primitive target int = -1 } struct NativeCapture { node int depth int slot int target int = -1 pc int = -1 alias int mut: written bool } struct NativePlan { root &Function nodes []&Function resolvers []&Function providers []NativeProvider argument_targets [8]int bindings []NativeBinding captures []NativeCapture capture_writes []int handle voidptr entry voidptr uses_pairs bool reads_pairs bool writes_vectors bool mut: disabled bool pair_inputs_rejected bool guards_valid bool guard_revision u64 guard_bindings u64 guard_syntax u64 } struct NativeVectorBucket { mut: epoch u64 index int } struct NativeScope { mut: metadata arena.Arena scratch arena.Arena plans []NativePlan rejected []&Function directory string hits u64 deopts u64 cache_hits u64 compilations u64 compiler string compiler_context string compiler_identity string cache_root string // Native calls cannot reenter the VM. Fill the live prefix on entry; // generated code reads only the capture selectors in its own plan. capture_values [1024]C.VileNativeValue capture_cells [1024]NativeCaptureCell capture_plan &NativePlan = unsafe { nil } vector_buckets [2048]NativeVectorBucket vector_epoch u64 binding_revision u64 guard_checks u64 pair_input_rejections u64 pair_nodes_visited u64 } // with_native_execution compiles eligible graphs within this synchronous // host scope. No procedure environment or dynamic-library handle // survives this scope; the VM never owns borrowed scope/arena storage. pub fn (mut vm VM) with_native_execution(work EvaluationFn) !Value { vm.ready()! if !isnil(vm.native_execution_scope) || !vm.native_execution_allowed() { return work(mut vm) } mut scope := NativeScope{ metadata: arena.new(), scratch: arena.new() } defer { vm.native_execution_scope = unsafe { nil } for plan in scope.plans { dl.close(plan.handle) } if scope.directory != '' { os.rmdir_all(scope.directory) or {} } scope.scratch.free() scope.metadata.free() } vm.native_execution_scope = voidptr(&scope) return work(mut vm) } struct NativeScalar { x i64 k i64 } // Zero is not a native value kind. Return it for unsupported handles without // an optional payload buffer on every vector read. Callers reject it before // passing the scalar to generated code. fn native_scalar(value Value) NativeScalar { return match value.tag { .integer { NativeScalar{ x: value.whole(), k: 1 } } .real { NativeScalar{ x: i64(math.f64_bits(value.floating())), k: 7 } } .boolean { NativeScalar{ x: if value.is_true() { 1 } else { 0 }, k: 2 } } .nil { NativeScalar{ x: 0, k: 3 } } .unspecified { NativeScalar{ x: 0, k: 5 } } .vector { NativeScalar{ x: i64(u64(value.pointer())), k: if value.read_only { 9 } else { 8 } } } .bytevector { NativeScalar{ x: i64(u64(value.pointer())), k: if value.read_only { 11 } else { 10 } } } .string { NativeScalar{ x: i64(u64(value.pointer())), k: if value.read_only { 13 } else { 12 } } } .character { NativeScalar{ x: value.whole(), k: 14 } } else { NativeScalar{} } } } fn native_compile(mut vm VM, mut scope NativeScope, root Value, arguments []Value) ?NativePlan { // All graph/transient procedure values die with this scratch reset. Binding // resolution can update compiler caches, but publishes no scratch allocations. scope.scratch.push() defer { scope.scratch.pop() scope.scratch.reset() } graph := native_graph(mut vm, root, arguments) or { return none } for node in graph.nodes { f := node.procedure.procedure_pointer().function if f.code.allocation_owner != vm.allocation_owner { return none } } layout := native_capture_layout(mut vm, graph) or { return none } if !native_capture_entry_worthwhile(graph, layout) { return none } code := native_emit(mut vm, graph, layout) or { return none } library := native_build_library(mut scope, code) or { return none } handle, entry := library.handle, library.entry // Only immutable function identities and binding/capture selectors survive. // They refer exclusively to this VM's retained allocation owner. scope.metadata.push() defer { scope.metadata.pop() } mut nodes := []&Function{} mut resolvers := []&Function{} mut providers := []NativeProvider{} mut argument_targets := [8]int{} mut bindings := []NativeBinding{} captures := layout.clone() mut capture_writes := []int{} for i, capture in captures { if capture.written { capture_writes << i } } mut uses_pairs := false mut reads_pairs := false for ni, node in graph.nodes { f := node.function nodes << node.procedure.procedure_pointer().function resolvers << native_retain_resolver(f, node.procedure.procedure_pointer().function) providers << node.provider if node.provider.kind == .argument { argument_targets[node.provider.slot] = ni } depths := native_stack_depths(f) or { dl.close(handle); return none } for pc, instruction in f.instructions { if depths[pc] < 0 { continue } if instruction.op in [.global, .global_reference] { slot := native_global_slot(mut vm, f, instruction) or { dl.close(handle) return none } value := if slot >= 0 { vm.globals[slot] } else { vm.pristine_standard(-slot - 2) } if value.tag != .procedure { continue } p := value.procedure_pointer() if p.mode == .primitive && p.primitive == .cons { uses_pairs = true } if p.mode == .primitive && p.primitive in [.car, .cdr] { reads_pairs = true } // The private bridge uses a reserved negative target instead of // adding per-binding storage; values is identified by its mode. mut target := if instruction.b == native_control_guard && p.mode == .closure { native_control_operator(p) } else { -1 } if p.mode == .closure && target !in [native_cwv_operator, native_wind_operator] { for j, n in graph.nodes { if n.provider.kind == .global && n.provider.slot == slot { target = j break } } } bindings << NativeBinding{ node: ni, pc: pc, slot: slot, mode: p.mode, primitive: p.primitive, target: target } } } } return NativePlan{ root: root.procedure_pointer().function, nodes: nodes, resolvers: resolvers, providers: providers, argument_targets: argument_targets, bindings: bindings, captures: captures, capture_writes: capture_writes, handle: handle, entry: entry, uses_pairs: uses_pairs, reads_pairs: reads_pairs, writes_vectors: graph.writes_vectors } } @[inline] fn (vm &VM) native_execution_allowed() bool { return sizeof(Value) == 16 && vm.options.max_steps == 0 && vm.options.max_frames == 0 && vm.options.max_open_files == none && vm.options.compile_list_limits == none && isnil(vm.owner.bounded_files) && (isnil(vm.system) || isnil(vm.system.evaluation)) && v_arena_current() == vm.allocation_owner } fn (mut m Machine) try_native_execution(mut vm VM, root Value, base int, argc int) ?Value { if isnil(vm.native_execution_scope) { return none } p := root.procedure_pointer() mut scope := unsafe { &NativeScope(vm.native_execution_scope) } mut selected := -1 for i in 0 .. scope.plans.len { if voidptr(scope.plans[i].root) == voidptr(p.function) { selected = i break } } // A rejected graph cannot execute native code in this scope. Check that // existing decision before inspecting argument tags or the active allocator. // Existing plans retain their direct path without scanning other rejections. if selected < 0 { for rejected in scope.rejected { if voidptr(rejected) == voidptr(p.function) { return none } } } else if scope.plans[selected].disabled { return none } if !vm.native_execution_allowed() || m.goops_pending_next.tag != .unspecified { return none } if p.mode != .closure || isnil(p.function.code) || p.function.code.allocation_owner != vm.allocation_owner || argc > 8 { return none } mut args := [8]C.VileNativeValue{} // Entry arity is at most eight. Plans are published only after graph/layout // validation proves at most 32 providers and 1024 captures. The local unsafe // accesses below use those fixed capacities; dynamic VM arrays stay checked. mut has_pair_inputs := false for i in 0 .. argc { value := m.stack[base + 1 + i] if value.tag == .procedure { provider := value.procedure_pointer() if provider.mode != .closure || voidptr(provider.owner) != voidptr(vm.owner) { return none } } else { if value.tag == .pair { if selected >= 0 && scope.plans[selected].pair_inputs_rejected { return none } has_pair_inputs = true } scalar := native_input_scalar(value) or { return none } unsafe { args[i] = C.VileNativeValue{ x: scalar.x, k: scalar.k } } } } if selected < 0 { if scope.plans.len >= 16 || scope.rejected.len >= 128 { return none } plan := native_compile(mut vm, mut scope, root, m.arguments(base + 1)) or { scope.metadata.push() scope.rejected << p.function scope.metadata.pop() return none } selected = scope.plans.len scope.metadata.push() scope.plans << plan scope.metadata.pop() } mut plan := &scope.plans[selected] guards_current := plan.guards_valid && plan.guard_revision == scope.binding_revision && plan.guard_bindings == vm.binding_epoch && plan.guard_syntax == vm.owner.syntax_generation && vm.owner.syntax_generation < ~u64(0) mut providers := [32]Value{} providers[0] = root for i in 1 .. plan.nodes.len { selector := plan.providers[i] value := match selector.kind { .global { vm.globals[selector.slot] } .argument { m.stack[base + 1 + selector.slot] } .capture { parent := unsafe { providers[selector.parent] } if parent.tag != .procedure { return none } native_capture_value(parent.procedure_pointer(), selector.depth, selector.slot) or { return none } } else { return none } } // Dynamic providers always validate, even when global guards are cached. if selector.kind != .global || !guards_current { if value.tag != .procedure { return none } provider := value.procedure_pointer() if voidptr(provider.owner) != voidptr(vm.owner) || provider.mode != .closure || voidptr(provider.function) != voidptr(plan.nodes[i]) { return none } } unsafe { providers[i] = value } } for i in 0 .. argc { target := unsafe { plan.argument_targets[i] } if m.stack[base + 1 + i].tag == .procedure { if target <= 0 { return none } unsafe { args[i] = C.VileNativeValue{ x: target, k: 4 } } } else if target > 0 { return none } } if !guards_current { plan.guards_valid = false scope.guard_checks++ for i in 0 .. plan.nodes.len { if i > 0 && plan.providers[i].kind != .global { continue } value := unsafe { providers[i] } if value.tag != .procedure { return none } provider := value.procedure_pointer() if voidptr(provider.owner) != voidptr(vm.owner) || provider.mode != .closure || voidptr(provider.function) != voidptr(plan.nodes[i]) { return none } } for binding in plan.bindings { f := plan.resolvers[binding.node] slot := native_global_slot(mut vm, f, f.instructions[binding.pc]) or { return none } if slot != binding.slot { return none } value := if slot >= 0 { vm.globals[slot] } else { vm.pristine_standard(-slot - 2) } if value.tag != .procedure { return none } target := value.procedure_pointer() if voidptr(target.owner) != voidptr(vm.owner) || target.mode != binding.mode { return none } if target.mode == .values { if native_control_operator(target) != native_values_operator { return none } } else if binding.target in [native_cwv_operator, native_wind_operator] { if native_control_operator(target) != binding.target { return none } } else if target.mode == .primitive { if !isnil(target.env) || target.primitive != binding.primitive { return none } } else if binding.target < 0 || voidptr(target.function) != voidptr(plan.nodes[binding.target]) { return none } } } defer { for i in 0 .. plan.captures.len { unsafe { scope.capture_values[i] = C.VileNativeValue{} } } for i in plan.capture_writes { unsafe { scope.capture_cells[i] = NativeCaptureCell{} } } scope.capture_plan = unsafe { nil } } if plan.capture_writes.len > 0 && !scope.prepare_capture_writes(plan, &providers[0]) { return none } for i, selector in plan.captures { value := if selector.depth == 0 { f := plan.resolvers[selector.node] if !guards_current { resolved := native_global_slot(mut vm, f, f.instructions[selector.pc]) or { return none } if resolved != selector.slot { plan.guards_valid = false; return none } } if selector.slot >= 0 { vm.globals[selector.slot] } else { vm.pristine_standard(-selector.slot - 2) } } else { provider := unsafe { providers[selector.node] } native_capture_value(provider.procedure_pointer(), selector.depth, selector.slot) or { return none } } if selector.target >= 0 { provider := unsafe { providers[selector.target] } if value.tag != .procedure || voidptr(value.procedure_pointer()) != voidptr(provider.procedure_pointer()) { return none } unsafe { scope.capture_values[i] = C.VileNativeValue{ x: selector.target, k: 4 } } continue } if value.tag == .pair { if plan.pair_inputs_rejected { return none } has_pair_inputs = true } scalar := native_input_scalar(value) or { return none } unsafe { scope.capture_values[i] = C.VileNativeValue{ x: scalar.x, k: scalar.k } } } if !guards_current { plan.guards_valid = true plan.guard_revision = scope.binding_revision plan.guard_bindings = vm.binding_epoch plan.guard_syntax = vm.owner.syntax_generation } // Predicates or ignored inputs do not justify copying a list. Keep those // entries on the VM path while preserving scalar/nil entries of this plan. if has_pair_inputs && !plan.reads_pairs { return none } mut pool := voidptr(unsafe { nil }) pooled := plan.uses_pairs || has_pair_inputs if pooled { if sizeof(C.VileNativePair) != 16 { return none } scope.scratch.push() pool = unsafe { malloc(native_pair_capacity * int(sizeof(C.VileNativePair))) } } defer { if pooled { scope.scratch.pop(); scope.scratch.reset() } } mut imported := 0 if has_pair_inputs { imported = scope.import_pair_inputs(mut plan, &args[0], argc, pool) or { return none } } remaining := native_pair_capacity - imported cells := unsafe { &C.VileNativePair(pool) } allocation_pool := if imported == 0 { pool } else { unsafe { voidptr(&cells[imported]) } } if plan.writes_vectors { scope.begin_vector_transaction() } if plan.capture_writes.len > 0 { scope.capture_plan = plan } api := C.VileNativeHostApi{ context: voidptr(scope), vector: native_vector_io, finish: native_vector_finish } mut out := C.VileNativeValue{} unsafe { C.vile_native_invoke(plan.entry, &scope.capture_values[0], &args[0], allocation_pool, remaining, &api, (if plan.writes_vectors { i64(1) } else { 0 }) | (if plan.capture_writes.len > 0 { i64(2) } else { 0 }), &out) } match out.k { 3, 8, 9, 10, 11, 12, 13, 14 { result := native_host_value(out) if result.tag != .uninitialized { scope.hits++ return result } } 1 { scope.hits++ return integer(out.x) } 2 { scope.hits++ return boolean(out.x != 0) } 7 { scope.hits++ return real(math.f64_from_bits(u64(out.x))) } 5 { scope.hits++ return unspecified() } else {} } scope.deopts++ // A limit or unsupported result must not repeat speculative work on every // recursive interpreter call after replay starts. Mutations are already undone. scope.plans[selected].disabled = true return none } // Debug counters for verification outside the measured interval. pub fn (vm &VM) native_execution_stats() (u64, u64) { if isnil(vm.native_execution_scope) { return 0, 0 } scope := unsafe { &NativeScope(vm.native_execution_scope) } return scope.hits, scope.deopts } const native_unknown_callee = -2000000000 fn native_callee_id(mut vm VM, graph NativeGraph, f &Function, instruction Instruction) !int { if instruction.b == native_control_guard { return native_unknown_callee } slot := native_global_slot(mut vm, f, instruction)! value := if slot >= 0 { vm.globals[slot] } else { vm.pristine_standard(-slot - 2) } if value.tag != .procedure { return native_unknown_callee } p := value.procedure_pointer() if p.mode == .primitive { return -1 - int(p.primitive) } for i, node in graph.nodes { if node.provider.kind == .global && node.provider.slot == slot { return i } } return error('missing native callee') } // Guarded global and captured procedure loads introduce known identities. // Merges retain an identity only when every incoming stack agrees. Calls // invalidate their result; parameters, local slots and scalar captures stay // conservative. No captured environment or VM pointer enters generated code. // Root procedure arguments already have guarded providers. An unchanged local // can use that provider directly; the emitted entry check also covers calls // back into this function from inside the native graph. fn native_argument_callees(graph NativeGraph, node int) []int { f := graph.nodes[node].function mut targets := []int{len: f.params, init: native_unknown_callee} if node != 0 { return targets } for i, candidate in graph.nodes { if candidate.provider.kind == .argument { targets[candidate.provider.slot] = i } } for ins in f.instructions { if ins.op in [.define_local, .assign_local] && ins.a == 0 && ins.b >= 0 && ins.b < f.params { targets[int(ins.b)] = native_unknown_callee } } return targets } fn native_callees(mut vm VM, graph NativeGraph, node int) ![]int { p := graph.nodes[node].procedure.procedure_pointer() f := graph.nodes[node].function argument_callees := native_argument_callees(graph, node) mut states := [][]int{len: f.instructions.len} mut visited := []bool{len: f.instructions.len} mut queue := [0] mut callees := []int{len: f.instructions.len, init: native_unknown_callee} visited[0] = true for qi := 0; qi < queue.len; qi++ { if queue.len > 16384 { return error('native control flow too complex') } pc := queue[qi] instruction := f.instructions[pc] a := int(instruction.a) mut after := states[pc].clone() match instruction.op { .global, .global_reference { after << native_callee_id(mut vm, graph, f, instruction)! } .constant { after << native_unknown_callee } .local { mut known := native_unknown_callee if instruction.a == 0 && instruction.b >= 0 && instruction.b < argument_callees.len { known = argument_callees[int(instruction.b)] } else if instruction.a > 0 { value := native_capture_value(p, int(instruction.a), int(instruction.b)) or { return error('missing captured slot') } if value.tag == .procedure { known = native_procedure_target(graph, node, value) if known < 0 { return error('missing captured procedure') } } } after << known } .duplicate { after << after.last() } .swap { n := after.len temporary := after[n - 1] after[n - 1] = after[n - 2] after[n - 2] = temporary } .drop, .jump_false { after.delete_last() } .define_local, .assign_local { after[after.len - 1] = native_unknown_callee } .implicit_call { callees[pc] = after.last() after[after.len - 1] = native_unknown_callee } .call, .tail_call { base := after.len - a - 1 callees[pc] = after[base] if instruction.op == .tail_call { continue } after.trim(base + 1) after[base] = native_unknown_callee } .ret { continue } else {} } mut nexts := []int{} match instruction.op { .jump { nexts << a } .jump_false, .and_jump, .or_jump { nexts << [a, pc + 1] } else { nexts << pc + 1 } } for branch, next in nexts { mut outgoing := after.clone() if instruction.op in [.and_jump, .or_jump] && branch == 1 { outgoing.delete_last() } if !visited[next] { states[next] = outgoing visited[next] = true queue << next } else { mut changed := false for j, value in outgoing { if states[next][j] != value && states[next][j] != native_unknown_callee { states[next][j] = native_unknown_callee changed = true } } if changed { queue << next } } } } return callees } fn native_application(graph NativeGraph, callee int, argc int, start int, floating bool) string { prefix := if floating { 'f' } else { 'i' } apply_name := if floating { 'apply' } else { 'integer_apply' } primitive_name := if floating { 'prim' } else { 'integer_prim' } if callee == native_unknown_callee { return '${apply_name}(c,s[${start - 1}],${argc},&s[${start}],d)' } if callee < 0 { return '${primitive_name}(c,${-callee - 1},${argc},&s[${start}])' } if argc != graph.nodes[callee].function.params { return 'fail()' } return '${prefix}${callee}(c,d+1${native_arguments('s', start, argc)})' } fn native_parameters(count int) string { mut out := '' for i in 0 .. count { out += ',V arg${i}' } return out } fn native_arguments(array_name string, start int, count int) string { mut out := '' for i in 0 .. count { out += ',${array_name}[${start + i}]' } return out } // A proven, unextended integer primitive can return from this pure graph on // failure directly. Successful operations construct only the actual result // tag, avoiding a merged error-value tag at every arithmetic call site. fn native_integer(mut code strings.Builder, callee int, argc int, start int, tail bool, floating bool) bool { if argc != 2 || callee >= 0 || callee == native_unknown_callee { return false } // Callee IDs originate only from admitted Primitive values in the graph. primitive := unsafe { Primitive(-callee - 1) } if primitive !in [.add, .subtract, .multiply, .num_eq, .less, .greater, .less_equal, .greater_equal] { return false } a, b, target := start, start + 1, start - 1 if floating { code.writeln('if(s[${a}].k==INT&&s[${b}].k==INT){') } else { code.writeln('if(s[${a}].k!=INT||s[${b}].k!=INT)return fail();') } if primitive in [.add, .subtract, .multiply] { operation := match primitive { .add { 'add' } .subtract { 'sub' } else { 'mul' } } code.writeln('{int64_t z;if(__builtin_${operation}_overflow(s[${a}].x,s[${b}].x,&z))return fail();s[${target}]=val(z,INT);}') } else { operation := match primitive { .num_eq { '==' } .less { '<' } .greater { '>' } .less_equal { '<=' } else { '>=' } } code.writeln('s[${target}]=val(s[${a}].x${operation}s[${b}].x,BOOL);') } if floating { code.writeln('}else{s[${target}]=prim(c,${int(primitive)},2,&s[${a}]);if(s[${target}].k==ERR)return fail();}') } if tail { code.writeln('return s[${target}];') } return true }