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