Skip to main content

synth_backend/
arm_backend.rs

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