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            let func_config = if params.is_some() || !func.block_arity.is_empty() {
90                Some(CompileConfig {
91                    current_func_params_i64: params.cloned().unwrap_or_default(),
92                    current_func_block_arity: func.block_arity.clone(),
93                    ..config.clone()
94                })
95            } else {
96                None
97            };
98            let cfg = func_config.as_ref().unwrap_or(config);
99            let compiled = self.compile_function(&name, &func.ops, cfg)?;
100            functions.push(compiled);
101        }
102
103        Ok(CompilationResult {
104            functions,
105            elf: None,
106            backend_name: self.name().to_string(),
107        })
108    }
109
110    fn compile_function(
111        &self,
112        name: &str,
113        ops: &[WasmOp],
114        config: &CompileConfig,
115    ) -> Result<CompiledFunction, BackendError> {
116        let (code, relocations, line_map) =
117            compile_wasm_to_arm(ops, config).map_err(BackendError::CompilationFailed)?;
118
119        Ok(CompiledFunction {
120            name: name.to_string(),
121            code,
122            wasm_ops: ops.to_vec(),
123            relocations,
124            line_map,
125        })
126    }
127
128    fn is_available(&self) -> bool {
129        true // Always available — it's a library backend
130    }
131}
132
133/// Count the number of function parameters by analyzing LocalGet patterns
134fn count_params(wasm_ops: &[WasmOp]) -> u32 {
135    let mut first_access: std::collections::HashMap<u32, bool> = std::collections::HashMap::new();
136    for op in wasm_ops {
137        match op {
138            WasmOp::LocalGet(idx) => {
139                first_access.entry(*idx).or_insert(true);
140            }
141            WasmOp::LocalSet(idx) | WasmOp::LocalTee(idx) => {
142                first_access.entry(*idx).or_insert(false);
143            }
144            _ => {}
145        }
146    }
147
148    first_access
149        .iter()
150        .filter_map(
151            |(&idx, &is_read_first)| {
152                if is_read_first { Some(idx + 1) } else { None }
153            },
154        )
155        .max()
156        .unwrap_or(0)
157}
158
159/// #539: fold the `i32.const 0; memory.grow m` idiom to `memory.size m`.
160/// `memory.grow(0)` always succeeds and returns the current page count (WASM
161/// Core §4.4.7), which is exactly `memory.size`; the fixed-memory backend
162/// otherwise emits a constant `-1` for every `memory.grow`, so the legal
163/// `memory.grow(0)` "read/validate current size" idiom wrongly reported failure.
164/// Only the ADJACENT const-0 delta is folded (a non-zero delta keeps the sound
165/// `-1` — fixed memory genuinely cannot grow; a runtime-computed 0 is a
166/// documented follow-up). Backend- and path-agnostic: `memory.size` reads the
167/// runtime memory-size register on every selector, so this fixes the optimized
168/// and direct paths at once.
169fn rewrite_memory_grow_zero(wasm_ops: &[WasmOp]) -> Vec<WasmOp> {
170    let mut out = Vec::with_capacity(wasm_ops.len());
171    let mut i = 0;
172    while i < wasm_ops.len() {
173        if matches!(wasm_ops[i], WasmOp::I32Const(0))
174            && let Some(WasmOp::MemoryGrow(m)) = wasm_ops.get(i + 1)
175        {
176            out.push(WasmOp::MemorySize(*m));
177            i += 2;
178        } else {
179            out.push(wasm_ops[i].clone());
180            i += 1;
181        }
182    }
183    out
184}
185
186/// #509: does the op stream contain a `br`/`br_if`/`br_table` that CARRIES a
187/// value — i.e. one targeting a result-typed block/if (forward edge with
188/// results > 0) or a parameterized loop header (backward edge with loop
189/// params > 0)?
190///
191/// The optimized path's wasm→IR lowering drops the carried value on such
192/// edges (the taken arm returns the fall-through result — same class as the
193/// #507 `br_table` drop, observed on `pick_br`/`pick_br_fall`), so — like
194/// #507 — the shape is detected on the raw op stream and routed to the direct
195/// selector, whose #509 designated-result-register lowering lands the value
196/// correctly. `block_arity` is the decoder's ordinal blocktype-arity
197/// side-table; when it is empty (hand-built op streams) every block reads as
198/// void and this never fires, keeping the optimized path byte-identical for
199/// every existing caller. Frozen-safe for the same reason as #507: the frozen
200/// fixtures compile `--relocatable` (already direct), and no optimized-path
201/// fixture branches to a result-typed block.
202fn has_value_carrying_branch(wasm_ops: &[WasmOp], block_arity: &[(u8, u8)]) -> bool {
203    // Open control constructs: (is_loop, params, results), innermost last.
204    let mut open: Vec<(bool, u8, u8)> = Vec::new();
205    let mut ctrl_ord = 0usize;
206    // A branch edge carries a value when its target is a result-typed forward
207    // join (block/if) or a parameterized loop header.
208    let carries = |open: &[(bool, u8, u8)], depth: u32| -> bool {
209        let Some(&(is_loop, params, results)) = open
210            .len()
211            .checked_sub(1 + depth as usize)
212            .and_then(|i| open.get(i))
213        else {
214            return false; // function-level target — handled by Return lowering
215        };
216        if is_loop { params > 0 } else { results > 0 }
217    };
218    for op in wasm_ops {
219        match op {
220            WasmOp::Block | WasmOp::If => {
221                let (p, r) = block_arity.get(ctrl_ord).copied().unwrap_or((0, 0));
222                ctrl_ord += 1;
223                open.push((false, p, r));
224            }
225            WasmOp::Loop => {
226                let (p, r) = block_arity.get(ctrl_ord).copied().unwrap_or((0, 0));
227                ctrl_ord += 1;
228                open.push((true, p, r));
229            }
230            WasmOp::End => {
231                open.pop(); // None only at the function-level end — harmless
232            }
233            WasmOp::Br(d) | WasmOp::BrIf(d) if carries(&open, *d) => return true,
234            WasmOp::BrTable { targets, default }
235                if targets
236                    .iter()
237                    .chain(std::iter::once(default))
238                    .any(|d| carries(&open, *d)) =>
239            {
240                return true;
241            }
242            _ => {}
243        }
244    }
245    false
246}
247
248/// Core compilation: WASM ops → ARM machine code bytes + relocations
249///
250/// Returns (code_bytes, relocations) where relocations record BL instructions
251/// that target external symbols (e.g., `__meld_dispatch_import` for import calls).
252fn compile_wasm_to_arm(
253    wasm_ops: &[WasmOp],
254    config: &CompileConfig,
255) -> Result<(Vec<u8>, Vec<CodeRelocation>, LineMap), String> {
256    // #539: `memory.grow(0)` must return the CURRENT page count, not the
257    // fixed-memory `-1` sentinel — growing by zero pages can never fail (WASM
258    // Core §4.4.7), so a guest doing `if (memory.grow(0) < 0) trap;` wrongly
259    // faulted. Every lowering path emitted a delta-agnostic `-1`. `memory.grow(0)`
260    // is semantically identical to `memory.size`, which the backend already
261    // computes from the runtime memory-size register (R10 >> 16 = pages), so fold
262    // the `i32.const 0; memory.grow` idiom to `memory.size` up front — backend-
263    // and path-agnostic. A non-zero delta keeps `-1` (fixed memory genuinely
264    // cannot grow); a runtime delta that happens to be 0 is the documented
265    // follow-up.
266    let rewritten = rewrite_memory_grow_zero(wasm_ops);
267    let wasm_ops: &[WasmOp] = &rewritten;
268
269    let num_params = count_params(wasm_ops);
270
271    let bounds_config = match config.effective_safety_bounds() {
272        SafetyBounds::None => BoundsCheckConfig::None,
273        SafetyBounds::Mpu => BoundsCheckConfig::Mpu,
274        SafetyBounds::Software => BoundsCheckConfig::Software,
275        SafetyBounds::Mask => BoundsCheckConfig::Masking,
276    };
277
278    // The non-optimized (direct) instruction-selection path. Handles f32 via
279    // VFP/FPU. Used directly when `--no-optimize` is set, and as the fallback
280    // when the optimized path declines a module (see issue #120 below).
281    //
282    // VCR-RA-001 step 3b-lite (#242): a FRESH selector per attempt, with
283    // `spill_on_exhaustion` set only on the retry — the first pass is the
284    // unmodified default, so every function that compiles today is selected by
285    // exactly the code that compiled it yesterday (bit-identity is structural,
286    // not behavioural).
287    let select_direct_attempt = |spill_on_exhaustion: bool,
288                                 param_backing_on_exhaustion: bool,
289                                 local_promote: bool,
290                                 i64_spill_slots: Option<usize>|
291     -> Result<Vec<ArmInstruction>, synth_core::Error> {
292        let db = RuleDatabase::with_standard_rules();
293        let mut selector =
294            InstructionSelector::with_bounds_check(db.rules().to_vec(), bounds_config);
295        selector.set_target(config.target.fpu, &config.target.triple);
296        if config.num_imports > 0 {
297            selector.set_num_imports(config.num_imports);
298        }
299        // #195: plumb the callee argument-count tables so the direct selector can
300        // marshal call arguments into R0–R3 per AAPCS.
301        selector.set_func_arg_counts(
302            config.func_arg_counts.clone(),
303            config.type_arg_counts.clone(),
304        );
305        // #197: in relocatable host-link mode, emit direct `func_N` BLs for
306        // imports (rewritten to the wasm field name by build_relocatable_elf)
307        // instead of `__meld_dispatch_import`.
308        selector.set_relocatable(config.relocatable);
309        // #237: native-pointer ABI — wasm statics become __synth_wasm_data-relative.
310        selector.set_native_pointer_abi(config.native_pointer_abi, config.linear_memory_bytes);
311        // #311: i64 call results are register PAIRS — tag them.
312        selector.set_result_types(config.func_ret_i64.clone(), config.type_ret_i64.clone());
313        // #359: declared param widths of THIS function, so the AAPCS stack-arg
314        // path can refuse 64-bit params (Ok-or-Err). Empty ⇒ assume i32.
315        selector.set_params_i64(config.current_func_params_i64.clone());
316        // #509: blocktype-arity side-table of THIS function, so value-carrying
317        // br/br_if/br_table land the carried value in the target block's
318        // designated result register instead of dropping it. Empty ⇒ legacy
319        // void-block lowering.
320        selector.set_block_arity(config.current_func_block_arity.clone());
321        // Stack-pointer promotion is meaningful only under the native-pointer ABI;
322        // gating here keeps every non-native compile (all frozen fixtures) on the
323        // legacy R9 globals-table path, bit-identical.
324        if config.native_pointer_abi
325            && let Some((sp_idx, sp_init)) = config.stack_pointer_global
326        {
327            selector.set_native_pointer_stack(sp_idx, sp_init);
328        }
329        selector.set_spill_on_exhaustion(spill_on_exhaustion);
330        selector.set_param_backing_on_exhaustion(param_backing_on_exhaustion);
331        // #587 pool-grow rung: a larger i64 spill-slot pool, set ONLY on the
332        // retry after an attempt failed with the slot-pool-exhausted Err —
333        // functions that compile with the default pool keep their frame
334        // byte-identical by construction.
335        if let Some(slots) = i64_spill_slots {
336            selector.set_i64_spill_slots(slots);
337        }
338        // VCR-RA local promotion (#390, #242): keep eligible non-param i32 locals
339        // in callee-saved registers instead of frame slots — the structural lever
340        // toward native parity. DEFAULT-ON as of v0.14.0: gale's G474RE DWT gate
341        // cleared it as a net win (gust_mix dissolved 58→50 cyc/call −14%, all 5
342        // stack spill/reloads eliminated, correctness bit-identical over [0,2047],
343        // 2.00×→1.72× vs LLVM). Escape hatch: `SYNTH_NO_LOCAL_PROMOTE=1` restores
344        // the frame-slot path. Leaf-only / i32-only / ARM-only (see
345        // compute_local_promotion); the leaf-only lift + i64 locals are follow-ons.
346        // #474: `local_promote` is now a per-attempt parameter so the retry ladder
347        // can drop promotion as an exhaustion-recovery rung (promotion pins r4-r8,
348        // which on a dense function leaves the spill allocator with nothing to
349        // free → the frame-slot path is the escape that restores compilability).
350        selector.set_local_promote(local_promote);
351        selector.select_with_stack(wasm_ops, num_params)
352    };
353    let select_direct = || -> Result<Vec<ArmInstruction>, String> {
354        const SINGLE_EXHAUSTION: &str = "all allocatable registers are live on the stack";
355        const PAIR_EXHAUSTION: &str = "no consecutive pair of free registers for i64";
356        const SLOT_EXHAUSTION: &str = "i64 spill-slot pool exhausted";
357        // The full exhaustion-recovery ladder, parameterized on whether local
358        // promotion is enabled. Each rung is reached only when the previous one
359        // returned a recoverable register-exhaustion Err, so a function that
360        // compiles on the first attempt is untouched by the later rungs. Returns
361        // the result AND which rung produced it (for the #242 measurement below).
362        let recovery_ladder =
363            |promote: bool,
364             i64_spill_slots: Option<usize>|
365             -> (Result<Vec<ArmInstruction>, synth_core::Error>, &'static str) {
366                let mut attempt = select_direct_attempt(false, false, promote, i64_spill_slots);
367                let mut rung = "base";
368                // VCR-RA-001 step 3b-lite (#242): the i32 register-exhaustion
369                // hard-fail is recoverable — retry with spill-on-exhaustion, which
370                // reserves the spill area and spills the deepest stack value when
371                // the pool is full.
372                if let Err(e) = &attempt
373                    && e.to_string().contains(SINGLE_EXHAUSTION)
374                {
375                    attempt = select_direct_attempt(true, false, promote, i64_spill_slots);
376                    rung = "spill";
377                }
378                // VCR-RA-001 acceptance increment (#242): the i64 consecutive-PAIR
379                // exhaustion is recoverable too — not by stack spilling (the pair
380                // allocator already spills stack values, #171) but by frame-backing
381                // the params (#204) so they stop pinning R0-R3, with spill kept on.
382                if let Err(e) = &attempt
383                    && e.to_string().contains(PAIR_EXHAUSTION)
384                {
385                    attempt = select_direct_attempt(true, true, promote, i64_spill_slots);
386                    rung = "param-backing";
387                }
388                (attempt, rung)
389            };
390        // #474: local promotion (default-on since v0.14.0) is an OPTIMIZATION — it
391        // must never be the reason a function fails to compile. Run the full ladder
392        // with promotion first (so every function that compiles today is
393        // bit-identical), and if it still ends in register exhaustion, fall back to
394        // the promotion-off ladder (the v0.12.0 frame-slot lowering — exactly what
395        // the `SYNTH_NO_LOCAL_PROMOTE=1` workaround does, now automatic). Promotion
396        // pins r4-r8 for the locals; on a dense function that leaves the allocator
397        // with nothing to free, so dropping it restores compilability. The fallback
398        // is reached ONLY by functions that exhaust WITH promotion, so promotion-on
399        // output is untouched by construction (frozen byte gate stays green).
400        let promote = std::env::var("SYNTH_NO_LOCAL_PROMOTE").is_err();
401        // The full pre-#587 recovery sequence (promotion-on ladder, then the
402        // #474 promotion-off fallback), parameterized on the pool size so the
403        // pool-grow retry below reruns it verbatim.
404        let full_sequence = |slots: Option<usize>| -> (
405            Result<Vec<ArmInstruction>, synth_core::Error>,
406            &'static str,
407            bool,
408        ) {
409            let (mut attempt, mut rung) = recovery_ladder(promote, slots);
410            let mut promotion_dropped = false;
411            if promote
412                && attempt
413                    .as_ref()
414                    .err()
415                    .is_some_and(|e| e.to_string().contains("register exhaustion"))
416            {
417                let (rescued, off_rung) = recovery_ladder(false, slots);
418                if rescued.is_ok() {
419                    attempt = rescued;
420                    rung = off_rung;
421                    promotion_dropped = true;
422                }
423            }
424            (attempt, rung, promotion_dropped)
425        };
426        let (mut attempt, mut rung, mut promotion_dropped) = full_sequence(None);
427        // #587 pool-grow retry (the falcon func_60/func_73 remainder): the fixed
428        // 8-slot i64 spill pool can exhaust while spilling is otherwise working —
429        // an i64-dense function simply has more values simultaneously live than
430        // the pool holds. Rerun the ENTIRE sequence (every rung, both promotion
431        // modes) with the pool sized from a conservative operand-stack-depth
432        // bound: the number of simultaneously spilled values can never exceed
433        // the operand-stack depth, plus a few transient slots (the arg-move
434        // cycle resolver and call-result parking each borrow one). The selector
435        // clamps the request to its 12-bit-friendly cap; a function that still
436        // exhausts stays an honest loud skip. Deliberately LAST — after the #474
437        // promotion-off fallback — so any function that compiled yesterday
438        // (through any rung or fallback) is produced by exactly yesterday's
439        // path, byte-identical; the grown pool only ever fires for functions
440        // whose every existing escape ended in the slot-pool Err.
441        if attempt
442            .as_ref()
443            .err()
444            .is_some_and(|e| e.to_string().contains(SLOT_EXHAUSTION))
445        {
446            let depth = synth_core::wasm_stack_check::max_depth_bound(wasm_ops) as usize;
447            let (grown, _, grown_dropped) = full_sequence(Some(depth.saturating_add(4)));
448            if grown.is_ok() {
449                attempt = grown;
450                rung = "pool-grow";
451                promotion_dropped = grown_dropped;
452            }
453        }
454        // VCR-RA measurement (#242): log which recovery rung produced the result,
455        // so the per-rung distribution across a corpus can be measured — the size
456        // of the failure surface a verified allocator must subsume (see
457        // scripts/repro/register_exhaustion_recovery_ladder.md). Logging only:
458        // emitted bytes are unchanged, so the frozen byte gate is unaffected.
459        if std::env::var("SYNTH_RECOVERY_STATS").is_ok() {
460            eprintln!(
461                "[recovery-stats] rung={rung}{} result={}",
462                if promotion_dropped {
463                    " promotion-off"
464                } else {
465                    ""
466                },
467                if attempt.is_ok() { "ok" } else { "exhausted" },
468            );
469        }
470        attempt.map_err(|e| format!("instruction selection failed: {}", e))
471    };
472
473    // Instruction selection: optimized or direct.
474    //
475    // #197: `--relocatable` (host-link ET_REL) forces the direct selector. The
476    // optimized path materializes an absolute linmem base (0x20000100) and does
477    // not preserve caller-saved registers across calls — both wrong for a
478    // host-linked object, where the linmem base arrives via `fp` at runtime and
479    // callees follow AAPCS. `select_with_stack` (now i64-spill capable after
480    // #171) handles fp-relative memory + caller-saved preservation correctly.
481    //
482    // #507: `br_table` is DROPPED during the optimized path's wasm→IR lowering
483    // (`optimize_full`), so `ir_to_arm` never sees the dispatch — it emits the
484    // arm bodies in fall-through sequence with no `cmp`/branch on the selector, a
485    // SILENT miscompile (every input hits the last arm). The selector value isn't
486    // even loaded. Because the drop happens before `ir_to_arm`, there's no `Err`
487    // to fall back on; detect it on the raw wasm op stream here and force the
488    // direct selector (`select_with_stack` lowers `br_table` correctly as a
489    // cmp-chain — confirmed on the `--relocatable` path). Same honest-degradation
490    // contract as the issue-#120 f32 decline: the function still compiles
491    // correctly, just without IR-level optimization. Frozen-safe: the frozen
492    // fixtures compile `--relocatable` (already direct), and no optimized-path
493    // fixture (control_step, flight_algo) contains `br_table`.
494    let has_br_table = wasm_ops
495        .iter()
496        .any(|op| matches!(op, WasmOp::BrTable { .. }));
497    // #509: the optimized path also drops the value carried by a `br`/`br_if`
498    // to a result-typed block (the taken edge returns the wrong arm's value —
499    // same silent-miscompile class as the #507 br_table drop). Route the shape
500    // to the direct selector, whose designated-result-register lowering (#509)
501    // lands the carried value at the join. Never fires for void-block control
502    // flow (all frozen/optimized fixtures), so those stay byte-identical.
503    let has_value_carry = has_value_carrying_branch(wasm_ops, &config.current_func_block_arity);
504    // #503-i64/#518: route any signature with a 64-bit (i64/f64) param to the
505    // direct selector. The optimized path's param homing is width-naive — its
506    // #518 decline covers only functions that READ an i64 param (an `I64Load`
507    // from a param index), so a function that reads an i32 param whose AAPCS
508    // home a preceding wide param SHIFTED (e.g. p1 of `(i64 i32)` lives in R2,
509    // not R1; p3 of `(i64 i32 i32 i32)` lives on the stack, not in R3) was
510    // silently miscompiled rather than falling back. The direct selector's
511    // `aapcs_param_layout` homing handles every such shape (i64-param READS
512    // already fell back to it via the ir_to_arm Err, so those functions emit
513    // the same bytes as before). `num_params` counts read-first locals, so a
514    // function that never touches any param keeps the optimized path.
515    let has_wide_param = config
516        .current_func_params_i64
517        .iter()
518        .take(num_params as usize)
519        .any(|&w| w);
520    let arm_instrs = if config.no_optimize
521        || config.relocatable
522        || has_br_table
523        || has_value_carry
524        || has_wide_param
525    {
526        if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
527            eprintln!("[path-debug] direct (pre-gate)");
528        }
529        select_direct()?
530    } else {
531        let opt_config = if config.loom_compat {
532            OptimizationConfig::loom_compat()
533        } else {
534            OptimizationConfig::all()
535        };
536
537        let mut bridge = OptimizerBridge::with_config(opt_config);
538        // #188: tell the bridge how many imports there are so it declines only
539        // LOCAL calls (and leaves import calls on the optimized path, keeping
540        // the #173 field-name relocation rewrite intact).
541        bridge.set_num_imports(config.num_imports);
542        // #543 Phase 2: thread the integrator-marked volatile DMA-window ranges
543        // (`--volatile-segment <base>:<len>`) to the bridge's address-caching
544        // levers — base-CSE (#468) excludes any access inside a marked range
545        // from its fold set, and the bridge-level const-CSE declines wholesale
546        // while any range is marked. Empty (the default) ⇒ byte-identical.
547        bridge.set_volatile_segments(config.volatile_segments.clone());
548        // `ir_to_arm` now returns `Result` — an `Err` means the optimized path
549        // hit an unmapped vreg (issue-#93-class). Treat it identically to an
550        // `optimize_full` failure: fall back to the direct selector rather
551        // than propagating, so the function still compiles correctly.
552        match bridge
553            .optimize_full(wasm_ops)
554            .and_then(|(opt_ir, _cfg, _stats)| bridge.ir_to_arm(&opt_ir, num_params as usize))
555        {
556            Ok(arm_ops) => {
557                if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
558                    eprintln!("[path-debug] optimized (ir_to_arm ok)");
559                }
560                arm_ops
561                    .into_iter()
562                    .map(|op| ArmInstruction {
563                        op,
564                        source_line: None,
565                    })
566                    .collect()
567            }
568            // Issue #120: the optimized path declines modules it cannot lower
569            // (notably scalar f32/f64 ops — the IR has no float opcodes). Fall
570            // back to the direct instruction selector, which handles f32 via
571            // VFP/FPU. This is honest degradation: the function still compiles
572            // correctly, just without IR-level optimization.
573            Err(e) => {
574                if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
575                    eprintln!("[path-debug] direct (fallback: {e})");
576                }
577                select_direct()?
578            }
579        }
580    };
581
582    // #257/#277: `mul`+`add`→`mla` fusion is intentionally NOT wired here.
583    // The transform is correct and ready (`synth_synthesis::liveness::fuse_mul_add`,
584    // fully tested), but it is **register-allocation-coupled**: over the current
585    // greedy single-pass selector, folding `mul rM,..; add rD,rM,rX` → `mla`
586    // extends the live ranges of the mul inputs to the mla point, and the added
587    // pressure (extra moves/spills) costs more than the single-cycle MLA saves —
588    // gale measured a +2 cyc on-target REGRESSION (flat_flight 255→257, G474RE)
589    // even though it removes 2 instructions and the seam stays 0x07FDF307. So the
590    // fusion stays unwired until the spill-aware allocator (VCR-RA-001) chooses
591    // registers, at which point it becomes net-positive (per #272's plan and the
592    // wiring design note). Lesson (#277): a register-pressure-affecting transform
593    // needs an on-target/allocator-aware gate, not a byte-count gate, before it
594    // can default on.
595
596    // VCR-RA-001 const-CSE / rematerialization-avoidance (#209): moved to run
597    // LAST, after the immediate-folds — see the apply_const_cse call below
598    // (#242). Earlier it ran here (before range-realloc and the folds), which is
599    // what let it grow gale's --relocatable `gust_mix` 90→92 B (#242 burndown,
600    // 2026-06-26): retargeting a read defeated a *downstream* immediate-fold that
601    // would otherwise have absorbed the constant. Running CSE-last makes those
602    // foldable consts already-folded-and-gone, so CSE only ever touches genuinely
603    // redundant materializations.
604
605    // VCR-RA-001 RANGE RE-ALLOCATION (#209/#242, wiring step 3a) — the first
606    // CONSEQUENTIAL allocator pass: re-colour each maximal straight-line
607    // segment over the R0-R8 pool with value ranges as the allocation unit
608    // (segment inputs + per-register live-outs pinned to their original
609    // registers, reserved R9-R12/SP identity-assigned — each segment is
610    // independently sound, no cross-segment liveness assumed). Renames
611    // registers only: never adds, removes, or reorders instructions, so
612    // labels/branch offsets are unaffected.
613    //
614    // DEFAULT-ON since v0.11.36: gale cleared the gate on-target (G474RE,
615    // #209 2026-06-10) — flag-on output byte-identical to flag-off on
616    // flat_flight/controller/control_step, fires on the filter family with
617    // zero cycle delta and a small size win, all selfchecks green on silicon.
618    // Opt out with `SYNTH_RANGE_REALLOC=0`; per-function stats with
619    // `SYNTH_REALLOC_STATS=1`.
620    //
621    // The companion dead callee-saved-save elimination (gale's "next
622    // consequential lever", same issue comment) then shrinks the prologue
623    // `push {r4-r8,lr}` / epilogue `pop {r4-r8,pc}` to the callee-saved
624    // registers the re-allocated body still touches (leaf-only,
625    // SP-untouched, even-count-padded — see shrink_callee_saved_saves):
626    // ~12 cycles of pure save/restore overhead removed on small leaves.
627    let realloc_on = std::env::var("SYNTH_RANGE_REALLOC").map_or(true, |v| v != "0");
628    let arm_instrs = if realloc_on {
629        use synth_synthesis::rules::Reg;
630        const POOL: [Reg; 9] = [
631            Reg::R0,
632            Reg::R1,
633            Reg::R2,
634            Reg::R3,
635            Reg::R4,
636            Reg::R5,
637            Reg::R6,
638            Reg::R7,
639            Reg::R8,
640        ];
641        let (out, stats) = synth_synthesis::liveness::reallocate_function(&arm_instrs, &POOL);
642        if std::env::var("SYNTH_REALLOC_STATS").is_ok() {
643            eprintln!(
644                "[range-realloc] {} segments: {} reallocated, {} declined ({} validator-rejected), {} need spill (step 4)",
645                stats.segments,
646                stats.reallocated,
647                stats.declined,
648                stats.validator_rejects,
649                stats.needs_spill
650            );
651        }
652        // VCR-RA-002 (#390, epic #242): eliminate a provably-dead stack frame
653        // (`sub sp,#N`/`add sp,#N` reserved by `compute_local_layout` for locals
654        // that promotion homed in registers, never accessed). Removing it saves
655        // the two instructions AND restores the SP-untouched precondition that
656        // `shrink_callee_saved_saves` requires — so it must run FIRST. Flag-off
657        // (opt-in `SYNTH_DEAD_FRAME_ELIM=1`); off ⇒ byte-identical. Default-on
658        // flip held for on-silicon validation, like the realloc/shrink levers.
659        let out = if std::env::var("SYNTH_DEAD_FRAME_ELIM").is_ok() {
660            synth_synthesis::liveness::elide_dead_frame(&out).unwrap_or(out)
661        } else {
662            out
663        };
664        // #490 (epic #242): the optimized selector uses r4-r8 as scratch /
665        // promoted locals but emits no prologue, silently clobbering a caller's
666        // callee-saved registers. Add the missing `push {r4-r8,lr}` /
667        // `pop {r4-r8,pc}` HERE — on the post-realloc body, where realloc has
668        // lowered low-pressure r4-r8 scratch back to r0-r3, so a save is added
669        // only for registers genuinely clobbered. `shrink_callee_saved_saves`
670        // (next) then trims it to the used set. No-op on the direct path (it
671        // already has its own prologue) and on callee-saved-free leaves.
672        let out = synth_synthesis::liveness::ensure_callee_saved_prologue(&out);
673        synth_synthesis::liveness::shrink_callee_saved_saves(&out).unwrap_or(out)
674    } else {
675        // Range-realloc off (`SYNTH_RANGE_REALLOC=0`): the optimized path still
676        // must preserve the callee-saved registers it clobbers (#490). No shrink
677        // (it is coupled to the realloc lever), so the conservative full save
678        // stays — correct, just not minimised in this debug configuration.
679        synth_synthesis::liveness::ensure_callee_saved_prologue(&arm_instrs)
680    };
681
682    // VCR-RA-001 SHADOW ALLOCATION (#209/#242): run the register allocator on
683    // the selected stream and LOG what it finds — without changing a single
684    // emitted byte. This is the measure-only bridge between the built analysis
685    // layer and the eventual virtual-register wiring: it shows, per real
686    // function, whether the allocator can colour it within the R0–R8 pool and
687    // how much const-CSE / rematerialization headroom exists (#209). Enable with
688    // `SYNTH_SHADOW_ALLOC=1`; off by default and side-effect-free either way.
689    if std::env::var("SYNTH_SHADOW_ALLOC").is_ok() {
690        use synth_synthesis::liveness::{
691            AllocationOutcome, allocate_function, function_peak_pressure,
692        };
693        // R9 globals / R10 mem-size / R11 mem-base / R12 IP-scratch are reserved;
694        // pin them above the 0..9 allocatable pool so the colourer keeps R0–R8.
695        let precolored = std::collections::BTreeMap::from([
696            (synth_synthesis::rules::Reg::R9, 9usize),
697            (synth_synthesis::rules::Reg::R10, 10),
698            (synth_synthesis::rules::Reg::R11, 11),
699            (synth_synthesis::rules::Reg::R12, 12),
700        ]);
701        // True VALUE pressure (one node per value, not per reused physical reg):
702        // a NeedsSpill with peak ≤ 9 is a SPURIOUS physical-register spill — the
703        // function fits once virtually allocated.
704        let peak = function_peak_pressure(&arm_instrs);
705        match allocate_function(&arm_instrs, 9, &precolored) {
706            AllocationOutcome::Allocated {
707                remat_opportunities,
708                coloring,
709            } => eprintln!(
710                "[shadow-alloc] OK: {} pregs coloured within R0-R8 pool, peak value-pressure {}, {} const-CSE/remat opportunities",
711                coloring.len(),
712                peak,
713                remat_opportunities
714            ),
715            AllocationOutcome::NeedsSpill(s) => eprintln!(
716                "[shadow-alloc] physical-graph would spill {:?}, but peak value-pressure is {} (≤9 ⇒ spurious; fits once virtually allocated)",
717                s, peak
718            ),
719            AllocationOutcome::Declined => {
720                eprintln!(
721                    "[shadow-alloc] declined (unmodeled construct — calls/i64/fp/offset-branch)"
722                )
723            }
724        }
725    }
726
727    // VCR-SEL-004 cmp→select → IT-block predication fusion (#242). The selector
728    // lowers a `select` whose condition is a comparison to a *materialize then
729    // re-test* sequence (`cmp a,b; SetCond D,c; cmp D,#0; movne dst,v1; moveq
730    // dst,v2`); this collapses it onto the comparison's own flags — deleting the
731    // `SetCond` and the `cmp D,#0` and retargeting the predicated moves to `c` /
732    // `invert(c)` — yielding the textbook predicated clamp (`cmp a,b; movc dst,v1;
733    // mov{!c} dst,v2`). −2 instructions per fused select. gale #428 measured this
734    // as the #1 hot-path size/cycle lever on the gust_mix clamp chain.
735    //
736    // Run LATE: after range re-allocation (so the dead-D proof sees final register
737    // identities) and before encode. Removal-only + rename-only ⇒ no spill
738    // regression and labels/branch offsets are unaffected. Each fusion is proven
739    // sound (flags reused only when nothing clobbers them in the window; the
740    // boolean deleted only when provably dead) — see `fuse_cmp_select`.
741    //
742    // DEFAULT-ON as of v0.13.0 (#428): cmp→select fusion ships by default. The
743    // byte-changing flip is validated by (a) the unicorn execution oracle that runs
744    // the two-move `mov{invert(c)}` arm (cmp_select_two_move_differential.py), (b)
745    // gale's gale_decider_diff 10,596-case sweep across all 8 verified primitives
746    // (native ≡ flag-off ≡ flag-on = 0x88e73178d232bcf5), and (c) the named-anchor
747    // differentials re-run with fusion ON — control_step still 0x00210A55, flat+
748    // inlined flight_algo still 0x07FDF307 (results preserved; bytes deliberately
749    // changed, re-frozen on this commit). Escape hatch: `SYNTH_NO_CMP_SELECT_FUSE=1`
750    // reverts to the pre-fusion lowering. The on-silicon G474RE DWT no-regression
751    // check is a tracked post-ship follow-up (gale owns it).
752    let arm_instrs = if std::env::var("SYNTH_NO_CMP_SELECT_FUSE").is_err() {
753        // The rewritten stream is identical to `fuse_cmp_select`'s 2-tuple form;
754        // the extra `two_move` count is diagnostic only (the fusion census /
755        // blast-radius datum — #7 made that arm reachable).
756        let (out, fused, two_move) =
757            synth_synthesis::liveness::fuse_cmp_select_with_stats(&arm_instrs);
758        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
759            let in_place = fused - two_move;
760            eprintln!(
761                "[cmp-select-fuse] {fused} select(s) fused to predicated moves \
762                 ({two_move} two-move, {in_place} in-place)"
763            );
764        }
765        out
766    } else {
767        arm_instrs
768    };
769
770    // Perf lever 1 toward native parity (#390): redundant stack-reload elimination.
771    // synth lowers every wasm local to a frame slot, so `local.set; local.get` emits
772    // `str rX,[sp,#N]; … ; ldr rY,[sp,#N]`; when rX still holds the value the reload
773    // (a ~2-cycle M4 load) becomes `mov rY,rX`. Removal-of-a-load + rename only ⇒ no
774    // new instruction form and no label/offset change. DEFAULT-ON (#242 feature
775    // loop): validated bit-identical RESULTS on every frozen anchor (control_step
776    // 0x00210A55 13/13, flat+inlined flight_algo 0x07FDF307) with .text reduced on
777    // the shipped --relocatable path, plus 8 unit tests + the frame_slot_dce
778    // execution differential — the same gated path cmp→select took to default-on in
779    // v0.13.0 (G474RE silicon confirms perf post-ship). Escape hatch:
780    // `SYNTH_NO_STACK_FWD=1` restores the frame-resident bytes (frozen-old goldens).
781    let stack_fwd = std::env::var("SYNTH_NO_STACK_FWD").is_err();
782    let arm_instrs = if stack_fwd {
783        let (out, fwd) = synth_synthesis::liveness::forward_stack_reloads(&arm_instrs);
784        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
785            eprintln!("[stack-fwd] {fwd} stack reload(s) forwarded to register moves");
786        }
787        out
788    } else {
789        arm_instrs
790    };
791
792    // VCR-RA frame-slot DCE (#242): once `forward_stack_reloads` has turned the
793    // reloads of a spill slot into register moves, the `str rX,[sp,#N]` that fed
794    // them is a dead store — its slot is never loaded again. Remove it. Pairs
795    // with (and only pays after) stack-reload forwarding, so it shares the flag.
796    let arm_instrs = if stack_fwd {
797        let (out, n) = synth_synthesis::liveness::eliminate_dead_frame_stores(&arm_instrs);
798        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
799            eprintln!("[frame-slot-dce] {n} dead frame store(s) removed");
800        }
801        out
802    } else {
803        arm_instrs
804    };
805
806    // VCR-RA-001 spill re-choice (#242), two stages behind one flag.
807    // Stage 1 (the #569 spike): slot-value forwarding BETWEEN reloads.
808    // `forward_stack_reloads` (above) forwards only from a spill store's
809    // SOURCE register, so when register pressure clobbers that source its
810    // reloads survive; this stage tracks which registers provably still hold
811    // a frame slot's value (through earlier reloads and reg-reg moves) and
812    // turns reload #2..#n into a 1-cycle `mov` (or deletes it when the target
813    // already holds the value). Stage 2 (the Belady re-choice): where NO
814    // register still holds the value — the genuine-spill case, flat_flight's
815    // peak-11 hot segment — the value was usually evicted while a dead
816    // register existed; the clobbering def(s) are renamed onto a provably-dead
817    // register (`spill_rechoice_segment`) so the value stays resident and the
818    // reload dissolves outright. A dissolved reload can leave the feeding
819    // store dead, so the frame-slot DCE sweep runs once more behind the same
820    // flag. Per-segment commit gates: executable same-value-flow trace
821    // equality, strict shrink, pool-pressure fit, sub-word/unknown-slot
822    // conservatism (see `apply_spill_realloc` / `spill_rechoice_segment`).
823    // Stage 3 (whole-function slot liveness): the segment-local DCE keeps a
824    // store whose slot reaches function end ("reach-end ≠ dead" — it cannot
825    // see other segments); `eliminate_unread_frame_stores` walks the whole
826    // function (labels/branches/loops, SP-displacement tracked) and drops a
827    // store whose slot NO reachable instruction can read — flat_flight's two
828    // surviving stores (#576), completing Belady's 0-load side with a 0-store
829    // side. Same flag: the three stages are one lever, flipped together.
830    // DEFAULT-ON (#242 feature loop, the v0.14.0 local-promotion pattern):
831    // Belady spilling ships by default. Evidence basis for the flip: three
832    // landed flag-off increments (#569 forwarding, #576 Belady re-choice,
833    // #579 whole-fn slot liveness), 40+ functions shrink / 0 grow across the
834    // 68-fixture × 2-path sweep, per-segment executable value-trace equality
835    // guards, and the unicorn-vs-wasmtime execution differentials re-run
836    // green on the new default bytes (flat+inlined flight_algo 0x07FDF307,
837    // const_cse, frame_slot_dce, spill_rung_581, r12_spill_496 — which covers
838    // control_step_decide vs wasmtime; control_step's .text is byte-identical
839    // under the flip) BEFORE the frozen goldens were re-pinned. Escape hatch:
840    // `SYNTH_SPILL_REALLOC=0` is the OPT-OUT — it disables all three stages
841    // and restores the pre-flip bytes (CI-gated by
842    // `frozen_fixtures_spill_realloc_escape_hatch_restores_old_bytes`). Any
843    // other value (or unset) runs the pass.
844    let arm_instrs = if !std::env::var("SYNTH_SPILL_REALLOC").is_ok_and(|v| v == "0") {
845        let (out, n) = synth_synthesis::liveness::apply_spill_realloc(&arm_instrs);
846        let (out, d) = synth_synthesis::liveness::eliminate_dead_frame_stores(&out);
847        let (out, u) = synth_synthesis::liveness::eliminate_unread_frame_stores(&out);
848        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
849            eprintln!(
850                "[spill-realloc] {n} reload(s) forwarded/eliminated, {d} newly-dead frame store(s) removed, {u} unread-slot store(s) removed"
851            );
852        }
853        out
854    } else {
855        arm_instrs
856    };
857
858    // VCR-RA immediate-shift folding (#390, #242): a constant shift amount the
859    // stack selector materialized into a scratch register (`movw rM,#C; lsl rD,rN,rM`)
860    // folds to the immediate form (`lsl rD,rN,#C`), removing the dead `movw` — −1
861    // instruction, −1 live register. Removal-only (offset-neutral before branch
862    // resolution, like the dead-store pass). DEFAULT-ON as of v0.15.0: validated
863    // bit-identical results + a net cycle win on the dissolved hot path (−2
864    // cyc/call, .text 100→90 B on gust_mix). Escape hatch: `SYNTH_NO_IMM_SHIFT_FOLD=1`.
865    let arm_instrs = if std::env::var("SYNTH_NO_IMM_SHIFT_FOLD").is_err() {
866        let (out, folds) = synth_synthesis::liveness::fold_immediate_shifts(&arm_instrs);
867        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
868            eprintln!(
869                "[imm-shift-fold] {folds} register shift(s) folded to immediate, movw dropped"
870            );
871        }
872        out
873    } else {
874        arm_instrs
875    };
876
877    // VCR-RA uxth/uxtb fold (#428, #242): `movw rM,#0xffff; and rD,rN,rM` →
878    // `uxth rD,rN` (and the 0xff/uxtb form), removing the dead `movw` — −1
879    // instruction, −1 live register per 16/8-bit mask. 0xffff/0xff are not Thumb-2
880    // modified immediates so the selector materializes them into a register; the
881    // dedicated zero-extend expresses the same masking inline. Removal-only +
882    // rewrite-in-place (offset-neutral). FLAG-OFF by default (opt-in
883    // `SYNTH_UXTH_FOLD=1`) ⇒ bit-identical (frozen gate green); the byte-changing
884    // default-on flip is the separate on-target-gated step, like the prior levers.
885    let arm_instrs = if std::env::var("SYNTH_UXTH_FOLD").is_ok() {
886        let (out, folds) = synth_synthesis::liveness::fold_uxth(&arm_instrs);
887        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
888            eprintln!("[uxth-fold] {folds} mask-and folded to uxth/uxtb, movw dropped");
889        }
890        out
891    } else {
892        arm_instrs
893    };
894
895    // VCR-RA-001 const-CSE / rematerialization-avoidance (#209, #242). Drops a
896    // `movw`/`mov #imm` that re-materializes a constant already resident in
897    // another register and retargets the reads — every rewrite proven by the
898    // liveness analysis. Runs LAST, after every immediate-fold (shift, uxth) and
899    // range-realloc, but BEFORE branch resolution/encoding (it removes
900    // instructions, shifting byte offsets). CSE-last is the #242 no-regression
901    // fix: the folds have already absorbed every foldable constant, so CSE can no
902    // longer defeat one (the gust_mix 90→92 mechanism). The pass additionally
903    // size-guards each segment via the byte-estimator — it commits a segment's
904    // rewrites only if they do not grow its estimated size — so a retarget that
905    // would flip a 16-bit encoding to 32-bit (higher base register) is declined.
906    // DEFAULT-ON (#242 flip-wave, the SYNTH_SPILL_REALLOC/SYNTH_BASE_CSE
907    // template): const-CSE ships by default. The flip prerequisites recorded in
908    // `const_cse_reduction_242.rs` were retired first — the bridge-level INLINE
909    // aliasing (the alias-eviction spill-bijection hazard) was DELETED from
910    // `optimizer_bridge::ir_to_arm`, so this post-hoc, liveness-proven pass is
911    // the flag's ONLY effect. Evidence basis: 152 fixture×path corpus sweep — 0
912    // functions grow (size-guarded per segment), 40 shrink (const_cse::spill12
913    // 236→148 B), total −536 B — and the execution differentials re-run green
914    // on the new default bytes BEFORE the frozen goldens were re-pinned
915    // (const_cse, frame_slot_dce, flight_seam 0x07FDF307, spill_rung_581,
916    // volatile_segment_543, control_step 0x00210A55). Escape hatch:
917    // `SYNTH_CONST_CSE=0` is the OPT-OUT — it restores the pre-flip bytes
918    // (CI-gated by `const_cse_escape_hatch_restores_old_bytes_242` and the
919    // frozen-anchor escape-hatch gate). Any other value (or unset) runs the pass.
920    //
921    // #543 Phase 2: const-CSE declines WHOLESALE while any volatile DMA range
922    // (`--volatile-segment`) is marked. At the ArmOp level a cached constant
923    // cannot be classified as address-vs-data (a retargeted read may be a
924    // memory-access base carrying a per-use immediate offset), so the
925    // conservative stance for statically-unknown addressing is to decline every
926    // aliasing rewrite — each constant is re-materialized at each occurrence,
927    // the documented volatile contract (`CompileConfig::volatile_segments`).
928    let arm_instrs = if !std::env::var("SYNTH_CONST_CSE").is_ok_and(|v| v == "0")
929        && config.volatile_segments.is_empty()
930    {
931        let (out, removed) = synth_synthesis::liveness::apply_const_cse(&arm_instrs);
932        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
933            eprintln!("[const-cse] {removed} redundant constant materialization(s) removed");
934        }
935        out
936    } else {
937        arm_instrs
938    };
939
940    // VCR-RA-001 spill-choice REPORT (#242): measure-only, like SYNTH_SHADOW_ALLOC.
941    // Per straight-line segment, the frame-slot traffic actually emitted vs the
942    // reload/store count a farthest-next-use (Belady) allocation over the R0-R8
943    // pool would need — the measured headroom for the full spill-choice rewrite.
944    // Printed on the FINAL stream (post all rewrite passes), so a flag-off run
945    // reports the greedy baseline and a flag-on run reports what remains.
946    if std::env::var("SYNTH_SPILL_REPORT").is_ok() {
947        for seg in synth_synthesis::liveness::spill_choice_report(&arm_instrs, 9) {
948            if seg.actual_reloads + seg.actual_spill_stores > 0 || seg.peak_pressure > 9 {
949                eprintln!(
950                    "[spill-report] seg@{} len={} peak={} actual={}ld+{}st belady(k=9)={}ld+{}st",
951                    seg.start,
952                    seg.len,
953                    seg.peak_pressure,
954                    seg.actual_reloads,
955                    seg.actual_spill_stores,
956                    seg.belady_reloads,
957                    seg.belady_spill_stores
958                );
959            }
960        }
961    }
962
963    // ISA feature gate: validate that all generated instructions are supported
964    // by the target. This catches FPU instructions on no-FPU targets, double-precision
965    // instructions on single-precision targets, etc.
966    validate_instructions(&arm_instrs, config.target.fpu, &config.target.triple)
967        .map_err(|e| format!("ISA validation failed: {}", e))?;
968
969    // Encode to binary — use Thumb-2 for Cortex-M targets
970    let use_thumb2 = matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
971
972    let encoder = if use_thumb2 {
973        ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
974    } else {
975        ArmEncoder::new_arm32()
976    };
977
978    // #202: resolve local label branches (Bcc/B/Bhs/Blo) to byte-accurate
979    // offsets before encoding. `select_with_stack` emits them as label
980    // placeholders and never resolves them — without this they encode as
981    // `bne.n #0` and land mid-instruction whenever a 32-bit Thumb-2 instruction
982    // sits between the branch and its target (UsageFault on real hardware).
983    // Only meaningful for Thumb-2 (the offset units are halfword/PC+4).
984    let arm_instrs = if use_thumb2 {
985        resolve_label_branches(arm_instrs, &encoder)?
986    } else {
987        arm_instrs
988    };
989
990    let mut code = Vec::new();
991    let mut relocations = Vec::new();
992
993    // #345: literal-pool address loads. Each `LdrSym` was encoded as a placeholder
994    // `LDR.W rd,[pc,#0]`; record where its instruction sits and what it loads so
995    // we can append a pooled word (carrying the symbol address via R_ARM_ABS32)
996    // and patch the PC-relative offset once the pool position is known.
997    struct PendingLiteral {
998        ldr_offset: u32,
999        symbol: String,
1000        addend: i32,
1001    }
1002    let mut pending_literals: Vec<PendingLiteral> = Vec::new();
1003
1004    // VCR-DBG-001: per-instruction source map for DWARF `.debug_line`. Captured
1005    // here because `code.len()` immediately before `encode()` is the final
1006    // machine offset of the instruction within this function's `.text` — nothing
1007    // after the loop shifts earlier instructions (the literal pool is appended at
1008    // the end; the LDR patch below is in-place/length-preserving). Purely
1009    // additive: it does not touch `code`, so `.text` is byte-identical.
1010    let mut line_map: LineMap = Vec::new();
1011
1012    for instr in &arm_instrs {
1013        // Record a relocation for every BL: the encoder emits `bl #0` and
1014        // relies on a relocation to patch the target. This covers BOTH import
1015        // dispatch stubs (`__meld_*`, undefined externals) AND internal calls
1016        // (`func_N`, defined in this object). Previously only `__meld_*` was
1017        // recorded, so internal `BL func_N` calls were left as unpatched
1018        // `bl #0` placeholders branching to a garbage address (#167).
1019        if let ArmOp::Bl { label } = &instr.op {
1020            relocations.push(CodeRelocation {
1021                offset: code.len() as u32,
1022                symbol: label.clone(),
1023                kind: synth_core::backend::RelocKind::ThmCall,
1024            });
1025        }
1026        // #237: symbol-relative MOVW/MOVT (the `--native-pointer-abi` static-data
1027        // addressing). The encoder writes the addend in place; record the matching
1028        // R_ARM_MOVW_ABS_NC / R_ARM_MOVT_ABS so the linker adds the symbol address.
1029        if let ArmOp::MovwSym { symbol, .. } = &instr.op {
1030            relocations.push(CodeRelocation {
1031                offset: code.len() as u32,
1032                symbol: symbol.clone(),
1033                kind: synth_core::backend::RelocKind::MovwAbs,
1034            });
1035        }
1036        if let ArmOp::MovtSym { symbol, .. } = &instr.op {
1037            relocations.push(CodeRelocation {
1038                offset: code.len() as u32,
1039                symbol: symbol.clone(),
1040                kind: synth_core::backend::RelocKind::MovtAbs,
1041            });
1042        }
1043        // #345: defer the literal-pool word + reloc + offset patch to the
1044        // post-loop pass (the pool address is not yet known).
1045        if let ArmOp::LdrSym { symbol, addend, .. } = &instr.op {
1046            pending_literals.push(PendingLiteral {
1047                ldr_offset: code.len() as u32,
1048                symbol: symbol.clone(),
1049                addend: *addend,
1050            });
1051        }
1052
1053        // The machine offset of this instruction is the current code length,
1054        // captured before the bytes are appended.
1055        line_map.push((code.len() as u32, instr.source_line));
1056
1057        let encoded = encoder
1058            .encode(&instr.op)
1059            .map_err(|e| format!("ARM encoding failed: {}", e))?;
1060        code.extend_from_slice(&encoded);
1061    }
1062
1063    // #345: place the literal pool at the end of this function's `.text`. Gated on
1064    // there being at least one `LdrSym` — functions without one are byte-identical
1065    // to before (no trailing padding, so downstream `func_offsets` are unchanged
1066    // and the frozen differential fixtures stay bit-for-bit equal).
1067    if !pending_literals.is_empty() {
1068        if !use_thumb2 {
1069            return Err("LdrSym literal-pool addressing requires Thumb-2".to_string());
1070        }
1071        // 4-byte align the pool start (Thumb-2 word loads require it, and
1072        // `Align(PC,4)` in the LDR-literal semantics assumes a word-aligned pool).
1073        while code.len() % 4 != 0 {
1074            code.push(0x00);
1075        }
1076        // One distinct pooled word per LdrSym (no dedup: different sites carry
1077        // different addends, and the REL addend lives in the word).
1078        for lit in &pending_literals {
1079            let word_offset = code.len() as u32;
1080
1081            // REL semantics: the linker computes `S + A`, where A is the in-place
1082            // value of the relocated word. Initialize the word to the addend so
1083            // the final loaded address is `symbol + addend`.
1084            code.extend_from_slice(&(lit.addend as u32).to_le_bytes());
1085            relocations.push(CodeRelocation {
1086                offset: word_offset,
1087                symbol: lit.symbol.clone(),
1088                kind: synth_core::backend::RelocKind::Abs32,
1089            });
1090
1091            // Patch the placeholder `LDR.W rd,[pc,#imm12]`. Thumb-2 LDR (literal):
1092            // address = Align(PC,4) + imm12, with PC = ldr_offset + 4. The pool is
1093            // always after the LDR, so U=1 (already set in hw1 = 0xF8DF).
1094            let pc = lit.ldr_offset + 4;
1095            let aligned_pc = pc & !3u32;
1096            let imm12 = word_offset - aligned_pc;
1097            if imm12 > 0xFFF {
1098                // Wide LDR-literal range is ±4 KB; these function bodies are far
1099                // smaller, but fail cleanly rather than miscompile if exceeded.
1100                return Err(format!(
1101                    "LdrSym literal pool out of range (#345): imm12={} > 4095 \
1102                     for symbol {}",
1103                    imm12, lit.symbol
1104                ));
1105            }
1106            let hw2_off = (lit.ldr_offset + 2) as usize;
1107            let mut hw2 = u16::from_le_bytes([code[hw2_off], code[hw2_off + 1]]);
1108            hw2 = (hw2 & 0xF000) | (imm12 as u16); // keep Rt, set imm12
1109            let hw2_bytes = hw2.to_le_bytes();
1110            code[hw2_off] = hw2_bytes[0];
1111            code[hw2_off + 1] = hw2_bytes[1];
1112        }
1113    }
1114
1115    Ok((code, relocations, line_map))
1116}
1117
1118/// Resolve local label branches to byte-accurate offsets (#202).
1119///
1120/// `select_with_stack` emits conditional/unconditional branches as label
1121/// placeholders (`Bcc`/`B`/`Bhs`/`Blo` + `Label`) and never resolves them; the
1122/// encoder then emits a `0xD000`/`0xE000` placeholder with offset 0. Before #197
1123/// this path only ran for `--no-optimize`/declined functions, so the latent bug
1124/// stayed hidden — routing relocatable code through it surfaced branches that
1125/// land mid-instruction (a Cortex-M UsageFault) whenever a 32-bit Thumb-2
1126/// instruction sits between the branch and its target.
1127///
1128/// This pass encodes each instruction to learn its real byte length (so 16- vs
1129/// 32-bit forms and multi-instruction expansions are exact), maps each `Label`
1130/// to its byte position, and rewrites every label branch to the displacement
1131/// the encoder consumes: `(target - branch - 4) / 2` halfwords. A bounded
1132/// fixed-point handles an offset growing a branch from 16- to 32-bit (which
1133/// shifts later positions). `BCondOffset`/`BOffset` already produced inline by
1134/// the optimized path carry no label and are left untouched.
1135fn resolve_label_branches(
1136    arm_instrs: Vec<ArmInstruction>,
1137    encoder: &ArmEncoder,
1138) -> Result<Vec<ArmInstruction>, String> {
1139    use std::collections::HashMap;
1140    use synth_synthesis::Condition;
1141
1142    enum BKind {
1143        Cond(Condition),
1144        Uncond,
1145    }
1146    // Record each label branch ONCE — indices are stable across iterations.
1147    let mut branches: Vec<(usize, BKind, String)> = Vec::new();
1148    for (i, instr) in arm_instrs.iter().enumerate() {
1149        match &instr.op {
1150            ArmOp::Bcc { cond, label } => branches.push((i, BKind::Cond(*cond), label.clone())),
1151            ArmOp::Bhs { label } => branches.push((i, BKind::Cond(Condition::HS), label.clone())),
1152            ArmOp::Blo { label } => branches.push((i, BKind::Cond(Condition::LO), label.clone())),
1153            ArmOp::B { label } => branches.push((i, BKind::Uncond, label.clone())),
1154            _ => {}
1155        }
1156    }
1157    if branches.is_empty() {
1158        return Ok(arm_instrs);
1159    }
1160
1161    let mut resolved = arm_instrs;
1162    // Sizes only grow (16→32-bit), so this converges quickly; cap for safety.
1163    for _ in 0..16 {
1164        // 1. Byte position of each instruction (Label encodes to 0 bytes).
1165        let mut positions = Vec::with_capacity(resolved.len());
1166        let mut pos: i64 = 0;
1167        for instr in &resolved {
1168            positions.push(pos);
1169            pos += encoder
1170                .encode(&instr.op)
1171                .map_err(|e| format!("branch-resolve size probe failed: {}", e))?
1172                .len() as i64;
1173        }
1174        // 2. Label name -> byte position (owned keys so the borrow ends here).
1175        let mut labels: HashMap<String, i64> = HashMap::new();
1176        for (i, instr) in resolved.iter().enumerate() {
1177            if let ArmOp::Label { name } = &instr.op {
1178                labels.insert(name.clone(), positions[i]);
1179            }
1180        }
1181        // 3. Rewrite each branch to its byte-accurate offset.
1182        let mut changed = false;
1183        for (idx, kind, label) in &branches {
1184            // A label not defined locally is an EXTERNAL target (e.g.
1185            // `Trap_Handler` resolved by a relocation / the vector table). Leave
1186            // such branches as their placeholder for the existing relocation
1187            // path — only local control-flow labels are byte-resolved here.
1188            let Some(&target) = labels.get(label) else {
1189                continue;
1190            };
1191            // Encoder consumes the field as (target - branch - 4) / 2 halfwords.
1192            // Positions are always even, so this division is exact.
1193            let halfword_offset = ((target - positions[*idx] - 4) / 2) as i32;
1194            let new_op = match kind {
1195                BKind::Cond(c) => ArmOp::BCondOffset {
1196                    cond: *c,
1197                    offset: halfword_offset,
1198                },
1199                BKind::Uncond => ArmOp::BOffset {
1200                    offset: halfword_offset,
1201                },
1202            };
1203            if resolved[*idx].op != new_op {
1204                resolved[*idx].op = new_op;
1205                changed = true;
1206            }
1207        }
1208        if !changed {
1209            break;
1210        }
1211    }
1212    Ok(resolved)
1213}
1214
1215#[cfg(test)]
1216mod tests {
1217    use super::*;
1218
1219    /// #539: `i32.const 0; memory.grow m` folds to `memory.size m`; other deltas
1220    /// (const non-zero, runtime) are left as `memory.grow` (→ the sound fixed-
1221    /// memory -1). Non-grow ops are untouched, so functions without the idiom are
1222    /// byte-identical.
1223    #[test]
1224    fn test_rewrite_memory_grow_zero_539() {
1225        // the idiom -> memory.size
1226        assert_eq!(
1227            rewrite_memory_grow_zero(&[WasmOp::I32Const(0), WasmOp::MemoryGrow(0)]),
1228            vec![WasmOp::MemorySize(0)]
1229        );
1230        // const non-zero delta: NOT folded
1231        assert_eq!(
1232            rewrite_memory_grow_zero(&[WasmOp::I32Const(2), WasmOp::MemoryGrow(0)]),
1233            vec![WasmOp::I32Const(2), WasmOp::MemoryGrow(0)]
1234        );
1235        // runtime delta (no preceding const): NOT folded
1236        assert_eq!(
1237            rewrite_memory_grow_zero(&[WasmOp::LocalGet(0), WasmOp::MemoryGrow(0)]),
1238            vec![WasmOp::LocalGet(0), WasmOp::MemoryGrow(0)]
1239        );
1240        // a bare const-0 not feeding a grow is untouched
1241        assert_eq!(
1242            rewrite_memory_grow_zero(&[WasmOp::I32Const(0), WasmOp::I32Add]),
1243            vec![WasmOp::I32Const(0), WasmOp::I32Add]
1244        );
1245        // fold is local: surrounding ops preserved, indices past the fold intact
1246        assert_eq!(
1247            rewrite_memory_grow_zero(&[
1248                WasmOp::LocalGet(0),
1249                WasmOp::I32Const(0),
1250                WasmOp::MemoryGrow(0),
1251                WasmOp::I32Add,
1252            ]),
1253            vec![WasmOp::LocalGet(0), WasmOp::MemorySize(0), WasmOp::I32Add]
1254        );
1255    }
1256
1257    #[test]
1258    fn test_arm_backend_name() {
1259        let backend = ArmBackend::new();
1260        assert_eq!(backend.name(), "arm");
1261        assert!(backend.is_available());
1262    }
1263
1264    #[test]
1265    fn test_arm_backend_capabilities() {
1266        let backend = ArmBackend::new();
1267        let caps = backend.capabilities();
1268        assert!(!caps.produces_elf);
1269        assert!(caps.supports_rule_verification);
1270        assert!(!caps.is_external);
1271    }
1272
1273    #[test]
1274    fn test_compile_add_function() {
1275        let backend = ArmBackend::new();
1276        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
1277        let config = CompileConfig::default();
1278
1279        let result = backend.compile_function("add", &ops, &config);
1280        assert!(result.is_ok());
1281
1282        let func = result.unwrap();
1283        assert_eq!(func.name, "add");
1284        assert!(!func.code.is_empty());
1285        assert_eq!(func.wasm_ops, ops);
1286    }
1287
1288    /// VCR-DBG-001: the per-instruction source map must cover the function with
1289    /// monotonic, in-bounds machine offsets, and must not perturb the emitted
1290    /// code (it is captured at encode time, never serialized here).
1291    #[test]
1292    fn test_line_map_is_wellformed_dbg001() {
1293        let backend = ArmBackend::new();
1294        let ops = vec![
1295            WasmOp::LocalGet(0),
1296            WasmOp::LocalGet(1),
1297            WasmOp::I32Add,
1298            WasmOp::End,
1299        ];
1300        let config = CompileConfig::default();
1301        let func = backend.compile_function("add", &ops, &config).unwrap();
1302
1303        // Non-empty, and the first instruction starts at machine offset 0.
1304        assert!(
1305            !func.line_map.is_empty(),
1306            "a non-trivial function captures a source map"
1307        );
1308        assert_eq!(func.line_map[0].0, 0, "first instruction at offset 0");
1309
1310        // Offsets strictly increase by at least one ARM/Thumb instruction (>= 2
1311        // bytes) and every mapped offset lies inside the emitted `.text`.
1312        for w in func.line_map.windows(2) {
1313            assert!(w[1].0 > w[0].0, "instruction offsets strictly increase");
1314            assert!(
1315                w[1].0 - w[0].0 >= 2,
1316                "each ARM/Thumb instruction is >= 2 bytes"
1317            );
1318        }
1319        let last = func.line_map.last().unwrap().0 as usize;
1320        assert!(
1321            last < func.code.len(),
1322            "every mapped offset lies inside .text"
1323        );
1324
1325        // The side-table is additive: recompiling is deterministic and the map is
1326        // consistent with that exact code (capturing it does not alter output).
1327        let again = backend.compile_function("add", &ops, &config).unwrap();
1328        assert_eq!(
1329            again.code, func.code,
1330            "compilation deterministic; map is additive"
1331        );
1332        assert_eq!(again.line_map, func.line_map);
1333    }
1334
1335    #[test]
1336    fn test_count_params() {
1337        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
1338        assert_eq!(count_params(&ops), 2);
1339
1340        let no_params = vec![WasmOp::I32Const(5), WasmOp::I32Const(3), WasmOp::I32Add];
1341        assert_eq!(count_params(&no_params), 0);
1342    }
1343
1344    #[test]
1345    fn test_arm_backend_register() {
1346        let mut registry = synth_core::BackendRegistry::new();
1347        registry.register(Box::new(ArmBackend::new()));
1348        assert!(registry.get("arm").is_some());
1349        assert_eq!(registry.available().len(), 1);
1350    }
1351
1352    #[test]
1353    fn test_compile_import_call_produces_relocations() {
1354        let backend = ArmBackend::new();
1355        // Simulate a WASM module where func index 0 is an import.
1356        // Call(0) should generate MOV R0, #0; BL __meld_dispatch_import
1357        let ops = vec![WasmOp::Call(0)];
1358        let config = CompileConfig {
1359            num_imports: 1,
1360            no_optimize: true, // Direct instruction selection to preserve Call semantics
1361            ..CompileConfig::default()
1362        };
1363
1364        let result = backend.compile_function("caller", &ops, &config);
1365        assert!(result.is_ok());
1366
1367        let func = result.unwrap();
1368        assert!(!func.code.is_empty());
1369        assert_eq!(func.relocations.len(), 1);
1370        assert_eq!(func.relocations[0].symbol, "__meld_dispatch_import");
1371        // The BL is the second instruction (after MOV R0, #0), so offset should be > 0
1372        assert!(func.relocations[0].offset > 0);
1373    }
1374
1375    /// Regression test for #197: in `relocatable` mode, an import call must
1376    /// relocate against the direct `func_N` symbol (rewritten to the wasm field
1377    /// name by `build_relocatable_elf`), NOT `__meld_dispatch_import`. This is
1378    /// the ABI half of the #197 fix — without it, a host linker cannot resolve
1379    /// the call to the real kernel symbol (e.g. `k_spin_lock`).
1380    #[test]
1381    fn test_compile_relocatable_import_uses_direct_func_symbol_197() {
1382        let backend = ArmBackend::new();
1383        let ops = vec![WasmOp::Call(0)]; // func 0 is an import
1384        let config = CompileConfig {
1385            num_imports: 1,
1386            relocatable: true,
1387            ..CompileConfig::default()
1388        };
1389
1390        let func = backend
1391            .compile_function("caller", &ops, &config)
1392            .expect("relocatable import call compiles");
1393
1394        assert_eq!(func.relocations.len(), 1);
1395        assert_eq!(
1396            func.relocations[0].symbol, "func_0",
1397            "#197: relocatable import must relocate against func_0 (→ field name), not Meld dispatch"
1398        );
1399    }
1400
1401    #[test]
1402    fn test_compile_no_imports_no_relocations() {
1403        let backend = ArmBackend::new();
1404        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
1405        let config = CompileConfig::default();
1406
1407        let func = backend.compile_function("add", &ops, &config).unwrap();
1408        assert!(func.relocations.is_empty());
1409    }
1410
1411    /// Regression test for #167: a call to an INTERNAL function
1412    /// (index `>= num_imports`) must record a relocation against `func_{index}`.
1413    /// Before the fix, only `__meld_*` (import) BLs were relocated, so
1414    /// internal `BL func_N` was emitted as an unpatched `bl #0` branching
1415    /// to a garbage address — making the object non-linkable. This test
1416    /// would have caught that regression.
1417    #[test]
1418    fn test_compile_internal_call_produces_relocation_167() {
1419        let backend = ArmBackend::new();
1420        // num_imports = 1, so Call(2) is an INTERNAL call → `BL func_2`.
1421        let ops = vec![WasmOp::Call(2)];
1422        let config = CompileConfig {
1423            num_imports: 1,
1424            no_optimize: true,
1425            ..CompileConfig::default()
1426        };
1427
1428        let func = backend
1429            .compile_function("caller", &ops, &config)
1430            .expect("internal call compiles");
1431
1432        assert_eq!(
1433            func.relocations.len(),
1434            1,
1435            "an internal call must emit exactly one relocation (#167)"
1436        );
1437        assert_eq!(
1438            func.relocations[0].symbol, "func_2",
1439            "internal call must relocate against the callee's func_{{index}} symbol (#167)"
1440        );
1441    }
1442
1443    // ─── Phase 1 safety-bounds plumbing for ARM ──────────────────────────
1444
1445    #[test]
1446    fn arm_safety_bounds_mpu_emits_same_code_as_none() {
1447        // Mpu mode must not introduce any inline check on ARM — the MPU
1448        // handles faults via hardware. The encoded bytes for an i32.load
1449        // should be identical between None and Mpu.
1450        let backend = ArmBackend::new();
1451        let ops = vec![
1452            WasmOp::LocalGet(0),
1453            WasmOp::I32Load {
1454                offset: 0,
1455                align: 2,
1456            },
1457        ];
1458        let cfg_none = CompileConfig {
1459            no_optimize: true,
1460            ..Default::default()
1461        };
1462        let cfg_mpu = CompileConfig {
1463            no_optimize: true,
1464            safety_bounds: SafetyBounds::Mpu,
1465            ..Default::default()
1466        };
1467        let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
1468        let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
1469        assert_eq!(
1470            n.code, m.code,
1471            "Mpu and None should produce identical ARM bytes (Mpu relies on hardware)"
1472        );
1473    }
1474
1475    #[test]
1476    fn arm_legacy_bounds_check_still_emits_software_check() {
1477        // Legacy CLI users with `--bounds-check` should keep getting the
1478        // software path even though the new SafetyBounds field defaults to None.
1479        let backend = ArmBackend::new();
1480        let ops = vec![
1481            WasmOp::LocalGet(0),
1482            WasmOp::I32Load {
1483                offset: 0,
1484                align: 2,
1485            },
1486        ];
1487        let cfg_legacy = CompileConfig {
1488            no_optimize: true,
1489            bounds_check: true,
1490            ..Default::default()
1491        };
1492        let cfg_software = CompileConfig {
1493            no_optimize: true,
1494            safety_bounds: SafetyBounds::Software,
1495            ..Default::default()
1496        };
1497        let l = backend.compile_function("ld", &ops, &cfg_legacy).unwrap();
1498        let s = backend.compile_function("ld", &ops, &cfg_software).unwrap();
1499        assert_eq!(
1500            l.code, s.code,
1501            "--bounds-check should produce the same bytes as --safety-bounds=software"
1502        );
1503    }
1504
1505    // ========================================================================
1506    // ISA feature gate tests — ensure the compiler never emits unsupported
1507    // instructions for a given target
1508    // ========================================================================
1509
1510    #[test]
1511    fn test_f32_rejected_on_cortex_m3_no_fpu() {
1512        let backend = ArmBackend::new();
1513        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
1514        let config = CompileConfig {
1515            target: TargetSpec::cortex_m3(),
1516            no_optimize: true,
1517            ..CompileConfig::default()
1518        };
1519
1520        let result = backend.compile_function("fadd", &ops, &config);
1521        assert!(
1522            result.is_err(),
1523            "f32 operations should fail on Cortex-M3 (no FPU)"
1524        );
1525    }
1526
1527    #[test]
1528    fn test_f32_accepted_on_cortex_m4f() {
1529        let backend = ArmBackend::new();
1530        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
1531        let config = CompileConfig {
1532            target: TargetSpec::cortex_m4f(),
1533            no_optimize: true,
1534            ..CompileConfig::default()
1535        };
1536
1537        let result = backend.compile_function("fadd", &ops, &config);
1538        assert!(
1539            result.is_ok(),
1540            "f32 operations should succeed on Cortex-M4F, got: {:?}",
1541            result.unwrap_err()
1542        );
1543    }
1544
1545    #[test]
1546    fn test_i32_works_on_all_targets() {
1547        let backend = ArmBackend::new();
1548        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
1549
1550        // Cortex-M3 (no FPU)
1551        let config_m3 = CompileConfig {
1552            target: TargetSpec::cortex_m3(),
1553            no_optimize: true,
1554            ..CompileConfig::default()
1555        };
1556        assert!(
1557            backend.compile_function("add", &ops, &config_m3).is_ok(),
1558            "i32 ops should work on Cortex-M3"
1559        );
1560
1561        // Cortex-M4F (single FPU)
1562        let config_m4f = CompileConfig {
1563            target: TargetSpec::cortex_m4f(),
1564            no_optimize: true,
1565            ..CompileConfig::default()
1566        };
1567        assert!(
1568            backend.compile_function("add", &ops, &config_m4f).is_ok(),
1569            "i32 ops should work on Cortex-M4F"
1570        );
1571
1572        // Cortex-M7DP (double FPU)
1573        let config_m7dp = CompileConfig {
1574            target: TargetSpec::cortex_m7dp(),
1575            no_optimize: true,
1576            ..CompileConfig::default()
1577        };
1578        assert!(
1579            backend.compile_function("add", &ops, &config_m7dp).is_ok(),
1580            "i32 ops should work on Cortex-M7DP"
1581        );
1582    }
1583
1584    #[test]
1585    fn test_f32_rejected_on_cortex_m4_no_fpu() {
1586        // Cortex-M4 (without F suffix) has no FPU
1587        let backend = ArmBackend::new();
1588        let ops = vec![WasmOp::F32Const(1.5), WasmOp::F32Const(2.5), WasmOp::F32Mul];
1589        let config = CompileConfig {
1590            target: TargetSpec::cortex_m4(),
1591            no_optimize: true,
1592            ..CompileConfig::default()
1593        };
1594
1595        let result = backend.compile_function("fmul", &ops, &config);
1596        assert!(
1597            result.is_err(),
1598            "f32 operations should fail on Cortex-M4 (no FPU)"
1599        );
1600    }
1601
1602    // ========================================================================
1603    // Issue #120 — f32 ops in the optimized lowering path
1604    //
1605    // `OptimizerBridge::wasm_to_ir` has no handlers for f32/f64 ops, so a
1606    // value-producing float op fell through to `Opcode::Nop`, leaving a
1607    // downstream consumer with an unmapped vreg and tripping the PR #101
1608    // defensive panic in `ir_to_arm`. Customer reproducer: `compiler_builtins
1609    // float::div` and `gale_compute_ipi_mask` in the `falcon-rate-component`
1610    // module.
1611    //
1612    // Fix: `optimize_full` declines float modules with a typed `Err`;
1613    // `compile_wasm_to_arm` falls back to the non-optimized `select_with_stack`
1614    // path, which handles f32 via VFP/FPU. These tests use the *default*
1615    // (optimized) config — `no_optimize` is NOT set — which is the exact
1616    // configuration that panicked pre-fix.
1617    // ========================================================================
1618
1619    /// Pre-fix: this panicked with "vreg vN has no assigned ARM register and
1620    /// no spill slot" inside `ir_to_arm`. Post-fix: the optimized path declines
1621    /// the module and the backend falls back to direct selection, producing a
1622    /// non-empty f32.div lowering on a Cortex-M4F.
1623    #[test]
1624    fn test_issue120_f32_div_compiles_via_optimized_default() {
1625        let backend = ArmBackend::new();
1626        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
1627        let config = CompileConfig {
1628            target: TargetSpec::cortex_m4f(),
1629            // no_optimize NOT set — this exercises the optimized path that
1630            // panicked in issue #120, then the fallback to direct selection.
1631            ..CompileConfig::default()
1632        };
1633
1634        let result = backend.compile_function("fdiv", &ops, &config);
1635        assert!(
1636            result.is_ok(),
1637            "f32.div must compile on Cortex-M4F via the optimized->direct \
1638             fallback (issue #120), got: {:?}",
1639            result.as_ref().err()
1640        );
1641        assert!(
1642            !result.unwrap().code.is_empty(),
1643            "f32.div must produce non-empty machine code"
1644        );
1645    }
1646
1647    /// A spread of f32 ops, all through the optimized (default) config, must
1648    /// compile via the fallback on an FPU target without panicking.
1649    #[test]
1650    fn test_issue120_assorted_f32_ops_compile_via_optimized_default() {
1651        let backend = ArmBackend::new();
1652        let config = CompileConfig {
1653            target: TargetSpec::cortex_m4f(),
1654            ..CompileConfig::default()
1655        };
1656
1657        let cases: Vec<(&str, Vec<WasmOp>)> = vec![
1658            (
1659                "fadd",
1660                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Add],
1661            ),
1662            (
1663                "fmul",
1664                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Mul],
1665            ),
1666            (
1667                "fsub",
1668                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Sub],
1669            ),
1670        ];
1671
1672        for (name, ops) in cases {
1673            let result = backend.compile_function(name, &ops, &config);
1674            assert!(
1675                result.is_ok(),
1676                "{name} must compile via the optimized->direct fallback \
1677                 (issue #120), got: {:?}",
1678                result.as_ref().err()
1679            );
1680            assert!(
1681                !result.unwrap().code.is_empty(),
1682                "{name} must produce non-empty machine code"
1683            );
1684        }
1685    }
1686
1687    /// The fallback must still honor the ISA feature gate: f32 on a no-FPU
1688    /// target must fail cleanly (not panic) even on the optimized path.
1689    #[test]
1690    fn test_issue120_f32_div_rejected_on_no_fpu_via_optimized() {
1691        let backend = ArmBackend::new();
1692        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
1693        let config = CompileConfig {
1694            target: TargetSpec::cortex_m3(),
1695            ..CompileConfig::default()
1696        };
1697
1698        let result = backend.compile_function("fdiv", &ops, &config);
1699        assert!(
1700            result.is_err(),
1701            "f32.div must be rejected on Cortex-M3 (no FPU), not panic"
1702        );
1703    }
1704
1705    /// #507: a `br_table` function compiled via the DEFAULT (optimized) config
1706    /// must produce the SAME bytes as the direct (`no_optimize`) selector —
1707    /// i.e. the optimized path declined it to direct, lowering the dispatch as a
1708    /// real cmp-chain instead of silently dropping it (which left all arms in
1709    /// fall-through). Pre-fix the two outputs differed (the optimized one had no
1710    /// selector compare). Execution correctness is gated by
1711    /// `scripts/repro/br_table_507_differential.py`.
1712    #[test]
1713    fn test_507_br_table_declines_to_direct() {
1714        let backend = ArmBackend::new();
1715        // dispatch(sel): br_table over 3 blocks, each storing a marker to mem[0].
1716        let ops = vec![
1717            WasmOp::Block,
1718            WasmOp::Block,
1719            WasmOp::Block,
1720            WasmOp::LocalGet(0),
1721            WasmOp::BrTable {
1722                targets: vec![0, 1, 2],
1723                default: 2,
1724            },
1725            WasmOp::End,
1726            WasmOp::I32Const(0),
1727            WasmOp::I32Const(10),
1728            WasmOp::I32Store {
1729                offset: 0,
1730                align: 2,
1731            },
1732            WasmOp::Return,
1733            WasmOp::End,
1734            WasmOp::I32Const(0),
1735            WasmOp::I32Const(20),
1736            WasmOp::I32Store {
1737                offset: 0,
1738                align: 2,
1739            },
1740            WasmOp::Return,
1741            WasmOp::End,
1742            WasmOp::I32Const(0),
1743            WasmOp::I32Const(30),
1744            WasmOp::I32Store {
1745                offset: 0,
1746                align: 2,
1747            },
1748        ];
1749        let opt = CompileConfig {
1750            target: TargetSpec::cortex_m4(),
1751            ..CompileConfig::default()
1752        };
1753        let direct = CompileConfig {
1754            target: TargetSpec::cortex_m4(),
1755            no_optimize: true,
1756            ..CompileConfig::default()
1757        };
1758        let a = backend
1759            .compile_function("dispatch", &ops, &opt)
1760            .expect("optimized-default must compile br_table (via decline)");
1761        let b = backend
1762            .compile_function("dispatch", &ops, &direct)
1763            .expect("direct must compile br_table");
1764        assert_eq!(
1765            a.code, b.code,
1766            "#507: optimized-default br_table output must be byte-identical to the \
1767             direct selector (i.e. declined to direct), not a dropped dispatch"
1768        );
1769    }
1770
1771    /// Issue #94: end-to-end byte-size check for the canonical u64-packed
1772    /// FFI-return hi32 extract pattern. Compiles two near-identical
1773    /// functions — one with the optimized shift-by-32, one with a generic
1774    /// shift-by-7 — and asserts the optimized form is meaningfully smaller.
1775    #[test]
1776    fn test_issue94_hi32_extract_is_smaller_than_generic_shift() {
1777        let backend = ArmBackend::new();
1778        let config = CompileConfig {
1779            target: TargetSpec::cortex_m4f(),
1780            ..CompileConfig::default()
1781        };
1782
1783        // #518: the i64 value must NOT come from an i64 PARAM — the optimized
1784        // path now declines i64-param functions to the direct selector (it homed
1785        // an i64 param in R4:R5 instead of R0:R1, a silent miscompile this test's
1786        // byte-size-only assertion masked). The canonical #94 case is a u64 from
1787        // an FFI return, not a param, anyway. Source the i64 from a sign-extended
1788        // i32 param (`extend_i32_s`): a runtime, non-constant-foldable i64 that
1789        // stays on the optimized path, so the shift-by-32 hi-extract peephole is
1790        // still exercised on CORRECT code.
1791        // Optimized path: `(i64.extend_i32_s (local.get 0)) >>> 32; wrap_i64`
1792        let ops_hi32 = vec![
1793            WasmOp::LocalGet(0), // i32 param in R0
1794            WasmOp::I64ExtendI32S,
1795            WasmOp::I64Const(32),
1796            WasmOp::I64ShrU,
1797            WasmOp::I32WrapI64,
1798        ];
1799        let func_hi32 = backend
1800            .compile_function("hi32_extract", &ops_hi32, &config)
1801            .unwrap();
1802
1803        // Generic path: `... >>> 7; wrap_i64` — same shape, but the shift amount
1804        // is not a multiple of 32, so it falls through to the runtime shift.
1805        let ops_generic = vec![
1806            WasmOp::LocalGet(0),
1807            WasmOp::I64ExtendI32S,
1808            WasmOp::I64Const(7),
1809            WasmOp::I64ShrU,
1810            WasmOp::I32WrapI64,
1811        ];
1812        let func_generic = backend
1813            .compile_function("generic_shr", &ops_generic, &config)
1814            .unwrap();
1815
1816        let bytes_hi32 = func_hi32.code.len();
1817        let bytes_generic = func_generic.code.len();
1818        println!(
1819            "\n[issue #94] hi32 extract: {} bytes (vs generic shift: {} bytes; saved {})",
1820            bytes_hi32,
1821            bytes_generic,
1822            bytes_generic.saturating_sub(bytes_hi32)
1823        );
1824        let hex: String = func_hi32
1825            .code
1826            .iter()
1827            .map(|b| format!("{:02x}", b))
1828            .collect::<Vec<_>>()
1829            .join(" ");
1830        println!("[issue #94] hi32 bytes: {}", hex);
1831        // We expect the optimized form to be at least 30 bytes smaller than
1832        // the generic 64-bit shift sequence. (Empirically: 14 vs 50 bytes.)
1833        assert!(
1834            bytes_hi32 + 30 <= bytes_generic,
1835            "issue #94: hi32 extract = {} bytes, generic shift = {} bytes; \
1836             expected optimized form to be at least 30 bytes smaller",
1837            bytes_hi32,
1838            bytes_generic,
1839        );
1840    }
1841}