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