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            let func_config = match config.func_params_i64.get(func.index as usize) {
84                Some(p) if !p.is_empty() => Some(CompileConfig {
85                    current_func_params_i64: p.clone(),
86                    ..config.clone()
87                }),
88                _ => None,
89            };
90            let cfg = func_config.as_ref().unwrap_or(config);
91            let compiled = self.compile_function(&name, &func.ops, cfg)?;
92            functions.push(compiled);
93        }
94
95        Ok(CompilationResult {
96            functions,
97            elf: None,
98            backend_name: self.name().to_string(),
99        })
100    }
101
102    fn compile_function(
103        &self,
104        name: &str,
105        ops: &[WasmOp],
106        config: &CompileConfig,
107    ) -> Result<CompiledFunction, BackendError> {
108        let (code, relocations, line_map) =
109            compile_wasm_to_arm(ops, config).map_err(BackendError::CompilationFailed)?;
110
111        Ok(CompiledFunction {
112            name: name.to_string(),
113            code,
114            wasm_ops: ops.to_vec(),
115            relocations,
116            line_map,
117        })
118    }
119
120    fn is_available(&self) -> bool {
121        true // Always available — it's a library backend
122    }
123}
124
125/// Count the number of function parameters by analyzing LocalGet patterns
126fn count_params(wasm_ops: &[WasmOp]) -> u32 {
127    let mut first_access: std::collections::HashMap<u32, bool> = std::collections::HashMap::new();
128    for op in wasm_ops {
129        match op {
130            WasmOp::LocalGet(idx) => {
131                first_access.entry(*idx).or_insert(true);
132            }
133            WasmOp::LocalSet(idx) | WasmOp::LocalTee(idx) => {
134                first_access.entry(*idx).or_insert(false);
135            }
136            _ => {}
137        }
138    }
139
140    first_access
141        .iter()
142        .filter_map(
143            |(&idx, &is_read_first)| {
144                if is_read_first { Some(idx + 1) } else { None }
145            },
146        )
147        .max()
148        .unwrap_or(0)
149}
150
151/// Core compilation: WASM ops → ARM machine code bytes + relocations
152///
153/// Returns (code_bytes, relocations) where relocations record BL instructions
154/// that target external symbols (e.g., `__meld_dispatch_import` for import calls).
155fn compile_wasm_to_arm(
156    wasm_ops: &[WasmOp],
157    config: &CompileConfig,
158) -> Result<(Vec<u8>, Vec<CodeRelocation>, LineMap), String> {
159    let num_params = count_params(wasm_ops);
160
161    let bounds_config = match config.effective_safety_bounds() {
162        SafetyBounds::None => BoundsCheckConfig::None,
163        SafetyBounds::Mpu => BoundsCheckConfig::Mpu,
164        SafetyBounds::Software => BoundsCheckConfig::Software,
165        SafetyBounds::Mask => BoundsCheckConfig::Masking,
166    };
167
168    // The non-optimized (direct) instruction-selection path. Handles f32 via
169    // VFP/FPU. Used directly when `--no-optimize` is set, and as the fallback
170    // when the optimized path declines a module (see issue #120 below).
171    //
172    // VCR-RA-001 step 3b-lite (#242): a FRESH selector per attempt, with
173    // `spill_on_exhaustion` set only on the retry — the first pass is the
174    // unmodified default, so every function that compiles today is selected by
175    // exactly the code that compiled it yesterday (bit-identity is structural,
176    // not behavioural).
177    let select_direct_attempt = |spill_on_exhaustion: bool,
178                                 param_backing_on_exhaustion: bool,
179                                 local_promote: bool|
180     -> Result<Vec<ArmInstruction>, synth_core::Error> {
181        let db = RuleDatabase::with_standard_rules();
182        let mut selector =
183            InstructionSelector::with_bounds_check(db.rules().to_vec(), bounds_config);
184        selector.set_target(config.target.fpu, &config.target.triple);
185        if config.num_imports > 0 {
186            selector.set_num_imports(config.num_imports);
187        }
188        // #195: plumb the callee argument-count tables so the direct selector can
189        // marshal call arguments into R0–R3 per AAPCS.
190        selector.set_func_arg_counts(
191            config.func_arg_counts.clone(),
192            config.type_arg_counts.clone(),
193        );
194        // #197: in relocatable host-link mode, emit direct `func_N` BLs for
195        // imports (rewritten to the wasm field name by build_relocatable_elf)
196        // instead of `__meld_dispatch_import`.
197        selector.set_relocatable(config.relocatable);
198        // #237: native-pointer ABI — wasm statics become __synth_wasm_data-relative.
199        selector.set_native_pointer_abi(config.native_pointer_abi, config.linear_memory_bytes);
200        // #311: i64 call results are register PAIRS — tag them.
201        selector.set_result_types(config.func_ret_i64.clone(), config.type_ret_i64.clone());
202        // #359: declared param widths of THIS function, so the AAPCS stack-arg
203        // path can refuse 64-bit params (Ok-or-Err). Empty ⇒ assume i32.
204        selector.set_params_i64(config.current_func_params_i64.clone());
205        // Stack-pointer promotion is meaningful only under the native-pointer ABI;
206        // gating here keeps every non-native compile (all frozen fixtures) on the
207        // legacy R9 globals-table path, bit-identical.
208        if config.native_pointer_abi
209            && let Some((sp_idx, sp_init)) = config.stack_pointer_global
210        {
211            selector.set_native_pointer_stack(sp_idx, sp_init);
212        }
213        selector.set_spill_on_exhaustion(spill_on_exhaustion);
214        selector.set_param_backing_on_exhaustion(param_backing_on_exhaustion);
215        // VCR-RA local promotion (#390, #242): keep eligible non-param i32 locals
216        // in callee-saved registers instead of frame slots — the structural lever
217        // toward native parity. DEFAULT-ON as of v0.14.0: gale's G474RE DWT gate
218        // cleared it as a net win (gust_mix dissolved 58→50 cyc/call −14%, all 5
219        // stack spill/reloads eliminated, correctness bit-identical over [0,2047],
220        // 2.00×→1.72× vs LLVM). Escape hatch: `SYNTH_NO_LOCAL_PROMOTE=1` restores
221        // the frame-slot path. Leaf-only / i32-only / ARM-only (see
222        // compute_local_promotion); the leaf-only lift + i64 locals are follow-ons.
223        // #474: `local_promote` is now a per-attempt parameter so the retry ladder
224        // can drop promotion as an exhaustion-recovery rung (promotion pins r4-r8,
225        // which on a dense function leaves the spill allocator with nothing to
226        // free → the frame-slot path is the escape that restores compilability).
227        selector.set_local_promote(local_promote);
228        selector.select_with_stack(wasm_ops, num_params)
229    };
230    let select_direct = || -> Result<Vec<ArmInstruction>, String> {
231        const SINGLE_EXHAUSTION: &str = "all allocatable registers are live on the stack";
232        const PAIR_EXHAUSTION: &str = "no consecutive pair of free registers for i64";
233        // The full exhaustion-recovery ladder, parameterized on whether local
234        // promotion is enabled. Each rung is reached only when the previous one
235        // returned a recoverable register-exhaustion Err, so a function that
236        // compiles on the first attempt is untouched by the later rungs.
237        let recovery_ladder = |promote: bool| -> Result<Vec<ArmInstruction>, synth_core::Error> {
238            let mut attempt = select_direct_attempt(false, false, promote);
239            // VCR-RA-001 step 3b-lite (#242): the i32 register-exhaustion
240            // hard-fail is recoverable — retry with spill-on-exhaustion, which
241            // reserves the spill area and spills the deepest stack value when the
242            // pool is full.
243            if let Err(e) = &attempt
244                && e.to_string().contains(SINGLE_EXHAUSTION)
245            {
246                attempt = select_direct_attempt(true, false, promote);
247            }
248            // VCR-RA-001 acceptance increment (#242): the i64 consecutive-PAIR
249            // exhaustion is recoverable too — not by stack spilling (the pair
250            // allocator already spills stack values, #171) but by frame-backing
251            // the params (#204) so they stop pinning R0-R3, with spill kept on.
252            if let Err(e) = &attempt
253                && e.to_string().contains(PAIR_EXHAUSTION)
254            {
255                attempt = select_direct_attempt(true, true, promote);
256            }
257            attempt
258        };
259        // #474: local promotion (default-on since v0.14.0) is an OPTIMIZATION — it
260        // must never be the reason a function fails to compile. Run the full ladder
261        // with promotion first (so every function that compiles today is
262        // bit-identical), and if it still ends in register exhaustion, fall back to
263        // the promotion-off ladder (the v0.12.0 frame-slot lowering — exactly what
264        // the `SYNTH_NO_LOCAL_PROMOTE=1` workaround does, now automatic). Promotion
265        // pins r4-r8 for the locals; on a dense function that leaves the allocator
266        // with nothing to free, so dropping it restores compilability. The fallback
267        // is reached ONLY by functions that exhaust WITH promotion, so promotion-on
268        // output is untouched by construction (frozen byte gate stays green).
269        let promote = std::env::var("SYNTH_NO_LOCAL_PROMOTE").is_err();
270        let mut attempt = recovery_ladder(promote);
271        if promote
272            && let Err(e) = &attempt
273            && e.to_string().contains("register exhaustion")
274            && let Ok(rescued) = recovery_ladder(false)
275        {
276            attempt = Ok(rescued);
277        }
278        attempt.map_err(|e| format!("instruction selection failed: {}", e))
279    };
280
281    // Instruction selection: optimized or direct.
282    //
283    // #197: `--relocatable` (host-link ET_REL) forces the direct selector. The
284    // optimized path materializes an absolute linmem base (0x20000100) and does
285    // not preserve caller-saved registers across calls — both wrong for a
286    // host-linked object, where the linmem base arrives via `fp` at runtime and
287    // callees follow AAPCS. `select_with_stack` (now i64-spill capable after
288    // #171) handles fp-relative memory + caller-saved preservation correctly.
289    let arm_instrs = if config.no_optimize || config.relocatable {
290        select_direct()?
291    } else {
292        let opt_config = if config.loom_compat {
293            OptimizationConfig::loom_compat()
294        } else {
295            OptimizationConfig::all()
296        };
297
298        let mut bridge = OptimizerBridge::with_config(opt_config);
299        // #188: tell the bridge how many imports there are so it declines only
300        // LOCAL calls (and leaves import calls on the optimized path, keeping
301        // the #173 field-name relocation rewrite intact).
302        bridge.set_num_imports(config.num_imports);
303        // `ir_to_arm` now returns `Result` — an `Err` means the optimized path
304        // hit an unmapped vreg (issue-#93-class). Treat it identically to an
305        // `optimize_full` failure: fall back to the direct selector rather
306        // than propagating, so the function still compiles correctly.
307        match bridge
308            .optimize_full(wasm_ops)
309            .and_then(|(opt_ir, _cfg, _stats)| bridge.ir_to_arm(&opt_ir, num_params as usize))
310        {
311            Ok(arm_ops) => arm_ops
312                .into_iter()
313                .map(|op| ArmInstruction {
314                    op,
315                    source_line: None,
316                })
317                .collect(),
318            // Issue #120: the optimized path declines modules it cannot lower
319            // (notably scalar f32/f64 ops — the IR has no float opcodes). Fall
320            // back to the direct instruction selector, which handles f32 via
321            // VFP/FPU. This is honest degradation: the function still compiles
322            // correctly, just without IR-level optimization.
323            Err(_) => select_direct()?,
324        }
325    };
326
327    // #257/#277: `mul`+`add`→`mla` fusion is intentionally NOT wired here.
328    // The transform is correct and ready (`synth_synthesis::liveness::fuse_mul_add`,
329    // fully tested), but it is **register-allocation-coupled**: over the current
330    // greedy single-pass selector, folding `mul rM,..; add rD,rM,rX` → `mla`
331    // extends the live ranges of the mul inputs to the mla point, and the added
332    // pressure (extra moves/spills) costs more than the single-cycle MLA saves —
333    // gale measured a +2 cyc on-target REGRESSION (flat_flight 255→257, G474RE)
334    // even though it removes 2 instructions and the seam stays 0x07FDF307. So the
335    // fusion stays unwired until the spill-aware allocator (VCR-RA-001) chooses
336    // registers, at which point it becomes net-positive (per #272's plan and the
337    // wiring design note). Lesson (#277): a register-pressure-affecting transform
338    // needs an on-target/allocator-aware gate, not a byte-count gate, before it
339    // can default on.
340
341    // VCR-RA-001 const-CSE / rematerialization-avoidance (#209), the first
342    // allocator-analysis-driven CODEGEN change. Drops `movw` re-materializations
343    // of a constant already resident in another register and retargets the reads
344    // — every rewrite proven by the liveness analysis, and it ONLY removes
345    // materializations (pressure never rises), so unlike the mla fusion (#277) it
346    // cannot regress on-target. Runs on the selected stream before branch
347    // resolution (it removes instructions, shifting byte offsets). Behind
348    // `SYNTH_CONST_CSE=1` while it is validated against the differential oracle +
349    // gale's five on-target baselines; off by default keeps every fixture
350    // bit-identical.
351    let arm_instrs = if std::env::var("SYNTH_CONST_CSE").is_ok() {
352        synth_synthesis::liveness::apply_const_cse(&arm_instrs).0
353    } else {
354        arm_instrs
355    };
356
357    // VCR-RA-001 RANGE RE-ALLOCATION (#209/#242, wiring step 3a) — the first
358    // CONSEQUENTIAL allocator pass: re-colour each maximal straight-line
359    // segment over the R0-R8 pool with value ranges as the allocation unit
360    // (segment inputs + per-register live-outs pinned to their original
361    // registers, reserved R9-R12/SP identity-assigned — each segment is
362    // independently sound, no cross-segment liveness assumed). Renames
363    // registers only: never adds, removes, or reorders instructions, so
364    // labels/branch offsets are unaffected.
365    //
366    // DEFAULT-ON since v0.11.36: gale cleared the gate on-target (G474RE,
367    // #209 2026-06-10) — flag-on output byte-identical to flag-off on
368    // flat_flight/controller/control_step, fires on the filter family with
369    // zero cycle delta and a small size win, all selfchecks green on silicon.
370    // Opt out with `SYNTH_RANGE_REALLOC=0`; per-function stats with
371    // `SYNTH_REALLOC_STATS=1`.
372    //
373    // The companion dead callee-saved-save elimination (gale's "next
374    // consequential lever", same issue comment) then shrinks the prologue
375    // `push {r4-r8,lr}` / epilogue `pop {r4-r8,pc}` to the callee-saved
376    // registers the re-allocated body still touches (leaf-only,
377    // SP-untouched, even-count-padded — see shrink_callee_saved_saves):
378    // ~12 cycles of pure save/restore overhead removed on small leaves.
379    let realloc_on = std::env::var("SYNTH_RANGE_REALLOC").map_or(true, |v| v != "0");
380    let arm_instrs = if realloc_on {
381        use synth_synthesis::rules::Reg;
382        const POOL: [Reg; 9] = [
383            Reg::R0,
384            Reg::R1,
385            Reg::R2,
386            Reg::R3,
387            Reg::R4,
388            Reg::R5,
389            Reg::R6,
390            Reg::R7,
391            Reg::R8,
392        ];
393        let (out, stats) = synth_synthesis::liveness::reallocate_function(&arm_instrs, &POOL);
394        if std::env::var("SYNTH_REALLOC_STATS").is_ok() {
395            eprintln!(
396                "[range-realloc] {} segments: {} reallocated, {} declined ({} validator-rejected), {} need spill (step 4)",
397                stats.segments,
398                stats.reallocated,
399                stats.declined,
400                stats.validator_rejects,
401                stats.needs_spill
402            );
403        }
404        synth_synthesis::liveness::shrink_callee_saved_saves(&out).unwrap_or(out)
405    } else {
406        arm_instrs
407    };
408
409    // VCR-RA-001 SHADOW ALLOCATION (#209/#242): run the register allocator on
410    // the selected stream and LOG what it finds — without changing a single
411    // emitted byte. This is the measure-only bridge between the built analysis
412    // layer and the eventual virtual-register wiring: it shows, per real
413    // function, whether the allocator can colour it within the R0–R8 pool and
414    // how much const-CSE / rematerialization headroom exists (#209). Enable with
415    // `SYNTH_SHADOW_ALLOC=1`; off by default and side-effect-free either way.
416    if std::env::var("SYNTH_SHADOW_ALLOC").is_ok() {
417        use synth_synthesis::liveness::{
418            AllocationOutcome, allocate_function, function_peak_pressure,
419        };
420        // R9 globals / R10 mem-size / R11 mem-base / R12 IP-scratch are reserved;
421        // pin them above the 0..9 allocatable pool so the colourer keeps R0–R8.
422        let precolored = std::collections::BTreeMap::from([
423            (synth_synthesis::rules::Reg::R9, 9usize),
424            (synth_synthesis::rules::Reg::R10, 10),
425            (synth_synthesis::rules::Reg::R11, 11),
426            (synth_synthesis::rules::Reg::R12, 12),
427        ]);
428        // True VALUE pressure (one node per value, not per reused physical reg):
429        // a NeedsSpill with peak ≤ 9 is a SPURIOUS physical-register spill — the
430        // function fits once virtually allocated.
431        let peak = function_peak_pressure(&arm_instrs);
432        match allocate_function(&arm_instrs, 9, &precolored) {
433            AllocationOutcome::Allocated {
434                remat_opportunities,
435                coloring,
436            } => eprintln!(
437                "[shadow-alloc] OK: {} pregs coloured within R0-R8 pool, peak value-pressure {}, {} const-CSE/remat opportunities",
438                coloring.len(),
439                peak,
440                remat_opportunities
441            ),
442            AllocationOutcome::NeedsSpill(s) => eprintln!(
443                "[shadow-alloc] physical-graph would spill {:?}, but peak value-pressure is {} (≤9 ⇒ spurious; fits once virtually allocated)",
444                s, peak
445            ),
446            AllocationOutcome::Declined => {
447                eprintln!(
448                    "[shadow-alloc] declined (unmodeled construct — calls/i64/fp/offset-branch)"
449                )
450            }
451        }
452    }
453
454    // VCR-SEL-004 cmp→select → IT-block predication fusion (#242). The selector
455    // lowers a `select` whose condition is a comparison to a *materialize then
456    // re-test* sequence (`cmp a,b; SetCond D,c; cmp D,#0; movne dst,v1; moveq
457    // dst,v2`); this collapses it onto the comparison's own flags — deleting the
458    // `SetCond` and the `cmp D,#0` and retargeting the predicated moves to `c` /
459    // `invert(c)` — yielding the textbook predicated clamp (`cmp a,b; movc dst,v1;
460    // mov{!c} dst,v2`). −2 instructions per fused select. gale #428 measured this
461    // as the #1 hot-path size/cycle lever on the gust_mix clamp chain.
462    //
463    // Run LATE: after range re-allocation (so the dead-D proof sees final register
464    // identities) and before encode. Removal-only + rename-only ⇒ no spill
465    // regression and labels/branch offsets are unaffected. Each fusion is proven
466    // sound (flags reused only when nothing clobbers them in the window; the
467    // boolean deleted only when provably dead) — see `fuse_cmp_select`.
468    //
469    // DEFAULT-ON as of v0.13.0 (#428): cmp→select fusion ships by default. The
470    // byte-changing flip is validated by (a) the unicorn execution oracle that runs
471    // the two-move `mov{invert(c)}` arm (cmp_select_two_move_differential.py), (b)
472    // gale's gale_decider_diff 10,596-case sweep across all 8 verified primitives
473    // (native ≡ flag-off ≡ flag-on = 0x88e73178d232bcf5), and (c) the named-anchor
474    // differentials re-run with fusion ON — control_step still 0x00210A55, flat+
475    // inlined flight_algo still 0x07FDF307 (results preserved; bytes deliberately
476    // changed, re-frozen on this commit). Escape hatch: `SYNTH_NO_CMP_SELECT_FUSE=1`
477    // reverts to the pre-fusion lowering. The on-silicon G474RE DWT no-regression
478    // check is a tracked post-ship follow-up (gale owns it).
479    let arm_instrs = if std::env::var("SYNTH_NO_CMP_SELECT_FUSE").is_err() {
480        // The rewritten stream is identical to `fuse_cmp_select`'s 2-tuple form;
481        // the extra `two_move` count is diagnostic only (the fusion census /
482        // blast-radius datum — #7 made that arm reachable).
483        let (out, fused, two_move) =
484            synth_synthesis::liveness::fuse_cmp_select_with_stats(&arm_instrs);
485        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
486            let in_place = fused - two_move;
487            eprintln!(
488                "[cmp-select-fuse] {fused} select(s) fused to predicated moves \
489                 ({two_move} two-move, {in_place} in-place)"
490            );
491        }
492        out
493    } else {
494        arm_instrs
495    };
496
497    // Perf lever 1 toward native parity (#390): redundant stack-reload elimination.
498    // synth lowers every wasm local to a frame slot, so `local.set; local.get` emits
499    // `str rX,[sp,#N]; … ; ldr rY,[sp,#N]`; when rX still holds the value the reload
500    // (a ~2-cycle M4 load) becomes `mov rY,rX`. Removal-of-a-load + rename only ⇒ no
501    // new instruction form and no label/offset change. BEHIND `SYNTH_STACK_FWD=1`
502    // (opt-in, off by default ⇒ bit-identical) while it is validated against the
503    // execution differential + gale's G474RE bench — the same gated path the
504    // cmp→select flip took before shipping default-on in v0.13.0.
505    let arm_instrs = if std::env::var("SYNTH_STACK_FWD").is_ok() {
506        let (out, fwd) = synth_synthesis::liveness::forward_stack_reloads(&arm_instrs);
507        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
508            eprintln!("[stack-fwd] {fwd} stack reload(s) forwarded to register moves");
509        }
510        out
511    } else {
512        arm_instrs
513    };
514
515    // VCR-RA immediate-shift folding (#390, #242): a constant shift amount the
516    // stack selector materialized into a scratch register (`movw rM,#C; lsl rD,rN,rM`)
517    // folds to the immediate form (`lsl rD,rN,#C`), removing the dead `movw` — −1
518    // instruction, −1 live register. Removal-only (offset-neutral before branch
519    // resolution, like the dead-store pass). DEFAULT-ON as of v0.15.0: validated
520    // bit-identical results + a net cycle win on the dissolved hot path (−2
521    // cyc/call, .text 100→90 B on gust_mix). Escape hatch: `SYNTH_NO_IMM_SHIFT_FOLD=1`.
522    let arm_instrs = if std::env::var("SYNTH_NO_IMM_SHIFT_FOLD").is_err() {
523        let (out, folds) = synth_synthesis::liveness::fold_immediate_shifts(&arm_instrs);
524        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
525            eprintln!(
526                "[imm-shift-fold] {folds} register shift(s) folded to immediate, movw dropped"
527            );
528        }
529        out
530    } else {
531        arm_instrs
532    };
533
534    // ISA feature gate: validate that all generated instructions are supported
535    // by the target. This catches FPU instructions on no-FPU targets, double-precision
536    // instructions on single-precision targets, etc.
537    validate_instructions(&arm_instrs, config.target.fpu, &config.target.triple)
538        .map_err(|e| format!("ISA validation failed: {}", e))?;
539
540    // Encode to binary — use Thumb-2 for Cortex-M targets
541    let use_thumb2 = matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
542
543    let encoder = if use_thumb2 {
544        ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
545    } else {
546        ArmEncoder::new_arm32()
547    };
548
549    // #202: resolve local label branches (Bcc/B/Bhs/Blo) to byte-accurate
550    // offsets before encoding. `select_with_stack` emits them as label
551    // placeholders and never resolves them — without this they encode as
552    // `bne.n #0` and land mid-instruction whenever a 32-bit Thumb-2 instruction
553    // sits between the branch and its target (UsageFault on real hardware).
554    // Only meaningful for Thumb-2 (the offset units are halfword/PC+4).
555    let arm_instrs = if use_thumb2 {
556        resolve_label_branches(arm_instrs, &encoder)?
557    } else {
558        arm_instrs
559    };
560
561    let mut code = Vec::new();
562    let mut relocations = Vec::new();
563
564    // #345: literal-pool address loads. Each `LdrSym` was encoded as a placeholder
565    // `LDR.W rd,[pc,#0]`; record where its instruction sits and what it loads so
566    // we can append a pooled word (carrying the symbol address via R_ARM_ABS32)
567    // and patch the PC-relative offset once the pool position is known.
568    struct PendingLiteral {
569        ldr_offset: u32,
570        symbol: String,
571        addend: i32,
572    }
573    let mut pending_literals: Vec<PendingLiteral> = Vec::new();
574
575    // VCR-DBG-001: per-instruction source map for DWARF `.debug_line`. Captured
576    // here because `code.len()` immediately before `encode()` is the final
577    // machine offset of the instruction within this function's `.text` — nothing
578    // after the loop shifts earlier instructions (the literal pool is appended at
579    // the end; the LDR patch below is in-place/length-preserving). Purely
580    // additive: it does not touch `code`, so `.text` is byte-identical.
581    let mut line_map: LineMap = Vec::new();
582
583    for instr in &arm_instrs {
584        // Record a relocation for every BL: the encoder emits `bl #0` and
585        // relies on a relocation to patch the target. This covers BOTH import
586        // dispatch stubs (`__meld_*`, undefined externals) AND internal calls
587        // (`func_N`, defined in this object). Previously only `__meld_*` was
588        // recorded, so internal `BL func_N` calls were left as unpatched
589        // `bl #0` placeholders branching to a garbage address (#167).
590        if let ArmOp::Bl { label } = &instr.op {
591            relocations.push(CodeRelocation {
592                offset: code.len() as u32,
593                symbol: label.clone(),
594                kind: synth_core::backend::RelocKind::ThmCall,
595            });
596        }
597        // #237: symbol-relative MOVW/MOVT (the `--native-pointer-abi` static-data
598        // addressing). The encoder writes the addend in place; record the matching
599        // R_ARM_MOVW_ABS_NC / R_ARM_MOVT_ABS so the linker adds the symbol address.
600        if let ArmOp::MovwSym { symbol, .. } = &instr.op {
601            relocations.push(CodeRelocation {
602                offset: code.len() as u32,
603                symbol: symbol.clone(),
604                kind: synth_core::backend::RelocKind::MovwAbs,
605            });
606        }
607        if let ArmOp::MovtSym { symbol, .. } = &instr.op {
608            relocations.push(CodeRelocation {
609                offset: code.len() as u32,
610                symbol: symbol.clone(),
611                kind: synth_core::backend::RelocKind::MovtAbs,
612            });
613        }
614        // #345: defer the literal-pool word + reloc + offset patch to the
615        // post-loop pass (the pool address is not yet known).
616        if let ArmOp::LdrSym { symbol, addend, .. } = &instr.op {
617            pending_literals.push(PendingLiteral {
618                ldr_offset: code.len() as u32,
619                symbol: symbol.clone(),
620                addend: *addend,
621            });
622        }
623
624        // The machine offset of this instruction is the current code length,
625        // captured before the bytes are appended.
626        line_map.push((code.len() as u32, instr.source_line));
627
628        let encoded = encoder
629            .encode(&instr.op)
630            .map_err(|e| format!("ARM encoding failed: {}", e))?;
631        code.extend_from_slice(&encoded);
632    }
633
634    // #345: place the literal pool at the end of this function's `.text`. Gated on
635    // there being at least one `LdrSym` — functions without one are byte-identical
636    // to before (no trailing padding, so downstream `func_offsets` are unchanged
637    // and the frozen differential fixtures stay bit-for-bit equal).
638    if !pending_literals.is_empty() {
639        if !use_thumb2 {
640            return Err("LdrSym literal-pool addressing requires Thumb-2".to_string());
641        }
642        // 4-byte align the pool start (Thumb-2 word loads require it, and
643        // `Align(PC,4)` in the LDR-literal semantics assumes a word-aligned pool).
644        while code.len() % 4 != 0 {
645            code.push(0x00);
646        }
647        // One distinct pooled word per LdrSym (no dedup: different sites carry
648        // different addends, and the REL addend lives in the word).
649        for lit in &pending_literals {
650            let word_offset = code.len() as u32;
651
652            // REL semantics: the linker computes `S + A`, where A is the in-place
653            // value of the relocated word. Initialize the word to the addend so
654            // the final loaded address is `symbol + addend`.
655            code.extend_from_slice(&(lit.addend as u32).to_le_bytes());
656            relocations.push(CodeRelocation {
657                offset: word_offset,
658                symbol: lit.symbol.clone(),
659                kind: synth_core::backend::RelocKind::Abs32,
660            });
661
662            // Patch the placeholder `LDR.W rd,[pc,#imm12]`. Thumb-2 LDR (literal):
663            // address = Align(PC,4) + imm12, with PC = ldr_offset + 4. The pool is
664            // always after the LDR, so U=1 (already set in hw1 = 0xF8DF).
665            let pc = lit.ldr_offset + 4;
666            let aligned_pc = pc & !3u32;
667            let imm12 = word_offset - aligned_pc;
668            if imm12 > 0xFFF {
669                // Wide LDR-literal range is ±4 KB; these function bodies are far
670                // smaller, but fail cleanly rather than miscompile if exceeded.
671                return Err(format!(
672                    "LdrSym literal pool out of range (#345): imm12={} > 4095 \
673                     for symbol {}",
674                    imm12, lit.symbol
675                ));
676            }
677            let hw2_off = (lit.ldr_offset + 2) as usize;
678            let mut hw2 = u16::from_le_bytes([code[hw2_off], code[hw2_off + 1]]);
679            hw2 = (hw2 & 0xF000) | (imm12 as u16); // keep Rt, set imm12
680            let hw2_bytes = hw2.to_le_bytes();
681            code[hw2_off] = hw2_bytes[0];
682            code[hw2_off + 1] = hw2_bytes[1];
683        }
684    }
685
686    Ok((code, relocations, line_map))
687}
688
689/// Resolve local label branches to byte-accurate offsets (#202).
690///
691/// `select_with_stack` emits conditional/unconditional branches as label
692/// placeholders (`Bcc`/`B`/`Bhs`/`Blo` + `Label`) and never resolves them; the
693/// encoder then emits a `0xD000`/`0xE000` placeholder with offset 0. Before #197
694/// this path only ran for `--no-optimize`/declined functions, so the latent bug
695/// stayed hidden — routing relocatable code through it surfaced branches that
696/// land mid-instruction (a Cortex-M UsageFault) whenever a 32-bit Thumb-2
697/// instruction sits between the branch and its target.
698///
699/// This pass encodes each instruction to learn its real byte length (so 16- vs
700/// 32-bit forms and multi-instruction expansions are exact), maps each `Label`
701/// to its byte position, and rewrites every label branch to the displacement
702/// the encoder consumes: `(target - branch - 4) / 2` halfwords. A bounded
703/// fixed-point handles an offset growing a branch from 16- to 32-bit (which
704/// shifts later positions). `BCondOffset`/`BOffset` already produced inline by
705/// the optimized path carry no label and are left untouched.
706fn resolve_label_branches(
707    arm_instrs: Vec<ArmInstruction>,
708    encoder: &ArmEncoder,
709) -> Result<Vec<ArmInstruction>, String> {
710    use std::collections::HashMap;
711    use synth_synthesis::Condition;
712
713    enum BKind {
714        Cond(Condition),
715        Uncond,
716    }
717    // Record each label branch ONCE — indices are stable across iterations.
718    let mut branches: Vec<(usize, BKind, String)> = Vec::new();
719    for (i, instr) in arm_instrs.iter().enumerate() {
720        match &instr.op {
721            ArmOp::Bcc { cond, label } => branches.push((i, BKind::Cond(*cond), label.clone())),
722            ArmOp::Bhs { label } => branches.push((i, BKind::Cond(Condition::HS), label.clone())),
723            ArmOp::Blo { label } => branches.push((i, BKind::Cond(Condition::LO), label.clone())),
724            ArmOp::B { label } => branches.push((i, BKind::Uncond, label.clone())),
725            _ => {}
726        }
727    }
728    if branches.is_empty() {
729        return Ok(arm_instrs);
730    }
731
732    let mut resolved = arm_instrs;
733    // Sizes only grow (16→32-bit), so this converges quickly; cap for safety.
734    for _ in 0..16 {
735        // 1. Byte position of each instruction (Label encodes to 0 bytes).
736        let mut positions = Vec::with_capacity(resolved.len());
737        let mut pos: i64 = 0;
738        for instr in &resolved {
739            positions.push(pos);
740            pos += encoder
741                .encode(&instr.op)
742                .map_err(|e| format!("branch-resolve size probe failed: {}", e))?
743                .len() as i64;
744        }
745        // 2. Label name -> byte position (owned keys so the borrow ends here).
746        let mut labels: HashMap<String, i64> = HashMap::new();
747        for (i, instr) in resolved.iter().enumerate() {
748            if let ArmOp::Label { name } = &instr.op {
749                labels.insert(name.clone(), positions[i]);
750            }
751        }
752        // 3. Rewrite each branch to its byte-accurate offset.
753        let mut changed = false;
754        for (idx, kind, label) in &branches {
755            // A label not defined locally is an EXTERNAL target (e.g.
756            // `Trap_Handler` resolved by a relocation / the vector table). Leave
757            // such branches as their placeholder for the existing relocation
758            // path — only local control-flow labels are byte-resolved here.
759            let Some(&target) = labels.get(label) else {
760                continue;
761            };
762            // Encoder consumes the field as (target - branch - 4) / 2 halfwords.
763            // Positions are always even, so this division is exact.
764            let halfword_offset = ((target - positions[*idx] - 4) / 2) as i32;
765            let new_op = match kind {
766                BKind::Cond(c) => ArmOp::BCondOffset {
767                    cond: *c,
768                    offset: halfword_offset,
769                },
770                BKind::Uncond => ArmOp::BOffset {
771                    offset: halfword_offset,
772                },
773            };
774            if resolved[*idx].op != new_op {
775                resolved[*idx].op = new_op;
776                changed = true;
777            }
778        }
779        if !changed {
780            break;
781        }
782    }
783    Ok(resolved)
784}
785
786#[cfg(test)]
787mod tests {
788    use super::*;
789
790    #[test]
791    fn test_arm_backend_name() {
792        let backend = ArmBackend::new();
793        assert_eq!(backend.name(), "arm");
794        assert!(backend.is_available());
795    }
796
797    #[test]
798    fn test_arm_backend_capabilities() {
799        let backend = ArmBackend::new();
800        let caps = backend.capabilities();
801        assert!(!caps.produces_elf);
802        assert!(caps.supports_rule_verification);
803        assert!(!caps.is_external);
804    }
805
806    #[test]
807    fn test_compile_add_function() {
808        let backend = ArmBackend::new();
809        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
810        let config = CompileConfig::default();
811
812        let result = backend.compile_function("add", &ops, &config);
813        assert!(result.is_ok());
814
815        let func = result.unwrap();
816        assert_eq!(func.name, "add");
817        assert!(!func.code.is_empty());
818        assert_eq!(func.wasm_ops, ops);
819    }
820
821    /// VCR-DBG-001: the per-instruction source map must cover the function with
822    /// monotonic, in-bounds machine offsets, and must not perturb the emitted
823    /// code (it is captured at encode time, never serialized here).
824    #[test]
825    fn test_line_map_is_wellformed_dbg001() {
826        let backend = ArmBackend::new();
827        let ops = vec![
828            WasmOp::LocalGet(0),
829            WasmOp::LocalGet(1),
830            WasmOp::I32Add,
831            WasmOp::End,
832        ];
833        let config = CompileConfig::default();
834        let func = backend.compile_function("add", &ops, &config).unwrap();
835
836        // Non-empty, and the first instruction starts at machine offset 0.
837        assert!(
838            !func.line_map.is_empty(),
839            "a non-trivial function captures a source map"
840        );
841        assert_eq!(func.line_map[0].0, 0, "first instruction at offset 0");
842
843        // Offsets strictly increase by at least one ARM/Thumb instruction (>= 2
844        // bytes) and every mapped offset lies inside the emitted `.text`.
845        for w in func.line_map.windows(2) {
846            assert!(w[1].0 > w[0].0, "instruction offsets strictly increase");
847            assert!(
848                w[1].0 - w[0].0 >= 2,
849                "each ARM/Thumb instruction is >= 2 bytes"
850            );
851        }
852        let last = func.line_map.last().unwrap().0 as usize;
853        assert!(
854            last < func.code.len(),
855            "every mapped offset lies inside .text"
856        );
857
858        // The side-table is additive: recompiling is deterministic and the map is
859        // consistent with that exact code (capturing it does not alter output).
860        let again = backend.compile_function("add", &ops, &config).unwrap();
861        assert_eq!(
862            again.code, func.code,
863            "compilation deterministic; map is additive"
864        );
865        assert_eq!(again.line_map, func.line_map);
866    }
867
868    #[test]
869    fn test_count_params() {
870        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
871        assert_eq!(count_params(&ops), 2);
872
873        let no_params = vec![WasmOp::I32Const(5), WasmOp::I32Const(3), WasmOp::I32Add];
874        assert_eq!(count_params(&no_params), 0);
875    }
876
877    #[test]
878    fn test_arm_backend_register() {
879        let mut registry = synth_core::BackendRegistry::new();
880        registry.register(Box::new(ArmBackend::new()));
881        assert!(registry.get("arm").is_some());
882        assert_eq!(registry.available().len(), 1);
883    }
884
885    #[test]
886    fn test_compile_import_call_produces_relocations() {
887        let backend = ArmBackend::new();
888        // Simulate a WASM module where func index 0 is an import.
889        // Call(0) should generate MOV R0, #0; BL __meld_dispatch_import
890        let ops = vec![WasmOp::Call(0)];
891        let config = CompileConfig {
892            num_imports: 1,
893            no_optimize: true, // Direct instruction selection to preserve Call semantics
894            ..CompileConfig::default()
895        };
896
897        let result = backend.compile_function("caller", &ops, &config);
898        assert!(result.is_ok());
899
900        let func = result.unwrap();
901        assert!(!func.code.is_empty());
902        assert_eq!(func.relocations.len(), 1);
903        assert_eq!(func.relocations[0].symbol, "__meld_dispatch_import");
904        // The BL is the second instruction (after MOV R0, #0), so offset should be > 0
905        assert!(func.relocations[0].offset > 0);
906    }
907
908    /// Regression test for #197: in `relocatable` mode, an import call must
909    /// relocate against the direct `func_N` symbol (rewritten to the wasm field
910    /// name by `build_relocatable_elf`), NOT `__meld_dispatch_import`. This is
911    /// the ABI half of the #197 fix — without it, a host linker cannot resolve
912    /// the call to the real kernel symbol (e.g. `k_spin_lock`).
913    #[test]
914    fn test_compile_relocatable_import_uses_direct_func_symbol_197() {
915        let backend = ArmBackend::new();
916        let ops = vec![WasmOp::Call(0)]; // func 0 is an import
917        let config = CompileConfig {
918            num_imports: 1,
919            relocatable: true,
920            ..CompileConfig::default()
921        };
922
923        let func = backend
924            .compile_function("caller", &ops, &config)
925            .expect("relocatable import call compiles");
926
927        assert_eq!(func.relocations.len(), 1);
928        assert_eq!(
929            func.relocations[0].symbol, "func_0",
930            "#197: relocatable import must relocate against func_0 (→ field name), not Meld dispatch"
931        );
932    }
933
934    #[test]
935    fn test_compile_no_imports_no_relocations() {
936        let backend = ArmBackend::new();
937        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
938        let config = CompileConfig::default();
939
940        let func = backend.compile_function("add", &ops, &config).unwrap();
941        assert!(func.relocations.is_empty());
942    }
943
944    /// Regression test for #167: a call to an INTERNAL function
945    /// (index `>= num_imports`) must record a relocation against `func_{index}`.
946    /// Before the fix, only `__meld_*` (import) BLs were relocated, so
947    /// internal `BL func_N` was emitted as an unpatched `bl #0` branching
948    /// to a garbage address — making the object non-linkable. This test
949    /// would have caught that regression.
950    #[test]
951    fn test_compile_internal_call_produces_relocation_167() {
952        let backend = ArmBackend::new();
953        // num_imports = 1, so Call(2) is an INTERNAL call → `BL func_2`.
954        let ops = vec![WasmOp::Call(2)];
955        let config = CompileConfig {
956            num_imports: 1,
957            no_optimize: true,
958            ..CompileConfig::default()
959        };
960
961        let func = backend
962            .compile_function("caller", &ops, &config)
963            .expect("internal call compiles");
964
965        assert_eq!(
966            func.relocations.len(),
967            1,
968            "an internal call must emit exactly one relocation (#167)"
969        );
970        assert_eq!(
971            func.relocations[0].symbol, "func_2",
972            "internal call must relocate against the callee's func_{{index}} symbol (#167)"
973        );
974    }
975
976    // ─── Phase 1 safety-bounds plumbing for ARM ──────────────────────────
977
978    #[test]
979    fn arm_safety_bounds_mpu_emits_same_code_as_none() {
980        // Mpu mode must not introduce any inline check on ARM — the MPU
981        // handles faults via hardware. The encoded bytes for an i32.load
982        // should be identical between None and Mpu.
983        let backend = ArmBackend::new();
984        let ops = vec![
985            WasmOp::LocalGet(0),
986            WasmOp::I32Load {
987                offset: 0,
988                align: 2,
989            },
990        ];
991        let cfg_none = CompileConfig {
992            no_optimize: true,
993            ..Default::default()
994        };
995        let cfg_mpu = CompileConfig {
996            no_optimize: true,
997            safety_bounds: SafetyBounds::Mpu,
998            ..Default::default()
999        };
1000        let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
1001        let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
1002        assert_eq!(
1003            n.code, m.code,
1004            "Mpu and None should produce identical ARM bytes (Mpu relies on hardware)"
1005        );
1006    }
1007
1008    #[test]
1009    fn arm_legacy_bounds_check_still_emits_software_check() {
1010        // Legacy CLI users with `--bounds-check` should keep getting the
1011        // software path even though the new SafetyBounds field defaults to None.
1012        let backend = ArmBackend::new();
1013        let ops = vec![
1014            WasmOp::LocalGet(0),
1015            WasmOp::I32Load {
1016                offset: 0,
1017                align: 2,
1018            },
1019        ];
1020        let cfg_legacy = CompileConfig {
1021            no_optimize: true,
1022            bounds_check: true,
1023            ..Default::default()
1024        };
1025        let cfg_software = CompileConfig {
1026            no_optimize: true,
1027            safety_bounds: SafetyBounds::Software,
1028            ..Default::default()
1029        };
1030        let l = backend.compile_function("ld", &ops, &cfg_legacy).unwrap();
1031        let s = backend.compile_function("ld", &ops, &cfg_software).unwrap();
1032        assert_eq!(
1033            l.code, s.code,
1034            "--bounds-check should produce the same bytes as --safety-bounds=software"
1035        );
1036    }
1037
1038    // ========================================================================
1039    // ISA feature gate tests — ensure the compiler never emits unsupported
1040    // instructions for a given target
1041    // ========================================================================
1042
1043    #[test]
1044    fn test_f32_rejected_on_cortex_m3_no_fpu() {
1045        let backend = ArmBackend::new();
1046        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
1047        let config = CompileConfig {
1048            target: TargetSpec::cortex_m3(),
1049            no_optimize: true,
1050            ..CompileConfig::default()
1051        };
1052
1053        let result = backend.compile_function("fadd", &ops, &config);
1054        assert!(
1055            result.is_err(),
1056            "f32 operations should fail on Cortex-M3 (no FPU)"
1057        );
1058    }
1059
1060    #[test]
1061    fn test_f32_accepted_on_cortex_m4f() {
1062        let backend = ArmBackend::new();
1063        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
1064        let config = CompileConfig {
1065            target: TargetSpec::cortex_m4f(),
1066            no_optimize: true,
1067            ..CompileConfig::default()
1068        };
1069
1070        let result = backend.compile_function("fadd", &ops, &config);
1071        assert!(
1072            result.is_ok(),
1073            "f32 operations should succeed on Cortex-M4F, got: {:?}",
1074            result.unwrap_err()
1075        );
1076    }
1077
1078    #[test]
1079    fn test_i32_works_on_all_targets() {
1080        let backend = ArmBackend::new();
1081        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
1082
1083        // Cortex-M3 (no FPU)
1084        let config_m3 = CompileConfig {
1085            target: TargetSpec::cortex_m3(),
1086            no_optimize: true,
1087            ..CompileConfig::default()
1088        };
1089        assert!(
1090            backend.compile_function("add", &ops, &config_m3).is_ok(),
1091            "i32 ops should work on Cortex-M3"
1092        );
1093
1094        // Cortex-M4F (single FPU)
1095        let config_m4f = CompileConfig {
1096            target: TargetSpec::cortex_m4f(),
1097            no_optimize: true,
1098            ..CompileConfig::default()
1099        };
1100        assert!(
1101            backend.compile_function("add", &ops, &config_m4f).is_ok(),
1102            "i32 ops should work on Cortex-M4F"
1103        );
1104
1105        // Cortex-M7DP (double FPU)
1106        let config_m7dp = CompileConfig {
1107            target: TargetSpec::cortex_m7dp(),
1108            no_optimize: true,
1109            ..CompileConfig::default()
1110        };
1111        assert!(
1112            backend.compile_function("add", &ops, &config_m7dp).is_ok(),
1113            "i32 ops should work on Cortex-M7DP"
1114        );
1115    }
1116
1117    #[test]
1118    fn test_f32_rejected_on_cortex_m4_no_fpu() {
1119        // Cortex-M4 (without F suffix) has no FPU
1120        let backend = ArmBackend::new();
1121        let ops = vec![WasmOp::F32Const(1.5), WasmOp::F32Const(2.5), WasmOp::F32Mul];
1122        let config = CompileConfig {
1123            target: TargetSpec::cortex_m4(),
1124            no_optimize: true,
1125            ..CompileConfig::default()
1126        };
1127
1128        let result = backend.compile_function("fmul", &ops, &config);
1129        assert!(
1130            result.is_err(),
1131            "f32 operations should fail on Cortex-M4 (no FPU)"
1132        );
1133    }
1134
1135    // ========================================================================
1136    // Issue #120 — f32 ops in the optimized lowering path
1137    //
1138    // `OptimizerBridge::wasm_to_ir` has no handlers for f32/f64 ops, so a
1139    // value-producing float op fell through to `Opcode::Nop`, leaving a
1140    // downstream consumer with an unmapped vreg and tripping the PR #101
1141    // defensive panic in `ir_to_arm`. Customer reproducer: `compiler_builtins
1142    // float::div` and `gale_compute_ipi_mask` in the `falcon-rate-component`
1143    // module.
1144    //
1145    // Fix: `optimize_full` declines float modules with a typed `Err`;
1146    // `compile_wasm_to_arm` falls back to the non-optimized `select_with_stack`
1147    // path, which handles f32 via VFP/FPU. These tests use the *default*
1148    // (optimized) config — `no_optimize` is NOT set — which is the exact
1149    // configuration that panicked pre-fix.
1150    // ========================================================================
1151
1152    /// Pre-fix: this panicked with "vreg vN has no assigned ARM register and
1153    /// no spill slot" inside `ir_to_arm`. Post-fix: the optimized path declines
1154    /// the module and the backend falls back to direct selection, producing a
1155    /// non-empty f32.div lowering on a Cortex-M4F.
1156    #[test]
1157    fn test_issue120_f32_div_compiles_via_optimized_default() {
1158        let backend = ArmBackend::new();
1159        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
1160        let config = CompileConfig {
1161            target: TargetSpec::cortex_m4f(),
1162            // no_optimize NOT set — this exercises the optimized path that
1163            // panicked in issue #120, then the fallback to direct selection.
1164            ..CompileConfig::default()
1165        };
1166
1167        let result = backend.compile_function("fdiv", &ops, &config);
1168        assert!(
1169            result.is_ok(),
1170            "f32.div must compile on Cortex-M4F via the optimized->direct \
1171             fallback (issue #120), got: {:?}",
1172            result.as_ref().err()
1173        );
1174        assert!(
1175            !result.unwrap().code.is_empty(),
1176            "f32.div must produce non-empty machine code"
1177        );
1178    }
1179
1180    /// A spread of f32 ops, all through the optimized (default) config, must
1181    /// compile via the fallback on an FPU target without panicking.
1182    #[test]
1183    fn test_issue120_assorted_f32_ops_compile_via_optimized_default() {
1184        let backend = ArmBackend::new();
1185        let config = CompileConfig {
1186            target: TargetSpec::cortex_m4f(),
1187            ..CompileConfig::default()
1188        };
1189
1190        let cases: Vec<(&str, Vec<WasmOp>)> = vec![
1191            (
1192                "fadd",
1193                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Add],
1194            ),
1195            (
1196                "fmul",
1197                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Mul],
1198            ),
1199            (
1200                "fsub",
1201                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Sub],
1202            ),
1203        ];
1204
1205        for (name, ops) in cases {
1206            let result = backend.compile_function(name, &ops, &config);
1207            assert!(
1208                result.is_ok(),
1209                "{name} must compile via the optimized->direct fallback \
1210                 (issue #120), got: {:?}",
1211                result.as_ref().err()
1212            );
1213            assert!(
1214                !result.unwrap().code.is_empty(),
1215                "{name} must produce non-empty machine code"
1216            );
1217        }
1218    }
1219
1220    /// The fallback must still honor the ISA feature gate: f32 on a no-FPU
1221    /// target must fail cleanly (not panic) even on the optimized path.
1222    #[test]
1223    fn test_issue120_f32_div_rejected_on_no_fpu_via_optimized() {
1224        let backend = ArmBackend::new();
1225        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
1226        let config = CompileConfig {
1227            target: TargetSpec::cortex_m3(),
1228            ..CompileConfig::default()
1229        };
1230
1231        let result = backend.compile_function("fdiv", &ops, &config);
1232        assert!(
1233            result.is_err(),
1234            "f32.div must be rejected on Cortex-M3 (no FPU), not panic"
1235        );
1236    }
1237
1238    /// Issue #94: end-to-end byte-size check for the canonical u64-packed
1239    /// FFI-return hi32 extract pattern. Compiles two near-identical
1240    /// functions — one with the optimized shift-by-32, one with a generic
1241    /// shift-by-7 — and asserts the optimized form is meaningfully smaller.
1242    #[test]
1243    fn test_issue94_hi32_extract_is_smaller_than_generic_shift() {
1244        let backend = ArmBackend::new();
1245        let config = CompileConfig {
1246            target: TargetSpec::cortex_m4f(),
1247            ..CompileConfig::default()
1248        };
1249
1250        // Optimized path: `(local.get 0) >>> 32; wrap_i64`
1251        let ops_hi32 = vec![
1252            WasmOp::LocalGet(0), // i64 param in R0:R1
1253            WasmOp::I64Const(32),
1254            WasmOp::I64ShrU,
1255            WasmOp::I32WrapI64,
1256        ];
1257        let func_hi32 = backend
1258            .compile_function("hi32_extract", &ops_hi32, &config)
1259            .unwrap();
1260
1261        // Generic path: `(local.get 0) >>> 7; wrap_i64` — same shape, but the
1262        // shift amount is not a multiple of 32, so it falls through to the
1263        // 38-byte runtime shift.
1264        let ops_generic = vec![
1265            WasmOp::LocalGet(0),
1266            WasmOp::I64Const(7),
1267            WasmOp::I64ShrU,
1268            WasmOp::I32WrapI64,
1269        ];
1270        let func_generic = backend
1271            .compile_function("generic_shr", &ops_generic, &config)
1272            .unwrap();
1273
1274        let bytes_hi32 = func_hi32.code.len();
1275        let bytes_generic = func_generic.code.len();
1276        println!(
1277            "\n[issue #94] hi32 extract: {} bytes (vs generic shift: {} bytes; saved {})",
1278            bytes_hi32,
1279            bytes_generic,
1280            bytes_generic.saturating_sub(bytes_hi32)
1281        );
1282        let hex: String = func_hi32
1283            .code
1284            .iter()
1285            .map(|b| format!("{:02x}", b))
1286            .collect::<Vec<_>>()
1287            .join(" ");
1288        println!("[issue #94] hi32 bytes: {}", hex);
1289        // We expect the optimized form to be at least 30 bytes smaller than
1290        // the generic 64-bit shift sequence. (Empirically: 14 vs 50 bytes.)
1291        assert!(
1292            bytes_hi32 + 30 <= bytes_generic,
1293            "issue #94: hi32 extract = {} bytes, generic shift = {} bytes; \
1294             expected optimized form to be at least 30 bytes smaller",
1295            bytes_hi32,
1296            bytes_generic,
1297        );
1298    }
1299}