Skip to main content

synth_backend/
arm_backend.rs

1//! ARM Backend — wraps the instruction selector + optimizer + encoder as a Backend
2//!
3//! This is Synth's custom ARM compiler targeting Cortex-M (Thumb-2).
4//! It's the only backend that supports per-rule formal verification (ASIL D path).
5
6use crate::ArmEncoder;
7use synth_core::backend::{
8    Backend, BackendCapabilities, BackendError, CodeRelocation, CompilationResult, CompileConfig,
9    CompiledFunction, LineMap, SafetyBounds,
10};
11use synth_core::target::{IsaVariant, TargetSpec};
12use synth_core::wasm_decoder::DecodedModule;
13use synth_core::wasm_op::WasmOp;
14use synth_synthesis::{
15    ArmInstruction, ArmOp, BoundsCheckConfig, InstructionSelector, OptimizationConfig,
16    OptimizerBridge, RuleDatabase, validate_instructions,
17};
18
19/// ARM Cortex-M backend using Synth's custom compiler pipeline
20pub struct ArmBackend;
21
22impl ArmBackend {
23    pub fn new() -> Self {
24        Self
25    }
26}
27
28impl Default for ArmBackend {
29    fn default() -> Self {
30        Self::new()
31    }
32}
33
34impl Backend for ArmBackend {
35    fn name(&self) -> &str {
36        "arm"
37    }
38
39    fn capabilities(&self) -> BackendCapabilities {
40        BackendCapabilities {
41            produces_elf: false,
42            supports_rule_verification: true,
43            supports_binary_verification: true,
44            is_external: false,
45        }
46    }
47
48    fn supported_targets(&self) -> Vec<TargetSpec> {
49        vec![
50            TargetSpec::cortex_m3(),
51            TargetSpec::cortex_m4(),
52            TargetSpec::cortex_m4f(),
53            TargetSpec::cortex_m7(),
54            TargetSpec::cortex_m7dp(),
55        ]
56    }
57
58    fn compile_module(
59        &self,
60        module: &DecodedModule,
61        config: &CompileConfig,
62    ) -> Result<CompilationResult, BackendError> {
63        let exports: Vec<_> = module
64            .functions
65            .iter()
66            .filter(|f| f.export_name.is_some())
67            .collect();
68
69        if exports.is_empty() {
70            return Err(BackendError::CompilationFailed(
71                "no exported functions found".into(),
72            ));
73        }
74
75        let mut functions = Vec::new();
76        for func in &exports {
77            let name = func.export_name.clone().unwrap();
78            // #359: copy THIS function's declared param widths into the config so
79            // `compile_function` (which carries no function index) can refuse a
80            // 64-bit param on the AAPCS stack-argument path. Cheap clone only when
81            // a signature table is present and this function has a width entry —
82            // otherwise reuse the shared config (every existing module unchanged).
83            // #509: same per-function pattern for the blocktype-arity side-table
84            // (value-carrying-branch lowering).
85            let params = config
86                .func_params_i64
87                .get(func.index as usize)
88                .filter(|p| !p.is_empty());
89            // #457: THIS function's DECLARED param count (imports-first full
90            // index), so the backend can cap the access-pattern inference that
91            // mistook a read-before-write local for a param. `None` when the
92            // driver supplied no arg-count table (hand-built modules).
93            let declared_params = config.func_arg_counts.get(func.index as usize).copied();
94            // GI-FPU-002 (#619/#369): THIS function's declared f32-param mask.
95            let params_f32 = config
96                .func_params_f32
97                .get(func.index as usize)
98                .filter(|p| !p.is_empty());
99            // GI-FPU-002 phase 2 (#369): THIS function's declared f64-param
100            // mask (hard-float targets decline f64 params loudly).
101            let params_f64 = config
102                .func_params_f64
103                .get(func.index as usize)
104                .filter(|p| !p.is_empty());
105            // GI-FPU-002 phase 2 (#719/#369): THIS function's declared f32/f64
106            // return flag, so the epilogue soundness guard fires on every driver
107            // path (not only the CLI loops).
108            let ret_f32 = config
109                .func_ret_f32
110                .get(func.index as usize)
111                .copied()
112                .unwrap_or(false);
113            let ret_f64 = config
114                .func_ret_f64
115                .get(func.index as usize)
116                .copied()
117                .unwrap_or(false);
118            let func_config = if params.is_some()
119                || params_f32.is_some()
120                || params_f64.is_some()
121                || !func.block_arity.is_empty()
122                || declared_params.is_some()
123                || ret_f32
124                || ret_f64
125            {
126                Some(CompileConfig {
127                    current_func_params_i64: params.cloned().unwrap_or_default(),
128                    current_func_params_f32: params_f32.cloned().unwrap_or_default(),
129                    current_func_params_f64: params_f64.cloned().unwrap_or_default(),
130                    current_func_ret_f32: ret_f32,
131                    current_func_ret_f64: ret_f64,
132                    current_func_block_arity: func.block_arity.clone(),
133                    current_func_param_count: declared_params,
134                    ..config.clone()
135                })
136            } else {
137                None
138            };
139            let cfg = func_config.as_ref().unwrap_or(config);
140            let compiled = self.compile_function(&name, &func.ops, cfg)?;
141            functions.push(compiled);
142        }
143
144        Ok(CompilationResult {
145            functions,
146            elf: None,
147            backend_name: self.name().to_string(),
148        })
149    }
150
151    fn compile_function(
152        &self,
153        name: &str,
154        ops: &[WasmOp],
155        config: &CompileConfig,
156    ) -> Result<CompiledFunction, BackendError> {
157        let (code, relocations, line_map, branch_map, final_instrs) =
158            compile_wasm_to_arm(ops, config).map_err(BackendError::CompilationFailed)?;
159
160        // #778: derive the SOUND static WCET bound from the final Thumb-2 stream.
161        // Only present for the Thumb-2 path; the core class (from the triple)
162        // decides whether the bound is sound (M3/M4) or declined (M7). Phase 2:
163        // any --wcet-hints entry for THIS function is verified (never trusted)
164        // by the loop analyzer.
165        let wcet = final_instrs.map(|instrs| {
166            let hints = config
167                .wcet_hints
168                .as_ref()
169                .and_then(|h| h.functions.get(name));
170            crate::wcet::function_wcet_with_hints(name, &instrs, &config.target.triple, hints)
171        });
172
173        Ok(CompiledFunction {
174            name: name.to_string(),
175            code,
176            wasm_ops: ops.to_vec(),
177            relocations,
178            line_map,
179            branch_map,
180            wcet,
181        })
182    }
183
184    fn is_available(&self) -> bool {
185        true // Always available — it's a library backend
186    }
187}
188
189/// Count the number of function parameters by analyzing LocalGet patterns
190fn count_params(wasm_ops: &[WasmOp]) -> u32 {
191    let mut first_access: std::collections::HashMap<u32, bool> = std::collections::HashMap::new();
192    for op in wasm_ops {
193        match op {
194            WasmOp::LocalGet(idx) => {
195                first_access.entry(*idx).or_insert(true);
196            }
197            WasmOp::LocalSet(idx) | WasmOp::LocalTee(idx) => {
198                first_access.entry(*idx).or_insert(false);
199            }
200            _ => {}
201        }
202    }
203
204    first_access
205        .iter()
206        .filter_map(
207            |(&idx, &is_read_first)| {
208                if is_read_first { Some(idx + 1) } else { None }
209            },
210        )
211        .max()
212        .unwrap_or(0)
213}
214
215/// #539: fold the `i32.const 0; memory.grow m` idiom to `memory.size m`.
216/// `memory.grow(0)` always succeeds and returns the current page count (WASM
217/// Core §4.4.7), which is exactly `memory.size`; the fixed-memory backend
218/// otherwise emits a constant `-1` for every `memory.grow`, so the legal
219/// `memory.grow(0)` "read/validate current size" idiom wrongly reported failure.
220/// Only the ADJACENT const-0 delta is folded (a non-zero delta keeps the sound
221/// `-1` — fixed memory genuinely cannot grow; a runtime-computed 0 is a
222/// documented follow-up). Backend- and path-agnostic: `memory.size` reads the
223/// runtime memory-size register on every selector, so this fixes the optimized
224/// and direct paths at once.
225fn rewrite_memory_grow_zero(wasm_ops: &[WasmOp]) -> Vec<WasmOp> {
226    let mut out = Vec::with_capacity(wasm_ops.len());
227    let mut i = 0;
228    while i < wasm_ops.len() {
229        if matches!(wasm_ops[i], WasmOp::I32Const(0))
230            && let Some(WasmOp::MemoryGrow(m)) = wasm_ops.get(i + 1)
231        {
232            out.push(WasmOp::MemorySize(*m));
233            i += 2;
234        } else {
235            out.push(wasm_ops[i].clone());
236            i += 1;
237        }
238    }
239    out
240}
241
242/// #509: does the op stream contain a `br`/`br_if`/`br_table` that CARRIES a
243/// value — i.e. one targeting a result-typed block/if (forward edge with
244/// results > 0) or a parameterized loop header (backward edge with loop
245/// params > 0)?
246///
247/// The optimized path's wasm→IR lowering drops the carried value on such
248/// edges (the taken arm returns the fall-through result — same class as the
249/// #507 `br_table` drop, observed on `pick_br`/`pick_br_fall`), so — like
250/// #507 — the shape is detected on the raw op stream and routed to the direct
251/// selector, whose #509 designated-result-register lowering lands the value
252/// correctly. `block_arity` is the decoder's ordinal blocktype-arity
253/// side-table; when it is empty (hand-built op streams) every block reads as
254/// void and this never fires, keeping the optimized path byte-identical for
255/// every existing caller. Frozen-safe for the same reason as #507: the frozen
256/// fixtures compile `--relocatable` (already direct), and no optimized-path
257/// fixture branches to a result-typed block.
258fn has_value_carrying_branch(wasm_ops: &[WasmOp], block_arity: &[(u8, u8)]) -> bool {
259    // Open control constructs: (is_loop, params, results), innermost last.
260    let mut open: Vec<(bool, u8, u8)> = Vec::new();
261    let mut ctrl_ord = 0usize;
262    // A branch edge carries a value when its target is a result-typed forward
263    // join (block/if) or a parameterized loop header.
264    let carries = |open: &[(bool, u8, u8)], depth: u32| -> bool {
265        let Some(&(is_loop, params, results)) = open
266            .len()
267            .checked_sub(1 + depth as usize)
268            .and_then(|i| open.get(i))
269        else {
270            return false; // function-level target — handled by Return lowering
271        };
272        if is_loop { params > 0 } else { results > 0 }
273    };
274    for op in wasm_ops {
275        match op {
276            WasmOp::Block | WasmOp::If => {
277                let (p, r) = block_arity.get(ctrl_ord).copied().unwrap_or((0, 0));
278                ctrl_ord += 1;
279                open.push((false, p, r));
280            }
281            WasmOp::Loop => {
282                let (p, r) = block_arity.get(ctrl_ord).copied().unwrap_or((0, 0));
283                ctrl_ord += 1;
284                open.push((true, p, r));
285            }
286            WasmOp::End => {
287                open.pop(); // None only at the function-level end — harmless
288            }
289            WasmOp::Br(d) | WasmOp::BrIf(d) if carries(&open, *d) => return true,
290            WasmOp::BrTable { targets, default }
291                if targets
292                    .iter()
293                    .chain(std::iter::once(default))
294                    .any(|d| carries(&open, *d)) =>
295            {
296                return true;
297            }
298            _ => {}
299        }
300    }
301    false
302}
303
304/// Core compilation: WASM ops → ARM machine code bytes + relocations
305///
306/// Returns (code_bytes, relocations) where relocations record BL instructions
307/// that target external symbols (e.g., `__meld_dispatch_import` for import calls).
308type CompileArmOutput = (
309    Vec<u8>,
310    Vec<CodeRelocation>,
311    LineMap,
312    synth_core::backend::BranchMap,
313    // #778: the SOUND static WCET result over the final Thumb-2 stream, computed
314    // by `compile_function` (which knows the function name); `None` for the A32
315    // path. Purely additive metadata — does not touch `code`.
316    Option<Vec<synth_synthesis::ArmInstruction>>,
317);
318
319fn compile_wasm_to_arm(
320    wasm_ops: &[WasmOp],
321    config: &CompileConfig,
322) -> Result<CompileArmOutput, String> {
323    // #539: `memory.grow(0)` must return the CURRENT page count, not the
324    // fixed-memory `-1` sentinel — growing by zero pages can never fail (WASM
325    // Core §4.4.7), so a guest doing `if (memory.grow(0) < 0) trap;` wrongly
326    // faulted. Every lowering path emitted a delta-agnostic `-1`. `memory.grow(0)`
327    // is semantically identical to `memory.size`, which the backend already
328    // computes from the runtime memory-size register (R10 >> 16 = pages), so fold
329    // the `i32.const 0; memory.grow` idiom to `memory.size` up front — backend-
330    // and path-agnostic. A non-zero delta keeps `-1` (fixed memory genuinely
331    // cannot grow); a runtime delta that happens to be 0 is the documented
332    // follow-up.
333    let rewritten = rewrite_memory_grow_zero(wasm_ops);
334    // #494 phase 2b: the fact-spec guard-elision marks are keyed by op index
335    // into the stream the DRIVER handed us. The memory.grow(0) fold above can
336    // only shift indices AT OR AFTER a `memory.grow` — an op the fact-spec
337    // walk never crosses (it stops at the first untracked op, so no mark can
338    // follow one). Defense in depth: if the fold fired at all, drop the marks
339    // loudly rather than risk keying a guard elision to the wrong op.
340    let (fact_div_zero_elide, fact_div_ovf_elide, fact_mem_bounds_elide): (
341        &[usize],
342        &[usize],
343        &[usize],
344    ) = if rewritten.len() == wasm_ops.len() {
345        (
346            &config.fact_div_zero_elide,
347            &config.fact_div_ovf_elide,
348            &config.fact_mem_bounds_elide,
349        )
350    } else {
351        if !config.fact_div_zero_elide.is_empty()
352            || !config.fact_div_ovf_elide.is_empty()
353            || !config.fact_mem_bounds_elide.is_empty()
354        {
355            eprintln!(
356                "fact-spec: DECLINE guard elision marks dropped — the                      memory.grow(0) fold shifted op indices (#494 defensive gate);                      general lowering emitted"
357            );
358        }
359        (&[], &[], &[])
360    };
361    let wasm_ops: &[WasmOp] = &rewritten;
362
363    // #457: `count_params` INFERS the param count from access patterns (a local
364    // whose first access is a read is assumed to be a param), so a
365    // read-before-write NON-PARAM local — which WASM zero-initializes — was
366    // indistinguishable from a param: it got homed in a parameter register and
367    // read caller garbage instead of 0. When the driver supplied the DECLARED
368    // count (`current_func_param_count`, from the module's type section), cap
369    // the inference with it. `min` (not a plain override) keeps every function
370    // whose inference is <= declared byte-identical: the inferred count can only
371    // EXCEED the declared one via a read-first local index >= the declared count
372    // — i.e. exactly the read-before-write locals this issue is about.
373    let inferred_params = count_params(wasm_ops);
374    let num_params = match config.current_func_param_count {
375        Some(declared) => inferred_params.min(declared),
376        None => inferred_params,
377    };
378    // A read-before-write non-param local exists iff the capped count dropped.
379    // Such locals need the wasm-mandated zero-init, which only the direct
380    // selector emits — the optimized path's `ir_to_arm` maps a non-param
381    // local's vreg onto an r4+ temp with no initialization (caller garbage).
382    let has_rbw_local = num_params < inferred_params;
383
384    let bounds_config = match config.effective_safety_bounds() {
385        SafetyBounds::None => BoundsCheckConfig::None,
386        SafetyBounds::Mpu => BoundsCheckConfig::Mpu,
387        SafetyBounds::Software => BoundsCheckConfig::Software,
388        SafetyBounds::Mask => {
389            // #651 (mirroring the RISC-V backend's compile-time decline):
390            // index masking wraps `ea & (size-1)` — a modulo only when the
391            // linear-memory size is a power of two. With a non-power-of-two
392            // size the AND would silently REMAP in-bounds addresses (e.g.
393            // 0x18000 & 0x2FFFF = 0x8000 for a 192 KiB memory). Decline
394            // loudly rather than miscompile. `linear_memory_bytes == 0`
395            // means "unknown" (plain per-function path, no module context)
396            // — the startup default of one 64 KiB page is a power of two.
397            let bytes = config.linear_memory_bytes;
398            if bytes != 0 && !bytes.is_power_of_two() {
399                return Err(format!(
400                    "--safety-bounds mask requires a power-of-two linear-memory \
401                     size, got {bytes} bytes — switch to --safety-bounds software \
402                     for the deterministic check (#651)"
403                ));
404            }
405            BoundsCheckConfig::Masking
406        }
407    };
408
409    // The non-optimized (direct) instruction-selection path. Handles f32 via
410    // VFP/FPU. Used directly when `--no-optimize` is set, and as the fallback
411    // when the optimized path declines a module (see issue #120 below).
412    //
413    // VCR-RA-001 step 3b-lite (#242): a FRESH selector per attempt, with
414    // `spill_on_exhaustion` set only on the retry — the first pass is the
415    // unmodified default, so every function that compiles today is selected by
416    // exactly the code that compiled it yesterday (bit-identity is structural,
417    // not behavioural).
418    let select_direct_attempt = |spill_on_exhaustion: bool,
419                                 param_backing_on_exhaustion: bool,
420                                 local_promote: bool,
421                                 i64_spill_slots: Option<usize>|
422     -> Result<Vec<ArmInstruction>, synth_core::Error> {
423        let db = RuleDatabase::with_standard_rules();
424        let mut selector =
425            InstructionSelector::with_bounds_check(db.rules().to_vec(), bounds_config);
426        selector.set_target(config.target.fpu, &config.target.triple);
427        if config.num_imports > 0 {
428            selector.set_num_imports(config.num_imports);
429        }
430        // #195: plumb the callee argument-count tables so the direct selector can
431        // marshal call arguments into R0–R3 per AAPCS.
432        selector.set_func_arg_counts(
433            config.func_arg_counts.clone(),
434            config.type_arg_counts.clone(),
435        );
436        // #197: in relocatable host-link mode, emit direct `func_N` BLs for
437        // imports (rewritten to the wasm field name by build_relocatable_elf)
438        // instead of `__meld_dispatch_import`.
439        selector.set_relocatable(config.relocatable);
440        // #642: call_indirect guard inputs (compile-time table size for the
441        // bounds guard + closed-world type verdicts). Without them, every
442        // call_indirect lowering declines loudly.
443        selector.set_call_indirect_guards(config.call_indirect_guards.clone());
444        // #275: on the self-contained image path (NOT --relocatable) the R11
445        // funcref-table dispatch is a silent miscompile — the region is only
446        // populated by an external runtime, which a self-contained ELF does
447        // not have, so the dispatch would read function pointers from
448        // linear-memory data. Two outcomes:
449        //  - the Thumb-2 `--cortex-m` image path (CLI-flagged: the builder
450        //    that emits and patches the flash-resident funcref table will
451        //    run) lowers call_indirect through that table, PC-relative,
452        //    never via R11;
453        //  - every OTHER self-contained configuration (A32/Cortex-R5, the
454        //    simple-ELF builder, imports present) keeps the loud decline.
455        // The host-linked (--relocatable) path keeps the guarded R11
456        // dispatch: there a runtime places the table region at R11.
457        let self_contained_table = config.self_contained_funcref_table
458            && matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
459        selector
460            .set_reject_self_contained_call_indirect(!config.relocatable && !self_contained_table);
461        selector.set_self_contained_funcref_table(self_contained_table);
462        // #237: native-pointer ABI — wasm statics become __synth_wasm_data-relative.
463        selector.set_native_pointer_abi(config.native_pointer_abi, config.linear_memory_bytes);
464        // VCR-MEM-002 phase 1 (#406): per-memory initial page counts — enables
465        // the multi-memory arms (memory-0 lowering never reads it; empty ⇒
466        // every multi-memory op declines loudly).
467        selector.set_memory_pages(config.memory_pages.clone());
468        // #311: i64 call results are register PAIRS — tag them.
469        selector.set_result_types(config.func_ret_i64.clone(), config.type_ret_i64.clone());
470        // #359: declared param widths of THIS function, so the AAPCS stack-arg
471        // path can refuse 64-bit params (Ok-or-Err). Empty ⇒ assume i32.
472        selector.set_params_i64(config.current_func_params_i64.clone());
473        // GI-FPU-002 (#619/#369): declared f32-param mask — home hard-float f32
474        // args in S0..S15 (AAPCS-VFP) instead of the R0..R3 integer path.
475        selector.set_params_f32(config.current_func_params_f32.clone());
476        // GI-FPU-002 phase 2 (#369): declared f64-param mask — hard-float
477        // targets decline f64-param functions loudly (no D-register homing yet).
478        selector.set_params_f64(config.current_func_params_f64.clone());
479        // GI-FPU-002 phase 2 (#719/#369): THIS function's f32/f64 return flag, so
480        // the epilogue loudly declines a float result reaching it in a core
481        // register (never a silent integer R0 return where a caller reads S0/D0).
482        selector.set_ret_float(config.current_func_ret_f32, config.current_func_ret_f64);
483        // GI-FPU-002 phase 3 (#369): per-callee float-signature tables. `Call`
484        // marshals the AAPCS-VFP boundary from these (float args into S0../D0..,
485        // float results out of S0/D0); `CallIndirect` still declines a
486        // float-returning static type loudly.
487        selector.set_float_call_signatures(
488            config.func_ret_f32.clone(),
489            config.func_ret_f64.clone(),
490            config.type_ret_f32.clone(),
491            config.type_ret_f64.clone(),
492            config.func_params_f32.clone(),
493            config.func_params_f64.clone(),
494        );
495        // #509: blocktype-arity side-table of THIS function, so value-carrying
496        // br/br_if/br_table land the carried value in the target block's
497        // designated result register instead of dropping it. Empty ⇒ legacy
498        // void-block lowering.
499        selector.set_block_arity(config.current_func_block_arity.clone());
500        // Stack-pointer promotion is meaningful only under the native-pointer ABI;
501        // gating here keeps every non-native compile (all frozen fixtures) on the
502        // legacy R9 globals-table path, bit-identical.
503        if config.native_pointer_abi
504            && let Some((sp_idx, sp_init)) = config.stack_pointer_global
505        {
506            selector.set_native_pointer_stack(sp_idx, sp_init);
507        }
508        // #643: per-global slot widths — i64/f64 globals occupy 8-byte slots
509        // (register-pair store/load) and shift every later global's offset.
510        // Empty for i32-only modules ⇒ the legacy `idx * 4` layout, unchanged.
511        selector.set_global_widths(config.global_widths.clone());
512        selector.set_spill_on_exhaustion(spill_on_exhaustion);
513        selector.set_param_backing_on_exhaustion(param_backing_on_exhaustion);
514        // #587 pool-grow rung: a larger i64 spill-slot pool, set ONLY on the
515        // retry after an attempt failed with the slot-pool-exhausted Err —
516        // functions that compile with the default pool keep their frame
517        // byte-identical by construction.
518        if let Some(slots) = i64_spill_slots {
519            selector.set_i64_spill_slots(slots);
520        }
521        // VCR-RA local promotion (#390, #242): keep eligible non-param i32 locals
522        // in callee-saved registers instead of frame slots — the structural lever
523        // toward native parity. DEFAULT-ON as of v0.14.0: gale's G474RE DWT gate
524        // cleared it as a net win (gust_mix dissolved 58→50 cyc/call −14%, all 5
525        // stack spill/reloads eliminated, correctness bit-identical over [0,2047],
526        // 2.00×→1.72× vs LLVM). Escape hatch: `SYNTH_NO_LOCAL_PROMOTE=1` restores
527        // the frame-slot path. Leaf-only / i32-only / ARM-only (see
528        // compute_local_promotion); the leaf-only lift + i64 locals are follow-ons.
529        // #474: `local_promote` is now a per-attempt parameter so the retry ladder
530        // can drop promotion as an exhaustion-recovery rung (promotion pins r4-r8,
531        // which on a dense function leaves the spill allocator with nothing to
532        // free → the frame-slot path is the escape that restores compilability).
533        selector.set_local_promote(local_promote);
534        // #494 phase 2b: certificate-discharged div/rem trap-guard elision
535        // marks (empty in every compile without SYNTH_FACT_SPEC + facts).
536        selector
537            .set_fact_div_guard_elisions(fact_div_zero_elide.to_vec(), fact_div_ovf_elide.to_vec());
538        // #494 bounds-elision: certificate-discharged memory bounds-guard
539        // marks (empty in every compile without SYNTH_FACT_SPEC + facts).
540        selector.set_fact_mem_bounds_elisions(fact_mem_bounds_elide.to_vec());
541        selector.select_with_stack(wasm_ops, num_params)
542    };
543    let select_direct = || -> Result<Vec<ArmInstruction>, String> {
544        const SINGLE_EXHAUSTION: &str = "all allocatable registers are live on the stack";
545        const PAIR_EXHAUSTION: &str = "no consecutive pair of free registers for i64";
546        const SLOT_EXHAUSTION: &str = "i64 spill-slot pool exhausted";
547        // The full exhaustion-recovery ladder, parameterized on whether local
548        // promotion is enabled. Each rung is reached only when the previous one
549        // returned a recoverable register-exhaustion Err, so a function that
550        // compiles on the first attempt is untouched by the later rungs. Returns
551        // the result AND which rung produced it (for the #242 measurement below).
552        let recovery_ladder =
553            |promote: bool,
554             i64_spill_slots: Option<usize>|
555             -> (Result<Vec<ArmInstruction>, synth_core::Error>, &'static str) {
556                let mut attempt = select_direct_attempt(false, false, promote, i64_spill_slots);
557                let mut rung = "base";
558                // VCR-RA-001 step 3b-lite (#242): the i32 register-exhaustion
559                // hard-fail is recoverable — retry with spill-on-exhaustion, which
560                // reserves the spill area and spills the deepest stack value when
561                // the pool is full.
562                if let Err(e) = &attempt
563                    && e.to_string().contains(SINGLE_EXHAUSTION)
564                {
565                    attempt = select_direct_attempt(true, false, promote, i64_spill_slots);
566                    rung = "spill";
567                }
568                // VCR-RA-001 acceptance increment (#242): the i64 consecutive-PAIR
569                // exhaustion is recoverable too — not by stack spilling (the pair
570                // allocator already spills stack values, #171) but by frame-backing
571                // the params (#204) so they stop pinning R0-R3, with spill kept on.
572                if let Err(e) = &attempt
573                    && e.to_string().contains(PAIR_EXHAUSTION)
574                {
575                    attempt = select_direct_attempt(true, true, promote, i64_spill_slots);
576                    rung = "param-backing";
577                }
578                (attempt, rung)
579            };
580        // #474: local promotion (default-on since v0.14.0) is an OPTIMIZATION — it
581        // must never be the reason a function fails to compile. Run the full ladder
582        // with promotion first (so every function that compiles today is
583        // bit-identical), and if it still ends in register exhaustion, fall back to
584        // the promotion-off ladder (the v0.12.0 frame-slot lowering — exactly what
585        // the `SYNTH_NO_LOCAL_PROMOTE=1` workaround does, now automatic). Promotion
586        // pins r4-r8 for the locals; on a dense function that leaves the allocator
587        // with nothing to free, so dropping it restores compilability. The fallback
588        // is reached ONLY by functions that exhaust WITH promotion, so promotion-on
589        // output is untouched by construction (frozen byte gate stays green).
590        let promote = std::env::var("SYNTH_NO_LOCAL_PROMOTE").is_err();
591        // The full pre-#587 recovery sequence (promotion-on ladder, then the
592        // #474 promotion-off fallback), parameterized on the pool size so the
593        // pool-grow retry below reruns it verbatim.
594        let full_sequence = |slots: Option<usize>| -> (
595            Result<Vec<ArmInstruction>, synth_core::Error>,
596            &'static str,
597            bool,
598        ) {
599            let (mut attempt, mut rung) = recovery_ladder(promote, slots);
600            let mut promotion_dropped = false;
601            if promote
602                && attempt
603                    .as_ref()
604                    .err()
605                    .is_some_and(|e| e.to_string().contains("register exhaustion"))
606            {
607                let (rescued, off_rung) = recovery_ladder(false, slots);
608                if rescued.is_ok() {
609                    attempt = rescued;
610                    rung = off_rung;
611                    promotion_dropped = true;
612                }
613            }
614            (attempt, rung, promotion_dropped)
615        };
616        let (mut attempt, mut rung, mut promotion_dropped) = full_sequence(None);
617        // #587 pool-grow retry (the falcon func_60/func_73 remainder): the fixed
618        // 8-slot i64 spill pool can exhaust while spilling is otherwise working —
619        // an i64-dense function simply has more values simultaneously live than
620        // the pool holds. Rerun the ENTIRE sequence (every rung, both promotion
621        // modes) with the pool sized from a conservative operand-stack-depth
622        // bound: the number of simultaneously spilled values can never exceed
623        // the operand-stack depth, plus a few transient slots (the arg-move
624        // cycle resolver and call-result parking each borrow one). The selector
625        // clamps the request to its 12-bit-friendly cap; a function that still
626        // exhausts stays an honest loud skip. Deliberately LAST — after the #474
627        // promotion-off fallback — so any function that compiled yesterday
628        // (through any rung or fallback) is produced by exactly yesterday's
629        // path, byte-identical; the grown pool only ever fires for functions
630        // whose every existing escape ended in the slot-pool Err.
631        if attempt
632            .as_ref()
633            .err()
634            .is_some_and(|e| e.to_string().contains(SLOT_EXHAUSTION))
635        {
636            let depth = synth_core::wasm_stack_check::max_depth_bound(wasm_ops) as usize;
637            let (grown, _, grown_dropped) = full_sequence(Some(depth.saturating_add(4)));
638            if grown.is_ok() {
639                attempt = grown;
640                rung = "pool-grow";
641                promotion_dropped = grown_dropped;
642            }
643        }
644        // VCR-RA measurement (#242): log which recovery rung produced the result,
645        // so the per-rung distribution across a corpus can be measured — the size
646        // of the failure surface a verified allocator must subsume (see
647        // scripts/repro/register_exhaustion_recovery_ladder.md). Logging only:
648        // emitted bytes are unchanged, so the frozen byte gate is unaffected.
649        if std::env::var("SYNTH_RECOVERY_STATS").is_ok() {
650            eprintln!(
651                "[recovery-stats] rung={rung}{} result={}",
652                if promotion_dropped {
653                    " promotion-off"
654                } else {
655                    ""
656                },
657                if attempt.is_ok() { "ok" } else { "exhausted" },
658            );
659        }
660        attempt.map_err(|e| format!("instruction selection failed: {}", e))
661    };
662
663    // Instruction selection: optimized or direct.
664    //
665    // #197: `--relocatable` (host-link ET_REL) forces the direct selector. The
666    // optimized path materializes an absolute linmem base (0x20000100) and does
667    // not preserve caller-saved registers across calls — both wrong for a
668    // host-linked object, where the linmem base arrives via `fp` at runtime and
669    // callees follow AAPCS. `select_with_stack` (now i64-spill capable after
670    // #171) handles fp-relative memory + caller-saved preservation correctly.
671    //
672    // #507: `br_table` is DROPPED during the optimized path's wasm→IR lowering
673    // (`optimize_full`), so `ir_to_arm` never sees the dispatch — it emits the
674    // arm bodies in fall-through sequence with no `cmp`/branch on the selector, a
675    // SILENT miscompile (every input hits the last arm). The selector value isn't
676    // even loaded. Because the drop happens before `ir_to_arm`, there's no `Err`
677    // to fall back on; detect it on the raw wasm op stream here and force the
678    // direct selector (`select_with_stack` lowers `br_table` correctly as a
679    // cmp-chain — confirmed on the `--relocatable` path). Same honest-degradation
680    // contract as the issue-#120 f32 decline: the function still compiles
681    // correctly, just without IR-level optimization. Frozen-safe: the frozen
682    // fixtures compile `--relocatable` (already direct), and no optimized-path
683    // fixture (control_step, flight_algo) contains `br_table`.
684    let has_br_table = wasm_ops
685        .iter()
686        .any(|op| matches!(op, WasmOp::BrTable { .. }));
687    // #509: the optimized path also drops the value carried by a `br`/`br_if`
688    // to a result-typed block (the taken edge returns the wrong arm's value —
689    // same silent-miscompile class as the #507 br_table drop). Route the shape
690    // to the direct selector, whose designated-result-register lowering (#509)
691    // lands the carried value at the join. Never fires for void-block control
692    // flow (all frozen/optimized fixtures), so those stay byte-identical.
693    let has_value_carry = has_value_carrying_branch(wasm_ops, &config.current_func_block_arity);
694    // #503-i64/#518: route any signature with a 64-bit (i64/f64) param to the
695    // direct selector. The optimized path's param homing is width-naive — its
696    // #518 decline covers only functions that READ an i64 param (an `I64Load`
697    // from a param index), so a function that reads an i32 param whose AAPCS
698    // home a preceding wide param SHIFTED (e.g. p1 of `(i64 i32)` lives in R2,
699    // not R1; p3 of `(i64 i32 i32 i32)` lives on the stack, not in R3) was
700    // silently miscompiled rather than falling back. The direct selector's
701    // `aapcs_param_layout` homing handles every such shape (i64-param READS
702    // already fell back to it via the ir_to_arm Err, so those functions emit
703    // the same bytes as before). `num_params` counts read-first locals, so a
704    // function that never touches any param keeps the optimized path.
705    let has_wide_param = config
706        .current_func_params_i64
707        .iter()
708        .take(num_params as usize)
709        .any(|&w| w);
710    // #494 phase 2b: div/rem guard-elision marks are consumed by the DIRECT
711    // selector only — the optimized path's IR passes (const-fold/CSE/DCE)
712    // renumber instructions, so an op-index-keyed mark cannot soundly survive
713    // them. Route marked functions direct (the #507/#509 honest-degradation
714    // pattern). Never fires without SYNTH_FACT_SPEC + facts + a discharged
715    // obligation, so every existing compile keeps its path byte-identical.
716    let has_fact_div_elide = !fact_div_zero_elide.is_empty()
717        || !fact_div_ovf_elide.is_empty()
718        // #494 bounds-elision: memory bounds-guard marks are direct-selector
719        // keyed for the same reason (IR passes renumber instructions).
720        || !fact_mem_bounds_elide.is_empty();
721    // #643: the optimized path's global lowering is width-naive — `GlobalGet`/
722    // `GlobalSet` are single-word `[R9, idx*4]` accesses, which (a) silently
723    // dropped the high word of every i64 global and (b) mis-address every
724    // global whose offset an earlier wide (i64/f64) slot shifted. When the
725    // module has any wide global, route every global-touching function to the
726    // direct selector, whose type-aware summed layout pairs the access (or
727    // declines loudly). Modules with only 4-byte globals — every existing
728    // fixture — keep the optimized path byte-identical.
729    let has_wide_global_module = config.global_widths.iter().any(|&w| w > 4);
730    let has_global_access = has_wide_global_module
731        && wasm_ops
732            .iter()
733            .any(|op| matches!(op, WasmOp::GlobalGet(_) | WasmOp::GlobalSet(_)));
734    // VCR-VER-001 (#242): `post_exhaust` scopes the post-exhaustion cleanup
735    // extensions to functions whose bytes the #580 spill-on-exhaustion
736    // machinery actually shaped (bridge-reported). Everything else — the
737    // direct path, non-exhausted optimized functions — stays byte-identical
738    // flag-on (the `vcr_ver_001_gate_242` lock's contract).
739    let (arm_instrs, post_exhaust) = if config.no_optimize
740        || config.relocatable
741        || has_br_table
742        || has_value_carry
743        || has_wide_param
744        || has_global_access
745        || has_fact_div_elide
746        // #457: route read-before-write non-param locals to the direct
747        // selector, whose prologue zero-init lands the wasm-mandated 0.
748        || has_rbw_local
749    {
750        if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
751            eprintln!("[path-debug] direct (pre-gate)");
752        }
753        (select_direct()?, false)
754    } else {
755        let opt_config = if config.loom_compat {
756            OptimizationConfig::loom_compat()
757        } else {
758            OptimizationConfig::all()
759        };
760
761        let mut bridge = OptimizerBridge::with_config(opt_config);
762        // #188: tell the bridge how many imports there are so it declines only
763        // LOCAL calls (and leaves import calls on the optimized path, keeping
764        // the #173 field-name relocation rewrite intact).
765        bridge.set_num_imports(config.num_imports);
766        // #543 Phase 2: thread the integrator-marked volatile DMA-window ranges
767        // (`--volatile-segment <base>:<len>`) to the bridge's address-caching
768        // levers — base-CSE (#468) excludes any access inside a marked range
769        // from its fold set, and the bridge-level const-CSE declines wholesale
770        // while any range is marked. Empty (the default) ⇒ byte-identical.
771        bridge.set_volatile_segments(config.volatile_segments.clone());
772        // #377: thread `--safety-bounds` to the bridge. Pre-fix the optimized
773        // path ignored it — `software`/`mask` were SILENT NO-OPS on the path
774        // that lowers the bulk of a flight loop's i32 loads/stores (byte-
775        // identical to `none`, while the safety manifest claimed otherwise).
776        // `Software` now emits the inline guard per access; `Masking` declines
777        // memory-accessing functions to the direct selector; `None`/`Mpu` are
778        // byte-identical to before.
779        bridge.set_bounds_check(bounds_config);
780        // #687: thread the absolute linear-memory base the optimized path
781        // materializes. Defaults to 0x2000_0100 (byte-identical);
782        // `--stack-layout=low` shifts it up by the reserved stack size so
783        // const-address accesses follow the moved linear memory.
784        bridge.set_linmem_base(config.linmem_base);
785        // `ir_to_arm` now returns `Result` — an `Err` means the optimized path
786        // hit an unmapped vreg (issue-#93-class). Treat it identically to an
787        // `optimize_full` failure: fall back to the direct selector rather
788        // than propagating, so the function still compiles correctly.
789        match bridge
790            .optimize_full(wasm_ops)
791            .and_then(|(opt_ir, _cfg, _stats)| bridge.ir_to_arm(&opt_ir, num_params as usize))
792        {
793            Ok(arm_ops) => {
794                if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
795                    eprintln!("[path-debug] optimized (ir_to_arm ok)");
796                }
797                (
798                    arm_ops
799                        .into_iter()
800                        .map(|op| ArmInstruction {
801                            op,
802                            source_line: None,
803                        })
804                        .collect(),
805                    bridge.spill_on_exhaust_fired(),
806                )
807            }
808            // Issue #120: the optimized path declines modules it cannot lower
809            // (notably scalar f32/f64 ops — the IR has no float opcodes). Fall
810            // back to the direct instruction selector, which handles f32 via
811            // VFP/FPU. This is honest degradation: the function still compiles
812            // correctly, just without IR-level optimization.
813            Err(e) => {
814                if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
815                    eprintln!("[path-debug] direct (fallback: {e})");
816                }
817                (select_direct()?, false)
818            }
819        }
820    };
821
822    // #257/#277: `mul`+`add`→`mla` fusion is intentionally NOT wired here.
823    // The transform is correct and ready (`synth_synthesis::liveness::fuse_mul_add`,
824    // fully tested), but it is **register-allocation-coupled**: over the current
825    // greedy single-pass selector, folding `mul rM,..; add rD,rM,rX` → `mla`
826    // extends the live ranges of the mul inputs to the mla point, and the added
827    // pressure (extra moves/spills) costs more than the single-cycle MLA saves —
828    // gale measured a +2 cyc on-target REGRESSION (flat_flight 255→257, G474RE)
829    // even though it removes 2 instructions and the seam stays 0x07FDF307. So the
830    // fusion stays unwired until the spill-aware allocator (VCR-RA-001) chooses
831    // registers, at which point it becomes net-positive (per #272's plan and the
832    // wiring design note). Lesson (#277): a register-pressure-affecting transform
833    // needs an on-target/allocator-aware gate, not a byte-count gate, before it
834    // can default on.
835
836    // VCR-RA-001 const-CSE / rematerialization-avoidance (#209): moved to run
837    // LAST, after the immediate-folds — see the apply_const_cse call below
838    // (#242). Earlier it ran here (before range-realloc and the folds), which is
839    // what let it grow gale's --relocatable `gust_mix` 90→92 B (#242 burndown,
840    // 2026-06-26): retargeting a read defeated a *downstream* immediate-fold that
841    // would otherwise have absorbed the constant. Running CSE-last makes those
842    // foldable consts already-folded-and-gone, so CSE only ever touches genuinely
843    // redundant materializations.
844
845    // VCR-RA-001 RANGE RE-ALLOCATION (#209/#242, wiring step 3a) — the first
846    // CONSEQUENTIAL allocator pass: re-colour each maximal straight-line
847    // segment over the R0-R8 pool with value ranges as the allocation unit
848    // (segment inputs + per-register live-outs pinned to their original
849    // registers, reserved R9-R12/SP identity-assigned — each segment is
850    // independently sound, no cross-segment liveness assumed). Renames
851    // registers only: never adds, removes, or reorders instructions, so
852    // labels/branch offsets are unaffected.
853    //
854    // DEFAULT-ON since v0.11.36: gale cleared the gate on-target (G474RE,
855    // #209 2026-06-10) — flag-on output byte-identical to flag-off on
856    // flat_flight/controller/control_step, fires on the filter family with
857    // zero cycle delta and a small size win, all selfchecks green on silicon.
858    // Opt out with `SYNTH_RANGE_REALLOC=0`; per-function stats with
859    // `SYNTH_REALLOC_STATS=1`.
860    //
861    // The companion dead callee-saved-save elimination (gale's "next
862    // consequential lever", same issue comment) then shrinks the prologue
863    // `push {r4-r8,lr}` / epilogue `pop {r4-r8,pc}` to the callee-saved
864    // registers the re-allocated body still touches (leaf-only,
865    // SP-untouched, even-count-padded — see shrink_callee_saved_saves):
866    // ~12 cycles of pure save/restore overhead removed on small leaves.
867    let realloc_on = std::env::var("SYNTH_RANGE_REALLOC").map_or(true, |v| v != "0");
868    let arm_instrs = if realloc_on {
869        use synth_synthesis::rules::Reg;
870        const POOL: [Reg; 9] = [
871            Reg::R0,
872            Reg::R1,
873            Reg::R2,
874            Reg::R3,
875            Reg::R4,
876            Reg::R5,
877            Reg::R6,
878            Reg::R7,
879            Reg::R8,
880        ];
881        // VCR-VER-001 (#242): on a function the spill-on-exhaustion machinery
882        // shaped, the terminal segment gets relaxed live-out pinning (only
883        // R0/R1 are observable past `bx lr` at this pre-prologue position) so
884        // the colourer can lower R4-R8-homed tails into caller-saved R0-R3 —
885        // shrinking the `push {r4-r8,lr}` the #580 exhaustion shapes pay for.
886        // `post_exhaust == false` selects the shipping pass bit for bit.
887        let (out, stats) = synth_synthesis::liveness::reallocate_function_post_exhaust(
888            &arm_instrs,
889            &POOL,
890            post_exhaust,
891        );
892        if std::env::var("SYNTH_REALLOC_STATS").is_ok() {
893            eprintln!(
894                "[range-realloc] {} segments: {} reallocated, {} declined ({} validator-rejected), {} need spill (step 4)",
895                stats.segments,
896                stats.reallocated,
897                stats.declined,
898                stats.validator_rejects,
899                stats.needs_spill
900            );
901        }
902        // VCR-RA-002 (#390, epic #242): eliminate a provably-dead stack frame
903        // (`sub sp,#N`/`add sp,#N` reserved by `compute_local_layout` for locals
904        // that promotion homed in registers, never accessed). Removing it saves
905        // the two instructions AND restores the SP-untouched precondition that
906        // `shrink_callee_saved_saves` requires — so it must run FIRST.
907        // DEFAULT-ON (#242 flag audit flip-wave, #592 audit item): evidence
908        // basis was the 2-path × repro-corpus sweep — 0 functions grow, 58
909        // shrink (flight_seam controller_step 250→242 −8 / filter_step 180→168
910        // −12, native_pointer frame_roundtrip 46→34 −12), locked by the
911        // `dead_frame_elim_no_grow_corpus_242` cargo gate; execution
912        // differentials re-run green on the new default bytes BEFORE the
913        // frozen ARM anchors were re-pinned (leaf_dead_frame, flight_seam,
914        // frame_slot_dce — see the flip PR). Escape hatch:
915        // `SYNTH_DEAD_FRAME_ELIM=0` opts out and restores the pre-flip bytes
916        // (CI-gated in `frozen_codegen_bytes.rs`).
917        let out = if !std::env::var("SYNTH_DEAD_FRAME_ELIM").is_ok_and(|v| v == "0") {
918            synth_synthesis::liveness::elide_dead_frame(&out).unwrap_or(out)
919        } else {
920            out
921        };
922        // #490 (epic #242): the optimized selector uses r4-r8 as scratch /
923        // promoted locals but emits no prologue, silently clobbering a caller's
924        // callee-saved registers. Add the missing `push {r4-r8,lr}` /
925        // `pop {r4-r8,pc}` HERE — on the post-realloc body, where realloc has
926        // lowered low-pressure r4-r8 scratch back to r0-r3, so a save is added
927        // only for registers genuinely clobbered. `shrink_callee_saved_saves`
928        // (next) then trims it to the used set. No-op on the direct path (it
929        // already has its own prologue) and on callee-saved-free leaves.
930        let out = synth_synthesis::liveness::ensure_callee_saved_prologue(&out);
931        synth_synthesis::liveness::shrink_callee_saved_saves(&out).unwrap_or(out)
932    } else {
933        // Range-realloc off (`SYNTH_RANGE_REALLOC=0`): the optimized path still
934        // must preserve the callee-saved registers it clobbers (#490). No shrink
935        // (it is coupled to the realloc lever), so the conservative full save
936        // stays — correct, just not minimised in this debug configuration.
937        synth_synthesis::liveness::ensure_callee_saved_prologue(&arm_instrs)
938    };
939
940    // VCR-RA-001 SHADOW ALLOCATION (#209/#242): run the register allocator on
941    // the selected stream and LOG what it finds — without changing a single
942    // emitted byte. This is the measure-only bridge between the built analysis
943    // layer and the eventual virtual-register wiring: it shows, per real
944    // function, whether the allocator can colour it within the R0–R8 pool and
945    // how much const-CSE / rematerialization headroom exists (#209). Enable with
946    // `SYNTH_SHADOW_ALLOC=1`; off by default and side-effect-free either way.
947    if std::env::var("SYNTH_SHADOW_ALLOC").is_ok() {
948        use synth_synthesis::liveness::{
949            AllocationOutcome, allocate_function, function_peak_pressure,
950        };
951        // R9 globals / R10 mem-size / R11 mem-base / R12 IP-scratch are reserved;
952        // pin them above the 0..9 allocatable pool so the colourer keeps R0–R8.
953        let precolored = std::collections::BTreeMap::from([
954            (synth_synthesis::rules::Reg::R9, 9usize),
955            (synth_synthesis::rules::Reg::R10, 10),
956            (synth_synthesis::rules::Reg::R11, 11),
957            (synth_synthesis::rules::Reg::R12, 12),
958        ]);
959        // True VALUE pressure (one node per value, not per reused physical reg):
960        // a NeedsSpill with peak ≤ 9 is a SPURIOUS physical-register spill — the
961        // function fits once virtually allocated.
962        let peak = function_peak_pressure(&arm_instrs);
963        match allocate_function(&arm_instrs, 9, &precolored) {
964            AllocationOutcome::Allocated {
965                remat_opportunities,
966                coloring,
967            } => eprintln!(
968                "[shadow-alloc] OK: {} pregs coloured within R0-R8 pool, peak value-pressure {}, {} const-CSE/remat opportunities",
969                coloring.len(),
970                peak,
971                remat_opportunities
972            ),
973            AllocationOutcome::NeedsSpill(s) => eprintln!(
974                "[shadow-alloc] physical-graph would spill {:?}, but peak value-pressure is {} (≤9 ⇒ spurious; fits once virtually allocated)",
975                s, peak
976            ),
977            AllocationOutcome::Declined => {
978                eprintln!(
979                    "[shadow-alloc] declined (unmodeled construct — calls/i64/fp/offset-branch)"
980                )
981            }
982        }
983    }
984
985    // VCR-SEL-004 cmp→select → IT-block predication fusion (#242). The selector
986    // lowers a `select` whose condition is a comparison to a *materialize then
987    // re-test* sequence (`cmp a,b; SetCond D,c; cmp D,#0; movne dst,v1; moveq
988    // dst,v2`); this collapses it onto the comparison's own flags — deleting the
989    // `SetCond` and the `cmp D,#0` and retargeting the predicated moves to `c` /
990    // `invert(c)` — yielding the textbook predicated clamp (`cmp a,b; movc dst,v1;
991    // mov{!c} dst,v2`). −2 instructions per fused select. gale #428 measured this
992    // as the #1 hot-path size/cycle lever on the gust_mix clamp chain.
993    //
994    // Run LATE: after range re-allocation (so the dead-D proof sees final register
995    // identities) and before encode. Removal-only + rename-only ⇒ no spill
996    // regression and labels/branch offsets are unaffected. Each fusion is proven
997    // sound (flags reused only when nothing clobbers them in the window; the
998    // boolean deleted only when provably dead) — see `fuse_cmp_select`.
999    //
1000    // DEFAULT-ON as of v0.13.0 (#428): cmp→select fusion ships by default. The
1001    // byte-changing flip is validated by (a) the unicorn execution oracle that runs
1002    // the two-move `mov{invert(c)}` arm (cmp_select_two_move_differential.py), (b)
1003    // gale's gale_decider_diff 10,596-case sweep across all 8 verified primitives
1004    // (native ≡ flag-off ≡ flag-on = 0x88e73178d232bcf5), and (c) the named-anchor
1005    // differentials re-run with fusion ON — control_step still 0x00210A55, flat+
1006    // inlined flight_algo still 0x07FDF307 (results preserved; bytes deliberately
1007    // changed, re-frozen on this commit). Escape hatch: `SYNTH_NO_CMP_SELECT_FUSE=1`
1008    // reverts to the pre-fusion lowering. The on-silicon G474RE DWT no-regression
1009    // check is a tracked post-ship follow-up (gale owns it).
1010    let arm_instrs = if std::env::var("SYNTH_NO_CMP_SELECT_FUSE").is_err() {
1011        // The rewritten stream is identical to `fuse_cmp_select`'s 2-tuple form;
1012        // the extra `two_move` count is diagnostic only (the fusion census /
1013        // blast-radius datum — #7 made that arm reachable).
1014        let (out, fused, two_move) =
1015            synth_synthesis::liveness::fuse_cmp_select_with_stats(&arm_instrs);
1016        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1017            let in_place = fused - two_move;
1018            eprintln!(
1019                "[cmp-select-fuse] {fused} select(s) fused to predicated moves \
1020                 ({two_move} two-move, {in_place} in-place)"
1021            );
1022        }
1023        out
1024    } else {
1025        arm_instrs
1026    };
1027
1028    // Perf lever 1 toward native parity (#390): redundant stack-reload elimination.
1029    // synth lowers every wasm local to a frame slot, so `local.set; local.get` emits
1030    // `str rX,[sp,#N]; … ; ldr rY,[sp,#N]`; when rX still holds the value the reload
1031    // (a ~2-cycle M4 load) becomes `mov rY,rX`. Removal-of-a-load + rename only ⇒ no
1032    // new instruction form and no label/offset change. DEFAULT-ON (#242 feature
1033    // loop): validated bit-identical RESULTS on every frozen anchor (control_step
1034    // 0x00210A55 13/13, flat+inlined flight_algo 0x07FDF307) with .text reduced on
1035    // the shipped --relocatable path, plus 8 unit tests + the frame_slot_dce
1036    // execution differential — the same gated path cmp→select took to default-on in
1037    // v0.13.0 (G474RE silicon confirms perf post-ship). Escape hatch:
1038    // `SYNTH_NO_STACK_FWD=1` restores the frame-resident bytes (frozen-old goldens).
1039    let stack_fwd = std::env::var("SYNTH_NO_STACK_FWD").is_err();
1040    let arm_instrs = if stack_fwd {
1041        let (out, fwd) = synth_synthesis::liveness::forward_stack_reloads(&arm_instrs);
1042        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1043            eprintln!("[stack-fwd] {fwd} stack reload(s) forwarded to register moves");
1044        }
1045        out
1046    } else {
1047        arm_instrs
1048    };
1049
1050    // VCR-RA frame-slot DCE (#242): once `forward_stack_reloads` has turned the
1051    // reloads of a spill slot into register moves, the `str rX,[sp,#N]` that fed
1052    // them is a dead store — its slot is never loaded again. Remove it. Pairs
1053    // with (and only pays after) stack-reload forwarding, so it shares the flag.
1054    let arm_instrs = if stack_fwd {
1055        let (out, n) = synth_synthesis::liveness::eliminate_dead_frame_stores(&arm_instrs);
1056        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1057            eprintln!("[frame-slot-dce] {n} dead frame store(s) removed");
1058        }
1059        out
1060    } else {
1061        arm_instrs
1062    };
1063
1064    // VCR-RA-001 spill re-choice (#242), two stages behind one flag.
1065    // Stage 1 (the #569 spike): slot-value forwarding BETWEEN reloads.
1066    // `forward_stack_reloads` (above) forwards only from a spill store's
1067    // SOURCE register, so when register pressure clobbers that source its
1068    // reloads survive; this stage tracks which registers provably still hold
1069    // a frame slot's value (through earlier reloads and reg-reg moves) and
1070    // turns reload #2..#n into a 1-cycle `mov` (or deletes it when the target
1071    // already holds the value). Stage 2 (the Belady re-choice): where NO
1072    // register still holds the value — the genuine-spill case, flat_flight's
1073    // peak-11 hot segment — the value was usually evicted while a dead
1074    // register existed; the clobbering def(s) are renamed onto a provably-dead
1075    // register (`spill_rechoice_segment`) so the value stays resident and the
1076    // reload dissolves outright. A dissolved reload can leave the feeding
1077    // store dead, so the frame-slot DCE sweep runs once more behind the same
1078    // flag. Per-segment commit gates: executable same-value-flow trace
1079    // equality, strict shrink, pool-pressure fit, sub-word/unknown-slot
1080    // conservatism (see `apply_spill_realloc` / `spill_rechoice_segment`).
1081    // Stage 3 (whole-function slot liveness): the segment-local DCE keeps a
1082    // store whose slot reaches function end ("reach-end ≠ dead" — it cannot
1083    // see other segments); `eliminate_unread_frame_stores` walks the whole
1084    // function (labels/branches/loops, SP-displacement tracked) and drops a
1085    // store whose slot NO reachable instruction can read — flat_flight's two
1086    // surviving stores (#576), completing Belady's 0-load side with a 0-store
1087    // side. Same flag: the three stages are one lever, flipped together.
1088    // DEFAULT-ON (#242 feature loop, the v0.14.0 local-promotion pattern):
1089    // Belady spilling ships by default. Evidence basis for the flip: three
1090    // landed flag-off increments (#569 forwarding, #576 Belady re-choice,
1091    // #579 whole-fn slot liveness), 40+ functions shrink / 0 grow across the
1092    // 68-fixture × 2-path sweep, per-segment executable value-trace equality
1093    // guards, and the unicorn-vs-wasmtime execution differentials re-run
1094    // green on the new default bytes (flat+inlined flight_algo 0x07FDF307,
1095    // const_cse, frame_slot_dce, spill_rung_581, r12_spill_496 — which covers
1096    // control_step_decide vs wasmtime; control_step's .text is byte-identical
1097    // under the flip) BEFORE the frozen goldens were re-pinned. Escape hatch:
1098    // `SYNTH_SPILL_REALLOC=0` is the OPT-OUT — it disables all three stages
1099    // and restores the pre-flip bytes (CI-gated by
1100    // `frozen_fixtures_spill_realloc_escape_hatch_restores_old_bytes`). Any
1101    // other value (or unset) runs the pass.
1102    // VCR-VER-001 post-exhaustion extensions (#242, the PR #659 verdict): with
1103    // `SYNTH_SPILL_ON_EXHAUST` active the #580 allocation-time Belady spill
1104    // keeps exhausted functions on the optimized path, and its slots present
1105    // shapes the shipping pass structurally cannot fire on (fresh-monotonic
1106    // slots defeat the overwrite-only DCE; the eviction store's source is
1107    // redefined immediately, defeating store→reload forwarding; R2/R3 are
1108    // never touched again, so the rename-target deadness proof declines them).
1109    // `post_exhaust` (bridge-scoped, see above) enables const
1110    // rematerialization of spilled constants, R2/R3 exit-dead rename targets,
1111    // and per-pair pressure commit — see `apply_spill_realloc_post_exhaust`.
1112    // Flag off (the default): `false` selects the shipping behavior bit for
1113    // bit.
1114    let arm_instrs = if !std::env::var("SYNTH_SPILL_REALLOC").is_ok_and(|v| v == "0") {
1115        let (out, n) =
1116            synth_synthesis::liveness::apply_spill_realloc_post_exhaust(&arm_instrs, post_exhaust);
1117        let (out, d) = synth_synthesis::liveness::eliminate_dead_frame_stores(&out);
1118        let (mut out, u) = synth_synthesis::liveness::eliminate_unread_frame_stores(&out);
1119        let (mut tn, mut td, mut tu) = (n, d, u);
1120        // Post-exhaustion only: iterate the triple to a bounded fixpoint. Each
1121        // dissolved spill pair frees registers and removes stores, exposing
1122        // rename windows and holder chains the previous iteration could not
1123        // prove — the allocation-time Belady slots (#580) routinely need two
1124        // or three rounds where the shipping single round suffices for the
1125        // default path's slots. Every iteration is individually gate-proven
1126        // (value-trace equality, pool pressure, strict shrink), so iterating
1127        // composes soundly; the bound keeps compile time deterministic.
1128        if post_exhaust {
1129            let mut progress = n + d + u > 0;
1130            for _ in 0..3 {
1131                if !progress {
1132                    break;
1133                }
1134                let (o, n) =
1135                    synth_synthesis::liveness::apply_spill_realloc_post_exhaust(&out, true);
1136                let (o, d) = synth_synthesis::liveness::eliminate_dead_frame_stores(&o);
1137                let (o, u) = synth_synthesis::liveness::eliminate_unread_frame_stores(&o);
1138                progress = n + d + u > 0;
1139                (tn, td, tu) = (tn + n, td + d, tu + u);
1140                out = o;
1141            }
1142            // The cleanup can leave the spill frame with zero surviving
1143            // accesses (every reload rematerialized/dissolved, every store
1144            // swept) — the balanced `sub sp,#K`/`add sp,#K` is then pure
1145            // overhead. `elide_dead_frame` proves that and removes the pair;
1146            // its early run (post-realloc) could not, because the spill
1147            // traffic was still in the stream at that point.
1148            out = synth_synthesis::liveness::elide_dead_frame(&out).unwrap_or(out);
1149        }
1150        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1151            eprintln!(
1152                "[spill-realloc] {tn} reload(s) forwarded/eliminated, {td} newly-dead frame store(s) removed, {tu} unread-slot store(s) removed"
1153            );
1154        }
1155        out
1156    } else {
1157        arm_instrs
1158    };
1159
1160    // VCR-RA immediate-shift folding (#390, #242): a constant shift amount the
1161    // stack selector materialized into a scratch register (`movw rM,#C; lsl rD,rN,rM`)
1162    // folds to the immediate form (`lsl rD,rN,#C`), removing the dead `movw` — −1
1163    // instruction, −1 live register. Removal-only (offset-neutral before branch
1164    // resolution, like the dead-store pass). DEFAULT-ON as of v0.15.0: validated
1165    // bit-identical results + a net cycle win on the dissolved hot path (−2
1166    // cyc/call, .text 100→90 B on gust_mix). Escape hatch: `SYNTH_NO_IMM_SHIFT_FOLD=1`.
1167    let arm_instrs = if std::env::var("SYNTH_NO_IMM_SHIFT_FOLD").is_err() {
1168        let (out, folds) = synth_synthesis::liveness::fold_immediate_shifts(&arm_instrs);
1169        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1170            eprintln!(
1171                "[imm-shift-fold] {folds} register shift(s) folded to immediate, movw dropped"
1172            );
1173        }
1174        out
1175    } else {
1176        arm_instrs
1177    };
1178
1179    // #686: elide the #682 mod-32 shift-amount mask (`and r12,rK,#31` before
1180    // every register-controlled i32 shl/shr) when the amount is STATICALLY
1181    // provable < 32 — a const amount folds to the immediate-shift form
1182    // (reduced mod 32, so >= 32 shrinks too), and an already-masked amount
1183    // (`rK = rX & c`, c < 32) drops the redundant re-mask. gale measured the
1184    // unconditional mask at ~12% cyc/call (+14 B) on gust_mix, whose Q8
1185    // fixed-point shifts are all constants (#686). The mask stays wherever
1186    // the bound is unproven — elision is an optimization, the mask is the
1187    // sound default (`liveness::elide_shift_masks` has the proof
1188    // obligations). Runs after `fold_immediate_shifts` (whose movw→shift
1189    // window the #682 mask intercepts, so it declines every masked const
1190    // shift) and before branch resolution (removal/rewrite-only ⇒
1191    // offset-neutral).
1192    //
1193    // FLAG-OFF (opt-in via `SYNTH_SHIFT_MASK_ELIDE=1`) because the elision
1194    // moves the frozen anchors: const-amount shifts in control_step (−20 B),
1195    // flight_seam (−164 B) and flight_seam_flat (−168 B) fold back to the
1196    // immediate form — byte-shapes the corpus had BEFORE the #682 mask, now
1197    // with the mask soundly kept for every unproven amount. Flipping
1198    // default-on is a deliberate byte-changing refreeze (all differentials
1199    // re-run on the new bytes, goldens re-pinned) owned by the maintainer.
1200    let arm_instrs = if std::env::var("SYNTH_SHIFT_MASK_ELIDE").is_ok_and(|v| v != "0") {
1201        let (out, elisions) = synth_synthesis::liveness::elide_shift_masks(&arm_instrs);
1202        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1203            eprintln!(
1204                "[shift-mask-elide] {elisions} provably-<32 shift-amount mask(s) elided (#686)"
1205            );
1206        }
1207        out
1208    } else {
1209        arm_instrs
1210    };
1211
1212    // VCR-RA uxth/uxtb fold (#428, #242): `movw rM,#0xffff; and rD,rN,rM` →
1213    // `uxth rD,rN` (and the 0xff/uxtb form), removing the dead `movw` — −1
1214    // instruction, −1 live register per 16/8-bit mask. 0xffff/0xff are not Thumb-2
1215    // modified immediates so the selector materializes them into a register; the
1216    // dedicated zero-extend expresses the same masking inline. Removal-only +
1217    // rewrite-in-place (offset-neutral). DEFAULT-ON (#242 flag audit flip-wave,
1218    // #592 audit item): evidence basis was the 2-path × repro-corpus sweep —
1219    // 0 functions grow, 13 shrink (control_step 300→294 −6, gust_mix 38→32 −6,
1220    // uxth_fold pack 36→24 −12), locked by the `uxth_fold_no_grow_corpus_242`
1221    // cargo gate; execution differentials re-run green on the new default
1222    // bytes BEFORE the frozen ARM anchors were re-pinned (uxth_fold,
1223    // control_step — see the flip PR). Escape hatch: `SYNTH_UXTH_FOLD=0` opts
1224    // out and restores the pre-flip bytes (CI-gated in
1225    // `frozen_codegen_bytes.rs`).
1226    let arm_instrs = if !std::env::var("SYNTH_UXTH_FOLD").is_ok_and(|v| v == "0") {
1227        let (out, folds) = synth_synthesis::liveness::fold_uxth(&arm_instrs);
1228        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1229            eprintln!("[uxth-fold] {folds} mask-and folded to uxth/uxtb, movw dropped");
1230        }
1231        out
1232    } else {
1233        arm_instrs
1234    };
1235
1236    // VCR-RA-001 const-CSE / rematerialization-avoidance (#209, #242). Drops a
1237    // `movw`/`mov #imm` that re-materializes a constant already resident in
1238    // another register and retargets the reads — every rewrite proven by the
1239    // liveness analysis. Runs LAST, after every immediate-fold (shift, uxth) and
1240    // range-realloc, but BEFORE branch resolution/encoding (it removes
1241    // instructions, shifting byte offsets). CSE-last is the #242 no-regression
1242    // fix: the folds have already absorbed every foldable constant, so CSE can no
1243    // longer defeat one (the gust_mix 90→92 mechanism). The pass additionally
1244    // size-guards each segment via the byte-estimator — it commits a segment's
1245    // rewrites only if they do not grow its estimated size — so a retarget that
1246    // would flip a 16-bit encoding to 32-bit (higher base register) is declined.
1247    // DEFAULT-ON (#242 flip-wave, the SYNTH_SPILL_REALLOC/SYNTH_BASE_CSE
1248    // template): const-CSE ships by default. The flip prerequisites recorded in
1249    // `const_cse_reduction_242.rs` were retired first — the bridge-level INLINE
1250    // aliasing (the alias-eviction spill-bijection hazard) was DELETED from
1251    // `optimizer_bridge::ir_to_arm`, so this post-hoc, liveness-proven pass is
1252    // the flag's ONLY effect. Evidence basis: 152 fixture×path corpus sweep — 0
1253    // functions grow (size-guarded per segment), 40 shrink (const_cse::spill12
1254    // 236→148 B), total −536 B — and the execution differentials re-run green
1255    // on the new default bytes BEFORE the frozen goldens were re-pinned
1256    // (const_cse, frame_slot_dce, flight_seam 0x07FDF307, spill_rung_581,
1257    // volatile_segment_543, control_step 0x00210A55). Escape hatch:
1258    // `SYNTH_CONST_CSE=0` is the OPT-OUT — it restores the pre-flip bytes
1259    // (CI-gated by `const_cse_escape_hatch_restores_old_bytes_242` and the
1260    // frozen-anchor escape-hatch gate). Any other value (or unset) runs the pass.
1261    //
1262    // #543 Phase 2: const-CSE declines WHOLESALE while any volatile DMA range
1263    // (`--volatile-segment`) is marked. At the ArmOp level a cached constant
1264    // cannot be classified as address-vs-data (a retargeted read may be a
1265    // memory-access base carrying a per-use immediate offset), so the
1266    // conservative stance for statically-unknown addressing is to decline every
1267    // aliasing rewrite — each constant is re-materialized at each occurrence,
1268    // the documented volatile contract (`CompileConfig::volatile_segments`).
1269    let arm_instrs = if !std::env::var("SYNTH_CONST_CSE").is_ok_and(|v| v == "0")
1270        && config.volatile_segments.is_empty()
1271    {
1272        let (out, removed) = synth_synthesis::liveness::apply_const_cse(&arm_instrs);
1273        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1274            eprintln!("[const-cse] {removed} redundant constant materialization(s) removed");
1275        }
1276        out
1277    } else {
1278        arm_instrs
1279    };
1280
1281    // VCR-RA-001 spill-choice REPORT (#242): measure-only, like SYNTH_SHADOW_ALLOC.
1282    // Per straight-line segment, the frame-slot traffic actually emitted vs the
1283    // reload/store count a farthest-next-use (Belady) allocation over the R0-R8
1284    // pool would need — the measured headroom for the full spill-choice rewrite.
1285    // Printed on the FINAL stream (post all rewrite passes), so a flag-off run
1286    // reports the greedy baseline and a flag-on run reports what remains.
1287    if std::env::var("SYNTH_SPILL_REPORT").is_ok() {
1288        for seg in synth_synthesis::liveness::spill_choice_report(&arm_instrs, 9) {
1289            if seg.actual_reloads + seg.actual_spill_stores > 0 || seg.peak_pressure > 9 {
1290                eprintln!(
1291                    "[spill-report] seg@{} len={} peak={} actual={}ld+{}st belady(k=9)={}ld+{}st",
1292                    seg.start,
1293                    seg.len,
1294                    seg.peak_pressure,
1295                    seg.actual_reloads,
1296                    seg.actual_spill_stores,
1297                    seg.belady_reloads,
1298                    seg.belady_spill_stores
1299                );
1300            }
1301        }
1302    }
1303
1304    // ISA feature gate: validate that all generated instructions are supported
1305    // by the target. This catches FPU instructions on no-FPU targets, double-precision
1306    // instructions on single-precision targets, etc.
1307    validate_instructions(&arm_instrs, config.target.fpu, &config.target.triple)
1308        .map_err(|e| format!("ISA validation failed: {}", e))?;
1309
1310    // Encode to binary — use Thumb-2 for Cortex-M targets
1311    let use_thumb2 = matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
1312
1313    let encoder = if use_thumb2 {
1314        ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
1315    } else {
1316        ArmEncoder::new_arm32()
1317    };
1318
1319    // #202: resolve local label branches (Bcc/B/Bhs/Blo) to byte-accurate
1320    // offsets before encoding. `select_with_stack` emits them as label
1321    // placeholders and never resolves them — without this they encode as
1322    // `bne.n #0` and land mid-instruction whenever a 32-bit Thumb-2 instruction
1323    // sits between the branch and its target (UsageFault on real hardware).
1324    // Only meaningful for Thumb-2 (the offset units are halfword/PC+4).
1325    let arm_instrs = if use_thumb2 {
1326        resolve_label_branches(arm_instrs, &encoder)?
1327    } else {
1328        arm_instrs
1329    };
1330
1331    // #778: capture the FINAL Thumb-2 instruction stream (post label-resolution,
1332    // the exact list the encode loop below consumes) so `compile_function` can
1333    // derive the sound WCET bound. Cheap clone; frozen-safe (the WCET walk is a
1334    // pure observation and never touches `code`). Only the Thumb-2 path — the A32
1335    // (Cortex-R5) cycle model is a follow-up.
1336    let final_instrs_for_wcet: Option<Vec<synth_synthesis::ArmInstruction>> = if use_thumb2 {
1337        Some(arm_instrs.clone())
1338    } else {
1339        None
1340    };
1341
1342    let mut code = Vec::new();
1343    let mut relocations = Vec::new();
1344
1345    // #345: literal-pool address loads. Each `LdrSym` was encoded as a placeholder
1346    // `LDR.W rd,[pc,#0]`; record where its instruction sits and what it loads so
1347    // we can append a pooled word (carrying the symbol address via R_ARM_ABS32)
1348    // and patch the PC-relative offset once the pool position is known.
1349    struct PendingLiteral {
1350        ldr_offset: u32,
1351        symbol: String,
1352        addend: i32,
1353    }
1354    let mut pending_literals: Vec<PendingLiteral> = Vec::new();
1355
1356    // VCR-DBG-001: per-instruction source map for DWARF `.debug_line`. Captured
1357    // here because `code.len()` immediately before `encode()` is the final
1358    // machine offset of the instruction within this function's `.text` — nothing
1359    // after the loop shifts earlier instructions (the literal pool is appended at
1360    // the end; the LDR patch below is in-place/length-preserving). Purely
1361    // additive: it does not touch `code`, so `.text` is byte-identical.
1362    let mut line_map: LineMap = Vec::new();
1363    // VCR-DEC-003 (#396): object-branch class per emitted instruction, parallel
1364    // to `line_map`. Cheap, additive, does not touch `code`.
1365    let mut branch_map: synth_core::backend::BranchMap = Vec::new();
1366
1367    for instr in &arm_instrs {
1368        // Record a relocation for every BL: the encoder emits `bl #0` and
1369        // relies on a relocation to patch the target. This covers BOTH import
1370        // dispatch stubs (`__meld_*`, undefined externals) AND internal calls
1371        // (`func_N`, defined in this object). Previously only `__meld_*` was
1372        // recorded, so internal `BL func_N` calls were left as unpatched
1373        // `bl #0` placeholders branching to a garbage address (#167).
1374        if let ArmOp::Bl { label } = &instr.op {
1375            relocations.push(CodeRelocation {
1376                offset: code.len() as u32,
1377                symbol: label.clone(),
1378                kind: synth_core::backend::RelocKind::ThmCall,
1379            });
1380        }
1381        // #237: symbol-relative MOVW/MOVT (the `--native-pointer-abi` static-data
1382        // addressing). The encoder writes the addend in place; record the matching
1383        // R_ARM_MOVW_ABS_NC / R_ARM_MOVT_ABS so the linker adds the symbol address.
1384        if let ArmOp::MovwSym { symbol, .. } = &instr.op {
1385            relocations.push(CodeRelocation {
1386                offset: code.len() as u32,
1387                symbol: symbol.clone(),
1388                kind: synth_core::backend::RelocKind::MovwAbs,
1389            });
1390        }
1391        if let ArmOp::MovtSym { symbol, .. } = &instr.op {
1392            relocations.push(CodeRelocation {
1393                offset: code.len() as u32,
1394                symbol: symbol.clone(),
1395                kind: synth_core::backend::RelocKind::MovtAbs,
1396            });
1397        }
1398        // #345: defer the literal-pool word + reloc + offset patch to the
1399        // post-loop pass (the pool address is not yet known).
1400        if let ArmOp::LdrSym { symbol, addend, .. } = &instr.op {
1401            pending_literals.push(PendingLiteral {
1402                ldr_offset: code.len() as u32,
1403                symbol: symbol.clone(),
1404                addend: *addend,
1405            });
1406        }
1407
1408        // The machine offset of this instruction is the current code length,
1409        // captured before the bytes are appended.
1410        line_map.push((code.len() as u32, instr.source_line));
1411        branch_map.push((code.len() as u32, classify_arm_branch(&instr.op)));
1412
1413        let encoded = encoder
1414            .encode(&instr.op)
1415            .map_err(|e| format!("ARM encoding failed: {}", e))?;
1416        code.extend_from_slice(&encoded);
1417    }
1418
1419    // #345: place the literal pool at the end of this function's `.text`. Gated on
1420    // there being at least one `LdrSym` — functions without one are byte-identical
1421    // to before (no trailing padding, so downstream `func_offsets` are unchanged
1422    // and the frozen differential fixtures stay bit-for-bit equal).
1423    if !pending_literals.is_empty() {
1424        if !use_thumb2 {
1425            return Err("LdrSym literal-pool addressing requires Thumb-2".to_string());
1426        }
1427        // 4-byte align the pool start (Thumb-2 word loads require it, and
1428        // `Align(PC,4)` in the LDR-literal semantics assumes a word-aligned pool).
1429        while code.len() % 4 != 0 {
1430            code.push(0x00);
1431        }
1432        // One distinct pooled word per LdrSym (no dedup: different sites carry
1433        // different addends, and the REL addend lives in the word).
1434        for lit in &pending_literals {
1435            let word_offset = code.len() as u32;
1436
1437            // REL semantics: the linker computes `S + A`, where A is the in-place
1438            // value of the relocated word. Initialize the word to the addend so
1439            // the final loaded address is `symbol + addend`.
1440            code.extend_from_slice(&(lit.addend as u32).to_le_bytes());
1441            relocations.push(CodeRelocation {
1442                offset: word_offset,
1443                symbol: lit.symbol.clone(),
1444                kind: synth_core::backend::RelocKind::Abs32,
1445            });
1446
1447            // Patch the placeholder `LDR.W rd,[pc,#imm12]`. Thumb-2 LDR (literal):
1448            // address = Align(PC,4) + imm12, with PC = ldr_offset + 4. The pool is
1449            // always after the LDR, so U=1 (already set in hw1 = 0xF8DF).
1450            let pc = lit.ldr_offset + 4;
1451            let aligned_pc = pc & !3u32;
1452            let imm12 = word_offset - aligned_pc;
1453            if imm12 > 0xFFF {
1454                // Wide LDR-literal range is ±4 KB; these function bodies are far
1455                // smaller, but fail cleanly rather than miscompile if exceeded.
1456                return Err(format!(
1457                    "LdrSym literal pool out of range (#345): imm12={} > 4095 \
1458                     for symbol {}",
1459                    imm12, lit.symbol
1460                ));
1461            }
1462            let hw2_off = (lit.ldr_offset + 2) as usize;
1463            let mut hw2 = u16::from_le_bytes([code[hw2_off], code[hw2_off + 1]]);
1464            hw2 = (hw2 & 0xF000) | (imm12 as u16); // keep Rt, set imm12
1465            let hw2_bytes = hw2.to_le_bytes();
1466            code[hw2_off] = hw2_bytes[0];
1467            code[hw2_off + 1] = hw2_bytes[1];
1468        }
1469    }
1470
1471    Ok((
1472        code,
1473        relocations,
1474        line_map,
1475        branch_map,
1476        final_instrs_for_wcet,
1477    ))
1478}
1479
1480/// VCR-DEC-003 (#396): classify one emitted `ArmOp` into its object-level
1481/// control-flow role for the `synth-provenance-v1` map. Conditional branches are
1482/// the object decision points MC/DC must reconcile; `SelectMove` is the folded
1483/// (IT-block) predicated form the cmp→select fuse produces — a decision with no
1484/// branch.
1485fn classify_arm_branch(op: &ArmOp) -> synth_core::backend::BranchClass {
1486    use synth_core::backend::BranchClass;
1487    match op {
1488        ArmOp::Bcc { .. } | ArmOp::Bhs { .. } | ArmOp::Blo { .. } | ArmOp::BCondOffset { .. } => {
1489            BranchClass::CondBranch
1490        }
1491        ArmOp::B { .. } | ArmOp::BOffset { .. } => BranchClass::UncondBranch,
1492        ArmOp::SelectMove { .. } => BranchClass::Predicated,
1493        _ => BranchClass::Other,
1494    }
1495}
1496
1497/// Resolve local label branches to byte-accurate offsets (#202).
1498///
1499/// `select_with_stack` emits conditional/unconditional branches as label
1500/// placeholders (`Bcc`/`B`/`Bhs`/`Blo` + `Label`) and never resolves them; the
1501/// encoder then emits a `0xD000`/`0xE000` placeholder with offset 0. Before #197
1502/// this path only ran for `--no-optimize`/declined functions, so the latent bug
1503/// stayed hidden — routing relocatable code through it surfaced branches that
1504/// land mid-instruction (a Cortex-M UsageFault) whenever a 32-bit Thumb-2
1505/// instruction sits between the branch and its target.
1506///
1507/// This pass encodes each instruction to learn its real byte length (so 16- vs
1508/// 32-bit forms and multi-instruction expansions are exact), maps each `Label`
1509/// to its byte position, and rewrites every label branch to the displacement
1510/// the encoder consumes: `(target - branch - 4) / 2` halfwords. A bounded
1511/// fixed-point handles an offset growing a branch from 16- to 32-bit (which
1512/// shifts later positions). `BCondOffset`/`BOffset` already produced inline by
1513/// the optimized path carry no label and are left untouched.
1514fn resolve_label_branches(
1515    arm_instrs: Vec<ArmInstruction>,
1516    encoder: &ArmEncoder,
1517) -> Result<Vec<ArmInstruction>, String> {
1518    use std::collections::HashMap;
1519    use synth_synthesis::Condition;
1520
1521    enum BKind {
1522        Cond(Condition),
1523        Uncond,
1524    }
1525    // Record each label branch ONCE — indices are stable across iterations.
1526    let mut branches: Vec<(usize, BKind, String)> = Vec::new();
1527    for (i, instr) in arm_instrs.iter().enumerate() {
1528        match &instr.op {
1529            ArmOp::Bcc { cond, label } => branches.push((i, BKind::Cond(*cond), label.clone())),
1530            ArmOp::Bhs { label } => branches.push((i, BKind::Cond(Condition::HS), label.clone())),
1531            ArmOp::Blo { label } => branches.push((i, BKind::Cond(Condition::LO), label.clone())),
1532            ArmOp::B { label } => branches.push((i, BKind::Uncond, label.clone())),
1533            _ => {}
1534        }
1535    }
1536    if branches.is_empty() {
1537        return Ok(arm_instrs);
1538    }
1539
1540    let mut resolved = arm_instrs;
1541    // Sizes only grow (16→32-bit), so this converges quickly; cap for safety.
1542    for _ in 0..16 {
1543        // 1. Byte position of each instruction (Label encodes to 0 bytes).
1544        let mut positions = Vec::with_capacity(resolved.len());
1545        let mut pos: i64 = 0;
1546        for instr in &resolved {
1547            positions.push(pos);
1548            pos += encoder
1549                .encode(&instr.op)
1550                .map_err(|e| format!("branch-resolve size probe failed: {}", e))?
1551                .len() as i64;
1552        }
1553        // 2. Label name -> byte position (owned keys so the borrow ends here).
1554        let mut labels: HashMap<String, i64> = HashMap::new();
1555        for (i, instr) in resolved.iter().enumerate() {
1556            if let ArmOp::Label { name } = &instr.op {
1557                labels.insert(name.clone(), positions[i]);
1558            }
1559        }
1560        // 3. Rewrite each branch to its byte-accurate offset.
1561        let mut changed = false;
1562        for (idx, kind, label) in &branches {
1563            // A label not defined locally is an EXTERNAL target (e.g.
1564            // `Trap_Handler` resolved by a relocation / the vector table). Leave
1565            // such branches as their placeholder for the existing relocation
1566            // path — only local control-flow labels are byte-resolved here.
1567            let Some(&target) = labels.get(label) else {
1568                continue;
1569            };
1570            // Encoder consumes the field as (target - branch - 4) / 2 halfwords.
1571            // Positions are always even, so this division is exact.
1572            let halfword_offset = ((target - positions[*idx] - 4) / 2) as i32;
1573            let new_op = match kind {
1574                BKind::Cond(c) => ArmOp::BCondOffset {
1575                    cond: *c,
1576                    offset: halfword_offset,
1577                },
1578                BKind::Uncond => ArmOp::BOffset {
1579                    offset: halfword_offset,
1580                },
1581            };
1582            if resolved[*idx].op != new_op {
1583                resolved[*idx].op = new_op;
1584                changed = true;
1585            }
1586        }
1587        if !changed {
1588            break;
1589        }
1590    }
1591    Ok(resolved)
1592}
1593
1594#[cfg(test)]
1595mod tests {
1596    use super::*;
1597
1598    /// #539: `i32.const 0; memory.grow m` folds to `memory.size m`; other deltas
1599    /// (const non-zero, runtime) are left as `memory.grow` (→ the sound fixed-
1600    /// memory -1). Non-grow ops are untouched, so functions without the idiom are
1601    /// byte-identical.
1602    #[test]
1603    fn test_rewrite_memory_grow_zero_539() {
1604        // the idiom -> memory.size
1605        assert_eq!(
1606            rewrite_memory_grow_zero(&[WasmOp::I32Const(0), WasmOp::MemoryGrow(0)]),
1607            vec![WasmOp::MemorySize(0)]
1608        );
1609        // const non-zero delta: NOT folded
1610        assert_eq!(
1611            rewrite_memory_grow_zero(&[WasmOp::I32Const(2), WasmOp::MemoryGrow(0)]),
1612            vec![WasmOp::I32Const(2), WasmOp::MemoryGrow(0)]
1613        );
1614        // runtime delta (no preceding const): NOT folded
1615        assert_eq!(
1616            rewrite_memory_grow_zero(&[WasmOp::LocalGet(0), WasmOp::MemoryGrow(0)]),
1617            vec![WasmOp::LocalGet(0), WasmOp::MemoryGrow(0)]
1618        );
1619        // a bare const-0 not feeding a grow is untouched
1620        assert_eq!(
1621            rewrite_memory_grow_zero(&[WasmOp::I32Const(0), WasmOp::I32Add]),
1622            vec![WasmOp::I32Const(0), WasmOp::I32Add]
1623        );
1624        // fold is local: surrounding ops preserved, indices past the fold intact
1625        assert_eq!(
1626            rewrite_memory_grow_zero(&[
1627                WasmOp::LocalGet(0),
1628                WasmOp::I32Const(0),
1629                WasmOp::MemoryGrow(0),
1630                WasmOp::I32Add,
1631            ]),
1632            vec![WasmOp::LocalGet(0), WasmOp::MemorySize(0), WasmOp::I32Add]
1633        );
1634    }
1635
1636    #[test]
1637    fn test_arm_backend_name() {
1638        let backend = ArmBackend::new();
1639        assert_eq!(backend.name(), "arm");
1640        assert!(backend.is_available());
1641    }
1642
1643    #[test]
1644    fn test_arm_backend_capabilities() {
1645        let backend = ArmBackend::new();
1646        let caps = backend.capabilities();
1647        assert!(!caps.produces_elf);
1648        assert!(caps.supports_rule_verification);
1649        assert!(!caps.is_external);
1650    }
1651
1652    #[test]
1653    fn test_compile_add_function() {
1654        let backend = ArmBackend::new();
1655        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
1656        let config = CompileConfig::default();
1657
1658        let result = backend.compile_function("add", &ops, &config);
1659        assert!(result.is_ok());
1660
1661        let func = result.unwrap();
1662        assert_eq!(func.name, "add");
1663        assert!(!func.code.is_empty());
1664        assert_eq!(func.wasm_ops, ops);
1665    }
1666
1667    /// VCR-DBG-001: the per-instruction source map must cover the function with
1668    /// monotonic, in-bounds machine offsets, and must not perturb the emitted
1669    /// code (it is captured at encode time, never serialized here).
1670    #[test]
1671    fn test_line_map_is_wellformed_dbg001() {
1672        let backend = ArmBackend::new();
1673        let ops = vec![
1674            WasmOp::LocalGet(0),
1675            WasmOp::LocalGet(1),
1676            WasmOp::I32Add,
1677            WasmOp::End,
1678        ];
1679        let config = CompileConfig::default();
1680        let func = backend.compile_function("add", &ops, &config).unwrap();
1681
1682        // Non-empty, and the first instruction starts at machine offset 0.
1683        assert!(
1684            !func.line_map.is_empty(),
1685            "a non-trivial function captures a source map"
1686        );
1687        assert_eq!(func.line_map[0].0, 0, "first instruction at offset 0");
1688
1689        // Offsets strictly increase by at least one ARM/Thumb instruction (>= 2
1690        // bytes) and every mapped offset lies inside the emitted `.text`.
1691        for w in func.line_map.windows(2) {
1692            assert!(w[1].0 > w[0].0, "instruction offsets strictly increase");
1693            assert!(
1694                w[1].0 - w[0].0 >= 2,
1695                "each ARM/Thumb instruction is >= 2 bytes"
1696            );
1697        }
1698        let last = func.line_map.last().unwrap().0 as usize;
1699        assert!(
1700            last < func.code.len(),
1701            "every mapped offset lies inside .text"
1702        );
1703
1704        // The side-table is additive: recompiling is deterministic and the map is
1705        // consistent with that exact code (capturing it does not alter output).
1706        let again = backend.compile_function("add", &ops, &config).unwrap();
1707        assert_eq!(
1708            again.code, func.code,
1709            "compilation deterministic; map is additive"
1710        );
1711        assert_eq!(again.line_map, func.line_map);
1712    }
1713
1714    #[test]
1715    fn test_count_params() {
1716        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
1717        assert_eq!(count_params(&ops), 2);
1718
1719        let no_params = vec![WasmOp::I32Const(5), WasmOp::I32Const(3), WasmOp::I32Add];
1720        assert_eq!(count_params(&no_params), 0);
1721    }
1722
1723    /// #457: the declared param count caps the access-pattern inference. The
1724    /// repro shape `(param i32)(local i32) → p0 + local1` reads local 1 before
1725    /// any write, so `count_params` infers 2 — with the declared count (1) the
1726    /// local is reclassified onto the zero-inited frame path instead of being
1727    /// read from R1 (caller garbage).
1728    #[test]
1729    fn declared_param_count_caps_inference_457() {
1730        let ops = vec![
1731            WasmOp::LocalGet(0),
1732            WasmOp::LocalGet(1),
1733            WasmOp::I32Add,
1734            WasmOp::End,
1735        ];
1736        // The inference alone still says 2 (the misclassification this caps).
1737        assert_eq!(count_params(&ops), 2);
1738
1739        let backend = ArmBackend::new();
1740        let inferred = backend
1741            .compile_function("rbw", &ops, &CompileConfig::default())
1742            .unwrap();
1743        let declared = backend
1744            .compile_function(
1745                "rbw",
1746                &ops,
1747                &CompileConfig {
1748                    current_func_param_count: Some(1),
1749                    ..CompileConfig::default()
1750                },
1751            )
1752            .unwrap();
1753        // The cap is consumed: the declared-count compile reclassifies local 1
1754        // and must emit different code than the param-misclassified one.
1755        assert_ne!(
1756            inferred.code, declared.code,
1757            "declared param count must reach the selector"
1758        );
1759        // The zero-init is present: a 16-bit Thumb `movs rN, #0`
1760        // (0x2000 | rd<<8 → LE bytes [0x00, 0x20+rd]) somewhere in the body.
1761        let has_movs_zero = declared
1762            .code
1763            .chunks_exact(2)
1764            .any(|h| h[0] == 0x00 && (0x20..=0x27).contains(&h[1]));
1765        assert!(
1766            has_movs_zero,
1767            "declared-count compile must zero-init the read-before-write local; code: {:02x?}",
1768            declared.code
1769        );
1770        // A declared count that matches (or exceeds) the inference changes
1771        // nothing — byte-identity for every function without rbw locals.
1772        let matching = backend
1773            .compile_function(
1774                "rbw",
1775                &ops,
1776                &CompileConfig {
1777                    current_func_param_count: Some(2),
1778                    ..CompileConfig::default()
1779                },
1780            )
1781            .unwrap();
1782        assert_eq!(
1783            matching.code, inferred.code,
1784            "declared >= inferred must stay byte-identical"
1785        );
1786    }
1787
1788    #[test]
1789    fn test_arm_backend_register() {
1790        let mut registry = synth_core::BackendRegistry::new();
1791        registry.register(Box::new(ArmBackend::new()));
1792        assert!(registry.get("arm").is_some());
1793        assert_eq!(registry.available().len(), 1);
1794    }
1795
1796    #[test]
1797    fn test_compile_import_call_produces_relocations() {
1798        let backend = ArmBackend::new();
1799        // Simulate a WASM module where func index 0 is an import.
1800        // Call(0) should generate MOV R0, #0; BL __meld_dispatch_import
1801        let ops = vec![WasmOp::Call(0)];
1802        let config = CompileConfig {
1803            num_imports: 1,
1804            no_optimize: true, // Direct instruction selection to preserve Call semantics
1805            ..CompileConfig::default()
1806        };
1807
1808        let result = backend.compile_function("caller", &ops, &config);
1809        assert!(result.is_ok());
1810
1811        let func = result.unwrap();
1812        assert!(!func.code.is_empty());
1813        assert_eq!(func.relocations.len(), 1);
1814        assert_eq!(func.relocations[0].symbol, "__meld_dispatch_import");
1815        // The BL is the second instruction (after MOV R0, #0), so offset should be > 0
1816        assert!(func.relocations[0].offset > 0);
1817    }
1818
1819    /// Regression test for #197: in `relocatable` mode, an import call must
1820    /// relocate against the direct `func_N` symbol (rewritten to the wasm field
1821    /// name by `build_relocatable_elf`), NOT `__meld_dispatch_import`. This is
1822    /// the ABI half of the #197 fix — without it, a host linker cannot resolve
1823    /// the call to the real kernel symbol (e.g. `k_spin_lock`).
1824    #[test]
1825    fn test_compile_relocatable_import_uses_direct_func_symbol_197() {
1826        let backend = ArmBackend::new();
1827        let ops = vec![WasmOp::Call(0)]; // func 0 is an import
1828        let config = CompileConfig {
1829            num_imports: 1,
1830            relocatable: true,
1831            ..CompileConfig::default()
1832        };
1833
1834        let func = backend
1835            .compile_function("caller", &ops, &config)
1836            .expect("relocatable import call compiles");
1837
1838        assert_eq!(func.relocations.len(), 1);
1839        assert_eq!(
1840            func.relocations[0].symbol, "func_0",
1841            "#197: relocatable import must relocate against func_0 (→ field name), not Meld dispatch"
1842        );
1843    }
1844
1845    #[test]
1846    fn test_compile_no_imports_no_relocations() {
1847        let backend = ArmBackend::new();
1848        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
1849        let config = CompileConfig::default();
1850
1851        let func = backend.compile_function("add", &ops, &config).unwrap();
1852        assert!(func.relocations.is_empty());
1853    }
1854
1855    /// Regression test for #167: a call to an INTERNAL function
1856    /// (index `>= num_imports`) must record a relocation against `func_{index}`.
1857    /// Before the fix, only `__meld_*` (import) BLs were relocated, so
1858    /// internal `BL func_N` was emitted as an unpatched `bl #0` branching
1859    /// to a garbage address — making the object non-linkable. This test
1860    /// would have caught that regression.
1861    #[test]
1862    fn test_compile_internal_call_produces_relocation_167() {
1863        let backend = ArmBackend::new();
1864        // num_imports = 1, so Call(2) is an INTERNAL call → `BL func_2`.
1865        let ops = vec![WasmOp::Call(2)];
1866        let config = CompileConfig {
1867            num_imports: 1,
1868            no_optimize: true,
1869            ..CompileConfig::default()
1870        };
1871
1872        let func = backend
1873            .compile_function("caller", &ops, &config)
1874            .expect("internal call compiles");
1875
1876        assert_eq!(
1877            func.relocations.len(),
1878            1,
1879            "an internal call must emit exactly one relocation (#167)"
1880        );
1881        assert_eq!(
1882            func.relocations[0].symbol, "func_2",
1883            "internal call must relocate against the callee's func_{{index}} symbol (#167)"
1884        );
1885    }
1886
1887    // ─── Phase 1 safety-bounds plumbing for ARM ──────────────────────────
1888
1889    #[test]
1890    fn arm_safety_bounds_mpu_emits_same_code_as_none() {
1891        // Mpu mode must not introduce any inline check on ARM — the MPU
1892        // handles faults via hardware. The encoded bytes for an i32.load
1893        // should be identical between None and Mpu.
1894        let backend = ArmBackend::new();
1895        let ops = vec![
1896            WasmOp::LocalGet(0),
1897            WasmOp::I32Load {
1898                offset: 0,
1899                align: 2,
1900            },
1901        ];
1902        let cfg_none = CompileConfig {
1903            no_optimize: true,
1904            ..Default::default()
1905        };
1906        let cfg_mpu = CompileConfig {
1907            no_optimize: true,
1908            safety_bounds: SafetyBounds::Mpu,
1909            ..Default::default()
1910        };
1911        let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
1912        let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
1913        assert_eq!(
1914            n.code, m.code,
1915            "Mpu and None should produce identical ARM bytes (Mpu relies on hardware)"
1916        );
1917    }
1918
1919    #[test]
1920    fn arm_legacy_bounds_check_still_emits_software_check() {
1921        // Legacy CLI users with `--bounds-check` should keep getting the
1922        // software path even though the new SafetyBounds field defaults to None.
1923        let backend = ArmBackend::new();
1924        let ops = vec![
1925            WasmOp::LocalGet(0),
1926            WasmOp::I32Load {
1927                offset: 0,
1928                align: 2,
1929            },
1930        ];
1931        let cfg_legacy = CompileConfig {
1932            no_optimize: true,
1933            bounds_check: true,
1934            ..Default::default()
1935        };
1936        let cfg_software = CompileConfig {
1937            no_optimize: true,
1938            safety_bounds: SafetyBounds::Software,
1939            ..Default::default()
1940        };
1941        let l = backend.compile_function("ld", &ops, &cfg_legacy).unwrap();
1942        let s = backend.compile_function("ld", &ops, &cfg_software).unwrap();
1943        assert_eq!(
1944            l.code, s.code,
1945            "--bounds-check should produce the same bytes as --safety-bounds=software"
1946        );
1947    }
1948
1949    /// #377: `--safety-bounds software` must be enforced on the OPTIMIZED path
1950    /// too. Pre-fix, `software` was byte-identical to `none` there (a silent
1951    /// no-op while the safety manifest claimed enforcement). The compiled
1952    /// bytes must now (a) differ from `none` and (b) contain the inline
1953    /// `CMP ip, sl` + `UDF` guard.
1954    #[test]
1955    fn arm_safety_bounds_software_enforced_on_optimized_path_377() {
1956        let backend = ArmBackend::new();
1957        // Dynamic-address store+load: the optimized path accepts this shape
1958        // (no calls, no i64 params, ≤4 params).
1959        let ops = vec![
1960            WasmOp::LocalGet(0),
1961            WasmOp::LocalGet(1),
1962            WasmOp::I32Store {
1963                offset: 4,
1964                align: 2,
1965            },
1966            WasmOp::LocalGet(0),
1967            WasmOp::I32Load {
1968                offset: 0,
1969                align: 2,
1970            },
1971        ];
1972        // no_optimize NOT set — this exercises the optimized path.
1973        let cfg_none = CompileConfig::default();
1974        let cfg_sw = CompileConfig {
1975            safety_bounds: SafetyBounds::Software,
1976            ..Default::default()
1977        };
1978        let n = backend.compile_function("st", &ops, &cfg_none).unwrap();
1979        let s = backend.compile_function("st", &ops, &cfg_sw).unwrap();
1980        assert_ne!(
1981            n.code, s.code,
1982            "#377: software bounds must CHANGE optimized-path codegen (was a silent no-op)"
1983        );
1984        // Thumb-2 `UDF #0` is 0xDE00 (LE bytes: 00 DE); the #752
1985        // wraparound-safe guard's borrow check `CMP sl, ip` (16-bit
1986        // high-reg form) is 0x45E2 (LE: E2 45). Both must appear — one
1987        // guard per access, traps inline.
1988        let has_udf = s.code.windows(2).any(|w| w == [0x00, 0xDE]);
1989        let has_cmp_sl_ip = s.code.windows(2).any(|w| w == [0xE2, 0x45]);
1990        assert!(has_udf, "#377: inline UDF trap missing from optimized path");
1991        assert!(
1992            has_cmp_sl_ip,
1993            "#377/#752: CMP sl, ip bounds borrow-check missing from optimized path"
1994        );
1995        // And `none` must contain NO UDF (the function has no other trap).
1996        assert!(
1997            !n.code.windows(2).any(|w| w == [0x00, 0xDE]),
1998            "none must not contain a UDF for this function"
1999        );
2000    }
2001
2002    /// #377: `mpu` on the optimized path is codegen-passthrough — identical
2003    /// bytes to `none` on BOTH paths (hardware enforcement is target-level;
2004    /// synth does not emit MPU region programming — tracked separately in
2005    /// #377's fix-direction discussion). This pins path-parity for `mpu`.
2006    #[test]
2007    fn arm_safety_bounds_mpu_optimized_path_parity_377() {
2008        let backend = ArmBackend::new();
2009        let ops = vec![
2010            WasmOp::LocalGet(0),
2011            WasmOp::I32Load {
2012                offset: 0,
2013                align: 2,
2014            },
2015        ];
2016        let cfg_none = CompileConfig::default();
2017        let cfg_mpu = CompileConfig {
2018            safety_bounds: SafetyBounds::Mpu,
2019            ..Default::default()
2020        };
2021        let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
2022        let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
2023        assert_eq!(
2024            n.code, m.code,
2025            "Mpu and None must produce identical bytes on the optimized path too"
2026        );
2027    }
2028
2029    /// #377: `mask` on the optimized path declines to the direct selector
2030    /// (honest degradation) — the compiled function must equal the
2031    /// `--no-optimize` masking bytes, i.e. the flag is honored, never dropped.
2032    #[test]
2033    fn arm_safety_bounds_mask_optimized_path_declines_to_direct_377() {
2034        let backend = ArmBackend::new();
2035        let ops = vec![
2036            WasmOp::LocalGet(0),
2037            WasmOp::LocalGet(1),
2038            WasmOp::I32Store {
2039                offset: 0,
2040                align: 2,
2041            },
2042        ];
2043        let cfg_mask_opt = CompileConfig {
2044            safety_bounds: SafetyBounds::Mask,
2045            ..Default::default()
2046        };
2047        let cfg_mask_direct = CompileConfig {
2048            no_optimize: true,
2049            safety_bounds: SafetyBounds::Mask,
2050            ..Default::default()
2051        };
2052        let o = backend.compile_function("st", &ops, &cfg_mask_opt).unwrap();
2053        let d = backend
2054            .compile_function("st", &ops, &cfg_mask_direct)
2055            .unwrap();
2056        assert_eq!(
2057            o.code, d.code,
2058            "#377: mask on the optimized path must fall back to the direct selector's masking"
2059        );
2060    }
2061
2062    // ========================================================================
2063    // ISA feature gate tests — ensure the compiler never emits unsupported
2064    // instructions for a given target
2065    // ========================================================================
2066
2067    #[test]
2068    fn test_f32_rejected_on_cortex_m3_no_fpu() {
2069        let backend = ArmBackend::new();
2070        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
2071        let config = CompileConfig {
2072            target: TargetSpec::cortex_m3(),
2073            no_optimize: true,
2074            ..CompileConfig::default()
2075        };
2076
2077        let result = backend.compile_function("fadd", &ops, &config);
2078        assert!(
2079            result.is_err(),
2080            "f32 operations should fail on Cortex-M3 (no FPU)"
2081        );
2082    }
2083
2084    #[test]
2085    fn test_f32_accepted_on_cortex_m4f() {
2086        let backend = ArmBackend::new();
2087        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
2088        let config = CompileConfig {
2089            target: TargetSpec::cortex_m4f(),
2090            no_optimize: true,
2091            ..CompileConfig::default()
2092        };
2093
2094        let result = backend.compile_function("fadd", &ops, &config);
2095        assert!(
2096            result.is_ok(),
2097            "f32 operations should succeed on Cortex-M4F, got: {:?}",
2098            result.unwrap_err()
2099        );
2100    }
2101
2102    #[test]
2103    fn test_i32_works_on_all_targets() {
2104        let backend = ArmBackend::new();
2105        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
2106
2107        // Cortex-M3 (no FPU)
2108        let config_m3 = CompileConfig {
2109            target: TargetSpec::cortex_m3(),
2110            no_optimize: true,
2111            ..CompileConfig::default()
2112        };
2113        assert!(
2114            backend.compile_function("add", &ops, &config_m3).is_ok(),
2115            "i32 ops should work on Cortex-M3"
2116        );
2117
2118        // Cortex-M4F (single FPU)
2119        let config_m4f = CompileConfig {
2120            target: TargetSpec::cortex_m4f(),
2121            no_optimize: true,
2122            ..CompileConfig::default()
2123        };
2124        assert!(
2125            backend.compile_function("add", &ops, &config_m4f).is_ok(),
2126            "i32 ops should work on Cortex-M4F"
2127        );
2128
2129        // Cortex-M7DP (double FPU)
2130        let config_m7dp = CompileConfig {
2131            target: TargetSpec::cortex_m7dp(),
2132            no_optimize: true,
2133            ..CompileConfig::default()
2134        };
2135        assert!(
2136            backend.compile_function("add", &ops, &config_m7dp).is_ok(),
2137            "i32 ops should work on Cortex-M7DP"
2138        );
2139    }
2140
2141    #[test]
2142    fn test_f32_rejected_on_cortex_m4_no_fpu() {
2143        // Cortex-M4 (without F suffix) has no FPU
2144        let backend = ArmBackend::new();
2145        let ops = vec![WasmOp::F32Const(1.5), WasmOp::F32Const(2.5), WasmOp::F32Mul];
2146        let config = CompileConfig {
2147            target: TargetSpec::cortex_m4(),
2148            no_optimize: true,
2149            ..CompileConfig::default()
2150        };
2151
2152        let result = backend.compile_function("fmul", &ops, &config);
2153        assert!(
2154            result.is_err(),
2155            "f32 operations should fail on Cortex-M4 (no FPU)"
2156        );
2157    }
2158
2159    // ========================================================================
2160    // Issue #120 — f32 ops in the optimized lowering path
2161    //
2162    // `OptimizerBridge::wasm_to_ir` has no handlers for f32/f64 ops, so a
2163    // value-producing float op fell through to `Opcode::Nop`, leaving a
2164    // downstream consumer with an unmapped vreg and tripping the PR #101
2165    // defensive panic in `ir_to_arm`. Customer reproducer: `compiler_builtins
2166    // float::div` and `gale_compute_ipi_mask` in the `falcon-rate-component`
2167    // module.
2168    //
2169    // Fix: `optimize_full` declines float modules with a typed `Err`;
2170    // `compile_wasm_to_arm` falls back to the non-optimized `select_with_stack`
2171    // path, which handles f32 via VFP/FPU. These tests use the *default*
2172    // (optimized) config — `no_optimize` is NOT set — which is the exact
2173    // configuration that panicked pre-fix.
2174    // ========================================================================
2175
2176    /// Pre-fix: this panicked with "vreg vN has no assigned ARM register and
2177    /// no spill slot" inside `ir_to_arm`. Post-fix: the optimized path declines
2178    /// the module and the backend falls back to direct selection, producing a
2179    /// non-empty f32.div lowering on a Cortex-M4F.
2180    #[test]
2181    fn test_issue120_f32_div_compiles_via_optimized_default() {
2182        let backend = ArmBackend::new();
2183        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
2184        let config = CompileConfig {
2185            target: TargetSpec::cortex_m4f(),
2186            // no_optimize NOT set — this exercises the optimized path that
2187            // panicked in issue #120, then the fallback to direct selection.
2188            // GI-FPU-002: the f32 params must be declared so the direct
2189            // selector homes them in S0/S1 (AAPCS-VFP) rather than declining.
2190            current_func_params_f32: vec![true, true],
2191            ..CompileConfig::default()
2192        };
2193
2194        let result = backend.compile_function("fdiv", &ops, &config);
2195        assert!(
2196            result.is_ok(),
2197            "f32.div must compile on Cortex-M4F via the optimized->direct \
2198             fallback (issue #120), got: {:?}",
2199            result.as_ref().err()
2200        );
2201        assert!(
2202            !result.unwrap().code.is_empty(),
2203            "f32.div must produce non-empty machine code"
2204        );
2205    }
2206
2207    /// A spread of f32 ops, all through the optimized (default) config, must
2208    /// compile via the fallback on an FPU target without panicking.
2209    #[test]
2210    fn test_issue120_assorted_f32_ops_compile_via_optimized_default() {
2211        let backend = ArmBackend::new();
2212        let config = CompileConfig {
2213            target: TargetSpec::cortex_m4f(),
2214            // GI-FPU-002: declare the two f32 params for AAPCS-VFP homing.
2215            current_func_params_f32: vec![true, true],
2216            ..CompileConfig::default()
2217        };
2218
2219        let cases: Vec<(&str, Vec<WasmOp>)> = vec![
2220            (
2221                "fadd",
2222                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Add],
2223            ),
2224            (
2225                "fmul",
2226                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Mul],
2227            ),
2228            (
2229                "fsub",
2230                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Sub],
2231            ),
2232        ];
2233
2234        for (name, ops) in cases {
2235            let result = backend.compile_function(name, &ops, &config);
2236            assert!(
2237                result.is_ok(),
2238                "{name} must compile via the optimized->direct fallback \
2239                 (issue #120), got: {:?}",
2240                result.as_ref().err()
2241            );
2242            assert!(
2243                !result.unwrap().code.is_empty(),
2244                "{name} must produce non-empty machine code"
2245            );
2246        }
2247    }
2248
2249    /// The fallback must still honor the ISA feature gate: f32 on a no-FPU
2250    /// target must fail cleanly (not panic) even on the optimized path.
2251    #[test]
2252    fn test_issue120_f32_div_rejected_on_no_fpu_via_optimized() {
2253        let backend = ArmBackend::new();
2254        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
2255        let config = CompileConfig {
2256            target: TargetSpec::cortex_m3(),
2257            ..CompileConfig::default()
2258        };
2259
2260        let result = backend.compile_function("fdiv", &ops, &config);
2261        assert!(
2262            result.is_err(),
2263            "f32.div must be rejected on Cortex-M3 (no FPU), not panic"
2264        );
2265    }
2266
2267    /// #507: a `br_table` function compiled via the DEFAULT (optimized) config
2268    /// must produce the SAME bytes as the direct (`no_optimize`) selector —
2269    /// i.e. the optimized path declined it to direct, lowering the dispatch as a
2270    /// real cmp-chain instead of silently dropping it (which left all arms in
2271    /// fall-through). Pre-fix the two outputs differed (the optimized one had no
2272    /// selector compare). Execution correctness is gated by
2273    /// `scripts/repro/br_table_507_differential.py`.
2274    #[test]
2275    fn test_507_br_table_declines_to_direct() {
2276        let backend = ArmBackend::new();
2277        // dispatch(sel): br_table over 3 blocks, each storing a marker to mem[0].
2278        let ops = vec![
2279            WasmOp::Block,
2280            WasmOp::Block,
2281            WasmOp::Block,
2282            WasmOp::LocalGet(0),
2283            WasmOp::BrTable {
2284                targets: vec![0, 1, 2],
2285                default: 2,
2286            },
2287            WasmOp::End,
2288            WasmOp::I32Const(0),
2289            WasmOp::I32Const(10),
2290            WasmOp::I32Store {
2291                offset: 0,
2292                align: 2,
2293            },
2294            WasmOp::Return,
2295            WasmOp::End,
2296            WasmOp::I32Const(0),
2297            WasmOp::I32Const(20),
2298            WasmOp::I32Store {
2299                offset: 0,
2300                align: 2,
2301            },
2302            WasmOp::Return,
2303            WasmOp::End,
2304            WasmOp::I32Const(0),
2305            WasmOp::I32Const(30),
2306            WasmOp::I32Store {
2307                offset: 0,
2308                align: 2,
2309            },
2310        ];
2311        let opt = CompileConfig {
2312            target: TargetSpec::cortex_m4(),
2313            ..CompileConfig::default()
2314        };
2315        let direct = CompileConfig {
2316            target: TargetSpec::cortex_m4(),
2317            no_optimize: true,
2318            ..CompileConfig::default()
2319        };
2320        let a = backend
2321            .compile_function("dispatch", &ops, &opt)
2322            .expect("optimized-default must compile br_table (via decline)");
2323        let b = backend
2324            .compile_function("dispatch", &ops, &direct)
2325            .expect("direct must compile br_table");
2326        assert_eq!(
2327            a.code, b.code,
2328            "#507: optimized-default br_table output must be byte-identical to the \
2329             direct selector (i.e. declined to direct), not a dropped dispatch"
2330        );
2331    }
2332
2333    /// Issue #94: end-to-end byte-size check for the canonical u64-packed
2334    /// FFI-return hi32 extract pattern. Compiles two near-identical
2335    /// functions — one with the optimized shift-by-32, one with a generic
2336    /// shift-by-7 — and asserts the optimized form is meaningfully smaller.
2337    #[test]
2338    fn test_issue94_hi32_extract_is_smaller_than_generic_shift() {
2339        let backend = ArmBackend::new();
2340        let config = CompileConfig {
2341            target: TargetSpec::cortex_m4f(),
2342            ..CompileConfig::default()
2343        };
2344
2345        // #518: the i64 value must NOT come from an i64 PARAM — the optimized
2346        // path now declines i64-param functions to the direct selector (it homed
2347        // an i64 param in R4:R5 instead of R0:R1, a silent miscompile this test's
2348        // byte-size-only assertion masked). The canonical #94 case is a u64 from
2349        // an FFI return, not a param, anyway. Source the i64 from a sign-extended
2350        // i32 param (`extend_i32_s`): a runtime, non-constant-foldable i64 that
2351        // stays on the optimized path, so the shift-by-32 hi-extract peephole is
2352        // still exercised on CORRECT code.
2353        // Optimized path: `(i64.extend_i32_s (local.get 0)) >>> 32; wrap_i64`
2354        let ops_hi32 = vec![
2355            WasmOp::LocalGet(0), // i32 param in R0
2356            WasmOp::I64ExtendI32S,
2357            WasmOp::I64Const(32),
2358            WasmOp::I64ShrU,
2359            WasmOp::I32WrapI64,
2360        ];
2361        let func_hi32 = backend
2362            .compile_function("hi32_extract", &ops_hi32, &config)
2363            .unwrap();
2364
2365        // Generic path: `... >>> 7; wrap_i64` — same shape, but the shift amount
2366        // is not a multiple of 32, so it falls through to the runtime shift.
2367        let ops_generic = vec![
2368            WasmOp::LocalGet(0),
2369            WasmOp::I64ExtendI32S,
2370            WasmOp::I64Const(7),
2371            WasmOp::I64ShrU,
2372            WasmOp::I32WrapI64,
2373        ];
2374        let func_generic = backend
2375            .compile_function("generic_shr", &ops_generic, &config)
2376            .unwrap();
2377
2378        let bytes_hi32 = func_hi32.code.len();
2379        let bytes_generic = func_generic.code.len();
2380        println!(
2381            "\n[issue #94] hi32 extract: {} bytes (vs generic shift: {} bytes; saved {})",
2382            bytes_hi32,
2383            bytes_generic,
2384            bytes_generic.saturating_sub(bytes_hi32)
2385        );
2386        let hex: String = func_hi32
2387            .code
2388            .iter()
2389            .map(|b| format!("{:02x}", b))
2390            .collect::<Vec<_>>()
2391            .join(" ");
2392        println!("[issue #94] hi32 bytes: {}", hex);
2393        // We expect the optimized form to be at least 30 bytes smaller than
2394        // the generic 64-bit shift sequence. (Empirically: 14 vs 50 bytes.)
2395        assert!(
2396            bytes_hi32 + 30 <= bytes_generic,
2397            "issue #94: hi32 extract = {} bytes, generic shift = {} bytes; \
2398             expected optimized form to be at least 30 bytes smaller",
2399            bytes_hi32,
2400            bytes_generic,
2401        );
2402    }
2403}