Skip to main content

synth_core/
backend.rs

1//! Backend trait and registry for multi-backend compilation
2//!
3//! Every compiler backend (ARM, aWsm, wasker, w2c2) implements the `Backend`
4//! trait, allowing the CLI and verification framework to treat them uniformly.
5
6use crate::target::TargetSpec;
7use crate::wasm_decoder::DecodedModule;
8use crate::wasm_op::WasmOp;
9use crate::wsc_facts::WscFact;
10use std::collections::HashMap;
11use thiserror::Error;
12
13/// Errors from backend compilation
14#[derive(Debug, Error)]
15pub enum BackendError {
16    #[error("compilation failed: {0}")]
17    CompilationFailed(String),
18
19    #[error("backend not available: {0}")]
20    NotAvailable(String),
21
22    #[error("unsupported configuration: {0}")]
23    UnsupportedConfig(String),
24
25    #[error("external tool error: {0}")]
26    ExternalToolError(String),
27}
28
29/// Memory-bounds safety strategy. Phase 1 of `docs/binary-safety-design.md` §3.1.
30///
31/// - `Mpu`/PMP: rely on hardware (ARM MPU or RV32 PMP) — no inline check.
32/// - `Software`: emit a `CMP/BHS Trap_Handler` (ARM) or `bgeu addr, mem_size, ebreak` (RV32)
33///   before every load/store.
34/// - `Mask`: emit `AND addr, addr, #(mem_size - 1)` — only valid when memory size
35///   is a power of two. Wraps on OOB rather than trapping (fuzz-profile semantics).
36/// - `None`: no bounds enforcement.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
38pub enum SafetyBounds {
39    /// No bounds check (caller assumes the WASM module is trusted)
40    #[default]
41    None,
42    /// ARM MPU / RV32 PMP — hardware enforcement, no inline guard
43    Mpu,
44    /// Software CMP/BHS (ARM) or BGEU+EBREAK (RV32) per access
45    Software,
46    /// AND-mask, requires power-of-two memory size
47    Mask,
48}
49
50impl SafetyBounds {
51    /// Parse the `--safety-bounds` argument value.
52    pub fn parse(s: &str) -> std::result::Result<Self, String> {
53        match s {
54            "none" => Ok(SafetyBounds::None),
55            "mpu" | "pmp" => Ok(SafetyBounds::Mpu),
56            "software" | "soft" => Ok(SafetyBounds::Software),
57            "mask" | "masking" => Ok(SafetyBounds::Mask),
58            other => Err(format!(
59                "unknown --safety-bounds value '{}'; expected one of: none, mpu, software, mask",
60                other
61            )),
62        }
63    }
64
65    /// String form used in the safety manifest.
66    pub fn as_str(self) -> &'static str {
67        match self {
68            SafetyBounds::None => "none",
69            SafetyBounds::Mpu => "mpu",
70            SafetyBounds::Software => "software",
71            SafetyBounds::Mask => "mask",
72        }
73    }
74}
75
76/// The absolute SRAM address the OPTIMIZED (non-relocatable) ARM path
77/// materializes as its linear-memory base (`MOVW/MOVT R12, #base` before each
78/// const-address access, and the #468 base-CSE R11 hoist). Historical value:
79/// 256 bytes above the SRAM start — the differential-harness contract for
80/// optimized-path fixtures maps linmem here. `CompileConfig::linmem_base`
81/// defaults to this; `--stack-layout=low` (#687) shifts it up by the reserved
82/// stack size so the moved layout reaches user code, not just the startup.
83pub const OPTIMIZED_LINMEM_BASE: u32 = 0x2000_0100;
84
85/// Configuration for a compilation run
86#[derive(Debug, Clone)]
87pub struct CompileConfig {
88    /// Optimization level (0 = none, 1 = fast, 2 = default, 3 = aggressive)
89    pub opt_level: u8,
90    /// Target specification
91    pub target: TargetSpec,
92    /// Legacy: enable software bounds checking for memory operations.
93    /// Deprecated in favor of `safety_bounds`. When set, equivalent to
94    /// `SafetyBounds::Software`. Kept for backwards compatibility with
95    /// callers that haven't migrated yet.
96    pub bounds_check: bool,
97    /// Phase-1 unified safety-bounds knob. If `bounds_check` is `true` and
98    /// this is `None`, the legacy field wins (back-compat). If both are set,
99    /// `safety_bounds` wins.
100    pub safety_bounds: SafetyBounds,
101    /// Hardware profile name (e.g. "nrf52840", "stm32f407")
102    pub hardware: String,
103    /// Skip optimization passes (direct instruction selection)
104    pub no_optimize: bool,
105    /// Use Loom-compatible optimization preset
106    pub loom_compat: bool,
107    /// Number of imported functions (calls to indices below this use Meld dispatch)
108    pub num_imports: u32,
109    /// AAPCS integer-argument count per function, indexed by full WASM function
110    /// index (imports first, then locals). Lets `Call` marshal the right number
111    /// of operand-stack values into R0–R3 (issue #195). Empty = pass no args
112    /// (pre-#195 behaviour).
113    pub func_arg_counts: Vec<u32>,
114    /// AAPCS integer-argument count per function type, indexed by type index.
115    /// Used by `call_indirect` (issue #195).
116    pub type_arg_counts: Vec<u32>,
117    /// Produce relocatable (ET_REL) host-link output. When set, the backend
118    /// uses the direct instruction selector (`select_with_stack`) rather than
119    /// the optimized path: the optimizer materializes an *absolute* linear-
120    /// memory base (0x20000100) and does not preserve caller-saved registers
121    /// across calls, both wrong for a host-linked object where the linmem base
122    /// is supplied via `fp` at runtime and callees follow AAPCS. Imports are
123    /// also emitted as direct `func_N` BLs (resolved to the wasm field name)
124    /// instead of `__meld_dispatch_import`. (#197 — follow-up to #188/#171.)
125    pub relocatable: bool,
126
127    /// #687 (`--stack-layout=low`): the absolute linear-memory base the
128    /// OPTIMIZED ARM path materializes into user code. Defaults to
129    /// [`OPTIMIZED_LINMEM_BASE`] (`0x2000_0100`, byte-identical to every
130    /// pre-#687 compile). Under the low stack layout the CLI shifts it up by
131    /// the reserved stack size so const-address loads/stores land in the moved
132    /// linear memory instead of the stack region. Only the optimized
133    /// (non-relocatable) path consumes it — the direct selector is R11/fp
134    /// - relative and follows the startup's R11 init instead.
135    pub linmem_base: u32,
136
137    /// #237: emit wasm function-static data as a base-independent `.data`
138    /// section (`__synth_wasm_data`) addressed via MOVW/MOVT symbol relocations,
139    /// so a host-pointer drop-in (linmem base = 0 for native `*ptr` derefs)
140    /// doesn't mis-resolve the statics. Off by default — only the leaves'
141    /// base-relative `[R11+const]` path is used unless explicitly requested.
142    pub native_pointer_abi: bool,
143
144    /// #237: wasm linear-memory minimum size in bytes — the full static-data
145    /// extent (initialized `(data)` segments plus the zero-init/BSS region).
146    /// Under `native_pointer_abi`, a const memory address below this is a wasm
147    /// static → symbol-relative; any address beyond it is a runtime host pointer
148    /// → `[R11=0 + addr]`.
149    pub linear_memory_bytes: u32,
150
151    /// VCR-MEM-002 phase 1 (#406): initial size in 64 KiB pages of EACH linear
152    /// memory, indexed by memory index. Consulted only by the multi-memory
153    /// lowering arms (loads/stores wrapped in `WasmOp::MultiMemory`,
154    /// `memory.size`/`grow` with a non-zero index) — memory-0 lowering never
155    /// reads it, so single-memory output is byte-identical whether it is set
156    /// or empty. Empty (the default) means "no multi-memory context": any
157    /// multi-memory op then declines loudly.
158    pub memory_pages: Vec<u32>,
159
160    /// #237: the wasm stack-pointer global as `(index, init_value)`, if the
161    /// module has one. Under `native_pointer_abi` the backend register-promotes
162    /// it: `global.get` materializes `__synth_wasm_data + init` (the real stack
163    /// top) and the init value doubles as the static-data base that separates
164    /// pointer consts (`>= init`) from frame-size scalars (`< init`).
165    pub stack_pointer_global: Option<(u32, i32)>,
166    /// #311: per-function (full index) / per-type "returns i64" — the call
167    /// lowering must tag i64 results as a register pair or the hi half is
168    /// invisible to liveness.
169    pub func_ret_i64: Vec<bool>,
170    pub type_ret_i64: Vec<bool>,
171    /// #643: byte width of each defined global's storage slot, indexed by
172    /// global index — 4 for i32/f32, 8 for i64/f64, 16 for v128 (from the
173    /// module's global section). The globals table is laid out by SUMMING
174    /// these widths: an i64 global needs a register-PAIR store/load at
175    /// `[R9, off]`/`[R9, off+4]`, and every later global's offset shifts.
176    /// Empty ⇒ every global assumed 4 bytes (the legacy `idx * 4` layout;
177    /// hand-built op streams and i32-only modules are byte-identical).
178    pub global_widths: Vec<u32>,
179    /// #359: declared parameter widths per *function* (full index, imports
180    /// first): `func_params_i64[f][k]` is true when param `k` of function `f` is
181    /// i64/f64. The AAPCS stack-argument path needs the *declared* widths
182    /// (op-stream inference can't see an unused i64 param that still shifts the
183    /// incoming-stack layout). The source of truth — a per-function driver loop
184    /// (`compile_module` / the CLI loop) indexes it by `func.index` and copies
185    /// the slice into [`current_func_params_i64`] before each `compile_function`.
186    /// Empty → every param assumed i32 (the legacy path; keeps every function
187    /// with <=4 params, or all-i32 params, byte-identical).
188    pub func_params_i64: Vec<Vec<bool>>,
189    /// #359: declared parameter widths of the function CURRENTLY being compiled
190    /// — `current_func_params_i64[k]` is true when param `k` is i64/f64. Set per
191    /// function (a cheap clone of the config) from [`func_params_i64`] by the
192    /// driver loop, because `compile_function` is shared across backends and
193    /// carries no function index. Empty → assume i32.
194    pub current_func_params_i64: Vec<bool>,
195    /// GI-FPU-002 (#619/#369): per-function declared f32-param mask (full index,
196    /// imports first). The driver copies `func_params_f32[f]` into
197    /// [`current_func_params_f32`] before each `compile_function`. Empty ⇒
198    /// all-non-f32 (byte-identical to before).
199    pub func_params_f32: Vec<Vec<bool>>,
200    /// GI-FPU-002: declared f32-param mask of the function CURRENTLY being
201    /// compiled — `current_func_params_f32[k]` is true when param `k` is f32.
202    /// Set per function from [`func_params_f32`], mirroring
203    /// [`current_func_params_i64`]. Empty ⇒ no f32 params.
204    pub current_func_params_f32: Vec<bool>,
205    /// GI-FPU-002 phase 2 (#369): per-function declared f64-param mask (full
206    /// index, imports first) and the CURRENT function's slice. Hard-float
207    /// targets decline f64-param functions loudly — the legacy width
208    /// inference treats an f64 param as an i64 CORE-register pair, which
209    /// reads the wrong registers under AAPCS-VFP (the caller put it in a
210    /// D-register). Empty ⇒ no f64 params (byte-identical legacy path).
211    pub func_params_f64: Vec<Vec<bool>>,
212    /// See [`func_params_f64`](Self::func_params_f64).
213    pub current_func_params_f64: Vec<bool>,
214    /// GI-FPU-002 phase 2 (#719/#369): whether the function CURRENTLY being
215    /// compiled returns f32. Set per function from the decoder's `func_ret_f32`.
216    /// The direct selector's epilogue uses it to loudly decline a result that
217    /// reaches the return in a core register instead of an S-register (a call
218    /// that returned f32 as integer-tagged R0 would otherwise be a silent
219    /// miscompile — the AAPCS-VFP caller reads S0). `false` for hand-built op
220    /// streams / non-f32 returns (byte-identical to before).
221    pub current_func_ret_f32: bool,
222    /// GI-FPU-002 phase 2 (#719/#369): whether the function CURRENTLY being
223    /// compiled returns f64 (D0 under AAPCS-VFP). Same epilogue-soundness role.
224    pub current_func_ret_f64: bool,
225    /// GI-FPU-002 phase 2 (#719/#369): per-function (full index, imports first)
226    /// "returns f32/f64" tables. The direct selector declines a `call` to an
227    /// f32/f64-returning callee LOUDLY at the call site — the result arrives in
228    /// S0/D0 (AAPCS-VFP), which this increment does not marshal into the operand
229    /// stack; tagging it as an integer R0 would be a silent miscompile. Also the
230    /// source for [`current_func_ret_f32`]/[`current_func_ret_f64`] in the
231    /// per-function driver loops. Empty ⇒ callees assumed non-float-returning
232    /// (hand-built op streams; byte-identical legacy behaviour).
233    pub func_ret_f32: Vec<bool>,
234    /// See [`func_ret_f32`](Self::func_ret_f32).
235    pub func_ret_f64: Vec<bool>,
236    /// GI-FPU-002 phase 2 (#719/#369): per-type "returns f32/f64" — the
237    /// `call_indirect` analogue of [`func_ret_f32`](Self::func_ret_f32).
238    pub type_ret_f32: Vec<bool>,
239    /// See [`type_ret_f32`](Self::type_ret_f32).
240    pub type_ret_f64: Vec<bool>,
241    /// #457: DECLARED parameter count of the function CURRENTLY being compiled,
242    /// from the module's type section (`func_arg_counts[func.index]`). Set per
243    /// function by the driver loops like [`current_func_params_i64`].
244    ///
245    /// The backends otherwise INFER the param count from local-access patterns
246    /// (`count_params`: a local whose first access is a read is assumed to be a
247    /// param) — which cannot distinguish a param from a read-before-write
248    /// non-param local. WASM zero-initializes non-param locals, so such a local
249    /// must read 0; the inference instead homed it in a parameter register and
250    /// read caller garbage (#457). The backends cap the inferred count at this
251    /// declared count when it is present, which reclassifies exactly the
252    /// read-before-write locals (an inferred count can only exceed the declared
253    /// one via a read-first index >= the declared count) and leaves every other
254    /// function's codegen byte-identical.
255    ///
256    /// `None` → declared signature unknown (hand-built op streams, direct
257    /// `compile_function` callers) → pure inference, the legacy behaviour.
258    pub current_func_param_count: Option<u32>,
259    /// #509: blocktype-arity side-table of the function CURRENTLY being compiled
260    /// — `(param_count, result_count)` of the k-th `Block`/`Loop`/`If` in its op
261    /// stream (ordinal-keyed; see [`FunctionOps::block_arity`]). Set per function
262    /// by the driver loop (like [`current_func_params_i64`]). The direct selector
263    /// uses it to land a value carried by `br`/`br_if`/`br_table` in the target
264    /// block's designated result register instead of dropping it. Empty → every
265    /// block treated as void (the legacy lowering; hand-built op streams).
266    ///
267    /// [`FunctionOps::block_arity`]: crate::wasm_decoder::FunctionOps::block_arity
268    pub current_func_block_arity: Vec<(u8, u8)>,
269
270    /// #543 Phase 1 — integrator-marked volatile linear-memory segments (the DMA
271    /// transfer window). Each range `[base, base+len)` names a region of the fused
272    /// linear memory that an EXTERNAL agent (the DMA engine, modelled by gale as a
273    /// Component-Model `own<buffer>` handoff — gale decision `DD-DMA-REGION-001`,
274    /// gale#124) rewrites out-of-band. Loads and stores whose address falls inside
275    /// a marked range must eventually be treated as VOLATILE: not cached, hoisted,
276    /// or reordered across the transfer boundary.
277    ///
278    /// PHASE-2 CONTRACT (implemented — issue #543): the optimizer's
279    /// address-caching passes HONOR these ranges. Consumption points:
280    ///  - the #468 base-CSE / const-address-fold
281    ///    (`optimizer_bridge::plan_base_cse`, DEFAULT-ON, opt-out
282    ///    `SYNTH_BASE_CSE=0`): a const-address access whose 4-byte window
283    ///    intersects a marked range is EXCLUDED from the fold set — it keeps
284    ///    its verbatim per-access materialize-and-access codegen, while
285    ///    accesses outside the range still fold;
286    ///  - const-CSE (`liveness::apply_const_cse` wired in `arm_backend.rs`,
287    ///    DEFAULT-ON, opt-out `SYNTH_CONST_CSE=0`; the former bridge-level
288    ///    inline cache is retired, #242): declines WHOLESALE while any range is
289    ///    marked — a cached constant cannot be classified address-vs-data at
290    ///    that level, so the conservative stance for statically-unknown
291    ///    addressing is to re-materialize every constant at each occurrence.
292    ///
293    /// Passes that only touch SP-relative frame slots (stack-reload forwarding,
294    /// frame-slot DCE, spill re-choice) are unaffected by design: these ranges
295    /// are LINEAR-MEMORY addresses, and frame slots are never linmem. Nothing on
296    /// the pipeline deletes, forwards, or reorders a linear-memory access (IR CSE
297    /// deliberately never CSEs `MemLoad`s; DCE removes only unreachable blocks),
298    /// so every marked access is issued verbatim, in program order.
299    ///
300    /// Empty (the default): zero behavior change by construction — every gate
301    /// reduces to the pre-#543 path, so the emitted `.text` is byte-identical
302    /// with or without this code (the frozen-codegen gate holds). See rivet
303    /// `VCR-DMA-001`.
304    pub volatile_segments: Vec<VolatileRange>,
305
306    /// VCR-PERF-002 Phase 1 (#494) — proven invariants forwarded by loom in
307    /// the `wsc.facts` custom section (encoding:
308    /// `docs/design/wsc-facts-encoding.md`; program:
309    /// `docs/design/proof-carrying-specialization.md`), whole-module table
310    /// keyed by `(func_index, value_id)`. The compile driver copies the
311    /// current function's slice into [`current_func_facts`] (the
312    /// `func_params_i64` → `current_func_params_i64` pattern), because
313    /// `compile_function` carries no function index.
314    ///
315    /// PHASE-1 CONTRACT: threaded but NOT consumed — no codegen path reads
316    /// facts, so emitted bytes are unchanged whether or not the module
317    /// carries the section (locked by `wsc_facts_ingestion_494.rs`). Phase 2
318    /// turns each fact into a premise for a flag-gated (`SYNTH_FACT_SPEC`),
319    /// per-elision ordeal-validated specialization; the facts-absent compile
320    /// stays byte-identical by construction (empty ⇒ every gate vacuous).
321    ///
322    /// [`current_func_facts`]: CompileConfig::current_func_facts
323    pub wsc_facts: Vec<WscFact>,
324    /// VCR-PERF-002 Phase 1 (#494): the `wsc.facts` invariants of the function
325    /// CURRENTLY being compiled (`fact.func_index == func.index`), set per
326    /// function by the driver loops like [`current_func_params_i64`]. This is
327    /// the field a Phase-2 selector pass will read its premises from. Empty →
328    /// no facts → no specialization may ever fire (the fail-safe default).
329    ///
330    /// [`current_func_params_i64`]: CompileConfig::current_func_params_i64
331    pub current_func_facts: Vec<WscFact>,
332    /// VCR-PERF-002 Phase 2b (#494, divisor-nonzero): op indices (into the op
333    /// stream passed to `compile_function`) of `div`/`rem` ops whose
334    /// DIVIDE-BY-ZERO trap guard is proven dead — the fact-spec pass
335    /// discharged `UNSAT(P ∧ divisor == 0)` per site through the
336    /// certificate-checked ordeal solver BEFORE the driver set this field.
337    /// Consumed by the ARM direct selector (`select_with_stack`); every other
338    /// path ignores it (guards stay — sound). Empty (the default) ⇒ every
339    /// guard is emitted, byte-identical to today.
340    pub fact_div_zero_elide: Vec<usize>,
341    /// VCR-PERF-002 Phase 2b (#494): op indices of `div_s` ops whose
342    /// `INT_MIN / -1` OVERFLOW trap guard is proven dead — a SEPARATE
343    /// obligation (`UNSAT(P ∧ dividend == INT_MIN ∧ divisor == -1)`). A
344    /// divisor-nonzero fact alone NEVER lands here: divisor ≠ 0 does not
345    /// exclude -1 (#633/#634 two-guard distinction). Empty ⇒ guard emitted.
346    pub fact_div_ovf_elide: Vec<usize>,
347    /// #494 bounds-elision (#390 `guard_bool`): op indices of i32 memory
348    /// accesses whose `--safety-bounds software` inline guard is proven dead
349    /// — the fact-spec pass discharged
350    /// `UNSAT(P ∧ trap_mem_oob(zext64(index) + offset, size,
351    /// min_memory_bytes))` per site through the certificate-checked ordeal
352    /// solver BEFORE the driver set this field (ordeal 0.9.1 `trap_mem_oob`
353    /// shape, wraparound-safe 64-bit extension). Consumed by the ARM direct
354    /// selector (`select_with_stack`); every other path ignores it (guards
355    /// stay — sound). Empty (the default) ⇒ every guard is emitted,
356    /// byte-identical to today.
357    pub fact_mem_bounds_elide: Vec<usize>,
358    /// #642: `call_indirect` guard inputs — the compile-time table size for
359    /// the runtime bounds check and the per-expected-type closed-world type
360    /// verdicts — computed from the decoded module by
361    /// [`crate::wasm_decoder::DecodedModule::call_indirect_guards`] and set by
362    /// the driver loops. The default (`table_size: None`, empty verdicts)
363    /// DECLINES every `call_indirect` lowering: an unchecked indirect branch
364    /// is never emitted (WASM Core §4.4.8 requires OOB/type-mismatch traps).
365    pub call_indirect_guards: crate::wasm_decoder::CallIndirectGuards,
366}
367
368/// #543 — an integrator-marked volatile linear-memory segment (the DMA transfer
369/// window): the half-open byte range `[base, base + len)` of the fused linear
370/// memory that an external agent rewrites out-of-band. Parsed from the CLI
371/// `--volatile-segment <base>:<len>` flag. See [`CompileConfig::volatile_segments`]
372/// for the Phase-1/Phase-2 split.
373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub struct VolatileRange {
375    /// Start address of the volatile region, in linear-memory bytes.
376    pub base: u32,
377    /// Length of the volatile region, in bytes. The region is `[base, base+len)`.
378    pub len: u32,
379}
380
381impl CompileConfig {
382    /// Resolve the effective safety-bounds setting, honouring the legacy
383    /// `bounds_check` field as a fallback. Used by backends to pick the
384    /// inline-check shape.
385    pub fn effective_safety_bounds(&self) -> SafetyBounds {
386        match (self.safety_bounds, self.bounds_check) {
387            (SafetyBounds::None, true) => SafetyBounds::Software,
388            (s, _) => s,
389        }
390    }
391}
392
393impl Default for CompileConfig {
394    fn default() -> Self {
395        Self {
396            opt_level: 2,
397            target: TargetSpec::cortex_m4(),
398            bounds_check: false,
399            safety_bounds: SafetyBounds::None,
400            hardware: String::new(),
401            no_optimize: false,
402            loom_compat: false,
403            num_imports: 0,
404            func_arg_counts: Vec::new(),
405            type_arg_counts: Vec::new(),
406            relocatable: false,
407            // #687: the historical optimized-path absolute base — every
408            // default compile stays byte-identical.
409            linmem_base: OPTIMIZED_LINMEM_BASE,
410            native_pointer_abi: false,
411            linear_memory_bytes: 0,
412            // #406: empty ⇒ no multi-memory context ⇒ multi-memory ops decline
413            // loudly; memory-0 lowering never reads it.
414            memory_pages: Vec::new(),
415            stack_pointer_global: None,
416            func_ret_i64: Vec::new(),
417            type_ret_i64: Vec::new(),
418            // #643: empty ⇒ legacy all-4-byte global slots (i32-only modules).
419            global_widths: Vec::new(),
420            func_params_i64: Vec::new(),
421            current_func_params_i64: Vec::new(),
422            func_params_f32: Vec::new(),
423            current_func_params_f32: Vec::new(),
424            // GI-FPU-002 phase 2 (#719/#369): false ⇒ non-float return (or a
425            // hand-built op stream); driver loops set it per function.
426            current_func_ret_f32: false,
427            current_func_ret_f64: false,
428            // GI-FPU-002 phase 2 (#719/#369): empty ⇒ callees assumed
429            // non-float-returning (hand-built op streams).
430            func_params_f64: Vec::new(),
431            current_func_params_f64: Vec::new(),
432            func_ret_f32: Vec::new(),
433            func_ret_f64: Vec::new(),
434            type_ret_f32: Vec::new(),
435            type_ret_f64: Vec::new(),
436            // #457: None ⇒ declared signature unknown ⇒ param-count inference
437            // only (unit tests / hand-built op streams); driver loops fill it.
438            current_func_param_count: None,
439            // #509: empty ⇒ legacy void-block lowering (unit tests / hand-built
440            // op streams); the driver loops fill it per function.
441            current_func_block_arity: Vec::new(),
442            // #543 Phase 1: no volatile segments unless the CLI flag names them.
443            // Empty ⇒ inert ⇒ emitted bytes unchanged.
444            volatile_segments: Vec::new(),
445            // VCR-PERF-002 Phase 1 (#494): no facts unless the module carries
446            // a parseable `wsc.facts` section. Empty ⇒ inert (and Phase 1 has
447            // no consumer anyway) ⇒ emitted bytes unchanged.
448            wsc_facts: Vec::new(),
449            current_func_facts: Vec::new(),
450            // VCR-PERF-002 Phase 2b (#494): no guard-elision marks unless the
451            // fact-spec pass discharged the per-site obligations. Empty ⇒
452            // every div/rem trap guard is emitted, byte-identical.
453            fact_div_zero_elide: Vec::new(),
454            fact_div_ovf_elide: Vec::new(),
455            fact_mem_bounds_elide: Vec::new(),
456            // #642: no guard inputs ⇒ every call_indirect lowering declines
457            // loudly (never an unchecked indirect branch). Driver loops fill
458            // this from the decoded module.
459            call_indirect_guards: crate::wasm_decoder::CallIndirectGuards::default(),
460        }
461    }
462}
463
464/// A relocation entry produced during compilation
465///
466/// Records that a BL instruction at `offset` bytes into the function's code
467/// targets an external symbol (e.g., `__meld_dispatch_import`). The linker
468/// resolves these when combining the Synth object with the Kiln bridge.
469#[derive(Debug, Clone, Copy, PartialEq, Eq)]
470pub enum RelocKind {
471    /// R_ARM_THM_CALL — a Thumb BL call site (the default; #167).
472    ThmCall,
473    /// R_ARM_MOVW_ABS_NC — the MOVW half of a symbol-relative address (#237).
474    MovwAbs,
475    /// R_ARM_MOVT_ABS — the MOVT half of a symbol-relative address (#237).
476    MovtAbs,
477    /// R_ARM_ABS32 — a 32-bit absolute address held in a `.text` literal-pool
478    /// word, loaded via `LDR rX, [pc, #off]` (#345). The link-survivable
479    /// replacement for the inline-immediate MOVW/MOVT-ABS pair: `ld`/bfd patches
480    /// the data word at link time (`S + A`, the addend living in the word, REL
481    /// semantics), which survives placement into a large multi-object image —
482    /// whereas an inline-instruction MOVW_ABS immediate can be mangled.
483    Abs32,
484}
485
486#[derive(Debug, Clone, PartialEq, Eq)]
487pub struct CodeRelocation {
488    /// Byte offset within the function's machine code where the reloc applies
489    pub offset: u32,
490    /// Target symbol name (e.g., "__meld_dispatch_import", "__synth_wasm_data")
491    pub symbol: String,
492    /// Which ARM relocation type to emit for this site.
493    pub kind: RelocKind,
494}
495
496/// VCR-DBG-001: a per-instruction source map — `(machine_offset_within_code,
497/// wasm_op_index)` pairs, one per emitted machine instruction. A `None` op-index
498/// marks an instruction with no originating wasm op (prologue/epilogue, literal
499/// pool). Consumed by the DWARF `.debug_line` emitter; empty when no source map
500/// was produced.
501pub type LineMap = Vec<(u32, Option<usize>)>;
502
503/// VCR-DEC-003 (#396, witness#130): the object-level control-flow class of one
504/// emitted machine instruction, captured at encode time alongside [`LineMap`].
505/// It is the piece post-hoc CLI derivation cannot recover — `line_map` records
506/// which wasm op an instruction came from, but not whether that instruction IS a
507/// conditional branch, an unconditional branch, or a predicated (IT-block) move.
508/// The `synth-provenance-v1` emitter needs it to enumerate the ACTUAL object
509/// conditional branches (so it can prove "every object branch resolves to a
510/// source condition", not just "every source branch has an object PC").
511#[derive(Debug, Clone, Copy, PartialEq, Eq)]
512pub enum BranchClass {
513    /// A conditional branch (`Bcc`/`Blo`/`Bhs`/`BCondOffset`) — an object-level
514    /// decision point MC/DC must account for.
515    CondBranch,
516    /// An unconditional branch (`B`/`BOffset`) — control flow, not a decision.
517    UncondBranch,
518    /// A predicated conditional move (`SelectMove`, the IT-block form the
519    /// cmp→select fuse produces) — a folded decision with no branch.
520    Predicated,
521    /// Anything else (data-processing, load/store, call, prologue/epilogue).
522    Other,
523}
524
525/// VCR-DEC-003: per-instruction object-branch class, parallel to [`LineMap`]
526/// (same length, same order — one entry per emitted machine instruction).
527/// `(machine_offset_within_code, class)`. Empty when provenance is not being
528/// produced (never serialized into `.text`; frozen-safe additive metadata).
529pub type BranchMap = Vec<(u32, BranchClass)>;
530
531/// A single compiled function
532#[derive(Debug, Clone)]
533pub struct CompiledFunction {
534    /// Function name (from WASM export or generated)
535    pub name: String,
536    /// Raw machine code bytes
537    pub code: Vec<u8>,
538    /// Original WASM ops (retained for verification)
539    pub wasm_ops: Vec<WasmOp>,
540    /// Relocations for external symbol references (BL to bridge functions)
541    pub relocations: Vec<CodeRelocation>,
542    /// VCR-DBG-001: per-instruction source map for DWARF `.debug_line` emission —
543    /// `(machine_offset_within_code, wasm_op_index)` captured at encode time, one
544    /// entry per emitted machine instruction. A `None` op-index marks an
545    /// instruction with no originating wasm op (prologue/epilogue, literal-pool
546    /// word). This is purely additive metadata: it is never serialized unless
547    /// `.debug_line` emission is requested, so the emitted `.text` is
548    /// byte-identical with or without it. Empty for backends/paths that do not
549    /// yet produce a source map (RISC-V, the optimized ARM path).
550    pub line_map: LineMap,
551    /// VCR-DEC-003 (#396): per-instruction object-branch class, parallel to
552    /// `line_map`. Lets the `synth-provenance-v1` emitter enumerate the real
553    /// object conditional branches (not just re-walk the wasm branch ops).
554    /// Purely additive metadata: never serialized into `.text`, so emitted bytes
555    /// are byte-identical with or without it. Empty for backends/paths that do
556    /// not produce it (RISC-V, the optimized ARM path).
557    pub branch_map: BranchMap,
558    /// #778 (v0.46): the SOUND static worst-case-cycle bound for this function,
559    /// or a loud decline, computed over the final Thumb-2 instruction stream (see
560    /// [`crate::wcet`]). `Some` only when the ARM backend produced it (the RISC-V
561    /// and AArch64 backends carry no cycle model yet → `None`). Purely additive
562    /// metadata: derived from the already-decided instruction list, never
563    /// serialized into `.text`, so emitted bytes are byte-identical with or
564    /// without it (frozen-safe). Emitted as the `<output>.wcet.json` sidecar only
565    /// under `--emit-wcet`.
566    pub wcet: Option<crate::wcet::WcetFunction>,
567}
568
569/// Result of compiling a full module
570#[derive(Debug)]
571pub struct CompilationResult {
572    /// Compiled functions
573    pub functions: Vec<CompiledFunction>,
574    /// Complete ELF binary (if backend produces one directly)
575    pub elf: Option<Vec<u8>>,
576    /// Name of the backend that produced this result
577    pub backend_name: String,
578}
579
580/// What a backend can and cannot do
581#[derive(Debug, Clone)]
582pub struct BackendCapabilities {
583    /// Backend produces complete ELF files (external backends like aWsm)
584    pub produces_elf: bool,
585    /// Backend supports per-rule verification (only our custom ARM backend)
586    pub supports_rule_verification: bool,
587    /// Backend supports binary-level verification (all backends via disassembly)
588    pub supports_binary_verification: bool,
589    /// Backend is an external tool (not a library)
590    pub is_external: bool,
591}
592
593/// Trait that every compilation backend implements
594pub trait Backend: Send + Sync {
595    /// Human-readable backend name
596    fn name(&self) -> &str;
597
598    /// What this backend can do
599    fn capabilities(&self) -> BackendCapabilities;
600
601    /// Which targets this backend supports
602    fn supported_targets(&self) -> Vec<TargetSpec>;
603
604    /// Compile an entire decoded WASM module
605    fn compile_module(
606        &self,
607        module: &DecodedModule,
608        config: &CompileConfig,
609    ) -> std::result::Result<CompilationResult, BackendError>;
610
611    /// Compile a single function from WASM ops to machine code
612    fn compile_function(
613        &self,
614        name: &str,
615        ops: &[WasmOp],
616        config: &CompileConfig,
617    ) -> std::result::Result<CompiledFunction, BackendError>;
618
619    /// Check if this backend is available (external tools installed, etc.)
620    fn is_available(&self) -> bool;
621}
622
623/// Registry of available backends
624pub struct BackendRegistry {
625    backends: HashMap<String, Box<dyn Backend>>,
626}
627
628impl BackendRegistry {
629    pub fn new() -> Self {
630        Self {
631            backends: HashMap::new(),
632        }
633    }
634
635    /// Register a backend under its name
636    pub fn register(&mut self, backend: Box<dyn Backend>) {
637        let name = backend.name().to_string();
638        self.backends.insert(name, backend);
639    }
640
641    /// Get a backend by name
642    pub fn get(&self, name: &str) -> Option<&dyn Backend> {
643        self.backends.get(name).map(|b| b.as_ref())
644    }
645
646    /// List all registered backends
647    pub fn list(&self) -> Vec<&dyn Backend> {
648        self.backends.values().map(|b| b.as_ref()).collect()
649    }
650
651    /// List backends that are actually available (installed and working)
652    pub fn available(&self) -> Vec<&dyn Backend> {
653        self.backends
654            .values()
655            .filter(|b| b.is_available())
656            .map(|b| b.as_ref())
657            .collect()
658    }
659}
660
661impl Default for BackendRegistry {
662    fn default() -> Self {
663        Self::new()
664    }
665}
666
667#[cfg(test)]
668mod tests {
669    use super::*;
670
671    #[test]
672    fn test_registry_empty() {
673        let reg = BackendRegistry::new();
674        assert!(reg.list().is_empty());
675        assert!(reg.available().is_empty());
676        assert!(reg.get("arm").is_none());
677    }
678
679    #[test]
680    fn test_compile_config_default() {
681        let config = CompileConfig::default();
682        assert_eq!(config.opt_level, 2);
683        assert!(!config.bounds_check);
684        assert_eq!(config.safety_bounds, SafetyBounds::None);
685        assert!(!config.no_optimize);
686    }
687
688    #[test]
689    fn safety_bounds_parse_round_trip() {
690        for s in ["none", "mpu", "software", "mask"] {
691            let sb = SafetyBounds::parse(s).unwrap();
692            assert_eq!(sb.as_str(), s);
693        }
694        assert_eq!(SafetyBounds::parse("pmp").unwrap(), SafetyBounds::Mpu);
695        assert_eq!(SafetyBounds::parse("soft").unwrap(), SafetyBounds::Software);
696        assert!(SafetyBounds::parse("nonsense").is_err());
697    }
698
699    #[test]
700    fn effective_safety_bounds_legacy_promotes_to_software() {
701        let cfg = CompileConfig {
702            bounds_check: true,
703            ..Default::default()
704        };
705        assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Software);
706    }
707
708    #[test]
709    fn effective_safety_bounds_new_field_wins() {
710        let cfg = CompileConfig {
711            bounds_check: true,
712            safety_bounds: SafetyBounds::Mpu,
713            ..Default::default()
714        };
715        assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Mpu);
716    }
717}