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            // GI-FPU-002 (#619/#369): THIS function's declared f32-param mask.
95            let params_f32 = config
96                .func_params_f32
97                .get(func.index as usize)
98                .filter(|p| !p.is_empty());
99            // GI-FPU-002 phase 2 (#369): THIS function's declared f64-param
100            // mask (hard-float targets decline f64 params loudly).
101            let params_f64 = config
102                .func_params_f64
103                .get(func.index as usize)
104                .filter(|p| !p.is_empty());
105            // GI-FPU-002 phase 2 (#719/#369): THIS function's declared f32/f64
106            // return flag, so the epilogue soundness guard fires on every driver
107            // path (not only the CLI loops).
108            let ret_f32 = config
109                .func_ret_f32
110                .get(func.index as usize)
111                .copied()
112                .unwrap_or(false);
113            let ret_f64 = config
114                .func_ret_f64
115                .get(func.index as usize)
116                .copied()
117                .unwrap_or(false);
118            // #1214: THIS function's declared-i64-local side-table. Guarded by
119            // `.any(i64)`, not `!is_empty()` — every function with ANY declared
120            // local (i32 included) has a non-empty vector, and that would
121            // widen this memoization guard to nearly every function for no
122            // reason; only a function that actually declares an i64 local
123            // needs the extra clone.
124            let declared_i64_locals = &func.declared_i64_locals;
125            let func_config = if params.is_some()
126                || params_f32.is_some()
127                || params_f64.is_some()
128                || !func.block_arity.is_empty()
129                || declared_params.is_some()
130                || ret_f32
131                || ret_f64
132                || declared_i64_locals.iter().any(|&b| b)
133            {
134                Some(CompileConfig {
135                    current_func_params_i64: params.cloned().unwrap_or_default(),
136                    current_func_params_f32: params_f32.cloned().unwrap_or_default(),
137                    current_func_params_f64: params_f64.cloned().unwrap_or_default(),
138                    current_func_ret_f32: ret_f32,
139                    current_func_ret_f64: ret_f64,
140                    current_func_block_arity: func.block_arity.clone(),
141                    current_func_declared_i64_locals: declared_i64_locals.clone(),
142                    current_func_param_count: declared_params,
143                    ..config.clone()
144                })
145            } else {
146                None
147            };
148            let cfg = func_config.as_ref().unwrap_or(config);
149            let compiled = self.compile_function(&name, &func.ops, cfg)?;
150            functions.push(compiled);
151        }
152
153        Ok(CompilationResult {
154            functions,
155            elf: None,
156            backend_name: self.name().to_string(),
157        })
158    }
159
160    fn compile_function(
161        &self,
162        name: &str,
163        ops: &[WasmOp],
164        config: &CompileConfig,
165    ) -> Result<CompiledFunction, BackendError> {
166        let (code, relocations, line_map, branch_map, final_instrs) =
167            compile_wasm_to_arm(ops, config).map_err(BackendError::CompilationFailed)?;
168
169        // #778: derive the SOUND static WCET intermediate from the final Thumb-2
170        // stream. Only present for the Thumb-2 path; the core class (from the
171        // triple) decides whether the bound is sound (M3/M4) or declined (M7).
172        // Phase 2: any --wcet-hints entry for THIS function is verified (never
173        // trusted) by the loop analyzer. Phase 3: the intermediate carries the
174        // own-body cycles + direct call sites; the module driver composes it across
175        // the call graph. `wcet` here is the SINGLE-FUNCTION view (unresolved direct
176        // calls decline `call`) — a valid standalone answer, overwritten by the
177        // composed result when the driver runs the second pass.
178        let wcet_intermediate = final_instrs.as_ref().map(|instrs| {
179            let hints = config
180                .wcet_hints
181                .as_ref()
182                .and_then(|h| h.functions.get(name));
183            let self_label = config.current_func_index.map(|i| format!("func_{i}"));
184            crate::wcet::function_wcet_intermediate(
185                name,
186                instrs,
187                &config.target.triple,
188                hints,
189                self_label.as_deref(),
190            )
191        });
192        // The SINGLE-FUNCTION standalone view (unresolved direct calls decline
193        // `call`). Kept as a per-function fallback for any consumer that reads a
194        // lone `CompiledFunction` without running the module composer; the CLI
195        // `--emit-wcet` path IGNORES this and composes `wcet_intermediate` across
196        // the whole call graph instead (its result overwrites the report).
197        let wcet = final_instrs.map(|instrs| {
198            let hints = config
199                .wcet_hints
200                .as_ref()
201                .and_then(|h| h.functions.get(name));
202            crate::wcet::function_wcet_with_hints(name, &instrs, &config.target.triple, hints)
203        });
204
205        Ok(CompiledFunction {
206            name: name.to_string(),
207            code,
208            wasm_ops: ops.to_vec(),
209            relocations,
210            line_map,
211            branch_map,
212            wcet,
213            wcet_intermediate,
214        })
215    }
216
217    fn is_available(&self) -> bool {
218        true // Always available — it's a library backend
219    }
220}
221
222/// Count the number of function parameters by analyzing LocalGet patterns
223/// RQ-58-MIRRORS (#242): was a private copy of the read-before-write param
224/// heuristic, byte-equivalent to the other two backends'. Now the ONE shared
225/// definition in `synth-core`, so a correction reaches every backend.
226fn count_params(wasm_ops: &[WasmOp]) -> u32 {
227    synth_core::count_params_heuristic(wasm_ops)
228}
229
230/// #457/#970: the parameter count the selector is given.
231///
232/// With a DECLARED count from the driver the bound is
233/// `min(`[`synth_core::referenced_locals`]`(ops), declared)` — the highest
234/// local index the body touches, clamped by the signature. That is exact in
235/// both directions: the clamp stops a read-before-write NON-PARAM local (which
236/// WASM zero-initializes) from being homed in an argument register and reading
237/// caller garbage (#457), and taking the max over ALL accesses — writes as well
238/// as reads — stops a PARAM from being demoted to a local.
239///
240/// The previous rule capped [`count_params`] (a READ-FIRST heuristic) with the
241/// declared count, which got the second direction wrong: a param written on ONE
242/// arm of an `if` is "written first" in linear op order, so it was demoted, and
243/// because the demoted local's first access is a WRITE the #457 zero-init
244/// skipped it too. The arm that does NOT write it then read an UNINITIALISED
245/// frame slot — measured under unicorn with the sub-SP stack poisoned,
246/// `cond_write_param(0, 42)` returned the poison word, i.e. previous-frame
247/// bytes rather than 42 (#970; the aarch64 instance was #851).
248///
249/// `min` rather than a plain `declared` override preserves the leniency for a
250/// body that only touches the first few of many declared params.
251///
252/// `None` (no declared signature: hand-built op streams, direct
253/// `compile_function` callers) keeps the legacy pure inference — see the
254/// residual documented on [`CompileConfig::current_func_param_count`].
255fn effective_num_params(wasm_ops: &[WasmOp], config: &CompileConfig) -> u32 {
256    match config.current_func_param_count {
257        Some(declared) => synth_core::referenced_locals(wasm_ops).min(declared),
258        None => count_params(wasm_ops),
259    }
260}
261
262/// #539: fold the `i32.const 0; memory.grow m` idiom to `memory.size m`.
263/// Moved to `synth_core::rewrite_memory_grow_zero` (#242, VCR-SEL-005) so the
264/// ARM and RISC-V backends share ONE implementation and cannot drift; re-export
265/// here keeps the existing `rewrite_memory_grow_zero(...)` call sites working.
266use synth_core::rewrite_memory_grow_zero;
267
268/// #509: does the op stream contain a `br`/`br_if`/`br_table` that CARRIES a
269/// value — i.e. one targeting a result-typed block/if (forward edge with
270/// results > 0) or a parameterized loop header (backward edge with loop
271/// params > 0)?
272///
273/// The optimized path's wasm→IR lowering drops the carried value on such
274/// edges (the taken arm returns the fall-through result — same class as the
275/// #507 `br_table` drop, observed on `pick_br`/`pick_br_fall`), so — like
276/// #507 — the shape is detected on the raw op stream and routed to the direct
277/// selector, whose #509 designated-result-register lowering lands the value
278/// correctly. `block_arity` is the decoder's ordinal blocktype-arity
279/// side-table; when it is empty (hand-built op streams) every block reads as
280/// void and this never fires, keeping the optimized path byte-identical for
281/// every existing caller. Frozen-safe for the same reason as #507: the frozen
282/// fixtures compile `--relocatable` (already direct), and no optimized-path
283/// fixture branches to a result-typed block.
284fn has_value_carrying_branch(wasm_ops: &[WasmOp], block_arity: &[(u8, u8)]) -> bool {
285    // Open control constructs: (is_loop, params, results), innermost last.
286    let mut open: Vec<(bool, u8, u8)> = Vec::new();
287    let mut ctrl_ord = 0usize;
288    // A branch edge carries a value when its target is a result-typed forward
289    // join (block/if) or a parameterized loop header.
290    let carries = |open: &[(bool, u8, u8)], depth: u32| -> bool {
291        let Some(&(is_loop, params, results)) = open
292            .len()
293            .checked_sub(1 + depth as usize)
294            .and_then(|i| open.get(i))
295        else {
296            return false; // function-level target — handled by Return lowering
297        };
298        if is_loop { params > 0 } else { results > 0 }
299    };
300    for op in wasm_ops {
301        match op {
302            WasmOp::Block | WasmOp::If => {
303                let (p, r) = block_arity.get(ctrl_ord).copied().unwrap_or((0, 0));
304                ctrl_ord += 1;
305                open.push((false, p, r));
306            }
307            WasmOp::Loop => {
308                let (p, r) = block_arity.get(ctrl_ord).copied().unwrap_or((0, 0));
309                ctrl_ord += 1;
310                open.push((true, p, r));
311            }
312            WasmOp::End => {
313                open.pop(); // None only at the function-level end — harmless
314            }
315            WasmOp::Br(d) | WasmOp::BrIf(d) if carries(&open, *d) => return true,
316            WasmOp::BrTable { targets, default }
317                if targets
318                    .iter()
319                    .chain(std::iter::once(default))
320                    .any(|d| carries(&open, *d)) =>
321            {
322                return true;
323            }
324            _ => {}
325        }
326    }
327    false
328}
329
330/// Core compilation: WASM ops → ARM machine code bytes + relocations
331///
332/// Returns (code_bytes, relocations) where relocations record BL instructions
333/// that target external symbols (e.g., `__meld_dispatch_import` for import calls).
334type CompileArmOutput = (
335    Vec<u8>,
336    Vec<CodeRelocation>,
337    LineMap,
338    synth_core::backend::BranchMap,
339    // #778: the SOUND static WCET result over the final Thumb-2 stream, computed
340    // by `compile_function` (which knows the function name); `None` for the A32
341    // path. Purely additive metadata — does not touch `code`.
342    Option<Vec<synth_synthesis::ArmInstruction>>,
343);
344
345fn compile_wasm_to_arm(
346    wasm_ops: &[WasmOp],
347    config: &CompileConfig,
348) -> Result<CompileArmOutput, String> {
349    // #1093: a PARAMETER-taking block type (`if`/`block`/`loop (param ..)`,
350    // wasm multi-value) declines LOUDLY here — the single choke point BOTH
351    // ARM codegen paths pass through, so neither the optimized route nor the
352    // #197 direct route can reach the selectors' frame-entry stack
353    // checkpoints, which cannot represent params consumed below them (the
354    // `split_off` panic with an `else`; a silently-wrong false-path value
355    // without one — see `find_param_block_type`). This is the aarch64
356    // VCR-A64-CF-001 frame-open refusal ported, NOT multi-value support.
357    // Checked on the driver's ORIGINAL stream, which is what the ordinal
358    // side-table was built against. Empty side-table (hand-built op streams)
359    // ⇒ never fires ⇒ byte-identical for every existing caller.
360    //
361    // RQ-64-MVLOWER (#1093): the guard is relaxed PER CONSTRUCT and PER PATH,
362    // from the one policy in synth-core (`arm_param_block_lowering`), on the
363    // configuration the #1097 oracle executes — `--relocatable`. The
364    // self-contained image path keeps the full decline: no oracle leg
365    // executes its images, so there is no evidence to relax on.
366    let lowered = synth_core::arm_param_block_lowering(config.relocatable);
367    if let Some((what, ord, arity)) = synth_core::find_unlowered_param_block_type(
368        wasm_ops,
369        &config.current_func_block_arity,
370        lowered,
371    ) {
372        return Err(synth_core::param_block_decline_msg(
373            if config.relocatable {
374                "the ARM direct selector (--relocatable)"
375            } else {
376                "the ARM selector (self-contained image path — no #1097 oracle \
377                 leg executes it)"
378            },
379            what,
380            ord,
381            arity,
382        ));
383    }
384    // #539: `memory.grow(0)` must return the CURRENT page count, not the
385    // fixed-memory `-1` sentinel — growing by zero pages can never fail (WASM
386    // Core §4.4.7), so a guest doing `if (memory.grow(0) < 0) trap;` wrongly
387    // faulted. Every lowering path emitted a delta-agnostic `-1`. `memory.grow(0)`
388    // is semantically identical to `memory.size`, which the backend already
389    // computes from the runtime memory-size register (R10 >> 16 = pages), so fold
390    // the `i32.const 0; memory.grow` idiom to `memory.size` up front — backend-
391    // and path-agnostic. A non-zero delta keeps `-1` (fixed memory genuinely
392    // cannot grow); a runtime delta that happens to be 0 is the documented
393    // follow-up.
394    let rewritten = rewrite_memory_grow_zero(wasm_ops);
395    // #494 phase 2b: the fact-spec guard-elision marks are keyed by op index
396    // into the stream the DRIVER handed us. The memory.grow(0) fold above can
397    // only shift indices AT OR AFTER a `memory.grow` — an op the fact-spec
398    // walk never crosses (it stops at the first untracked op, so no mark can
399    // follow one). Defense in depth: if the fold fired at all, drop the marks
400    // loudly rather than risk keying a guard elision to the wrong op.
401    //
402    // VCR-MEM-004 (#901): scry's externally-proven bounds-guard marks ride the
403    // SAME defensive gate for the SAME reason — they are op-index keyed, so an
404    // index shift would strip the guard off the wrong access. They are unioned
405    // with #494's certificate-discharged marks here (one consumption point,
406    // two authorities; `CompileConfig` keeps them separate so the attestation
407    // can say which one covered each site).
408    let (fact_div_zero_elide, fact_div_ovf_elide, mem_bounds_elide): (
409        &[usize],
410        &[usize],
411        Vec<usize>,
412    ) = if rewritten.len() == wasm_ops.len() {
413        let mut mem = config.fact_mem_bounds_elide.clone();
414        mem.extend_from_slice(&config.proven_safe_mem_elide);
415        mem.sort_unstable();
416        mem.dedup();
417        (&config.fact_div_zero_elide, &config.fact_div_ovf_elide, mem)
418    } else {
419        if !config.fact_div_zero_elide.is_empty()
420            || !config.fact_div_ovf_elide.is_empty()
421            || !config.fact_mem_bounds_elide.is_empty()
422        {
423            eprintln!(
424                "fact-spec: DECLINE guard elision marks dropped — the                      memory.grow(0) fold shifted op indices (#494 defensive gate);                      general lowering emitted"
425            );
426        }
427        if !config.proven_safe_mem_elide.is_empty() {
428            eprintln!(
429                "proven-safe: DECLINE {} bounds-guard elision mark(s) dropped — the \
430                 memory.grow(0) fold shifted op indices, so the (func, pc) keys no longer \
431                 name the accesses scry proved (VCR-MEM-004 defensive gate, #901); every \
432                 guard is retained",
433                config.proven_safe_mem_elide.len()
434            );
435        }
436        (&[], &[], Vec::new())
437    };
438    let wasm_ops: &[WasmOp] = &rewritten;
439
440    // #457: `count_params` INFERS the param count from access patterns (a local
441    // whose first access is a read is assumed to be a param), so a
442    // read-before-write NON-PARAM local — which WASM zero-initializes — was
443    // indistinguishable from a param: it got homed in a parameter register and
444    // read caller garbage instead of 0. The driver supplies the DECLARED count
445    // (`current_func_param_count`, from the module's type section) to settle it.
446    //
447    // #970 (RQ-57-CONDPARAM): see [`effective_num_params`] for the bound and
448    // why the read-first inference is not it.
449    let inferred_params = count_params(wasm_ops);
450    let num_params = effective_num_params(wasm_ops, config);
451    // A read-before-write non-param local exists iff the ACCESS-PATTERN
452    // inference overshot the declared count — the read-first rule can only
453    // exceed it via a read-first index >= the declared count, which is exactly
454    // such a local. (Unchanged by #970: `referenced >= inferred` always, so
455    // `num_params < inferred_params` still holds iff `inferred > declared`;
456    // stated directly here rather than left to that algebra.)
457    let has_rbw_local = match config.current_func_param_count {
458        Some(declared) => inferred_params > declared,
459        None => false,
460    };
461
462    let bounds_config = match config.effective_safety_bounds() {
463        SafetyBounds::None => BoundsCheckConfig::None,
464        SafetyBounds::Mpu => BoundsCheckConfig::Mpu,
465        SafetyBounds::Software => BoundsCheckConfig::Software,
466        SafetyBounds::Mask => {
467            // #651 (mirroring the RISC-V backend's compile-time decline):
468            // index masking wraps `ea & (size-1)` — a modulo only when the
469            // linear-memory size is a power of two. With a non-power-of-two
470            // size the AND would silently REMAP in-bounds addresses (e.g.
471            // 0x18000 & 0x2FFFF = 0x8000 for a 192 KiB memory). Decline
472            // loudly rather than miscompile.
473            //
474            // RQ-57-SENTINEL (#953 sibling): `bytes == 0` used to be EXEMPT
475            // from this check, because 0 was read as "unknown — plain
476            // per-function path, no module context". But 0 is also exactly
477            // what a module declaring `(memory 0)` produces, and for that
478            // module the emitted guard (`SUB R12, R10, #1; AND addr, R12`,
479            // R10 = 0 baked by the startup) computes `0 - 1 = 0xFFFFFFFF` —
480            // an IDENTITY mask. Every access then executes unmasked at
481            // `[R11 + addr]` for any 32-bit addr: an unbounded OOB read/write
482            // in the mode whose purpose is bounding. Same sentinel/value
483            // collision as #932/#953, third backend-mode instance.
484            //
485            // 0 now means what #953 made it mean everywhere: a zero-byte
486            // memory. No mask can bound an access into a memory with no bytes
487            // (wasm semantics: every access traps), and wrap-not-trap has
488            // nothing to wrap into — refuse. Callers with no module context
489            // must state the size (the #953 contract; the CLI single-function
490            // path now threads the module's declared size for all backends).
491            let bytes = config.linear_memory_bytes;
492            if bytes == 0 {
493                return Err("--safety-bounds mask: the linear memory has ZERO bytes \
494                     (`(memory 0)`, or a driver that did not state the size) — \
495                     every access is out of bounds and a mask cannot express a \
496                     trap. Use --safety-bounds software (traps every access) \
497                     or declare a non-zero memory (RQ-57-SENTINEL, #953)"
498                    .to_string());
499            }
500            if !bytes.is_power_of_two() {
501                return Err(format!(
502                    "--safety-bounds mask requires a power-of-two linear-memory \
503                     size, got {bytes} bytes — switch to --safety-bounds software \
504                     for the deterministic check (#651)"
505                ));
506            }
507            BoundsCheckConfig::Masking
508        }
509    };
510
511    // The non-optimized (direct) instruction-selection path. Handles f32 via
512    // VFP/FPU. Used directly when `--no-optimize` is set, and as the fallback
513    // when the optimized path declines a module (see issue #120 below).
514    //
515    // VCR-RA-001 step 3b-lite (#242): a FRESH selector per attempt, with
516    // `spill_on_exhaustion` set only on the retry — the first pass is the
517    // unmodified default, so every function that compiles today is selected by
518    // exactly the code that compiled it yesterday (bit-identity is structural,
519    // not behavioural).
520    // #1321: the allocator spill areas the direct selector reserved for the
521    // attempt that actually produced the returned stream, as
522    // `(frame_size, areas)`. Written only on a SUCCESSFUL selection, so after
523    // the recovery ladder it holds the rung that won. Left `None` on the
524    // optimized path, which supplies no layout — and `None` means "police every
525    // offset", i.e. exactly today's behaviour.
526    let selected_spill_areas: std::cell::RefCell<Option<(i32, Vec<std::ops::Range<i32>>)>> =
527        std::cell::RefCell::new(None);
528    let select_direct_attempt = |spill_on_exhaustion: bool,
529                                 param_backing_on_exhaustion: bool,
530                                 local_promote: bool,
531                                 i64_spill_slots: Option<usize>,
532                                 vfp_spill_on_exhaustion: bool,
533                                 vfp_frame_home_locals: bool,
534                                 vfp_wide_file: bool|
535     -> Result<Vec<ArmInstruction>, synth_core::Error> {
536        let db = RuleDatabase::with_standard_rules();
537        let mut selector =
538            InstructionSelector::with_bounds_check(db.rules().to_vec(), bounds_config);
539        selector.set_target(config.target.fpu, &config.target.triple);
540        if config.num_imports > 0 {
541            selector.set_num_imports(config.num_imports);
542        }
543        // #195: plumb the callee argument-count tables so the direct selector can
544        // marshal call arguments into R0–R3 per AAPCS.
545        selector.set_func_arg_counts(
546            config.func_arg_counts.clone(),
547            config.type_arg_counts.clone(),
548        );
549        // #197: in relocatable host-link mode, emit direct `func_N` BLs for
550        // imports (rewritten to the wasm field name by build_relocatable_elf)
551        // instead of `__meld_dispatch_import`.
552        selector.set_relocatable(config.relocatable);
553        // #642: call_indirect guard inputs (compile-time table size for the
554        // bounds guard + closed-world type verdicts). Without them, every
555        // call_indirect lowering declines loudly.
556        selector.set_call_indirect_guards(config.call_indirect_guards.clone());
557        // #275: on the self-contained image path (NOT --relocatable) the R11
558        // funcref-table dispatch is a silent miscompile — the region is only
559        // populated by an external runtime, which a self-contained ELF does
560        // not have, so the dispatch would read function pointers from
561        // linear-memory data. Two outcomes:
562        //  - the Thumb-2 `--cortex-m` image path (CLI-flagged: the builder
563        //    that emits and patches the flash-resident funcref table will
564        //    run) lowers call_indirect through that table, PC-relative,
565        //    never via R11;
566        //  - every OTHER self-contained configuration (A32/Cortex-R5, the
567        //    simple-ELF builder, imports present) keeps the loud decline.
568        // The host-linked (--relocatable) path keeps the guarded R11
569        // dispatch: there a runtime places the table region at R11.
570        let self_contained_table = config.self_contained_funcref_table
571            && matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
572        selector
573            .set_reject_self_contained_call_indirect(!config.relocatable && !self_contained_table);
574        selector.set_self_contained_funcref_table(self_contained_table);
575        // #237: native-pointer ABI — wasm statics become __synth_wasm_data-relative.
576        selector.set_native_pointer_abi(config.native_pointer_abi, config.linear_memory_bytes);
577        // VCR-MEM-002 phase 1 (#406): per-memory initial page counts — enables
578        // the multi-memory arms (memory-0 lowering never reads it; empty ⇒
579        // every multi-memory op declines loudly).
580        selector.set_memory_pages(config.memory_pages.clone());
581        // #311: i64 call results are register PAIRS — tag them.
582        selector.set_result_types(config.func_ret_i64.clone(), config.type_ret_i64.clone());
583        // #1210: per-function result COUNT (0 = void) — `func_ret_i64` alone
584        // cannot tell a void callee from an i32-returning one.
585        selector.set_func_result_counts(config.func_result_counts.clone());
586        // #359: declared param widths of THIS function, so the AAPCS stack-arg
587        // path can refuse 64-bit params (Ok-or-Err). Empty ⇒ assume i32.
588        selector.set_params_i64(config.current_func_params_i64.clone());
589        // GI-FPU-002 (#619/#369): declared f32-param mask — home hard-float f32
590        // args in S0..S15 (AAPCS-VFP) instead of the R0..R3 integer path.
591        selector.set_params_f32(config.current_func_params_f32.clone());
592        // GI-FPU-002 phase 2 (#369): declared f64-param mask — hard-float
593        // targets decline f64-param functions loudly (no D-register homing yet).
594        selector.set_params_f64(config.current_func_params_f64.clone());
595        // GI-FPU-002 phase 2 (#719/#369): THIS function's f32/f64 return flag, so
596        // the epilogue loudly declines a float result reaching it in a core
597        // register (never a silent integer R0 return where a caller reads S0/D0).
598        selector.set_ret_float(config.current_func_ret_f32, config.current_func_ret_f64);
599        // GI-FPU-002 phase 3 (#369): per-callee float-signature tables. `Call`
600        // marshals the AAPCS-VFP boundary from these (float args into S0../D0..,
601        // float results out of S0/D0); `CallIndirect` still declines a
602        // float-returning static type loudly.
603        selector.set_float_call_signatures(
604            config.func_ret_f32.clone(),
605            config.func_ret_f64.clone(),
606            config.type_ret_f32.clone(),
607            config.type_ret_f64.clone(),
608            config.func_params_f32.clone(),
609            config.func_params_f64.clone(),
610        );
611        // #509: blocktype-arity side-table of THIS function, so value-carrying
612        // br/br_if/br_table land the carried value in the target block's
613        // designated result register instead of dropping it. Empty ⇒ legacy
614        // void-block lowering.
615        selector.set_block_arity(config.current_func_block_arity.clone());
616        // #1214: THIS function's declared-i64-local side-table — see
617        // `compute_local_layout`'s use of it. Empty ⇒ exactly the prior
618        // dataflow-only width inference.
619        selector.set_declared_i64_locals(config.current_func_declared_i64_locals.clone());
620        // Stack-pointer promotion is meaningful only under the native-pointer ABI;
621        // gating here keeps every non-native compile (all frozen fixtures) on the
622        // legacy R9 globals-table path, bit-identical.
623        if config.native_pointer_abi
624            && let Some((sp_idx, sp_init)) = config.stack_pointer_global
625        {
626            selector.set_native_pointer_stack(sp_idx, sp_init);
627        }
628        // #643: per-global slot widths — i64/f64 globals occupy 8-byte slots
629        // (register-pair store/load) and shift every later global's offset.
630        // Empty for i32-only modules ⇒ the legacy `idx * 4` layout, unchanged.
631        selector.set_global_widths(config.global_widths.clone());
632        selector.set_spill_on_exhaustion(spill_on_exhaustion);
633        selector.set_param_backing_on_exhaustion(param_backing_on_exhaustion);
634        // #881 (VCR-RA-004): VFP register-file spilling, set ONLY on the retry
635        // after an attempt failed with a GI-FPU-002 exhaustion Err — functions
636        // that compile without it keep byte-identical output by construction.
637        selector.set_vfp_spill_on_exhaustion(vfp_spill_on_exhaustion);
638        // #1069: LAST-resort residence lever — set ONLY by the final VFP
639        // retry below, after the plain #881 rung also exhausted, so every
640        // function that compiles through base path or plain rung is produced
641        // by exactly yesterday's path (byte-identity is structural).
642        selector.set_vfp_frame_home_locals(vfp_frame_home_locals);
643        // RQ-67-VFPREACH (#1267): the AAPCS callee-saved VFP half.
644        selector.set_vfp_wide_file(vfp_wide_file);
645        // #587 pool-grow rung: a larger i64 spill-slot pool, set ONLY on the
646        // retry after an attempt failed with the slot-pool-exhausted Err —
647        // functions that compile with the default pool keep their frame
648        // byte-identical by construction.
649        if let Some(slots) = i64_spill_slots {
650            selector.set_i64_spill_slots(slots);
651        }
652        // VCR-RA local promotion (#390, #242): keep eligible non-param i32 locals
653        // in callee-saved registers instead of frame slots — the structural lever
654        // toward native parity. DEFAULT-ON as of v0.14.0: gale's G474RE DWT gate
655        // cleared it as a net win (gust_mix dissolved 58→50 cyc/call −14%, all 5
656        // stack spill/reloads eliminated, correctness bit-identical over [0,2047],
657        // 2.00×→1.72× vs LLVM). Escape hatch: `SYNTH_NO_LOCAL_PROMOTE=1` restores
658        // the frame-slot path. Leaf-only / i32-only / ARM-only (see
659        // compute_local_promotion); the leaf-only lift + i64 locals are follow-ons.
660        // #474: `local_promote` is now a per-attempt parameter so the retry ladder
661        // can drop promotion as an exhaustion-recovery rung (promotion pins r4-r8,
662        // which on a dense function leaves the spill allocator with nothing to
663        // free → the frame-slot path is the escape that restores compilability).
664        selector.set_local_promote(local_promote);
665        // #494 phase 2b: certificate-discharged div/rem trap-guard elision
666        // marks (empty in every compile without SYNTH_FACT_SPEC + facts).
667        selector
668            .set_fact_div_guard_elisions(fact_div_zero_elide.to_vec(), fact_div_ovf_elide.to_vec());
669        // #494 bounds-elision + VCR-MEM-004 (#901): per-site memory
670        // bounds-guard marks, unioned above. Empty in every compile without
671        // SYNTH_FACT_SPEC + facts or --proven-safe.
672        selector.set_fact_mem_bounds_elisions(mem_bounds_elide.clone());
673        let selected = selector.select_with_stack(wasm_ops, num_params);
674        if selected.is_ok() {
675            // #1321: only a SUCCESSFUL attempt's layout describes the stream we
676            // return; a failed rung's frame is discarded with it.
677            *selected_spill_areas.borrow_mut() = selector.frame_spill_areas().cloned();
678        }
679        selected
680    };
681    let select_direct = || -> Result<Vec<ArmInstruction>, String> {
682        const SINGLE_EXHAUSTION: &str = "all allocatable registers are live on the stack";
683        const PAIR_EXHAUSTION: &str = "no consecutive pair of free registers for i64";
684        const SLOT_EXHAUSTION: &str = "i64 spill-slot pool exhausted";
685        // The full exhaustion-recovery ladder, parameterized on whether local
686        // promotion is enabled. Each rung is reached only when the previous one
687        // returned a recoverable register-exhaustion Err, so a function that
688        // compiles on the first attempt is untouched by the later rungs. Returns
689        // the result AND which rung produced it (for the #242 measurement below).
690        let recovery_ladder =
691            |promote: bool,
692             i64_spill_slots: Option<usize>,
693             vfp_spill: bool,
694             vfp_frame: bool,
695             vfp_wide: bool|
696             -> (Result<Vec<ArmInstruction>, synth_core::Error>, &'static str) {
697                let mut attempt = select_direct_attempt(
698                    false,
699                    false,
700                    promote,
701                    i64_spill_slots,
702                    vfp_spill,
703                    vfp_frame,
704                    vfp_wide,
705                );
706                let mut rung = "base";
707                // VCR-RA-001 step 3b-lite (#242): the i32 register-exhaustion
708                // hard-fail is recoverable — retry with spill-on-exhaustion, which
709                // reserves the spill area and spills the deepest stack value when
710                // the pool is full.
711                if let Err(e) = &attempt
712                    && e.to_string().contains(SINGLE_EXHAUSTION)
713                {
714                    attempt = select_direct_attempt(
715                        true,
716                        false,
717                        promote,
718                        i64_spill_slots,
719                        vfp_spill,
720                        vfp_frame,
721                        vfp_wide,
722                    );
723                    rung = "spill";
724                }
725                // VCR-RA-001 acceptance increment (#242): the i64 consecutive-PAIR
726                // exhaustion is recoverable too — not by stack spilling (the pair
727                // allocator already spills stack values, #171) but by frame-backing
728                // the params (#204) so they stop pinning R0-R3, with spill kept on.
729                if let Err(e) = &attempt
730                    && e.to_string().contains(PAIR_EXHAUSTION)
731                {
732                    attempt = select_direct_attempt(
733                        true,
734                        true,
735                        promote,
736                        i64_spill_slots,
737                        vfp_spill,
738                        vfp_frame,
739                        vfp_wide,
740                    );
741                    rung = "param-backing";
742                }
743                (attempt, rung)
744            };
745        // #474: local promotion (default-on since v0.14.0) is an OPTIMIZATION — it
746        // must never be the reason a function fails to compile. Run the full ladder
747        // with promotion first (so every function that compiles today is
748        // bit-identical), and if it still ends in register exhaustion, fall back to
749        // the promotion-off ladder (the v0.12.0 frame-slot lowering — exactly what
750        // the `SYNTH_NO_LOCAL_PROMOTE=1` workaround does, now automatic). Promotion
751        // pins r4-r8 for the locals; on a dense function that leaves the allocator
752        // with nothing to free, so dropping it restores compilability. The fallback
753        // is reached ONLY by functions that exhaust WITH promotion, so promotion-on
754        // output is untouched by construction (frozen byte gate stays green).
755        let promote = std::env::var("SYNTH_NO_LOCAL_PROMOTE").is_err();
756        // RQ-69-FALCON (#1318): per-rung reporting, because the summary line
757        // below CANNOT distinguish the two failures it is asked about. `rung`
758        // is only assigned when an attempt SUCCEEDS, so a function that climbs
759        // the whole ladder and exhausts every rung prints `rung=base
760        // result=exhausted` — identical to one that never climbed at all. Worse,
761        // the Err the caller finally reports is stage 2's, so a stage-3
762        // (wide-file) failure is invisible even in the user-facing message:
763        // #1318's `step` reports the #1069 slot-pool message while the wide-file
764        // rung it also failed says nothing. Measured on the reporter's module
765        // before this was written; reading the source was the only way to tell
766        // which of the two had happened.
767        //
768        // Logging only, behind the same env var, so emitted bytes are unchanged
769        // and the frozen byte gate is unaffected.
770        let stats = std::env::var("SYNTH_RECOVERY_STATS").is_ok();
771        // Every rung's Err, in attempt order (#1318). The ladder keeps the
772        // EARLIER attempt's Err whenever a later rung also fails — stage 3
773        // falls back to stage 2's `fh`, each pool-grow falls back to its
774        // ungrown attempt — so the reporter of #1318 was told "spill-slot pool
775        // exhausted" while the wall three of the four rungs actually hit was
776        // the VSTR/VLDR [sp,#imm] window. Reporting the LAST rung's Err is no
777        // better: the last rung attempted is the wide-file one, whose Err is
778        // the pool message again. So report what was actually tried, deduped.
779        // Control flow is untouched — every rung still runs exactly when it
780        // ran before, and the substrings other code matches on are all still
781        // present in the joined message.
782        let tried: std::cell::RefCell<Vec<(String, String)>> = std::cell::RefCell::new(Vec::new());
783        let note = |name: &str, r: &Result<Vec<ArmInstruction>, synth_core::Error>| {
784            if let Err(e) = r {
785                let m = e.to_string();
786                let first = m.lines().next().unwrap_or("").to_string();
787                tried.borrow_mut().push((name.to_string(), first));
788            }
789            if stats {
790                match r {
791                    Ok(_) => eprintln!("[recovery-stats]   tried rung={name} -> ok"),
792                    Err(e) => {
793                        let m = e.to_string();
794                        let first = m
795                            .lines()
796                            .next()
797                            .unwrap_or("")
798                            .chars()
799                            .take(140)
800                            .collect::<String>();
801                        eprintln!("[recovery-stats]   tried rung={name} -> exhausted: {first}");
802                    }
803                }
804            }
805        };
806        // The full pre-#587 recovery sequence (promotion-on ladder, then the
807        // #474 promotion-off fallback), parameterized on the pool size so the
808        // pool-grow retry below reruns it verbatim.
809        let full_sequence = |slots: Option<usize>,
810                             vfp_spill: bool,
811                             vfp_frame: bool,
812                             vfp_wide: bool|
813         -> (
814            Result<Vec<ArmInstruction>, synth_core::Error>,
815            &'static str,
816            bool,
817        ) {
818            let (mut attempt, mut rung) =
819                recovery_ladder(promote, slots, vfp_spill, vfp_frame, vfp_wide);
820            let mut promotion_dropped = false;
821            if promote
822                && attempt
823                    .as_ref()
824                    .err()
825                    .is_some_and(|e| e.to_string().contains("register exhaustion"))
826            {
827                let (rescued, off_rung) =
828                    recovery_ladder(false, slots, vfp_spill, vfp_frame, vfp_wide);
829                if rescued.is_ok() {
830                    attempt = rescued;
831                    rung = off_rung;
832                    promotion_dropped = true;
833                }
834            }
835            (attempt, rung, promotion_dropped)
836        };
837        let (mut attempt, mut rung, mut promotion_dropped) =
838            full_sequence(None, false, false, false);
839        // #587 pool-grow retry (the falcon func_60/func_73 remainder): the fixed
840        // 8-slot i64 spill pool can exhaust while spilling is otherwise working —
841        // an i64-dense function simply has more values simultaneously live than
842        // the pool holds. Rerun the ENTIRE sequence (every rung, both promotion
843        // modes) with the pool sized from a conservative operand-stack-depth
844        // bound: the number of simultaneously spilled values can never exceed
845        // the operand-stack depth, plus a few transient slots (the arg-move
846        // cycle resolver and call-result parking each borrow one). The selector
847        // clamps the request to its 12-bit-friendly cap; a function that still
848        // exhausts stays an honest loud skip. Deliberately LAST — after the #474
849        // promotion-off fallback — so any function that compiled yesterday
850        // (through any rung or fallback) is produced by exactly yesterday's
851        // path, byte-identical; the grown pool only ever fires for functions
852        // whose every existing escape ended in the slot-pool Err.
853        if attempt
854            .as_ref()
855            .err()
856            .is_some_and(|e| e.to_string().contains(SLOT_EXHAUSTION))
857        {
858            let depth = synth_core::wasm_stack_check::max_depth_bound(wasm_ops) as usize;
859            let (grown, _, grown_dropped) =
860                full_sequence(Some(depth.saturating_add(4)), false, false, false);
861            note("pool-grow", &grown);
862            if grown.is_ok() {
863                attempt = grown;
864                rung = "pool-grow";
865                promotion_dropped = grown_dropped;
866            }
867        }
868        // #881 (VCR-RA-004): the GI-FPU-002 VFP register-file exhaustion is
869        // recoverable too — retry the ENTIRE sequence with VFP spilling
870        // enabled (the pre-op pressure guard spills the deepest segment-local
871        // f32/f64 stack value into the shared spill area and reloads spilled
872        // operands before their consumers). Deliberately LAST, after every
873        // integer rung, so any function that compiled yesterday is produced
874        // by exactly yesterday's path; the VFP rung only ever fires for
875        // functions whose every existing escape ended in a GI-FPU-002
876        // exhaustion Err (previously an unconditional loud skip). A VFP-
877        // spilling function can in turn exhaust the shared slot pool — the
878        // #587 pool-grow retry composes inside the rung.
879        const VFP_S_EXHAUSTION: &str = "VFP register file exhausted";
880        const VFP_D_EXHAUSTION: &str = "VFP D-register file exhausted";
881        if attempt.as_ref().err().is_some_and(|e| {
882            let msg = e.to_string();
883            msg.contains(VFP_S_EXHAUSTION) || msg.contains(VFP_D_EXHAUSTION)
884        }) {
885            // Stage 1 — the plain #881 rung, exactly yesterday's path
886            // (sequence, pool sizing and all): any function it rescues is
887            // byte-identical to what it shipped yesterday, by construction.
888            let (vfp, vfp_rung, vfp_dropped) = full_sequence(None, true, false, false);
889            note("vfp-spill", &vfp);
890            let (vfp, vfp_rung, vfp_dropped) = if vfp.as_ref().err().is_some_and(|e| {
891                let msg = e.to_string();
892                msg.contains(SLOT_EXHAUSTION) || msg.contains("spilling the VFP register file")
893            }) {
894                let depth = synth_core::wasm_stack_check::max_depth_bound(wasm_ops) as usize;
895                let (grown, grown_rung, grown_dropped) =
896                    full_sequence(Some(depth.saturating_add(4)), true, false, false);
897                note("vfp-spill+pool-grow", &grown);
898                if grown.is_ok() {
899                    (grown, grown_rung, grown_dropped)
900                } else {
901                    (vfp, vfp_rung, vfp_dropped)
902                }
903            } else {
904                (vfp, vfp_rung, vfp_dropped)
905            };
906            if vfp.is_ok() {
907                attempt = vfp;
908                rung = match vfp_rung {
909                    "base" => "vfp-spill",
910                    _ => "vfp-spill+int",
911                };
912                promotion_dropped = vfp_dropped;
913            } else {
914                // Stage 2 (#1069, RQ-60-VFPPRESSURE increment 2) — LAST
915                // resort: the plain rung ALSO failed, i.e. the pressure is
916                // not (only) operand-stack values but PINNED LOCAL HOMES,
917                // which the #881 victim search rightly never touches (a home
918                // lives for the function's extent). Rerun the entire
919                // sequence with frame-homed overflow locals: a fresh
920                // f32/f64 local whose home grant would pin above the S7/D3
921                // cap lives in the frame from its first def. Reached ONLY by
922                // functions that failed every prior escape, so nothing that
923                // compiles today moves a byte.
924                let (fh, fh_rung, fh_dropped) = full_sequence(None, true, true, false);
925                note("vfp-frame-locals", &fh);
926                let (fh, fh_rung, fh_dropped) = if fh.as_ref().err().is_some_and(|e| {
927                    let msg = e.to_string();
928                    // The frame-homed-local slot demand (a PERMANENT slot per
929                    // frame-resident float local) is a third way the shared
930                    // pool exhausts — its trigger substring is the selector's
931                    // own pub const, not a second copy that could drift (the
932                    // #881 substring-is-control-flow lesson, pinned red-first
933                    // by the live24 fixture test).
934                    msg.contains(SLOT_EXHAUSTION)
935                        || msg.contains("spilling the VFP register file")
936                        || msg.contains(
937                            synth_synthesis::instruction_selector::VFP_FRAME_HOME_SLOT_EXHAUSTION,
938                        )
939                }) {
940                    let depth = synth_core::wasm_stack_check::max_depth_bound(wasm_ops) as usize;
941                    // Frame-homed locals hold their slots for the function's
942                    // extent, OUTSIDE the operand-stack depth bound — size
943                    // the grown pool for both. Distinct `local.set`/
944                    // `local.tee` targets over-approximate the frame-homed
945                    // local count; the selector clamps the request to its
946                    // cap, and a function that still exhausts stays an
947                    // honest loud skip.
948                    let local_targets: std::collections::HashSet<u32> = wasm_ops
949                        .iter()
950                        .filter_map(|op| match op {
951                            synth_synthesis::WasmOp::LocalSet(i)
952                            | synth_synthesis::WasmOp::LocalTee(i) => Some(*i),
953                            _ => None,
954                        })
955                        .collect();
956                    let (grown, grown_rung, grown_dropped) = full_sequence(
957                        Some(depth.saturating_add(local_targets.len()).saturating_add(4)),
958                        true,
959                        true,
960                        false,
961                    );
962                    note(
963                        &format!(
964                            "vfp-frame-locals+pool-grow({})",
965                            depth.saturating_add(local_targets.len()).saturating_add(4)
966                        ),
967                        &grown,
968                    );
969                    if grown.is_ok() {
970                        (grown, grown_rung, grown_dropped)
971                    } else {
972                        (fh, fh_rung, fh_dropped)
973                    }
974                } else {
975                    (fh, fh_rung, fh_dropped)
976                };
977                if fh.is_ok() {
978                    attempt = fh;
979                    rung = match fh_rung {
980                        "base" => "vfp-frame-locals",
981                        _ => "vfp-frame-locals+int",
982                    };
983                    promotion_dropped = fh_dropped;
984                } else {
985                    // Stage 3 (#1267, RQ-67-VFPREACH) — THE LAST RESORT, and the
986                    // reach half of #1204's root shape. Every escape above has
987                    // now ended in GI-FPU-002, so this function DECLINES today.
988                    //
989                    // It declines against HALF the register file: synth
990                    // allocates S0-S15/D0-D7 because S16-S31/D8-D15 are AAPCS
991                    // CALLEE-saved and, until this release, nothing could save
992                    // them — VPUSH/VPOP did not exist in the encoder. Every FPU
993                    // target synth supports actually has D0-D15 = S0-S31.
994                    //
995                    // Reached ONLY here, so a function that compiles today is
996                    // produced by exactly today's path and cannot move a byte —
997                    // the #881 rung discipline, measured over the corpus rather
998                    // than asserted. The selector emits the VPUSH/VPOP pair and
999                    // REFUSES functions with stack-passed params (#1273), so a
1000                    // failure here stays the honest loud decline it already was.
1001                    let (wide, wide_rung, wide_dropped) = full_sequence(None, true, true, true);
1002                    note("vfp-wide-file", &wide);
1003                    if wide.is_ok() {
1004                        attempt = wide;
1005                        rung = match wide_rung {
1006                            "base" => "vfp-wide-file",
1007                            _ => "vfp-wide-file+int",
1008                        };
1009                        promotion_dropped = wide_dropped;
1010                    } else {
1011                        attempt = fh;
1012                        promotion_dropped = fh_dropped;
1013                    }
1014                }
1015            }
1016        }
1017        // VCR-RA measurement (#242): log which recovery rung produced the result,
1018        // so the per-rung distribution across a corpus can be measured — the size
1019        // of the failure surface a verified allocator must subsume (see
1020        // scripts/repro/register_exhaustion_recovery_ladder.md). Logging only:
1021        // emitted bytes are unchanged, so the frozen byte gate is unaffected.
1022        if stats {
1023            // `rung` holds the last SUCCESSFUL rung; on total exhaustion it is
1024            // still "base", which said nothing about how far the ladder climbed
1025            // (#1318). Report it as `none` and let the per-rung lines above
1026            // carry the detail.
1027            let rung = if attempt.is_ok() { rung } else { "none" };
1028            eprintln!(
1029                "[recovery-stats] rung={rung}{} result={}",
1030                if promotion_dropped {
1031                    " promotion-off"
1032                } else {
1033                    ""
1034                },
1035                if attempt.is_ok() { "ok" } else { "exhausted" },
1036            );
1037        }
1038        attempt.map_err(|e| {
1039            // The kept Err first (so every substring any caller or test matches
1040            // on is exactly where it was), then the rungs that were tried and
1041            // what each one hit. Deduped by message: three rungs reporting one
1042            // wall should say so once, and name the three (#1318).
1043            let base = format!("instruction selection failed: {}", e);
1044            let rungs = tried.borrow();
1045            if rungs.len() < 2 {
1046                return base;
1047            }
1048            let mut by_msg: Vec<(String, Vec<String>)> = Vec::new();
1049            for (rung, msg) in rungs.iter() {
1050                match by_msg.iter_mut().find(|(m, _)| m == msg) {
1051                    Some((_, names)) => names.push(rung.clone()),
1052                    None => by_msg.push((msg.clone(), vec![rung.clone()])),
1053                }
1054            }
1055            let detail = by_msg
1056                .iter()
1057                .map(|(msg, names)| format!("{} -> {}", names.join(" + "), msg))
1058                .collect::<Vec<_>>()
1059                .join(" | ");
1060            format!("{base} [every recovery rung failed: {detail}]")
1061        })
1062    };
1063
1064    // Instruction selection: optimized or direct.
1065    //
1066    // #197: `--relocatable` (host-link ET_REL) forces the direct selector. The
1067    // optimized path materializes an absolute linmem base (0x20000100) and does
1068    // not preserve caller-saved registers across calls — both wrong for a
1069    // host-linked object, where the linmem base arrives via `fp` at runtime and
1070    // callees follow AAPCS. `select_with_stack` (now i64-spill capable after
1071    // #171) handles fp-relative memory + caller-saved preservation correctly.
1072    //
1073    // #507: `br_table` is DROPPED during the optimized path's wasm→IR lowering
1074    // (`optimize_full`), so `ir_to_arm` never sees the dispatch — it emits the
1075    // arm bodies in fall-through sequence with no `cmp`/branch on the selector, a
1076    // SILENT miscompile (every input hits the last arm). The selector value isn't
1077    // even loaded. Because the drop happens before `ir_to_arm`, there's no `Err`
1078    // to fall back on; detect it on the raw wasm op stream here and force the
1079    // direct selector (`select_with_stack` lowers `br_table` correctly as a
1080    // cmp-chain — confirmed on the `--relocatable` path). Same honest-degradation
1081    // contract as the issue-#120 f32 decline: the function still compiles
1082    // correctly, just without IR-level optimization. Frozen-safe: the frozen
1083    // fixtures compile `--relocatable` (already direct), and no optimized-path
1084    // fixture (control_step, flight_algo) contains `br_table`.
1085    let has_br_table = wasm_ops
1086        .iter()
1087        .any(|op| matches!(op, WasmOp::BrTable { .. }));
1088    // #509: the optimized path also drops the value carried by a `br`/`br_if`
1089    // to a result-typed block (the taken edge returns the wrong arm's value —
1090    // same silent-miscompile class as the #507 br_table drop). Route the shape
1091    // to the direct selector, whose designated-result-register lowering (#509)
1092    // lands the carried value at the join. Never fires for void-block control
1093    // flow (all frozen/optimized fixtures), so those stay byte-identical.
1094    let has_value_carry = has_value_carrying_branch(wasm_ops, &config.current_func_block_arity);
1095    // #503-i64/#518: route any signature with a 64-bit (i64/f64) param to the
1096    // direct selector. The optimized path's param homing is width-naive — its
1097    // #518 decline covers only functions that READ an i64 param (an `I64Load`
1098    // from a param index), so a function that reads an i32 param whose AAPCS
1099    // home a preceding wide param SHIFTED (e.g. p1 of `(i64 i32)` lives in R2,
1100    // not R1; p3 of `(i64 i32 i32 i32)` lives on the stack, not in R3) was
1101    // silently miscompiled rather than falling back. The direct selector's
1102    // `aapcs_param_layout` homing handles every such shape (i64-param READS
1103    // already fell back to it via the ir_to_arm Err, so those functions emit
1104    // the same bytes as before). `num_params` counts read-first locals, so a
1105    // function that never touches any param keeps the optimized path.
1106    let has_wide_param = config
1107        .current_func_params_i64
1108        .iter()
1109        .take(num_params as usize)
1110        .any(|&w| w);
1111    // #782(b): a HARD-float (FPU) target passes f32 args in VFP S-registers
1112    // and returns floats in S0/D0 (AAPCS-VFP) — but the optimized path's
1113    // param/return homing is float-naive (integer R0..R3 args, R0 return). A
1114    // function whose ops ALL lower on the optimized path but whose SIGNATURE
1115    // carries a float — e.g. the pure value-pick
1116    // `(param f32 f32 i32) (result f32) select`, no float OP to trip the
1117    // issue-#120 ir_to_arm fallback — was silently compiled with the integer
1118    // ABI: callers marshal S0/S1, the body reads R0/R1. Route every
1119    // float-signature function to the direct selector (AAPCS-VFP homing, or
1120    // an honest decline). Soft-float targets (no FPU) keep the optimized
1121    // path: the integer treatment IS the ABI there — byte-identical. (f64
1122    // params already route direct via `has_wide_param`; this adds f32 params
1123    // and f32/f64 returns.)
1124    let has_float_sig = config.target.fpu.is_some()
1125        && (config.current_func_ret_f32
1126            || config.current_func_ret_f64
1127            || config
1128                .current_func_params_f32
1129                .iter()
1130                .take(num_params as usize)
1131                .any(|&f| f)
1132            || config
1133                .current_func_params_f64
1134                .iter()
1135                .take(num_params as usize)
1136                .any(|&f| f));
1137    // #494 phase 2b: div/rem guard-elision marks are consumed by the DIRECT
1138    // selector only — the optimized path's IR passes (const-fold/CSE/DCE)
1139    // renumber instructions, so an op-index-keyed mark cannot soundly survive
1140    // them. Route marked functions direct (the #507/#509 honest-degradation
1141    // pattern). Never fires without SYNTH_FACT_SPEC + facts + a discharged
1142    // obligation, so every existing compile keeps its path byte-identical.
1143    let has_fact_div_elide = !fact_div_zero_elide.is_empty()
1144        || !fact_div_ovf_elide.is_empty()
1145        // #494 bounds-elision + VCR-MEM-004 (#901): memory bounds-guard marks
1146        // are direct-selector keyed for the same reason (IR passes renumber
1147        // instructions). This is ALSO why the optimized path's
1148        // `push_software_bounds_guard` sites never need mark plumbing: a
1149        // marked function is routed away from that path entirely.
1150        || !mem_bounds_elide.is_empty();
1151    // #643: the optimized path's global lowering is width-naive — `GlobalGet`/
1152    // `GlobalSet` are single-word `[R9, idx*4]` accesses, which (a) silently
1153    // dropped the high word of every i64 global and (b) mis-address every
1154    // global whose offset an earlier wide (i64/f64) slot shifted. When the
1155    // module has any wide global, route every global-touching function to the
1156    // direct selector, whose type-aware summed layout pairs the access (or
1157    // declines loudly). Modules with only 4-byte globals — every existing
1158    // fixture — keep the optimized path byte-identical.
1159    let has_wide_global_module = config.global_widths.iter().any(|&w| w > 4);
1160    let has_global_access = has_wide_global_module
1161        && wasm_ops
1162            .iter()
1163            .any(|op| matches!(op, WasmOp::GlobalGet(_) | WasmOp::GlobalSet(_)));
1164    // VCR-VER-001 (#242): `post_exhaust` scopes the post-exhaustion cleanup
1165    // extensions to functions whose bytes the #580 spill-on-exhaustion
1166    // machinery actually shaped (bridge-reported). Everything else — the
1167    // direct path, non-exhausted optimized functions — stays byte-identical
1168    // flag-on (the `vcr_ver_001_gate_242` lock's contract).
1169    let (arm_instrs, post_exhaust) = if config.no_optimize
1170        || config.relocatable
1171        || has_br_table
1172        || has_value_carry
1173        || has_wide_param
1174        || has_float_sig
1175        || has_global_access
1176        || has_fact_div_elide
1177        // #457: route read-before-write non-param locals to the direct
1178        // selector, whose prologue zero-init lands the wasm-mandated 0.
1179        || has_rbw_local
1180    {
1181        if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
1182            // RQ-65-PARITY (#197): name WHICH pre-gate predicate diverted the
1183            // function and which function it was, so the selector-parity
1184            // oracle can record every "only one path accepted this" case with
1185            // its reason instead of a bare count. The leading text is kept
1186            // verbatim — the #377/#1021 harnesses match on it.
1187            let reasons: Vec<&str> = [
1188                (config.no_optimize, "no-optimize"),
1189                (config.relocatable, "relocatable"),
1190                (has_br_table, "br-table"),
1191                (has_value_carry, "value-carry"),
1192                (has_wide_param, "wide-param"),
1193                (has_float_sig, "float-sig"),
1194                (has_global_access, "wide-global-access"),
1195                (has_fact_div_elide, "fact-elide"),
1196                (has_rbw_local, "rbw-local"),
1197            ]
1198            .iter()
1199            .filter(|(on, _)| *on)
1200            .map(|(_, name)| *name)
1201            .collect();
1202            eprintln!(
1203                "[path-debug] direct (pre-gate) func={} reasons={}",
1204                config
1205                    .current_func_index
1206                    .map_or("?".to_string(), |i| i.to_string()),
1207                reasons.join(",")
1208            );
1209        }
1210        (select_direct()?, false)
1211    } else {
1212        let opt_config = if config.loom_compat {
1213            OptimizationConfig::loom_compat()
1214        } else {
1215            OptimizationConfig::all()
1216        };
1217
1218        let mut bridge = OptimizerBridge::with_config(opt_config);
1219        // #188: tell the bridge how many imports there are so it declines only
1220        // LOCAL calls (and leaves import calls on the optimized path, keeping
1221        // the #173 field-name relocation rewrite intact).
1222        bridge.set_num_imports(config.num_imports);
1223        // #543 Phase 2: thread the integrator-marked volatile DMA-window ranges
1224        // (`--volatile-segment <base>:<len>`) to the bridge's address-caching
1225        // levers — base-CSE (#468) excludes any access inside a marked range
1226        // from its fold set, and the bridge-level const-CSE declines wholesale
1227        // while any range is marked. Empty (the default) ⇒ byte-identical.
1228        bridge.set_volatile_segments(config.volatile_segments.clone());
1229        // #377: thread `--safety-bounds` to the bridge. Pre-fix the optimized
1230        // path ignored it — `software`/`mask` were SILENT NO-OPS on the path
1231        // that lowers the bulk of a flight loop's i32 loads/stores (byte-
1232        // identical to `none`, while the safety manifest claimed otherwise).
1233        // `Software` now emits the inline guard per access; `Masking` declines
1234        // memory-accessing functions to the direct selector; `None`/`Mpu` are
1235        // byte-identical to before.
1236        bridge.set_bounds_check(bounds_config);
1237        // #687: thread the absolute linear-memory base the optimized path
1238        // materializes. Defaults to 0x2000_0100 (byte-identical);
1239        // `--stack-layout=low` shifts it up by the reserved stack size so
1240        // const-address accesses follow the moved linear memory.
1241        bridge.set_linmem_base(config.linmem_base);
1242        // `ir_to_arm` now returns `Result` — an `Err` means the optimized path
1243        // hit an unmapped vreg (issue-#93-class). Treat it identically to an
1244        // `optimize_full` failure: fall back to the direct selector rather
1245        // than propagating, so the function still compiles correctly.
1246        match bridge
1247            .optimize_full(wasm_ops)
1248            .and_then(|(opt_ir, _cfg, _stats)| bridge.ir_to_arm(&opt_ir, num_params as usize))
1249        {
1250            Ok(arm_ops) => {
1251                if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
1252                    eprintln!(
1253                        "[path-debug] optimized (ir_to_arm ok) func={}",
1254                        config
1255                            .current_func_index
1256                            .map_or("?".to_string(), |i| i.to_string())
1257                    );
1258                }
1259                (
1260                    arm_ops
1261                        .into_iter()
1262                        .map(|op| ArmInstruction {
1263                            op,
1264                            source_line: None,
1265                        })
1266                        .collect(),
1267                    bridge.spill_on_exhaust_fired(),
1268                )
1269            }
1270            // Issue #120: the optimized path declines modules it cannot lower
1271            // (notably scalar f32/f64 ops — the IR has no float opcodes). Fall
1272            // back to the direct instruction selector, which handles f32 via
1273            // VFP/FPU. This is honest degradation: the function still compiles
1274            // correctly, just without IR-level optimization.
1275            Err(e) => {
1276                if std::env::var("SYNTH_PATH_DEBUG").is_ok() {
1277                    eprintln!(
1278                        "[path-debug] direct (fallback: {e}) func={}",
1279                        config
1280                            .current_func_index
1281                            .map_or("?".to_string(), |i| i.to_string())
1282                    );
1283                }
1284                (select_direct()?, false)
1285            }
1286        }
1287    };
1288
1289    // #257/#277: `mul`+`add`→`mla` fusion is intentionally NOT wired here.
1290    // The transform is correct and ready (`synth_synthesis::liveness::fuse_mul_add`,
1291    // fully tested), but it is **register-allocation-coupled**: over the current
1292    // greedy single-pass selector, folding `mul rM,..; add rD,rM,rX` → `mla`
1293    // extends the live ranges of the mul inputs to the mla point, and the added
1294    // pressure (extra moves/spills) costs more than the single-cycle MLA saves —
1295    // gale measured a +2 cyc on-target REGRESSION (flat_flight 255→257, G474RE)
1296    // even though it removes 2 instructions and the seam stays 0x07FDF307. So the
1297    // fusion stays unwired until the spill-aware allocator (VCR-RA-001) chooses
1298    // registers, at which point it becomes net-positive (per #272's plan and the
1299    // wiring design note). Lesson (#277): a register-pressure-affecting transform
1300    // needs an on-target/allocator-aware gate, not a byte-count gate, before it
1301    // can default on.
1302
1303    // VCR-RA-001 const-CSE / rematerialization-avoidance (#209): moved to run
1304    // LAST, after the immediate-folds — see the apply_const_cse call below
1305    // (#242). Earlier it ran here (before range-realloc and the folds), which is
1306    // what let it grow gale's --relocatable `gust_mix` 90→92 B (#242 burndown,
1307    // 2026-06-26): retargeting a read defeated a *downstream* immediate-fold that
1308    // would otherwise have absorbed the constant. Running CSE-last makes those
1309    // foldable consts already-folded-and-gone, so CSE only ever touches genuinely
1310    // redundant materializations.
1311
1312    // VCR-RA-001 RANGE RE-ALLOCATION (#209/#242, wiring step 3a) — the first
1313    // CONSEQUENTIAL allocator pass: re-colour each maximal straight-line
1314    // segment over the R0-R8 pool with value ranges as the allocation unit
1315    // (segment inputs + per-register live-outs pinned to their original
1316    // registers, reserved R9-R12/SP identity-assigned — each segment is
1317    // independently sound, no cross-segment liveness assumed). Renames
1318    // registers only: never adds, removes, or reorders instructions, so
1319    // labels/branch offsets are unaffected.
1320    //
1321    // DEFAULT-ON since v0.11.36: gale cleared the gate on-target (G474RE,
1322    // #209 2026-06-10) — flag-on output byte-identical to flag-off on
1323    // flat_flight/controller/control_step, fires on the filter family with
1324    // zero cycle delta and a small size win, all selfchecks green on silicon.
1325    // Opt out with `SYNTH_RANGE_REALLOC=0`; per-function stats with
1326    // `SYNTH_REALLOC_STATS=1`.
1327    //
1328    // The companion dead callee-saved-save elimination (gale's "next
1329    // consequential lever", same issue comment) then shrinks the prologue
1330    // `push {r4-r8,lr}` / epilogue `pop {r4-r8,pc}` to the callee-saved
1331    // registers the re-allocated body still touches (leaf-only,
1332    // SP-untouched, even-count-padded — see shrink_callee_saved_saves):
1333    // ~12 cycles of pure save/restore overhead removed on small leaves.
1334    let realloc_on = std::env::var("SYNTH_RANGE_REALLOC").map_or(true, |v| v != "0");
1335    let (arm_instrs, ran_realloc) = if realloc_on {
1336        use synth_synthesis::rules::Reg;
1337        const POOL: [Reg; 9] = synth_synthesis::reg_contract::ALLOCATABLE;
1338        // VCR-DEC-001 (epic #242, the North Star's first foothold): the
1339        // SYNTH_GRAPH_ALLOC graph-colouring allocator SPIKE. When enabled it
1340        // replaces STEP 1 of the re-allocation (the segment-based
1341        // `reallocate_function`) with a whole-function Chaitin/Briggs colouring
1342        // (`graph_alloc::reallocate`) built against the SAME acceptance oracle
1343        // (`validate_segment_rewrite` trace-equality); the later dead-frame /
1344        // callee-saved-prologue / shrink passes still run on its output, so a
1345        // value it homes in R4-R8 still gets its callee-saved push (the
1346        // invariant the unconditional VCR-RA-003 validator guards). It is
1347        // BOUNDED to whole straight-line functions and DECLINES (returns None)
1348        // to the shipping `reallocate_function` on any control flow, spill, or
1349        // unmodeled op — never a hard-fail. Flag-OFF (`SYNTH_GRAPH_ALLOC` unset)
1350        // never enters this branch, so the shipping bytes are byte-identical
1351        // (the GOLDEN trick — frozen fixtures unchanged). NO default flip: the
1352        // spike ships flag-off; the flip is a later, evidence-gated step.
1353        //
1354        // VCR-VER-001 (#242): on a function the spill-on-exhaustion machinery
1355        // shaped, the terminal segment gets relaxed live-out pinning (only
1356        // R0/R1 are observable past `bx lr` at this pre-prologue position) so
1357        // the colourer can lower R4-R8-homed tails into caller-saved R0-R3 —
1358        // shrinking the `push {r4-r8,lr}` the #580 exhaustion shapes pay for.
1359        // `post_exhaust == false` selects the shipping pass bit for bit.
1360        let (out, stats) = if synth_synthesis::graph_alloc::enabled() {
1361            // RQ-60-RACOST increment 2 (#242): the colourer prices every
1362            // colour choice in REAL-ENCODER bytes. The sizer is the same
1363            // encoder family the emit loop below constructs — Thumb-2 (with
1364            // the target's FPU) or A32 — asked per candidate instruction, so
1365            // there is no hand size table to drift (#936). On the fixed-width
1366            // A32 ISA every candidate ties and the cost model degenerates to
1367            // the identity hint (zero churn).
1368            let sizing_encoder =
1369                if matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb) {
1370                    ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
1371                } else {
1372                    ArmEncoder::new_arm32()
1373                };
1374            let enc = |op: &synth_synthesis::rules::ArmOp| {
1375                sizing_encoder.encode(op).ok().map(|b| b.len())
1376            };
1377            let stats_on = std::env::var("SYNTH_GRAPH_ALLOC_STATS").is_ok();
1378            match synth_synthesis::graph_alloc::reallocate(&arm_instrs, &POOL, &enc) {
1379                // SYNTH_GRAPH_ALLOC_FORCE (test seam, RQ-60-RACOST
1380                // increment 2): ship every validated candidate WITHOUT the
1381                // final-byte arbiter — the pre-arbiter behaviour. Used by
1382                // `vcr_dec_001_join_alloc_execution_differential.py` so the
1383                // unicorn-vs-wasmtime oracle executes the colourer's
1384                // proposals on EVERY reachable shape (call, i64-pair,
1385                // shift-expansion), not only the ones the arbiter lets ship —
1386                // an arbiter-declined candidate is still a candidate a future
1387                // change could promote, and the execution teeth must stay
1388                // ahead of that. Never set in production; the arbiter is the
1389                // shipping behaviour.
1390                Some(candidate)
1391                    if std::env::var("SYNTH_GRAPH_ALLOC_FORCE").is_ok_and(|v| v != "0") =>
1392                {
1393                    if stats_on {
1394                        eprintln!(
1395                            "[graph-alloc] whole-function colouring APPLIED \
1396                             (validated; FORCED — arbiter bypassed)"
1397                        );
1398                    }
1399                    (
1400                        candidate,
1401                        synth_synthesis::liveness::ReallocStats::default(),
1402                    )
1403                }
1404                Some(candidate) => {
1405                    // FINAL-BYTE ARBITER (RQ-60-RACOST increment 2). A
1406                    // colour-time cost model — however faithful its byte sizes
1407                    // — cannot price DOWNSTREAM PASS INTERACTIONS: measured on
1408                    // const_cse.wat::spill12, an identity-shaped colouring
1409                    // that merely PRESERVED the greedy allocator's register
1410                    // rotation defeated const-CSE's canonicalization and grew
1411                    // the function 148 -> 244 B (+96), with not one occurrence
1412                    // priced differently at colour time. So the candidate is
1413                    // sized through the REAL downstream pipeline
1414                    // (`finish_allocated_stream` — the exact passes the
1415                    // shipped stream runs, not a mirror) plus label resolution
1416                    // and the REAL encoder, against the shipping allocator's
1417                    // stream sized identically, and it ships only when it is
1418                    // STRICTLY smaller. A tie or a refusal keeps the shipping
1419                    // bytes — growth on an applied function is structurally
1420                    // impossible, which is exactly the wired
1421                    // vcr_dec_001_graph_alloc_differential no-growth
1422                    // assertion, promoted from a gate into a construction.
1423                    let ship = synth_synthesis::liveness::reallocate_function_post_exhaust(
1424                        &arm_instrs,
1425                        &POOL,
1426                        post_exhaust,
1427                    );
1428                    let size_of = |stream: &[synth_synthesis::ArmInstruction]| -> Option<usize> {
1429                        let finished = match finish_allocated_stream(
1430                            stream.to_vec(),
1431                            config,
1432                            post_exhaust,
1433                            true,
1434                            selected_spill_areas.borrow().as_ref(),
1435                        ) {
1436                            Ok(f) => f,
1437                            Err(e) => {
1438                                if stats_on {
1439                                    // The differential greps for the RA-003
1440                                    // hard-error string to detect a SHIPPED
1441                                    // violation; a candidate refused during
1442                                    // sizing is a decline, not a shipped
1443                                    // violation, so that marker is rewritten.
1444                                    let e = e.replace(
1445                                        "register-allocation validation FAILED",
1446                                        "register-allocation validation refused the candidate",
1447                                    );
1448                                    eprintln!(
1449                                        "[graph-alloc] arbiter: stream refused by the \
1450                                         pipeline/validators: {e}"
1451                                    );
1452                                }
1453                                return None;
1454                            }
1455                        };
1456                        let finished = if matches!(
1457                            config.target.isa,
1458                            IsaVariant::Thumb2 | IsaVariant::Thumb
1459                        ) {
1460                            resolve_label_branches(finished, &sizing_encoder).ok()?
1461                        } else {
1462                            finished
1463                        };
1464                        let mut total = 0usize;
1465                        let mut literals = 0usize;
1466                        for ins in &finished {
1467                            total += sizing_encoder.encode(&ins.op).ok()?.len();
1468                            if matches!(ins.op, synth_synthesis::rules::ArmOp::LdrSym { .. }) {
1469                                literals += 1;
1470                            }
1471                        }
1472                        if literals > 0 {
1473                            // The emit loop 4-aligns the literal pool and
1474                            // appends one word per LdrSym (no dedup — each
1475                            // site carries its own addend).
1476                            total += (4 - total % 4) % 4 + 4 * literals;
1477                        }
1478                        Some(total)
1479                    };
1480                    match (size_of(&candidate), size_of(&ship.0)) {
1481                        (Some(cand), Some(base)) if cand < base => {
1482                            if stats_on {
1483                                eprintln!(
1484                                    "[graph-alloc] whole-function colouring APPLIED \
1485                                     (validated; arbiter: {cand} B < shipping {base} B)"
1486                                );
1487                            }
1488                            (
1489                                candidate,
1490                                synth_synthesis::liveness::ReallocStats::default(),
1491                            )
1492                        }
1493                        (cand, base) => {
1494                            if stats_on {
1495                                eprintln!(
1496                                    "[graph-alloc] arbiter kept shipping bytes \
1497                                     (candidate {cand:?} B vs shipping {base:?} B) → \
1498                                     shipping reallocate_function"
1499                                );
1500                            }
1501                            ship
1502                        }
1503                    }
1504                }
1505                None => {
1506                    if stats_on {
1507                        eprintln!("[graph-alloc] DECLINED → shipping reallocate_function");
1508                    }
1509                    synth_synthesis::liveness::reallocate_function_post_exhaust(
1510                        &arm_instrs,
1511                        &POOL,
1512                        post_exhaust,
1513                    )
1514                }
1515            }
1516        } else {
1517            synth_synthesis::liveness::reallocate_function_post_exhaust(
1518                &arm_instrs,
1519                &POOL,
1520                post_exhaust,
1521            )
1522        };
1523        if std::env::var("SYNTH_REALLOC_STATS").is_ok() {
1524            eprintln!(
1525                "[range-realloc] {} segments: {} reallocated, {} declined ({} validator-rejected), {} need spill (step 4)",
1526                stats.segments,
1527                stats.reallocated,
1528                stats.declined,
1529                stats.validator_rejects,
1530                stats.needs_spill
1531            );
1532        }
1533        // VCR-VER-004 AUDIT (#242) — report-only, opt-in, never gating.
1534        //
1535        // The ABI observable-contract validator is a GATE on the flag-off
1536        // graph-colouring spike. This hook asks the same question of the
1537        // SHIPPING allocator's rewrite, so the answer is a MEASUREMENT rather
1538        // than a claim: how much of the shipping path can a value-level,
1539        // ABI-anchored check actually see today? Report-only DELIBERATELY —
1540        // making it gate here would risk a false rejection on the default
1541        // path, and the honest sequence is measure first, flip on evidence.
1542        // `SYNTH_ABI_CONTRACT_AUDIT=1` prints one verdict per function.
1543        if std::env::var_os("SYNTH_ABI_CONTRACT_AUDIT").is_some() {
1544            eprintln!(
1545                "[abi-contract-audit] {:?}",
1546                synth_synthesis::abi_contract::validate_abi_contract(&arm_instrs, &out)
1547            );
1548        }
1549        (out, true)
1550    } else {
1551        (arm_instrs, false)
1552    };
1553    // RQ-60-RACOST increment 2 (#242): every rewrite pass between the chosen
1554    // allocation and the encoder now lives in `finish_allocated_stream`, so
1555    // the SYNTH_GRAPH_ALLOC final-byte arbiter can size a candidate through
1556    // the REAL pipeline. Flag-off this is the exact pre-extraction sequence,
1557    // called once, in the same place.
1558    let arm_instrs = finish_allocated_stream(
1559        arm_instrs,
1560        config,
1561        post_exhaust,
1562        ran_realloc,
1563        selected_spill_areas.borrow().as_ref(),
1564    )?;
1565
1566    // Encode to binary — use Thumb-2 for Cortex-M targets
1567    let use_thumb2 = matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
1568
1569    let encoder = if use_thumb2 {
1570        ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
1571    } else {
1572        ArmEncoder::new_arm32()
1573    };
1574
1575    // #202: resolve local label branches (Bcc/B/Bhs/Blo) to byte-accurate
1576    // offsets before encoding. `select_with_stack` emits them as label
1577    // placeholders and never resolves them — without this they encode as
1578    // `bne.n #0` and land mid-instruction whenever a 32-bit Thumb-2 instruction
1579    // sits between the branch and its target (UsageFault on real hardware).
1580    // Only meaningful for Thumb-2 (the offset units are halfword/PC+4).
1581    let arm_instrs = if use_thumb2 {
1582        let resolved = resolve_label_branches(arm_instrs, &encoder)?;
1583        // SC-5 (#740/#930): hard-gate every branch target onto the
1584        // instruction-start set of the final stream — both codegen paths
1585        // funnel through here. See `validate_branch_targets`.
1586        validate_branch_targets(&resolved, &encoder)?;
1587        resolved
1588    } else {
1589        arm_instrs
1590    };
1591
1592    // #778: capture the FINAL Thumb-2 instruction stream (post label-resolution,
1593    // the exact list the encode loop below consumes) so `compile_function` can
1594    // derive the sound WCET bound. Cheap clone; frozen-safe (the WCET walk is a
1595    // pure observation and never touches `code`). Only the Thumb-2 path — the A32
1596    // (Cortex-R5) cycle model is a follow-up.
1597    let final_instrs_for_wcet: Option<Vec<synth_synthesis::ArmInstruction>> = if use_thumb2 {
1598        Some(arm_instrs.clone())
1599    } else {
1600        None
1601    };
1602
1603    let mut code = Vec::new();
1604    let mut relocations = Vec::new();
1605
1606    // #345: literal-pool address loads. Each `LdrSym` was encoded as a placeholder
1607    // `LDR.W rd,[pc,#0]`; record where its instruction sits and what it loads so
1608    // we can append a pooled word (carrying the symbol address via R_ARM_ABS32)
1609    // and patch the PC-relative offset once the pool position is known.
1610    struct PendingLiteral {
1611        ldr_offset: u32,
1612        symbol: String,
1613        addend: i32,
1614    }
1615    let mut pending_literals: Vec<PendingLiteral> = Vec::new();
1616
1617    // VCR-DBG-001: per-instruction source map for DWARF `.debug_line`. Captured
1618    // here because `code.len()` immediately before `encode()` is the final
1619    // machine offset of the instruction within this function's `.text` — nothing
1620    // after the loop shifts earlier instructions (the literal pool is appended at
1621    // the end; the LDR patch below is in-place/length-preserving). Purely
1622    // additive: it does not touch `code`, so `.text` is byte-identical.
1623    let mut line_map: LineMap = Vec::new();
1624    // VCR-DEC-003 (#396): object-branch class per emitted instruction, parallel
1625    // to `line_map`. Cheap, additive, does not touch `code`.
1626    let mut branch_map: synth_core::backend::BranchMap = Vec::new();
1627
1628    for instr in &arm_instrs {
1629        // Record a relocation for every BL: the encoder emits `bl #0` and
1630        // relies on a relocation to patch the target. This covers BOTH import
1631        // dispatch stubs (`__meld_*`, undefined externals) AND internal calls
1632        // (`func_N`, defined in this object). Previously only `__meld_*` was
1633        // recorded, so internal `BL func_N` calls were left as unpatched
1634        // `bl #0` placeholders branching to a garbage address (#167).
1635        if let ArmOp::Bl { label } = &instr.op {
1636            // #1040: the relocation type is ISA-STATE-dependent and this is the
1637            // only site that knows the state. An A32 (Cortex-R) `bl` is
1638            // R_ARM_CALL (28); a Thumb `bl` is R_ARM_THM_CALL (10). Emitting
1639            // the Thumb type for an A32 word made any consumer that trusts the
1640            // declared type patch Thumb halfwords into an ARM-state
1641            // instruction. Decided here rather than in the ELF emitter, where
1642            // `config.target` is no longer in scope and the ISA would have to
1643            // be re-derived — the shape that produced the bug.
1644            let kind = if config.target.isa == synth_core::target::IsaVariant::Arm32 {
1645                synth_core::backend::RelocKind::ArmCall
1646            } else {
1647                synth_core::backend::RelocKind::ThmCall
1648            };
1649            relocations.push(CodeRelocation {
1650                offset: code.len() as u32,
1651                symbol: label.clone(),
1652                kind,
1653            });
1654        }
1655        // #237: symbol-relative MOVW/MOVT (the `--native-pointer-abi` static-data
1656        // addressing). The encoder writes the addend in place; record the matching
1657        // R_ARM_MOVW_ABS_NC / R_ARM_MOVT_ABS so the linker adds the symbol address.
1658        if let ArmOp::MovwSym { symbol, .. } = &instr.op {
1659            relocations.push(CodeRelocation {
1660                offset: code.len() as u32,
1661                symbol: symbol.clone(),
1662                kind: synth_core::backend::RelocKind::MovwAbs,
1663            });
1664        }
1665        if let ArmOp::MovtSym { symbol, .. } = &instr.op {
1666            relocations.push(CodeRelocation {
1667                offset: code.len() as u32,
1668                symbol: symbol.clone(),
1669                kind: synth_core::backend::RelocKind::MovtAbs,
1670            });
1671        }
1672        // #345: defer the literal-pool word + reloc + offset patch to the
1673        // post-loop pass (the pool address is not yet known).
1674        if let ArmOp::LdrSym { symbol, addend, .. } = &instr.op {
1675            pending_literals.push(PendingLiteral {
1676                ldr_offset: code.len() as u32,
1677                symbol: symbol.clone(),
1678                addend: *addend,
1679            });
1680        }
1681
1682        // The machine offset of this instruction is the current code length,
1683        // captured before the bytes are appended.
1684        line_map.push((code.len() as u32, instr.source_line));
1685        branch_map.push((code.len() as u32, classify_arm_branch(&instr.op)));
1686
1687        let encoded = encoder
1688            .encode(&instr.op)
1689            .map_err(|e| format!("ARM encoding failed: {}", e))?;
1690        code.extend_from_slice(&encoded);
1691    }
1692
1693    // #345: place the literal pool at the end of this function's `.text`. Gated on
1694    // there being at least one `LdrSym` — functions without one are byte-identical
1695    // to before (no trailing padding, so downstream `func_offsets` are unchanged
1696    // and the frozen differential fixtures stay bit-for-bit equal).
1697    if !pending_literals.is_empty() {
1698        if !use_thumb2 {
1699            return Err("LdrSym literal-pool addressing requires Thumb-2".to_string());
1700        }
1701        // 4-byte align the pool start (Thumb-2 word loads require it, and
1702        // `Align(PC,4)` in the LDR-literal semantics assumes a word-aligned pool).
1703        while code.len() % 4 != 0 {
1704            code.push(0x00);
1705        }
1706        // One distinct pooled word per LdrSym (no dedup: different sites carry
1707        // different addends, and the REL addend lives in the word).
1708        for lit in &pending_literals {
1709            let word_offset = code.len() as u32;
1710
1711            // REL semantics: the linker computes `S + A`, where A is the in-place
1712            // value of the relocated word. Initialize the word to the addend so
1713            // the final loaded address is `symbol + addend`.
1714            code.extend_from_slice(&(lit.addend as u32).to_le_bytes());
1715            relocations.push(CodeRelocation {
1716                offset: word_offset,
1717                symbol: lit.symbol.clone(),
1718                kind: synth_core::backend::RelocKind::Abs32,
1719            });
1720
1721            // Patch the placeholder `LDR.W rd,[pc,#imm12]`. Thumb-2 LDR (literal):
1722            // address = Align(PC,4) + imm12, with PC = ldr_offset + 4. The pool is
1723            // always after the LDR, so U=1 (already set in hw1 = 0xF8DF).
1724            let pc = lit.ldr_offset + 4;
1725            let aligned_pc = pc & !3u32;
1726            let imm12 = word_offset - aligned_pc;
1727            if imm12 > 0xFFF {
1728                // Wide LDR-literal range is ±4 KB; these function bodies are far
1729                // smaller, but fail cleanly rather than miscompile if exceeded.
1730                return Err(format!(
1731                    "LdrSym literal pool out of range (#345): imm12={} > 4095 \
1732                     for symbol {}",
1733                    imm12, lit.symbol
1734                ));
1735            }
1736            let hw2_off = (lit.ldr_offset + 2) as usize;
1737            let mut hw2 = u16::from_le_bytes([code[hw2_off], code[hw2_off + 1]]);
1738            hw2 = (hw2 & 0xF000) | (imm12 as u16); // keep Rt, set imm12
1739            let hw2_bytes = hw2.to_le_bytes();
1740            code[hw2_off] = hw2_bytes[0];
1741            code[hw2_off + 1] = hw2_bytes[1];
1742        }
1743    }
1744
1745    Ok((
1746        code,
1747        relocations,
1748        line_map,
1749        branch_map,
1750        final_instrs_for_wcet,
1751    ))
1752}
1753
1754/// RQ-60-RACOST increment 2 (#242): every rewrite pass between a CHOSEN
1755/// register allocation and the encoder, as ONE reusable sequence.
1756///
1757/// Extracted VERBATIM from `compile_wasm_to_arm` (pure code motion) so the
1758/// `SYNTH_GRAPH_ALLOC` final-byte arbiter can size a candidate allocation
1759/// through the REAL downstream pipeline — the same passes, in the same order,
1760/// reading the same flags — rather than through a hand-mirrored predicate of
1761/// them (the #936 drift class: a hand mirror of the encoder's offset-fold
1762/// threshold was UNSOUND at authoring; a hand mirror of eleven rewrite passes
1763/// would be worse). Flag-off behaviour is byte-identical: the shipping path
1764/// calls this exactly once, on the same stream, in the same place it always
1765/// ran.
1766///
1767/// `ran_realloc` selects the historical branch: the dead-frame /
1768/// callee-saved-prologue / shrink trio runs only downstream of the range
1769/// re-allocation lever (`SYNTH_RANGE_REALLOC` on), exactly as before the
1770/// extraction. Diagnostics inside (SYNTH_FUSE_STATS, SYNTH_SHADOW_ALLOC,
1771/// SYNTH_SPILL_REPORT) print once per CALL, so an arbiter sizing run repeats
1772/// them — measurement noise under two opt-in flags, never a byte change.
1773fn finish_allocated_stream(
1774    arm_instrs: Vec<synth_synthesis::ArmInstruction>,
1775    config: &CompileConfig,
1776    post_exhaust: bool,
1777    ran_realloc: bool,
1778    // #1321: `(frame_size, areas)` recorded by the direct selector for the
1779    // attempt that produced this stream — the frame regions that are genuinely
1780    // allocator SPILL slots. Used to scope VCR-RA-003's #331 check, and ONLY
1781    // after `frame_size` is re-proven against this stream (see the use site).
1782    // `None` on the optimized path and whenever no area was reserved.
1783    recorded_spill_areas: Option<&(i32, Vec<std::ops::Range<i32>>)>,
1784) -> Result<Vec<synth_synthesis::ArmInstruction>, String> {
1785    let arm_instrs = if ran_realloc {
1786        let out = arm_instrs;
1787        // VCR-RA-002 (#390, epic #242): eliminate a provably-dead stack frame
1788        // (`sub sp,#N`/`add sp,#N` reserved by `compute_local_layout` for locals
1789        // that promotion homed in registers, never accessed). Removing it saves
1790        // the two instructions AND restores the SP-untouched precondition that
1791        // `shrink_callee_saved_saves` requires — so it must run FIRST.
1792        // DEFAULT-ON (#242 flag audit flip-wave, #592 audit item): evidence
1793        // basis was the 2-path × repro-corpus sweep — 0 functions grow, 58
1794        // shrink (flight_seam controller_step 250→242 −8 / filter_step 180→168
1795        // −12, native_pointer frame_roundtrip 46→34 −12), locked by the
1796        // `dead_frame_elim_no_grow_corpus_242` cargo gate; execution
1797        // differentials re-run green on the new default bytes BEFORE the
1798        // frozen ARM anchors were re-pinned (leaf_dead_frame, flight_seam,
1799        // frame_slot_dce — see the flip PR). Escape hatch:
1800        // `SYNTH_DEAD_FRAME_ELIM=0` opts out and restores the pre-flip bytes
1801        // (CI-gated in `frozen_codegen_bytes.rs`).
1802        let out = if !std::env::var("SYNTH_DEAD_FRAME_ELIM").is_ok_and(|v| v == "0") {
1803            synth_synthesis::liveness::elide_dead_frame(&out).unwrap_or(out)
1804        } else {
1805            out
1806        };
1807        // #490 (epic #242): the optimized selector uses r4-r8 as scratch /
1808        // promoted locals but emits no prologue, silently clobbering a caller's
1809        // callee-saved registers. Add the missing `push {r4-r8,lr}` /
1810        // `pop {r4-r8,pc}` HERE — on the post-realloc body, where realloc has
1811        // lowered low-pressure r4-r8 scratch back to r0-r3, so a save is added
1812        // only for registers genuinely clobbered. `shrink_callee_saved_saves`
1813        // (next) then trims it to the used set. No-op on the direct path (it
1814        // already has its own prologue) and on callee-saved-free leaves.
1815        let out = synth_synthesis::liveness::ensure_callee_saved_prologue(&out);
1816        synth_synthesis::liveness::shrink_callee_saved_saves(&out).unwrap_or(out)
1817    } else {
1818        // Range-realloc off (`SYNTH_RANGE_REALLOC=0`): the optimized path still
1819        // must preserve the callee-saved registers it clobbers (#490). No shrink
1820        // (it is coupled to the realloc lever), so the conservative full save
1821        // stays — correct, just not minimised in this debug configuration.
1822        synth_synthesis::liveness::ensure_callee_saved_prologue(&arm_instrs)
1823    };
1824    // VCR-RA-001 SHADOW ALLOCATION (#209/#242): run the register allocator on
1825    // the selected stream and LOG what it finds — without changing a single
1826    // emitted byte. This is the measure-only bridge between the built analysis
1827    // layer and the eventual virtual-register wiring: it shows, per real
1828    // function, whether the allocator can colour it within the R0–R8 pool and
1829    // how much const-CSE / rematerialization headroom exists (#209). Enable with
1830    // `SYNTH_SHADOW_ALLOC=1`; off by default and side-effect-free either way.
1831    if std::env::var("SYNTH_SHADOW_ALLOC").is_ok() {
1832        use synth_synthesis::liveness::{
1833            AllocationOutcome, allocate_function, function_peak_pressure,
1834        };
1835        // R9 globals / R10 mem-size / R11 mem-base / R12 IP-scratch are reserved;
1836        // pin them above the 0..9 allocatable pool so the colourer keeps R0–R8.
1837        let precolored = std::collections::BTreeMap::from([
1838            (synth_synthesis::rules::Reg::R9, 9usize),
1839            (synth_synthesis::rules::Reg::R10, 10),
1840            (synth_synthesis::rules::Reg::R11, 11),
1841            (synth_synthesis::rules::Reg::R12, 12),
1842        ]);
1843        // True VALUE pressure (one node per value, not per reused physical reg):
1844        // a NeedsSpill with peak ≤ 9 is a SPURIOUS physical-register spill — the
1845        // function fits once virtually allocated.
1846        let peak = function_peak_pressure(&arm_instrs);
1847        match allocate_function(&arm_instrs, 9, &precolored) {
1848            AllocationOutcome::Allocated {
1849                remat_opportunities,
1850                coloring,
1851            } => eprintln!(
1852                "[shadow-alloc] OK: {} pregs coloured within R0-R8 pool, peak value-pressure {}, {} const-CSE/remat opportunities",
1853                coloring.len(),
1854                peak,
1855                remat_opportunities
1856            ),
1857            AllocationOutcome::NeedsSpill(s) => eprintln!(
1858                "[shadow-alloc] physical-graph would spill {:?}, but peak value-pressure is {} (≤9 ⇒ spurious; fits once virtually allocated)",
1859                s, peak
1860            ),
1861            AllocationOutcome::Declined => {
1862                eprintln!(
1863                    "[shadow-alloc] declined (unmodeled construct — calls/i64/fp/offset-branch)"
1864                )
1865            }
1866        }
1867    }
1868
1869    // VCR-SEL-004 cmp→select → IT-block predication fusion (#242). The selector
1870    // lowers a `select` whose condition is a comparison to a *materialize then
1871    // re-test* sequence (`cmp a,b; SetCond D,c; cmp D,#0; movne dst,v1; moveq
1872    // dst,v2`); this collapses it onto the comparison's own flags — deleting the
1873    // `SetCond` and the `cmp D,#0` and retargeting the predicated moves to `c` /
1874    // `invert(c)` — yielding the textbook predicated clamp (`cmp a,b; movc dst,v1;
1875    // mov{!c} dst,v2`). −2 instructions per fused select. gale #428 measured this
1876    // as the #1 hot-path size/cycle lever on the gust_mix clamp chain.
1877    //
1878    // Run LATE: after range re-allocation (so the dead-D proof sees final register
1879    // identities) and before encode. Removal-only + rename-only ⇒ no spill
1880    // regression and labels/branch offsets are unaffected. Each fusion is proven
1881    // sound (flags reused only when nothing clobbers them in the window; the
1882    // boolean deleted only when provably dead) — see `fuse_cmp_select`.
1883    //
1884    // DEFAULT-ON as of v0.13.0 (#428): cmp→select fusion ships by default. The
1885    // byte-changing flip is validated by (a) the unicorn execution oracle that runs
1886    // the two-move `mov{invert(c)}` arm (cmp_select_two_move_differential.py), (b)
1887    // gale's gale_decider_diff 10,596-case sweep across all 8 verified primitives
1888    // (native ≡ flag-off ≡ flag-on = 0x88e73178d232bcf5), and (c) the named-anchor
1889    // differentials re-run with fusion ON — control_step still 0x00210A55, flat+
1890    // inlined flight_algo still 0x07FDF307 (results preserved; bytes deliberately
1891    // changed, re-frozen on this commit). Escape hatch: `SYNTH_NO_CMP_SELECT_FUSE=1`
1892    // reverts to the pre-fusion lowering. The on-silicon G474RE DWT no-regression
1893    // check is a tracked post-ship follow-up (gale owns it).
1894    let arm_instrs = if std::env::var("SYNTH_NO_CMP_SELECT_FUSE").is_err() {
1895        // The rewritten stream is identical to `fuse_cmp_select`'s 2-tuple form;
1896        // the extra `two_move` count is diagnostic only (the fusion census /
1897        // blast-radius datum — #7 made that arm reachable).
1898        let (out, fused, two_move) =
1899            synth_synthesis::liveness::fuse_cmp_select_with_stats(&arm_instrs);
1900        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1901            let in_place = fused - two_move;
1902            eprintln!(
1903                "[cmp-select-fuse] {fused} select(s) fused to predicated moves \
1904                 ({two_move} two-move, {in_place} in-place)"
1905            );
1906        }
1907        out
1908    } else {
1909        arm_instrs
1910    };
1911
1912    // Perf lever 1 toward native parity (#390): redundant stack-reload elimination.
1913    // synth lowers every wasm local to a frame slot, so `local.set; local.get` emits
1914    // `str rX,[sp,#N]; … ; ldr rY,[sp,#N]`; when rX still holds the value the reload
1915    // (a ~2-cycle M4 load) becomes `mov rY,rX`. Removal-of-a-load + rename only ⇒ no
1916    // new instruction form and no label/offset change. DEFAULT-ON (#242 feature
1917    // loop): validated bit-identical RESULTS on every frozen anchor (control_step
1918    // 0x00210A55 13/13, flat+inlined flight_algo 0x07FDF307) with .text reduced on
1919    // the shipped --relocatable path, plus 8 unit tests + the frame_slot_dce
1920    // execution differential — the same gated path cmp→select took to default-on in
1921    // v0.13.0 (G474RE silicon confirms perf post-ship). Escape hatch:
1922    // `SYNTH_NO_STACK_FWD=1` restores the frame-resident bytes (frozen-old goldens).
1923    let stack_fwd = std::env::var("SYNTH_NO_STACK_FWD").is_err();
1924    let arm_instrs = if stack_fwd {
1925        let (out, fwd) = synth_synthesis::liveness::forward_stack_reloads(&arm_instrs);
1926        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1927            eprintln!("[stack-fwd] {fwd} stack reload(s) forwarded to register moves");
1928        }
1929        out
1930    } else {
1931        arm_instrs
1932    };
1933
1934    // VCR-RA frame-slot DCE (#242): once `forward_stack_reloads` has turned the
1935    // reloads of a spill slot into register moves, the `str rX,[sp,#N]` that fed
1936    // them is a dead store — its slot is never loaded again. Remove it. Pairs
1937    // with (and only pays after) stack-reload forwarding, so it shares the flag.
1938    let arm_instrs = if stack_fwd {
1939        let (out, n) = synth_synthesis::liveness::eliminate_dead_frame_stores(&arm_instrs);
1940        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
1941            eprintln!("[frame-slot-dce] {n} dead frame store(s) removed");
1942        }
1943        out
1944    } else {
1945        arm_instrs
1946    };
1947
1948    // VCR-RA-001 spill re-choice (#242), two stages behind one flag.
1949    // Stage 1 (the #569 spike): slot-value forwarding BETWEEN reloads.
1950    // `forward_stack_reloads` (above) forwards only from a spill store's
1951    // SOURCE register, so when register pressure clobbers that source its
1952    // reloads survive; this stage tracks which registers provably still hold
1953    // a frame slot's value (through earlier reloads and reg-reg moves) and
1954    // turns reload #2..#n into a 1-cycle `mov` (or deletes it when the target
1955    // already holds the value). Stage 2 (the Belady re-choice): where NO
1956    // register still holds the value — the genuine-spill case, flat_flight's
1957    // peak-11 hot segment — the value was usually evicted while a dead
1958    // register existed; the clobbering def(s) are renamed onto a provably-dead
1959    // register (`spill_rechoice_segment`) so the value stays resident and the
1960    // reload dissolves outright. A dissolved reload can leave the feeding
1961    // store dead, so the frame-slot DCE sweep runs once more behind the same
1962    // flag. Per-segment commit gates: executable same-value-flow trace
1963    // equality, strict shrink, pool-pressure fit, sub-word/unknown-slot
1964    // conservatism (see `apply_spill_realloc` / `spill_rechoice_segment`).
1965    // Stage 3 (whole-function slot liveness): the segment-local DCE keeps a
1966    // store whose slot reaches function end ("reach-end ≠ dead" — it cannot
1967    // see other segments); `eliminate_unread_frame_stores` walks the whole
1968    // function (labels/branches/loops, SP-displacement tracked) and drops a
1969    // store whose slot NO reachable instruction can read — flat_flight's two
1970    // surviving stores (#576), completing Belady's 0-load side with a 0-store
1971    // side. Same flag: the three stages are one lever, flipped together.
1972    // DEFAULT-ON (#242 feature loop, the v0.14.0 local-promotion pattern):
1973    // Belady spilling ships by default. Evidence basis for the flip: three
1974    // landed flag-off increments (#569 forwarding, #576 Belady re-choice,
1975    // #579 whole-fn slot liveness), 40+ functions shrink / 0 grow across the
1976    // 68-fixture × 2-path sweep, per-segment executable value-trace equality
1977    // guards, and the unicorn-vs-wasmtime execution differentials re-run
1978    // green on the new default bytes (flat+inlined flight_algo 0x07FDF307,
1979    // const_cse, frame_slot_dce, spill_rung_581, r12_spill_496 — which covers
1980    // control_step_decide vs wasmtime; control_step's .text is byte-identical
1981    // under the flip) BEFORE the frozen goldens were re-pinned. Escape hatch:
1982    // `SYNTH_SPILL_REALLOC=0` is the OPT-OUT — it disables all three stages
1983    // and restores the pre-flip bytes (CI-gated by
1984    // `frozen_fixtures_spill_realloc_escape_hatch_restores_old_bytes`). Any
1985    // other value (or unset) runs the pass.
1986    // VCR-VER-001 post-exhaustion extensions (#242, the PR #659 verdict): with
1987    // `SYNTH_SPILL_ON_EXHAUST` active the #580 allocation-time Belady spill
1988    // keeps exhausted functions on the optimized path, and its slots present
1989    // shapes the shipping pass structurally cannot fire on (fresh-monotonic
1990    // slots defeat the overwrite-only DCE; the eviction store's source is
1991    // redefined immediately, defeating store→reload forwarding; R2/R3 are
1992    // never touched again, so the rename-target deadness proof declines them).
1993    // `post_exhaust` (bridge-scoped, see above) enables const
1994    // rematerialization of spilled constants, R2/R3 exit-dead rename targets,
1995    // and per-pair pressure commit — see `apply_spill_realloc_post_exhaust`.
1996    // Flag off (the default): `false` selects the shipping behavior bit for
1997    // bit.
1998    let arm_instrs = if !std::env::var("SYNTH_SPILL_REALLOC").is_ok_and(|v| v == "0") {
1999        let (out, n) =
2000            synth_synthesis::liveness::apply_spill_realloc_post_exhaust(&arm_instrs, post_exhaust);
2001        let (out, d) = synth_synthesis::liveness::eliminate_dead_frame_stores(&out);
2002        let (mut out, u) = synth_synthesis::liveness::eliminate_unread_frame_stores(&out);
2003        let (mut tn, mut td, mut tu) = (n, d, u);
2004        // Post-exhaustion only: iterate the triple to a bounded fixpoint. Each
2005        // dissolved spill pair frees registers and removes stores, exposing
2006        // rename windows and holder chains the previous iteration could not
2007        // prove — the allocation-time Belady slots (#580) routinely need two
2008        // or three rounds where the shipping single round suffices for the
2009        // default path's slots. Every iteration is individually gate-proven
2010        // (value-trace equality, pool pressure, strict shrink), so iterating
2011        // composes soundly; the bound keeps compile time deterministic.
2012        if post_exhaust {
2013            let mut progress = n + d + u > 0;
2014            for _ in 0..3 {
2015                if !progress {
2016                    break;
2017                }
2018                let (o, n) =
2019                    synth_synthesis::liveness::apply_spill_realloc_post_exhaust(&out, true);
2020                let (o, d) = synth_synthesis::liveness::eliminate_dead_frame_stores(&o);
2021                let (o, u) = synth_synthesis::liveness::eliminate_unread_frame_stores(&o);
2022                progress = n + d + u > 0;
2023                (tn, td, tu) = (tn + n, td + d, tu + u);
2024                out = o;
2025            }
2026            // The cleanup can leave the spill frame with zero surviving
2027            // accesses (every reload rematerialized/dissolved, every store
2028            // swept) — the balanced `sub sp,#K`/`add sp,#K` is then pure
2029            // overhead. `elide_dead_frame` proves that and removes the pair;
2030            // its early run (post-realloc) could not, because the spill
2031            // traffic was still in the stream at that point.
2032            out = synth_synthesis::liveness::elide_dead_frame(&out).unwrap_or(out);
2033        }
2034        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2035            eprintln!(
2036                "[spill-realloc] {tn} reload(s) forwarded/eliminated, {td} newly-dead frame store(s) removed, {tu} unread-slot store(s) removed"
2037            );
2038        }
2039        out
2040    } else {
2041        arm_instrs
2042    };
2043
2044    // VCR-RA immediate-shift folding (#390, #242): a constant shift amount the
2045    // stack selector materialized into a scratch register (`movw rM,#C; lsl rD,rN,rM`)
2046    // folds to the immediate form (`lsl rD,rN,#C`), removing the dead `movw` — −1
2047    // instruction, −1 live register. Removal-only (offset-neutral before branch
2048    // resolution, like the dead-store pass). DEFAULT-ON as of v0.15.0: validated
2049    // bit-identical results + a net cycle win on the dissolved hot path (−2
2050    // cyc/call, .text 100→90 B on gust_mix). Escape hatch: `SYNTH_NO_IMM_SHIFT_FOLD=1`.
2051    let arm_instrs = if std::env::var("SYNTH_NO_IMM_SHIFT_FOLD").is_err() {
2052        let (out, folds) = synth_synthesis::liveness::fold_immediate_shifts(&arm_instrs);
2053        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2054            eprintln!(
2055                "[imm-shift-fold] {folds} register shift(s) folded to immediate, movw dropped"
2056            );
2057        }
2058        out
2059    } else {
2060        arm_instrs
2061    };
2062
2063    // #686: elide the #682 mod-32 shift-amount mask (`and r12,rK,#31` before
2064    // every register-controlled i32 shl/shr) when the amount is STATICALLY
2065    // provable < 32 — a const amount folds to the immediate-shift form
2066    // (reduced mod 32, so >= 32 shrinks too), and an already-masked amount
2067    // (`rK = rX & c`, c < 32) drops the redundant re-mask. gale measured the
2068    // unconditional mask at ~12% cyc/call (+14 B) on gust_mix, whose Q8
2069    // fixed-point shifts are all constants (#686). The mask stays wherever
2070    // the bound is unproven — elision is an optimization, the mask is the
2071    // sound default (`liveness::elide_shift_masks` has the proof
2072    // obligations). Runs after `fold_immediate_shifts` (whose movw→shift
2073    // window the #682 mask intercepts, so it declines every masked const
2074    // shift) and before branch resolution (removal/rewrite-only ⇒
2075    // offset-neutral).
2076    //
2077    // DEFAULT-ON since v0.50.1 (opt-out via `SYNTH_SHIFT_MASK_ELIDE=0`; #846).
2078    // gale's gpio-thin driver regressed +44 B / +9% on synth 0.49 — its pin
2079    // bit-arithmetic (`pin & 31` then a register shift) emits the source
2080    // `and rN,#0x1f` IMMEDIATELY followed by the #682 mod-32 re-mask
2081    // `and r12,rN,#0x1f`; the second is provably redundant (Pattern B: an
2082    // operand produced by `and X,#c`, c<32, is already in [0,31]), so the
2083    // pass drops it. Flipping default-on is a deliberate byte-changing
2084    // refreeze: the elision also moves the frozen anchors (const-amount
2085    // shifts fold back to the immediate form) — control_step −20 B,
2086    // flight_seam −166 B, flight_seam_flat −168 B — all size DECREASES with
2087    // the mask soundly kept for every unproven amount. All differentials were
2088    // re-run on the new bytes and the goldens re-pinned (see #846 PR /
2089    // `frozen_codegen_bytes.rs`). `SYNTH_SHIFT_MASK_ELIDE=0` restores the
2090    // pre-flip bytes (opt-out gate in `shift_mask_elide_686.rs`).
2091    let arm_instrs = if std::env::var("SYNTH_SHIFT_MASK_ELIDE").is_ok_and(|v| v == "0") {
2092        arm_instrs
2093    } else {
2094        let (out, elisions) = synth_synthesis::liveness::elide_shift_masks(&arm_instrs);
2095        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2096            eprintln!(
2097                "[shift-mask-elide] {elisions} provably-<32 shift-amount mask(s) elided (#686)"
2098            );
2099        }
2100        out
2101    };
2102
2103    // VCR-RA uxth/uxtb fold (#428, #242): `movw rM,#0xffff; and rD,rN,rM` →
2104    // `uxth rD,rN` (and the 0xff/uxtb form), removing the dead `movw` — −1
2105    // instruction, −1 live register per 16/8-bit mask. 0xffff/0xff are not Thumb-2
2106    // modified immediates so the selector materializes them into a register; the
2107    // dedicated zero-extend expresses the same masking inline. Removal-only +
2108    // rewrite-in-place (offset-neutral). DEFAULT-ON (#242 flag audit flip-wave,
2109    // #592 audit item): evidence basis was the 2-path × repro-corpus sweep —
2110    // 0 functions grow, 13 shrink (control_step 300→294 −6, gust_mix 38→32 −6,
2111    // uxth_fold pack 36→24 −12), locked by the `uxth_fold_no_grow_corpus_242`
2112    // cargo gate; execution differentials re-run green on the new default
2113    // bytes BEFORE the frozen ARM anchors were re-pinned (uxth_fold,
2114    // control_step — see the flip PR). Escape hatch: `SYNTH_UXTH_FOLD=0` opts
2115    // out and restores the pre-flip bytes (CI-gated in
2116    // `frozen_codegen_bytes.rs`).
2117    let arm_instrs = if !std::env::var("SYNTH_UXTH_FOLD").is_ok_and(|v| v == "0") {
2118        let (out, folds) = synth_synthesis::liveness::fold_uxth(&arm_instrs);
2119        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2120            eprintln!("[uxth-fold] {folds} mask-and folded to uxth/uxtb, movw dropped");
2121        }
2122        out
2123    } else {
2124        arm_instrs
2125    };
2126
2127    // VCR-RA-001 const-CSE / rematerialization-avoidance (#209, #242). Drops a
2128    // `movw`/`mov #imm` that re-materializes a constant already resident in
2129    // another register and retargets the reads — every rewrite proven by the
2130    // liveness analysis. Runs LAST, after every immediate-fold (shift, uxth) and
2131    // range-realloc, but BEFORE branch resolution/encoding (it removes
2132    // instructions, shifting byte offsets). CSE-last is the #242 no-regression
2133    // fix: the folds have already absorbed every foldable constant, so CSE can no
2134    // longer defeat one (the gust_mix 90→92 mechanism). The pass additionally
2135    // size-guards each segment via the byte-estimator — it commits a segment's
2136    // rewrites only if they do not grow its estimated size — so a retarget that
2137    // would flip a 16-bit encoding to 32-bit (higher base register) is declined.
2138    // DEFAULT-ON (#242 flip-wave, the SYNTH_SPILL_REALLOC/SYNTH_BASE_CSE
2139    // template): const-CSE ships by default. The flip prerequisites recorded in
2140    // `const_cse_reduction_242.rs` were retired first — the bridge-level INLINE
2141    // aliasing (the alias-eviction spill-bijection hazard) was DELETED from
2142    // `optimizer_bridge::ir_to_arm`, so this post-hoc, liveness-proven pass is
2143    // the flag's ONLY effect. Evidence basis: 152 fixture×path corpus sweep — 0
2144    // functions grow (size-guarded per segment), 40 shrink (const_cse::spill12
2145    // 236→148 B), total −536 B — and the execution differentials re-run green
2146    // on the new default bytes BEFORE the frozen goldens were re-pinned
2147    // (const_cse, frame_slot_dce, flight_seam 0x07FDF307, spill_rung_581,
2148    // volatile_segment_543, control_step 0x00210A55). Escape hatch:
2149    // `SYNTH_CONST_CSE=0` is the OPT-OUT — it restores the pre-flip bytes
2150    // (CI-gated by `const_cse_escape_hatch_restores_old_bytes_242` and the
2151    // frozen-anchor escape-hatch gate). Any other value (or unset) runs the pass.
2152    //
2153    // #543 Phase 2: const-CSE declines WHOLESALE while any volatile DMA range
2154    // (`--volatile-segment`) is marked. At the ArmOp level a cached constant
2155    // cannot be classified as address-vs-data (a retargeted read may be a
2156    // memory-access base carrying a per-use immediate offset), so the
2157    // conservative stance for statically-unknown addressing is to decline every
2158    // aliasing rewrite — each constant is re-materialized at each occurrence,
2159    // the documented volatile contract (`CompileConfig::volatile_segments`).
2160    let arm_instrs = if !std::env::var("SYNTH_CONST_CSE").is_ok_and(|v| v == "0")
2161        && config.volatile_segments.is_empty()
2162    {
2163        let (out, removed) = synth_synthesis::liveness::apply_const_cse(&arm_instrs);
2164        if std::env::var("SYNTH_FUSE_STATS").is_ok() {
2165            eprintln!("[const-cse] {removed} redundant constant materialization(s) removed");
2166        }
2167        out
2168    } else {
2169        arm_instrs
2170    };
2171
2172    // VCR-RA-001 spill-choice REPORT (#242): measure-only, like SYNTH_SHADOW_ALLOC.
2173    // Per straight-line segment, the frame-slot traffic actually emitted vs the
2174    // reload/store count a farthest-next-use (Belady) allocation over the R0-R8
2175    // pool would need — the measured headroom for the full spill-choice rewrite.
2176    // Printed on the FINAL stream (post all rewrite passes), so a flag-off run
2177    // reports the greedy baseline and a flag-on run reports what remains.
2178    if std::env::var("SYNTH_SPILL_REPORT").is_ok() {
2179        for seg in synth_synthesis::liveness::spill_choice_report(&arm_instrs, 9) {
2180            if seg.actual_reloads + seg.actual_spill_stores > 0 || seg.peak_pressure > 9 {
2181                eprintln!(
2182                    "[spill-report] seg@{} len={} peak={} actual={}ld+{}st belady(k=9)={}ld+{}st",
2183                    seg.start,
2184                    seg.len,
2185                    seg.peak_pressure,
2186                    seg.actual_reloads,
2187                    seg.actual_spill_stores,
2188                    seg.belady_reloads,
2189                    seg.belady_spill_stores
2190                );
2191            }
2192        }
2193    }
2194
2195    // ISA feature gate: validate that all generated instructions are supported
2196    // by the target. This catches FPU instructions on no-FPU targets, double-precision
2197    // instructions on single-precision targets, etc.
2198    validate_instructions(&arm_instrs, config.target.fpu, &config.target.triple)
2199        .map_err(|e| format!("ISA validation failed: {}", e))?;
2200
2201    // VCR-RA-003 (epic #242): UNCONDITIONAL per-compilation register-allocation
2202    // validation. The register allocator is the last major unverified codegen
2203    // component; this whole-function checker proves — by construction, on the
2204    // EXACT emitted stream about to be encoded — that the allocation preserves
2205    // FOUR invariants whose reference lives in the stream (or the ABI): (1)
2206    // callee-saved preservation (#490), (2) spill-slot non-aliasing (#331), and
2207    // — PHASE 2 (#49), extending past straight-line — (3) caller-saved
2208    // preservation across calls (a value in R2/R3/R12 live across a `bl` the
2209    // AAPCS boundary destroys), and (4) value availability across control-flow
2210    // joins (a live-in to a join must be defined on every incoming edge). It runs
2211    // on every ARM compile in the DEFAULT shipping build (NOT behind
2212    // `--features verify`; a verify-gated check would be dormant in exactly the
2213    // build that ships — the #757 / VCR-VER-003 lesson) and hard-errors the
2214    // compile on a VIOLATION. A `NotAttempted` verdict (the join check declines
2215    // on an unmodeled-CF function: numeric branch, `BrTable`, etc.) is NON-FATAL
2216    // — the compile proceeds; the other three invariants were still checked and
2217    // held. This is the decline>guess doctrine applied to the checker itself: it
2218    // never claims join coherence it cannot prove, but it also never blocks a
2219    // correct compile for a construct it simply doesn't model yet. Frozen-safe:
2220    // it emits nothing, so `.text` is byte-identical (proven by the frozen suite).
2221    // #1321: scope the #331 spill-slot check to the frame regions the allocator
2222    // actually hands out as spill slots — but ONLY while the record provably
2223    // still describes THIS stream. Between selection and here the stream passes
2224    // through re-allocation, dead-frame elimination and prologue shrink, any of
2225    // which can re-lay or remove the frame. A stale area list would narrow the
2226    // check over the wrong offsets — the silent weakening this lane exists to
2227    // avoid — so the areas are used only if the final stream still allocates
2228    // EXACTLY the frame they were computed for. On any mismatch (re-laid frame,
2229    // eliminated frame, optimized path, no record) we pass `None` and every
2230    // `[sp,#N]` offset is policed, bit for bit as before. The fix can go stale;
2231    // it cannot go wrong.
2232    let spill_areas: Option<&[std::ops::Range<i32>]> = match recorded_spill_areas {
2233        Some((frame_size, areas))
2234            if arm_instrs.iter().any(|ins| {
2235                matches!(
2236                    &ins.op,
2237                    synth_synthesis::rules::ArmOp::Sub {
2238                        rd: synth_synthesis::rules::Reg::SP,
2239                        rn: synth_synthesis::rules::Reg::SP,
2240                        op2: synth_synthesis::rules::Operand2::Imm(n),
2241                    } if n == frame_size
2242                )
2243            }) =>
2244        {
2245            Some(areas.as_slice())
2246        }
2247        _ => None,
2248    };
2249    match synth_synthesis::liveness::validate_final_allocation_in_areas(&arm_instrs, spill_areas) {
2250        synth_synthesis::liveness::RaFinalVerdict::Violation(v) => {
2251            return Err(format!(
2252                "VCR-RA-003: register-allocation validation FAILED — {v:?}. \
2253                 The emitted stream violates a register-allocation invariant \
2254                 (callee-saved preservation #490 / spill-slot non-aliasing #331 \
2255                 / caller-saved-across-call / join-value-availability / the #881 \
2256                 VFP twins); this is a \
2257                 compiler bug, not a program error. Refusing to emit a \
2258                 miscompiled object."
2259            ));
2260        }
2261        // Loud honest decline (join reasoning skipped for an unmodeled-CF
2262        // function). Non-fatal — the straight-line / callee-saved / across-call
2263        // invariants still ran and held; only the across-JOIN availability
2264        // reasoning is skipped. Since the #819 redo the optimized path's
2265        // pre-resolved NUMERIC branches are modeled too (build_join_cfg_numeric
2266        // + the PRESERVED entry-availability discriminator), so this fires only
2267        // on genuinely unmodeled shapes: BrTable, computed Bx, mixed
2268        // label+numeric streams, off-boundary numeric targets.
2269        // Surfaced only under `SYNTH_RA003_VERBOSE` so a production compile stays
2270        // quiet: emitting it unconditionally would print on every branchy
2271        // optimized-path compile (new stderr noise phase 1 never produced), yet
2272        // it must remain observable on demand for the honest-scope audit.
2273        synth_synthesis::liveness::RaFinalVerdict::NotAttempted { reason } => {
2274            if std::env::var_os("SYNTH_RA003_VERBOSE").is_some() {
2275                eprintln!(
2276                    "VCR-RA-003: across-join validation NOT ATTEMPTED ({reason}) — \
2277                     straight-line / callee-saved / across-call invariants held; \
2278                     join-availability reasoning declined on this control-flow shape."
2279                );
2280            }
2281        }
2282        synth_synthesis::liveness::RaFinalVerdict::Consistent => {
2283            if std::env::var_os("SYNTH_RA003_VERBOSE").is_some() {
2284                eprintln!("VCR-RA-003: Consistent");
2285            }
2286        }
2287    }
2288    Ok(arm_instrs)
2289}
2290
2291/// VCR-DEC-003 (#396): classify one emitted `ArmOp` into its object-level
2292/// control-flow role for the `synth-provenance-v1` map. Conditional branches are
2293/// the object decision points MC/DC must reconcile; `SelectMove` is the folded
2294/// (IT-block) predicated form the cmp→select fuse produces — a decision with no
2295/// branch.
2296fn classify_arm_branch(op: &ArmOp) -> synth_core::backend::BranchClass {
2297    use synth_core::backend::BranchClass;
2298    match op {
2299        ArmOp::Bcc { .. } | ArmOp::Bhs { .. } | ArmOp::Blo { .. } | ArmOp::BCondOffset { .. } => {
2300            BranchClass::CondBranch
2301        }
2302        ArmOp::B { .. } | ArmOp::BOffset { .. } => BranchClass::UncondBranch,
2303        ArmOp::SelectMove { .. } => BranchClass::Predicated,
2304        _ => BranchClass::Other,
2305    }
2306}
2307
2308/// Resolve local label branches to byte-accurate offsets (#202).
2309///
2310/// `select_with_stack` emits conditional/unconditional branches as label
2311/// placeholders (`Bcc`/`B`/`Bhs`/`Blo` + `Label`) and never resolves them; the
2312/// encoder then emits a `0xD000`/`0xE000` placeholder with offset 0. Before #197
2313/// this path only ran for `--no-optimize`/declined functions, so the latent bug
2314/// stayed hidden — routing relocatable code through it surfaced branches that
2315/// land mid-instruction (a Cortex-M UsageFault) whenever a 32-bit Thumb-2
2316/// instruction sits between the branch and its target.
2317///
2318/// This pass encodes each instruction to learn its real byte length (so 16- vs
2319/// 32-bit forms and multi-instruction expansions are exact), maps each `Label`
2320/// to its byte position, and rewrites every label branch to the displacement
2321/// the encoder consumes: `(target - branch - 4) / 2` halfwords. A bounded
2322/// fixed-point handles an offset growing a branch from 16- to 32-bit (which
2323/// shifts later positions). `BCondOffset`/`BOffset` already produced inline by
2324/// the optimized path carry no label and are left untouched.
2325fn resolve_label_branches(
2326    arm_instrs: Vec<ArmInstruction>,
2327    encoder: &ArmEncoder,
2328) -> Result<Vec<ArmInstruction>, String> {
2329    use std::collections::HashMap;
2330    use synth_synthesis::Condition;
2331
2332    enum BKind {
2333        Cond(Condition),
2334        Uncond,
2335    }
2336    // Record each label branch ONCE — indices are stable across iterations.
2337    let mut branches: Vec<(usize, BKind, String)> = Vec::new();
2338    for (i, instr) in arm_instrs.iter().enumerate() {
2339        match &instr.op {
2340            ArmOp::Bcc { cond, label } => branches.push((i, BKind::Cond(*cond), label.clone())),
2341            ArmOp::Bhs { label } => branches.push((i, BKind::Cond(Condition::HS), label.clone())),
2342            ArmOp::Blo { label } => branches.push((i, BKind::Cond(Condition::LO), label.clone())),
2343            ArmOp::B { label } => branches.push((i, BKind::Uncond, label.clone())),
2344            _ => {}
2345        }
2346    }
2347    if branches.is_empty() {
2348        return Ok(arm_instrs);
2349    }
2350
2351    let mut resolved = arm_instrs;
2352    // Sizes only grow (16→32-bit), so this converges quickly; cap for safety.
2353    for _ in 0..16 {
2354        // 1. Byte position of each instruction (Label encodes to 0 bytes).
2355        let mut positions = Vec::with_capacity(resolved.len());
2356        let mut pos: i64 = 0;
2357        for instr in &resolved {
2358            positions.push(pos);
2359            pos += encoder
2360                .encode(&instr.op)
2361                .map_err(|e| format!("branch-resolve size probe failed: {}", e))?
2362                .len() as i64;
2363        }
2364        // 2. Label name -> byte position (owned keys so the borrow ends here).
2365        let mut labels: HashMap<String, i64> = HashMap::new();
2366        for (i, instr) in resolved.iter().enumerate() {
2367            if let ArmOp::Label { name } = &instr.op {
2368                labels.insert(name.clone(), positions[i]);
2369            }
2370        }
2371        // 3. Rewrite each branch to its byte-accurate offset.
2372        let mut changed = false;
2373        for (idx, kind, label) in &branches {
2374            // A label not defined locally is an EXTERNAL target (e.g.
2375            // `Trap_Handler` resolved by a relocation / the vector table). Leave
2376            // such branches as their placeholder for the existing relocation
2377            // path — only local control-flow labels are byte-resolved here.
2378            let Some(&target) = labels.get(label) else {
2379                continue;
2380            };
2381            // Encoder consumes the field as (target - branch - 4) / 2 halfwords.
2382            // Positions are always even, so this division is exact.
2383            let halfword_offset = ((target - positions[*idx] - 4) / 2) as i32;
2384            let new_op = match kind {
2385                BKind::Cond(c) => ArmOp::BCondOffset {
2386                    cond: *c,
2387                    offset: halfword_offset,
2388                },
2389                BKind::Uncond => ArmOp::BOffset {
2390                    offset: halfword_offset,
2391                },
2392            };
2393            if resolved[*idx].op != new_op {
2394                resolved[*idx].op = new_op;
2395                changed = true;
2396            }
2397        }
2398        if !changed {
2399            break;
2400        }
2401    }
2402    Ok(resolved)
2403}
2404
2405/// SC-5 branch-target boundary gate (#740, #930): every emitted branch target
2406/// must be a member of the instruction-start set of the final stream.
2407///
2408/// "Branch offset calculation shall account for Thumb instruction alignment
2409/// and variable instruction widths" (`safety/stpa/system-constraints.yaml`
2410/// SC-5). Thumb-2 mixes 16- and 32-bit encodings, so an off-by-one-halfword
2411/// target lands on the SECOND halfword of a wide instruction and the CPU
2412/// executes a halfword that was never an instruction — silent garbage, exit 0
2413/// (#930: the skipped `movw` left the `br_if` condition register at its reset
2414/// value). Both known escapes of that sentence were of this class: #740
2415/// (`B<cond>.W` T3 offset halved) and #930 (inner-block end label never
2416/// emitted, `b #0` placeholder). The encoder knows where every instruction
2417/// starts, so a target outside that set is a hard error here rather than
2418/// silent garbage on target.
2419///
2420/// Runs on the FINAL Thumb-2 stream for BOTH codegen paths — the direct
2421/// (`select_with_stack`, label branches byte-resolved above) and the optimized
2422/// (`optimizer_bridge`, numeric `BOffset`/`BCondOffset` pre-resolved inline) —
2423/// since both funnel through this encode pipeline. Two checks, jointly total
2424/// over local control flow:
2425///
2426/// 1. every numeric branch target is in the instruction-start set;
2427/// 2. no LOCAL (`.L`-prefixed) label branch survives unresolved — the resolver
2428///    deliberately skips labels it cannot find because an external target
2429///    (`Trap_Handler`, `func_N`) is legitimately absent and patched by
2430///    relocation, but a `.L` label is only ever defined in this same stream,
2431///    so an unresolved one is a dropped label (#930), not an external.
2432///
2433/// A32 (Cortex-R5) is fixed-width, so the mid-instruction class needs no gate
2434/// there (and its branches do not flow through the Thumb-2 resolver).
2435fn validate_branch_targets(instrs: &[ArmInstruction], encoder: &ArmEncoder) -> Result<(), String> {
2436    use std::collections::HashSet;
2437
2438    // Byte position of each element (`Label` encodes to 0 bytes, so a label's
2439    // position is exactly the start of the instruction that follows it).
2440    let mut positions = Vec::with_capacity(instrs.len());
2441    let mut pos: i64 = 0;
2442    for instr in instrs {
2443        positions.push(pos);
2444        pos += encoder
2445            .encode(&instr.op)
2446            .map_err(|e| format!("SC-5 branch-target gate: size probe failed: {}", e))?
2447            .len() as i64;
2448    }
2449    let starts: HashSet<i64> = positions.iter().copied().collect();
2450
2451    for (i, instr) in instrs.iter().enumerate() {
2452        let offset = match &instr.op {
2453            ArmOp::BOffset { offset } => *offset,
2454            ArmOp::BCondOffset { offset, .. } => *offset,
2455            ArmOp::B { label }
2456            | ArmOp::Bcc { label, .. }
2457            | ArmOp::Bhs { label }
2458            | ArmOp::Blo { label }
2459                if label.starts_with(".L") =>
2460            {
2461                return Err(format!(
2462                    "SC-5 branch-target gate: local branch label '{}' is not \
2463                     defined anywhere in the emitted stream (branch at byte \
2464                     offset 0x{:x}). A `.L` label is only ever defined locally, \
2465                     so this is a dropped label (the #930 class) — the branch \
2466                     would encode as a `b #0` placeholder and land \
2467                     mid-instruction. Refusing to emit a miscompiled object.",
2468                    label, positions[i]
2469                ));
2470            }
2471            _ => continue,
2472        };
2473        // Thumb branch semantics: target = branch_pc + 4 + 2*offset.
2474        let target = positions[i] + 4 + 2 * offset as i64;
2475        if !starts.contains(&target) {
2476            return Err(format!(
2477                "SC-5 branch-target gate: branch at byte offset 0x{:x} targets \
2478                 0x{:x}, which is not an instruction boundary (instruction-start \
2479                 set violation — the target lands mid-instruction, the \
2480                 #740/#930 class). Refusing to emit a miscompiled object.",
2481                positions[i], target
2482            ));
2483        }
2484    }
2485    Ok(())
2486}
2487
2488#[cfg(test)]
2489mod tests {
2490    use super::*;
2491    use synth_synthesis::{Operand2, Reg};
2492
2493    /// #539: `i32.const 0; memory.grow m` folds to `memory.size m`; other deltas
2494    /// (const non-zero, runtime) are left as `memory.grow` (→ the sound fixed-
2495    /// memory -1). Non-grow ops are untouched, so functions without the idiom are
2496    /// byte-identical.
2497    #[test]
2498    fn test_rewrite_memory_grow_zero_539() {
2499        // the idiom -> memory.size
2500        assert_eq!(
2501            rewrite_memory_grow_zero(&[WasmOp::I32Const(0), WasmOp::MemoryGrow(0)]),
2502            vec![WasmOp::MemorySize(0)]
2503        );
2504        // const non-zero delta: NOT folded
2505        assert_eq!(
2506            rewrite_memory_grow_zero(&[WasmOp::I32Const(2), WasmOp::MemoryGrow(0)]),
2507            vec![WasmOp::I32Const(2), WasmOp::MemoryGrow(0)]
2508        );
2509        // runtime delta (no preceding const): NOT folded
2510        assert_eq!(
2511            rewrite_memory_grow_zero(&[WasmOp::LocalGet(0), WasmOp::MemoryGrow(0)]),
2512            vec![WasmOp::LocalGet(0), WasmOp::MemoryGrow(0)]
2513        );
2514        // a bare const-0 not feeding a grow is untouched
2515        assert_eq!(
2516            rewrite_memory_grow_zero(&[WasmOp::I32Const(0), WasmOp::I32Add]),
2517            vec![WasmOp::I32Const(0), WasmOp::I32Add]
2518        );
2519        // fold is local: surrounding ops preserved, indices past the fold intact
2520        assert_eq!(
2521            rewrite_memory_grow_zero(&[
2522                WasmOp::LocalGet(0),
2523                WasmOp::I32Const(0),
2524                WasmOp::MemoryGrow(0),
2525                WasmOp::I32Add,
2526            ]),
2527            vec![WasmOp::LocalGet(0), WasmOp::MemorySize(0), WasmOp::I32Add]
2528        );
2529    }
2530
2531    /// SC-5 (#740/#930): the branch-target boundary gate. Every emitted branch
2532    /// target must be a member of the instruction-start set of the final
2533    /// Thumb-2 stream; a `.L`-local label branch surviving unresolved is a
2534    /// dropped label. Red-first: both rejection arms were written against the
2535    /// exact #930 stream shape (a `b #0` placeholder whose pc+4 target falls
2536    /// on the second halfword of a 32-bit `movw`) and fail without the gate.
2537    #[test]
2538    fn test_validate_branch_targets_sc5_930() {
2539        let enc = ArmEncoder::new_thumb2();
2540        let ins = |op: ArmOp| ArmInstruction {
2541            op,
2542            source_line: None,
2543        };
2544
2545        // 1. Boundary-valid stream: b over a wide movw onto the mov — OK.
2546        //    positions: 0 BOffset(2B), 2 Movw(4B), 6 Mov(2B)
2547        //    target = 0 + 4 + 2*1 = 6 = start of Mov.
2548        let good = vec![
2549            ins(ArmOp::BOffset { offset: 1 }),
2550            ins(ArmOp::Movw {
2551                rd: Reg::R3,
2552                imm16: 1,
2553            }),
2554            ins(ArmOp::Mov {
2555                rd: Reg::R0,
2556                op2: Operand2::Reg(Reg::R3),
2557            }),
2558        ];
2559        assert!(validate_branch_targets(&good, &enc).is_ok());
2560
2561        // 2. The exact #930 shape: `b #0` (offset 0) -> target = pc+4 = 4,
2562        //    the SECOND halfword of the 4-byte movw spanning 2..6. Hard error.
2563        let mid = vec![
2564            ins(ArmOp::BOffset { offset: 0 }),
2565            ins(ArmOp::Movw {
2566                rd: Reg::R3,
2567                imm16: 1,
2568            }),
2569            ins(ArmOp::Mov {
2570                rd: Reg::R0,
2571                op2: Operand2::Reg(Reg::R3),
2572            }),
2573        ];
2574        let err = validate_branch_targets(&mid, &enc).unwrap_err();
2575        assert!(err.contains("SC-5"), "boundary violation names SC-5: {err}");
2576        assert!(err.contains("not an instruction boundary"), "{err}");
2577
2578        // 3. Conditional form of the same violation.
2579        let mid_cond = vec![
2580            ins(ArmOp::BCondOffset {
2581                cond: synth_synthesis::Condition::NE,
2582                offset: 0,
2583            }),
2584            ins(ArmOp::Movw {
2585                rd: Reg::R3,
2586                imm16: 1,
2587            }),
2588            ins(ArmOp::Mov {
2589                rd: Reg::R0,
2590                op2: Operand2::Reg(Reg::R3),
2591            }),
2592        ];
2593        assert!(validate_branch_targets(&mid_cond, &enc).is_err());
2594
2595        // 4. A `.L`-local label branch that was never resolved (the dropped
2596        //    end label, #930's mechanism) is a hard error even though it
2597        //    would encode as a well-formed placeholder.
2598        let dropped = vec![
2599            ins(ArmOp::B {
2600                label: ".Lblock_end_3".to_string(),
2601            }),
2602            ins(ArmOp::Movw {
2603                rd: Reg::R3,
2604                imm16: 1,
2605            }),
2606        ];
2607        let err = validate_branch_targets(&dropped, &enc).unwrap_err();
2608        assert!(err.contains(".Lblock_end_3"), "{err}");
2609        assert!(err.contains("dropped label"), "{err}");
2610
2611        // 5. An EXTERNAL label branch (no `.L` prefix) is legitimately absent
2612        //    (patched via relocation / vector table) and must NOT trip the
2613        //    gate — the carve-out that used to swallow #930 stays for real
2614        //    externals only.
2615        let external = vec![
2616            ins(ArmOp::B {
2617                label: "Trap_Handler".to_string(),
2618            }),
2619            ins(ArmOp::Movw {
2620                rd: Reg::R3,
2621                imm16: 1,
2622            }),
2623        ];
2624        assert!(validate_branch_targets(&external, &enc).is_ok());
2625
2626        // 6. Labels are zero-width: a target on a Label position is the start
2627        //    of the instruction that follows it — OK.
2628        let labeled = vec![
2629            ins(ArmOp::BOffset { offset: 1 }),
2630            ins(ArmOp::Movw {
2631                rd: Reg::R3,
2632                imm16: 1,
2633            }),
2634            ins(ArmOp::Label {
2635                name: ".Lend".to_string(),
2636            }),
2637            ins(ArmOp::Mov {
2638                rd: Reg::R0,
2639                op2: Operand2::Reg(Reg::R3),
2640            }),
2641        ];
2642        assert!(validate_branch_targets(&labeled, &enc).is_ok());
2643    }
2644
2645    /// SC-5 (#930) end-to-end at the backend seam: the labels.wast `br_if2`
2646    /// shape — a `br_if` exiting an enclosing block from inside an `if`, its
2647    /// value operand a block-that-branches — must COMPILE (the pre-fix
2648    /// selector dropped the inner block's end label, which the SC-5 gate now
2649    /// turns into a hard error, so compile success proves the label was
2650    /// emitted) and every branch in the emitted bytes must land on an
2651    /// instruction boundary (re-derived from the encoded halfwords, not from
2652    /// the resolver's own bookkeeping).
2653    #[test]
2654    fn test_930_brif2_shape_compiles_and_targets_boundaries() {
2655        let backend = ArmBackend::new();
2656        let ops = vec![
2657            WasmOp::Block, // $l0 (result i32)
2658            WasmOp::I32Const(1),
2659            WasmOp::If,
2660            WasmOp::Block, // $l1 (result i32)
2661            WasmOp::I32Const(1),
2662            WasmOp::Br(0), // br $l1
2663            WasmOp::End,
2664            WasmOp::I32Const(1),
2665            WasmOp::BrIf(1), // br_if $l0
2666            WasmOp::Drop,
2667            WasmOp::End, // end if
2668            WasmOp::I32Const(0),
2669            WasmOp::End, // end $l0
2670            WasmOp::End,
2671        ];
2672        let config = CompileConfig::default();
2673        let func = backend
2674            .compile_function("t", &ops, &config)
2675            .expect("#930 shape must compile (SC-5 gate passes)");
2676
2677        // Walk the encoded halfwords: collect instruction starts, then check
2678        // every narrow/wide B / B<cond> target is a member.
2679        let code = &func.code;
2680        let mut starts = std::collections::HashSet::new();
2681        let mut widths = Vec::new();
2682        let mut off = 0usize;
2683        while off + 2 <= code.len() {
2684            starts.insert(off as i64);
2685            let hw = u16::from_le_bytes([code[off], code[off + 1]]);
2686            let wide = (hw & 0xF800) >= 0xE800; // 0b11101/0b11110/0b11111
2687            widths.push((off, hw, wide));
2688            off += if wide { 4 } else { 2 };
2689        }
2690        for (off, hw, wide) in widths {
2691            let target = if !wide && (hw & 0xF800) == 0xE000 {
2692                // T2 B: imm11, halfwords
2693                let imm = ((hw & 0x7FF) as i32) << 21 >> 21;
2694                Some(off as i64 + 4 + 2 * imm as i64)
2695            } else if !wide && (hw & 0xF000) == 0xD000 && (hw & 0x0F00) < 0x0E00 {
2696                // T1 B<cond>: imm8, halfwords
2697                let imm = ((hw & 0xFF) as i32) << 24 >> 24;
2698                Some(off as i64 + 4 + 2 * imm as i64)
2699            } else {
2700                None
2701            };
2702            if let Some(t) = target {
2703                assert!(
2704                    starts.contains(&t),
2705                    "branch at 0x{off:x} (hw 0x{hw:04x}) targets 0x{t:x}, \
2706                     not an instruction boundary — the #930 miscompile shape"
2707                );
2708            }
2709        }
2710    }
2711
2712    #[test]
2713    fn test_arm_backend_name() {
2714        let backend = ArmBackend::new();
2715        assert_eq!(backend.name(), "arm");
2716        assert!(backend.is_available());
2717    }
2718
2719    #[test]
2720    fn test_arm_backend_capabilities() {
2721        let backend = ArmBackend::new();
2722        let caps = backend.capabilities();
2723        assert!(!caps.produces_elf);
2724        assert!(caps.supports_rule_verification);
2725        assert!(!caps.is_external);
2726    }
2727
2728    #[test]
2729    fn test_compile_add_function() {
2730        let backend = ArmBackend::new();
2731        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
2732        let config = CompileConfig::default();
2733
2734        let result = backend.compile_function("add", &ops, &config);
2735        assert!(result.is_ok());
2736
2737        let func = result.unwrap();
2738        assert_eq!(func.name, "add");
2739        assert!(!func.code.is_empty());
2740        assert_eq!(func.wasm_ops, ops);
2741    }
2742
2743    /// VCR-DBG-001: the per-instruction source map must cover the function with
2744    /// monotonic, in-bounds machine offsets, and must not perturb the emitted
2745    /// code (it is captured at encode time, never serialized here).
2746    #[test]
2747    fn test_line_map_is_wellformed_dbg001() {
2748        let backend = ArmBackend::new();
2749        let ops = vec![
2750            WasmOp::LocalGet(0),
2751            WasmOp::LocalGet(1),
2752            WasmOp::I32Add,
2753            WasmOp::End,
2754        ];
2755        let config = CompileConfig::default();
2756        let func = backend.compile_function("add", &ops, &config).unwrap();
2757
2758        // Non-empty, and the first instruction starts at machine offset 0.
2759        assert!(
2760            !func.line_map.is_empty(),
2761            "a non-trivial function captures a source map"
2762        );
2763        assert_eq!(func.line_map[0].0, 0, "first instruction at offset 0");
2764
2765        // Offsets strictly increase by at least one ARM/Thumb instruction (>= 2
2766        // bytes) and every mapped offset lies inside the emitted `.text`.
2767        for w in func.line_map.windows(2) {
2768            assert!(w[1].0 > w[0].0, "instruction offsets strictly increase");
2769            assert!(
2770                w[1].0 - w[0].0 >= 2,
2771                "each ARM/Thumb instruction is >= 2 bytes"
2772            );
2773        }
2774        let last = func.line_map.last().unwrap().0 as usize;
2775        assert!(
2776            last < func.code.len(),
2777            "every mapped offset lies inside .text"
2778        );
2779
2780        // The side-table is additive: recompiling is deterministic and the map is
2781        // consistent with that exact code (capturing it does not alter output).
2782        let again = backend.compile_function("add", &ops, &config).unwrap();
2783        assert_eq!(
2784            again.code, func.code,
2785            "compilation deterministic; map is additive"
2786        );
2787        assert_eq!(again.line_map, func.line_map);
2788    }
2789
2790    #[test]
2791    fn test_count_params() {
2792        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
2793        assert_eq!(count_params(&ops), 2);
2794
2795        let no_params = vec![WasmOp::I32Const(5), WasmOp::I32Const(3), WasmOp::I32Add];
2796        assert_eq!(count_params(&no_params), 0);
2797    }
2798
2799    /// #457: the declared param count caps the access-pattern inference. The
2800    /// repro shape `(param i32)(local i32) → p0 + local1` reads local 1 before
2801    /// any write, so `count_params` infers 2 — with the declared count (1) the
2802    /// local is reclassified onto the zero-inited frame path instead of being
2803    /// read from R1 (caller garbage).
2804    #[test]
2805    fn declared_param_count_caps_inference_457() {
2806        let ops = vec![
2807            WasmOp::LocalGet(0),
2808            WasmOp::LocalGet(1),
2809            WasmOp::I32Add,
2810            WasmOp::End,
2811        ];
2812        // The inference alone still says 2 (the misclassification this caps).
2813        assert_eq!(count_params(&ops), 2);
2814
2815        let backend = ArmBackend::new();
2816        let inferred = backend
2817            .compile_function("rbw", &ops, &CompileConfig::default())
2818            .unwrap();
2819        let declared = backend
2820            .compile_function(
2821                "rbw",
2822                &ops,
2823                &CompileConfig {
2824                    current_func_param_count: Some(1),
2825                    ..CompileConfig::default()
2826                },
2827            )
2828            .unwrap();
2829        // The cap is consumed: the declared-count compile reclassifies local 1
2830        // and must emit different code than the param-misclassified one.
2831        assert_ne!(
2832            inferred.code, declared.code,
2833            "declared param count must reach the selector"
2834        );
2835        // The zero-init is present: a 16-bit Thumb `movs rN, #0`
2836        // (0x2000 | rd<<8 → LE bytes [0x00, 0x20+rd]) somewhere in the body.
2837        let has_movs_zero = declared
2838            .code
2839            .as_chunks::<2>()
2840            .0
2841            .iter()
2842            .any(|h| h[0] == 0x00 && (0x20..=0x27).contains(&h[1]));
2843        assert!(
2844            has_movs_zero,
2845            "declared-count compile must zero-init the read-before-write local; code: {:02x?}",
2846            declared.code
2847        );
2848        // A declared count that matches (or exceeds) the inference changes
2849        // nothing — byte-identity for every function without rbw locals.
2850        let matching = backend
2851            .compile_function(
2852                "rbw",
2853                &ops,
2854                &CompileConfig {
2855                    current_func_param_count: Some(2),
2856                    ..CompileConfig::default()
2857                },
2858            )
2859            .unwrap();
2860        assert_eq!(
2861            matching.code, inferred.code,
2862            "declared >= inferred must stay byte-identical"
2863        );
2864    }
2865
2866    /// #970: a CONDITIONALLY-written param must stay a param.
2867    ///
2868    /// The read-first heuristic sees `LocalSet(1)` before any `LocalGet(1)` in
2869    /// LINEAR op order and demotes index 1 — even though the `if` means the
2870    /// write may not execute at all. `min(referenced, declared)` keeps it.
2871    /// The RED symptom this pins is not a wrong constant: the demoted local's
2872    /// first access is a WRITE, so the #457 zero-init skips it and the
2873    /// fall-through arm reads an UNINITIALISED frame slot (executed evidence:
2874    /// `scripts/repro/cond_write_param_970_arm_differential.py`).
2875    #[test]
2876    fn conditionally_written_param_stays_a_param_970() {
2877        // (param i32 i32): if (local.get 0) { local.set 1 = 5 }; local.get 1
2878        let ops = vec![
2879            WasmOp::LocalGet(0),
2880            WasmOp::If,
2881            WasmOp::I32Const(5),
2882            WasmOp::LocalSet(1),
2883            WasmOp::End,
2884            WasmOp::LocalGet(1),
2885            WasmOp::End,
2886        ];
2887        let declared = CompileConfig {
2888            current_func_param_count: Some(2),
2889            ..CompileConfig::default()
2890        };
2891        // The old rule: index 1 is written before it is read, so it is not
2892        // counted — this is the undercount that produced the miscompile.
2893        assert_eq!(
2894            count_params(&ops),
2895            1,
2896            "the read-first heuristic must still undercount (this is the defect)"
2897        );
2898        assert_eq!(
2899            effective_num_params(&ops, &declared),
2900            2,
2901            "a conditionally-written param must be counted as a param"
2902        );
2903        // The #457 direction is untouched: a genuine non-param local is still
2904        // clamped away by the declared count.
2905        let rbw = vec![
2906            WasmOp::LocalGet(0),
2907            WasmOp::LocalGet(1),
2908            WasmOp::I32Add,
2909            WasmOp::End,
2910        ];
2911        assert_eq!(
2912            effective_num_params(
2913                &rbw,
2914                &CompileConfig {
2915                    current_func_param_count: Some(1),
2916                    ..CompileConfig::default()
2917                }
2918            ),
2919            1,
2920            "#457: a read-before-write non-param local must NOT become a param"
2921        );
2922        // Leniency: a body touching only the first few of many declared params
2923        // still lowers with the small count (the selector homes at most 4 in
2924        // registers; `min` is what keeps this from becoming `declared`).
2925        assert_eq!(
2926            effective_num_params(
2927                &rbw,
2928                &CompileConfig {
2929                    current_func_param_count: Some(12),
2930                    ..CompileConfig::default()
2931                }
2932            ),
2933            2,
2934            "declared >> referenced must stay at the referenced count"
2935        );
2936        // No declared count: the legacy inference, unchanged (honest residual).
2937        assert_eq!(
2938            effective_num_params(&ops, &CompileConfig::default()),
2939            count_params(&ops)
2940        );
2941    }
2942
2943    #[test]
2944    fn test_arm_backend_register() {
2945        let mut registry = synth_core::BackendRegistry::new();
2946        registry.register(Box::new(ArmBackend::new()));
2947        assert!(registry.get("arm").is_some());
2948        assert_eq!(registry.available().len(), 1);
2949    }
2950
2951    #[test]
2952    fn test_compile_import_call_produces_relocations() {
2953        let backend = ArmBackend::new();
2954        // Simulate a WASM module where func index 0 is an import.
2955        // Call(0) should generate MOV R0, #0; BL __meld_dispatch_import
2956        let ops = vec![WasmOp::Call(0)];
2957        let config = CompileConfig {
2958            num_imports: 1,
2959            no_optimize: true, // Direct instruction selection to preserve Call semantics
2960            ..CompileConfig::default()
2961        };
2962
2963        let result = backend.compile_function("caller", &ops, &config);
2964        assert!(result.is_ok());
2965
2966        let func = result.unwrap();
2967        assert!(!func.code.is_empty());
2968        assert_eq!(func.relocations.len(), 1);
2969        assert_eq!(func.relocations[0].symbol, "__meld_dispatch_import");
2970        // The BL is the second instruction (after MOV R0, #0), so offset should be > 0
2971        assert!(func.relocations[0].offset > 0);
2972    }
2973
2974    /// Regression test for #197: in `relocatable` mode, an import call must
2975    /// relocate against the direct `func_N` symbol (rewritten to the wasm field
2976    /// name by `build_relocatable_elf`), NOT `__meld_dispatch_import`. This is
2977    /// the ABI half of the #197 fix — without it, a host linker cannot resolve
2978    /// the call to the real kernel symbol (e.g. `k_spin_lock`).
2979    #[test]
2980    fn test_compile_relocatable_import_uses_direct_func_symbol_197() {
2981        let backend = ArmBackend::new();
2982        let ops = vec![WasmOp::Call(0)]; // func 0 is an import
2983        let config = CompileConfig {
2984            num_imports: 1,
2985            relocatable: true,
2986            ..CompileConfig::default()
2987        };
2988
2989        let func = backend
2990            .compile_function("caller", &ops, &config)
2991            .expect("relocatable import call compiles");
2992
2993        assert_eq!(func.relocations.len(), 1);
2994        assert_eq!(
2995            func.relocations[0].symbol, "func_0",
2996            "#197: relocatable import must relocate against func_0 (→ field name), not Meld dispatch"
2997        );
2998    }
2999
3000    #[test]
3001    fn test_compile_no_imports_no_relocations() {
3002        let backend = ArmBackend::new();
3003        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
3004        let config = CompileConfig::default();
3005
3006        let func = backend.compile_function("add", &ops, &config).unwrap();
3007        assert!(func.relocations.is_empty());
3008    }
3009
3010    /// Regression test for #167: a call to an INTERNAL function
3011    /// (index `>= num_imports`) must record a relocation against `func_{index}`.
3012    /// Before the fix, only `__meld_*` (import) BLs were relocated, so
3013    /// internal `BL func_N` was emitted as an unpatched `bl #0` branching
3014    /// to a garbage address — making the object non-linkable. This test
3015    /// would have caught that regression.
3016    #[test]
3017    fn test_compile_internal_call_produces_relocation_167() {
3018        let backend = ArmBackend::new();
3019        // num_imports = 1, so Call(2) is an INTERNAL call → `BL func_2`.
3020        let ops = vec![WasmOp::Call(2)];
3021        let config = CompileConfig {
3022            num_imports: 1,
3023            no_optimize: true,
3024            ..CompileConfig::default()
3025        };
3026
3027        let func = backend
3028            .compile_function("caller", &ops, &config)
3029            .expect("internal call compiles");
3030
3031        assert_eq!(
3032            func.relocations.len(),
3033            1,
3034            "an internal call must emit exactly one relocation (#167)"
3035        );
3036        assert_eq!(
3037            func.relocations[0].symbol, "func_2",
3038            "internal call must relocate against the callee's func_{{index}} symbol (#167)"
3039        );
3040    }
3041
3042    // ─── Phase 1 safety-bounds plumbing for ARM ──────────────────────────
3043
3044    #[test]
3045    fn arm_safety_bounds_mpu_emits_same_code_as_none() {
3046        // Mpu mode must not introduce any inline check on ARM — the MPU
3047        // handles faults via hardware. The encoded bytes for an i32.load
3048        // should be identical between None and Mpu.
3049        let backend = ArmBackend::new();
3050        let ops = vec![
3051            WasmOp::LocalGet(0),
3052            WasmOp::I32Load {
3053                offset: 0,
3054                align: 2,
3055            },
3056        ];
3057        let cfg_none = CompileConfig {
3058            no_optimize: true,
3059            ..Default::default()
3060        };
3061        let cfg_mpu = CompileConfig {
3062            no_optimize: true,
3063            safety_bounds: SafetyBounds::Mpu,
3064            ..Default::default()
3065        };
3066        let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
3067        let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
3068        assert_eq!(
3069            n.code, m.code,
3070            "Mpu and None should produce identical ARM bytes (Mpu relies on hardware)"
3071        );
3072    }
3073
3074    #[test]
3075    fn arm_legacy_bounds_check_still_emits_software_check() {
3076        // Legacy CLI users with `--bounds-check` should keep getting the
3077        // software path even though the new SafetyBounds field defaults to None.
3078        let backend = ArmBackend::new();
3079        let ops = vec![
3080            WasmOp::LocalGet(0),
3081            WasmOp::I32Load {
3082                offset: 0,
3083                align: 2,
3084            },
3085        ];
3086        let cfg_legacy = CompileConfig {
3087            no_optimize: true,
3088            bounds_check: true,
3089            ..Default::default()
3090        };
3091        let cfg_software = CompileConfig {
3092            no_optimize: true,
3093            safety_bounds: SafetyBounds::Software,
3094            ..Default::default()
3095        };
3096        let l = backend.compile_function("ld", &ops, &cfg_legacy).unwrap();
3097        let s = backend.compile_function("ld", &ops, &cfg_software).unwrap();
3098        assert_eq!(
3099            l.code, s.code,
3100            "--bounds-check should produce the same bytes as --safety-bounds=software"
3101        );
3102    }
3103
3104    /// #377: `--safety-bounds software` must be enforced on the OPTIMIZED path
3105    /// too. Pre-fix, `software` was byte-identical to `none` there (a silent
3106    /// no-op while the safety manifest claimed enforcement). The compiled
3107    /// bytes must now (a) differ from `none` and (b) contain the inline
3108    /// `CMP ip, sl` + `UDF` guard.
3109    #[test]
3110    fn arm_safety_bounds_software_enforced_on_optimized_path_377() {
3111        let backend = ArmBackend::new();
3112        // Dynamic-address store+load: the optimized path accepts this shape
3113        // (no calls, no i64 params, ≤4 params).
3114        let ops = vec![
3115            WasmOp::LocalGet(0),
3116            WasmOp::LocalGet(1),
3117            WasmOp::I32Store {
3118                offset: 4,
3119                align: 2,
3120            },
3121            WasmOp::LocalGet(0),
3122            WasmOp::I32Load {
3123                offset: 0,
3124                align: 2,
3125            },
3126        ];
3127        // no_optimize NOT set — this exercises the optimized path.
3128        let cfg_none = CompileConfig::default();
3129        let cfg_sw = CompileConfig {
3130            safety_bounds: SafetyBounds::Software,
3131            ..Default::default()
3132        };
3133        let n = backend.compile_function("st", &ops, &cfg_none).unwrap();
3134        let s = backend.compile_function("st", &ops, &cfg_sw).unwrap();
3135        assert_ne!(
3136            n.code, s.code,
3137            "#377: software bounds must CHANGE optimized-path codegen (was a silent no-op)"
3138        );
3139        // Thumb-2 `UDF #0` is 0xDE00 (LE bytes: 00 DE); the #752
3140        // wraparound-safe guard's borrow check `CMP sl, ip` (16-bit
3141        // high-reg form) is 0x45E2 (LE: E2 45). Both must appear — one
3142        // guard per access, traps inline.
3143        let has_udf = s.code.windows(2).any(|w| w == [0x00, 0xDE]);
3144        let has_cmp_sl_ip = s.code.windows(2).any(|w| w == [0xE2, 0x45]);
3145        assert!(has_udf, "#377: inline UDF trap missing from optimized path");
3146        assert!(
3147            has_cmp_sl_ip,
3148            "#377/#752: CMP sl, ip bounds borrow-check missing from optimized path"
3149        );
3150        // And `none` must contain NO UDF (the function has no other trap).
3151        assert!(
3152            !n.code.windows(2).any(|w| w == [0x00, 0xDE]),
3153            "none must not contain a UDF for this function"
3154        );
3155    }
3156
3157    /// #377: `mpu` on the optimized path is codegen-passthrough — identical
3158    /// bytes to `none` on BOTH paths (hardware enforcement is target-level;
3159    /// synth does not emit MPU region programming — tracked separately in
3160    /// #377's fix-direction discussion). This pins path-parity for `mpu`.
3161    #[test]
3162    fn arm_safety_bounds_mpu_optimized_path_parity_377() {
3163        let backend = ArmBackend::new();
3164        let ops = vec![
3165            WasmOp::LocalGet(0),
3166            WasmOp::I32Load {
3167                offset: 0,
3168                align: 2,
3169            },
3170        ];
3171        let cfg_none = CompileConfig::default();
3172        let cfg_mpu = CompileConfig {
3173            safety_bounds: SafetyBounds::Mpu,
3174            ..Default::default()
3175        };
3176        let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
3177        let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
3178        assert_eq!(
3179            n.code, m.code,
3180            "Mpu and None must produce identical bytes on the optimized path too"
3181        );
3182    }
3183
3184    /// #377: `mask` on the optimized path declines to the direct selector
3185    /// (honest degradation) — the compiled function must equal the
3186    /// `--no-optimize` masking bytes, i.e. the flag is honored, never dropped.
3187    #[test]
3188    fn arm_safety_bounds_mask_optimized_path_declines_to_direct_377() {
3189        let backend = ArmBackend::new();
3190        let ops = vec![
3191            WasmOp::LocalGet(0),
3192            WasmOp::LocalGet(1),
3193            WasmOp::I32Store {
3194                offset: 0,
3195                align: 2,
3196            },
3197        ];
3198        // RQ-57-SENTINEL: mask now requires a STATED non-zero power-of-two
3199        // size (0 = zero-byte memory = refused), so the test states one —
3200        // exactly what the #953 fix required of the rv32 driver test.
3201        let cfg_mask_opt = CompileConfig {
3202            safety_bounds: SafetyBounds::Mask,
3203            linear_memory_bytes: 64 * 1024,
3204            ..Default::default()
3205        };
3206        let cfg_mask_direct = CompileConfig {
3207            no_optimize: true,
3208            safety_bounds: SafetyBounds::Mask,
3209            linear_memory_bytes: 64 * 1024,
3210            ..Default::default()
3211        };
3212        let o = backend.compile_function("st", &ops, &cfg_mask_opt).unwrap();
3213        let d = backend
3214            .compile_function("st", &ops, &cfg_mask_direct)
3215            .unwrap();
3216        assert_eq!(
3217            o.code, d.code,
3218            "#377: mask on the optimized path must fall back to the direct selector's masking"
3219        );
3220    }
3221
3222    /// RQ-57-SENTINEL (#953 sibling): `--safety-bounds mask` with a ZERO-byte
3223    /// linear memory must REFUSE at compile time. Before this fix, `bytes == 0`
3224    /// was exempt from the power-of-two gate ("0 means unknown"), and the
3225    /// emitted `SUB R12, R10, #1; AND` guard degenerated to an IDENTITY mask
3226    /// at runtime (R10 = 0 baked by the startup for a `(memory 0)` module):
3227    /// an unbounded OOB access in the mode whose purpose is bounding.
3228    /// Red-first: pre-fix this compile SUCCEEDED (verified on the v0.56.1
3229    /// tree: exit 0, `movw r10, #0x0` in the reset handler, AND-masked body).
3230    #[test]
3231    fn arm_safety_bounds_mask_zero_size_refused_rq57() {
3232        let backend = ArmBackend::new();
3233        let ops = vec![
3234            WasmOp::LocalGet(0),
3235            WasmOp::I32Load {
3236                offset: 0,
3237                align: 2,
3238            },
3239        ];
3240        let cfg = CompileConfig {
3241            safety_bounds: SafetyBounds::Mask,
3242            linear_memory_bytes: 0,
3243            ..Default::default()
3244        };
3245        let err = backend
3246            .compile_function("ld", &ops, &cfg)
3247            .expect_err("mask over a zero-byte memory must refuse, not emit an identity mask");
3248        let msg = format!("{err}");
3249        assert!(
3250            msg.contains("ZERO bytes"),
3251            "refusal must name the zero-byte cause, got: {msg}"
3252        );
3253    }
3254
3255    // ========================================================================
3256    // ISA feature gate tests — ensure the compiler never emits unsupported
3257    // instructions for a given target
3258    // ========================================================================
3259
3260    #[test]
3261    fn test_f32_rejected_on_cortex_m3_no_fpu() {
3262        let backend = ArmBackend::new();
3263        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
3264        let config = CompileConfig {
3265            target: TargetSpec::cortex_m3(),
3266            no_optimize: true,
3267            ..CompileConfig::default()
3268        };
3269
3270        let result = backend.compile_function("fadd", &ops, &config);
3271        assert!(
3272            result.is_err(),
3273            "f32 operations should fail on Cortex-M3 (no FPU)"
3274        );
3275    }
3276
3277    #[test]
3278    fn test_f32_accepted_on_cortex_m4f() {
3279        let backend = ArmBackend::new();
3280        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
3281        let config = CompileConfig {
3282            target: TargetSpec::cortex_m4f(),
3283            no_optimize: true,
3284            ..CompileConfig::default()
3285        };
3286
3287        let result = backend.compile_function("fadd", &ops, &config);
3288        assert!(
3289            result.is_ok(),
3290            "f32 operations should succeed on Cortex-M4F, got: {:?}",
3291            result.unwrap_err()
3292        );
3293    }
3294
3295    #[test]
3296    fn test_i32_works_on_all_targets() {
3297        let backend = ArmBackend::new();
3298        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
3299
3300        // Cortex-M3 (no FPU)
3301        let config_m3 = CompileConfig {
3302            target: TargetSpec::cortex_m3(),
3303            no_optimize: true,
3304            ..CompileConfig::default()
3305        };
3306        assert!(
3307            backend.compile_function("add", &ops, &config_m3).is_ok(),
3308            "i32 ops should work on Cortex-M3"
3309        );
3310
3311        // Cortex-M4F (single FPU)
3312        let config_m4f = CompileConfig {
3313            target: TargetSpec::cortex_m4f(),
3314            no_optimize: true,
3315            ..CompileConfig::default()
3316        };
3317        assert!(
3318            backend.compile_function("add", &ops, &config_m4f).is_ok(),
3319            "i32 ops should work on Cortex-M4F"
3320        );
3321
3322        // Cortex-M7DP (double FPU)
3323        let config_m7dp = CompileConfig {
3324            target: TargetSpec::cortex_m7dp(),
3325            no_optimize: true,
3326            ..CompileConfig::default()
3327        };
3328        assert!(
3329            backend.compile_function("add", &ops, &config_m7dp).is_ok(),
3330            "i32 ops should work on Cortex-M7DP"
3331        );
3332    }
3333
3334    #[test]
3335    fn test_f32_rejected_on_cortex_m4_no_fpu() {
3336        // Cortex-M4 (without F suffix) has no FPU
3337        let backend = ArmBackend::new();
3338        let ops = vec![WasmOp::F32Const(1.5), WasmOp::F32Const(2.5), WasmOp::F32Mul];
3339        let config = CompileConfig {
3340            target: TargetSpec::cortex_m4(),
3341            no_optimize: true,
3342            ..CompileConfig::default()
3343        };
3344
3345        let result = backend.compile_function("fmul", &ops, &config);
3346        assert!(
3347            result.is_err(),
3348            "f32 operations should fail on Cortex-M4 (no FPU)"
3349        );
3350    }
3351
3352    // ========================================================================
3353    // Issue #120 — f32 ops in the optimized lowering path
3354    //
3355    // `OptimizerBridge::wasm_to_ir` has no handlers for f32/f64 ops, so a
3356    // value-producing float op fell through to `Opcode::Nop`, leaving a
3357    // downstream consumer with an unmapped vreg and tripping the PR #101
3358    // defensive panic in `ir_to_arm`. Customer reproducer: `compiler_builtins
3359    // float::div` and `gale_compute_ipi_mask` in the `falcon-rate-component`
3360    // module.
3361    //
3362    // Fix: `optimize_full` declines float modules with a typed `Err`;
3363    // `compile_wasm_to_arm` falls back to the non-optimized `select_with_stack`
3364    // path, which handles f32 via VFP/FPU. These tests use the *default*
3365    // (optimized) config — `no_optimize` is NOT set — which is the exact
3366    // configuration that panicked pre-fix.
3367    // ========================================================================
3368
3369    /// RQ-65-DECLINE (#1208 / #1213 / #1205): a shape the optimized path
3370    /// used to lower WRONG must now reach the direct selector through the
3371    /// fallback, so the DEFAULT configuration is byte-identical to
3372    /// `--no-optimize` on it — the selector-parity property
3373    /// (`selector_parity_197_differential.py`), asserted at the unit level
3374    /// for one instance of each declined class.
3375    #[test]
3376    fn test_rq65_declined_shapes_default_equals_no_optimize() {
3377        let backend = ArmBackend::new();
3378        let cases: Vec<(&str, Vec<WasmOp>)> = vec![
3379            (
3380                "ld8u",
3381                vec![
3382                    WasmOp::LocalGet(0),
3383                    WasmOp::I64Load8U {
3384                        offset: 0,
3385                        align: 0,
3386                    },
3387                ],
3388            ),
3389            (
3390                "st16",
3391                vec![
3392                    WasmOp::LocalGet(0),
3393                    WasmOp::I64Const(7),
3394                    WasmOp::I64Store16 {
3395                        offset: 0,
3396                        align: 1,
3397                    },
3398                ],
3399            ),
3400            (
3401                "sel64",
3402                vec![
3403                    WasmOp::I64Const(1),
3404                    WasmOp::I64Const(0),
3405                    WasmOp::LocalGet(0),
3406                    WasmOp::Select,
3407                    WasmOp::I32WrapI64,
3408                ],
3409            ),
3410            (
3411                "vif",
3412                vec![
3413                    WasmOp::LocalGet(0),
3414                    WasmOp::LocalGet(1),
3415                    WasmOp::I32GtS,
3416                    WasmOp::If,
3417                    WasmOp::I32Const(7),
3418                    WasmOp::Else,
3419                    WasmOp::I32Const(9),
3420                    WasmOp::End,
3421                ],
3422            ),
3423        ];
3424        for (name, ops) in cases {
3425            let default = backend
3426                .compile_function(name, &ops, &CompileConfig::default())
3427                .unwrap_or_else(|e| {
3428                    panic!("{name}: default config must compile via the fallback: {e}")
3429                });
3430            let direct = backend
3431                .compile_function(
3432                    name,
3433                    &ops,
3434                    &CompileConfig {
3435                        no_optimize: true,
3436                        ..CompileConfig::default()
3437                    },
3438                )
3439                .unwrap_or_else(|e| panic!("{name}: --no-optimize must compile: {e}"));
3440            assert_eq!(
3441                default.code, direct.code,
3442                "{name}: the declined shape must be the direct selector's bytes"
3443            );
3444            assert!(default.code.len() > 2, "{name}: not the #1208 empty body");
3445        }
3446    }
3447
3448    /// Pre-fix: this panicked with "vreg vN has no assigned ARM register and
3449    /// no spill slot" inside `ir_to_arm`. Post-fix: the optimized path declines
3450    /// the module and the backend falls back to direct selection, producing a
3451    /// non-empty f32.div lowering on a Cortex-M4F.
3452    #[test]
3453    fn test_issue120_f32_div_compiles_via_optimized_default() {
3454        let backend = ArmBackend::new();
3455        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
3456        let config = CompileConfig {
3457            target: TargetSpec::cortex_m4f(),
3458            // no_optimize NOT set — this exercises the optimized path that
3459            // panicked in issue #120, then the fallback to direct selection.
3460            // GI-FPU-002: the f32 params must be declared so the direct
3461            // selector homes them in S0/S1 (AAPCS-VFP) rather than declining.
3462            current_func_params_f32: vec![true, true],
3463            ..CompileConfig::default()
3464        };
3465
3466        let result = backend.compile_function("fdiv", &ops, &config);
3467        assert!(
3468            result.is_ok(),
3469            "f32.div must compile on Cortex-M4F via the optimized->direct \
3470             fallback (issue #120), got: {:?}",
3471            result.as_ref().err()
3472        );
3473        assert!(
3474            !result.unwrap().code.is_empty(),
3475            "f32.div must produce non-empty machine code"
3476        );
3477    }
3478
3479    /// A spread of f32 ops, all through the optimized (default) config, must
3480    /// compile via the fallback on an FPU target without panicking.
3481    #[test]
3482    fn test_issue120_assorted_f32_ops_compile_via_optimized_default() {
3483        let backend = ArmBackend::new();
3484        let config = CompileConfig {
3485            target: TargetSpec::cortex_m4f(),
3486            // GI-FPU-002: declare the two f32 params for AAPCS-VFP homing.
3487            current_func_params_f32: vec![true, true],
3488            ..CompileConfig::default()
3489        };
3490
3491        let cases: Vec<(&str, Vec<WasmOp>)> = vec![
3492            (
3493                "fadd",
3494                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Add],
3495            ),
3496            (
3497                "fmul",
3498                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Mul],
3499            ),
3500            (
3501                "fsub",
3502                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Sub],
3503            ),
3504        ];
3505
3506        for (name, ops) in cases {
3507            let result = backend.compile_function(name, &ops, &config);
3508            assert!(
3509                result.is_ok(),
3510                "{name} must compile via the optimized->direct fallback \
3511                 (issue #120), got: {:?}",
3512                result.as_ref().err()
3513            );
3514            assert!(
3515                !result.unwrap().code.is_empty(),
3516                "{name} must produce non-empty machine code"
3517            );
3518        }
3519    }
3520
3521    /// The fallback must still honor the ISA feature gate: f32 on a no-FPU
3522    /// target must fail cleanly (not panic) even on the optimized path.
3523    #[test]
3524    fn test_issue120_f32_div_rejected_on_no_fpu_via_optimized() {
3525        let backend = ArmBackend::new();
3526        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
3527        let config = CompileConfig {
3528            target: TargetSpec::cortex_m3(),
3529            ..CompileConfig::default()
3530        };
3531
3532        let result = backend.compile_function("fdiv", &ops, &config);
3533        assert!(
3534            result.is_err(),
3535            "f32.div must be rejected on Cortex-M3 (no FPU), not panic"
3536        );
3537    }
3538
3539    /// #507: a `br_table` function compiled via the DEFAULT (optimized) config
3540    /// must produce the SAME bytes as the direct (`no_optimize`) selector —
3541    /// i.e. the optimized path declined it to direct, lowering the dispatch as a
3542    /// real cmp-chain instead of silently dropping it (which left all arms in
3543    /// fall-through). Pre-fix the two outputs differed (the optimized one had no
3544    /// selector compare). Execution correctness is gated by
3545    /// `scripts/repro/br_table_507_differential.py`.
3546    #[test]
3547    fn test_507_br_table_declines_to_direct() {
3548        let backend = ArmBackend::new();
3549        // dispatch(sel): br_table over 3 blocks, each storing a marker to mem[0].
3550        let ops = vec![
3551            WasmOp::Block,
3552            WasmOp::Block,
3553            WasmOp::Block,
3554            WasmOp::LocalGet(0),
3555            WasmOp::BrTable {
3556                targets: vec![0, 1, 2],
3557                default: 2,
3558            },
3559            WasmOp::End,
3560            WasmOp::I32Const(0),
3561            WasmOp::I32Const(10),
3562            WasmOp::I32Store {
3563                offset: 0,
3564                align: 2,
3565            },
3566            WasmOp::Return,
3567            WasmOp::End,
3568            WasmOp::I32Const(0),
3569            WasmOp::I32Const(20),
3570            WasmOp::I32Store {
3571                offset: 0,
3572                align: 2,
3573            },
3574            WasmOp::Return,
3575            WasmOp::End,
3576            WasmOp::I32Const(0),
3577            WasmOp::I32Const(30),
3578            WasmOp::I32Store {
3579                offset: 0,
3580                align: 2,
3581            },
3582        ];
3583        let opt = CompileConfig {
3584            target: TargetSpec::cortex_m4(),
3585            ..CompileConfig::default()
3586        };
3587        let direct = CompileConfig {
3588            target: TargetSpec::cortex_m4(),
3589            no_optimize: true,
3590            ..CompileConfig::default()
3591        };
3592        let a = backend
3593            .compile_function("dispatch", &ops, &opt)
3594            .expect("optimized-default must compile br_table (via decline)");
3595        let b = backend
3596            .compile_function("dispatch", &ops, &direct)
3597            .expect("direct must compile br_table");
3598        assert_eq!(
3599            a.code, b.code,
3600            "#507: optimized-default br_table output must be byte-identical to the \
3601             direct selector (i.e. declined to direct), not a dropped dispatch"
3602        );
3603    }
3604
3605    /// Issue #94: end-to-end byte-size check for the canonical u64-packed
3606    /// FFI-return hi32 extract pattern. Compiles two near-identical
3607    /// functions — one with the optimized shift-by-32, one with a generic
3608    /// shift-by-7 — and asserts the optimized form is meaningfully smaller.
3609    #[test]
3610    fn test_issue94_hi32_extract_is_smaller_than_generic_shift() {
3611        let backend = ArmBackend::new();
3612        let config = CompileConfig {
3613            target: TargetSpec::cortex_m4f(),
3614            ..CompileConfig::default()
3615        };
3616
3617        // #518: the i64 value must NOT come from an i64 PARAM — the optimized
3618        // path now declines i64-param functions to the direct selector (it homed
3619        // an i64 param in R4:R5 instead of R0:R1, a silent miscompile this test's
3620        // byte-size-only assertion masked). The canonical #94 case is a u64 from
3621        // an FFI return, not a param, anyway. Source the i64 from a sign-extended
3622        // i32 param (`extend_i32_s`): a runtime, non-constant-foldable i64 that
3623        // stays on the optimized path, so the shift-by-32 hi-extract peephole is
3624        // still exercised on CORRECT code.
3625        // Optimized path: `(i64.extend_i32_s (local.get 0)) >>> 32; wrap_i64`
3626        let ops_hi32 = vec![
3627            WasmOp::LocalGet(0), // i32 param in R0
3628            WasmOp::I64ExtendI32S,
3629            WasmOp::I64Const(32),
3630            WasmOp::I64ShrU,
3631            WasmOp::I32WrapI64,
3632        ];
3633        let func_hi32 = backend
3634            .compile_function("hi32_extract", &ops_hi32, &config)
3635            .unwrap();
3636
3637        // Generic path: `... >>> 7; wrap_i64` — same shape, but the shift amount
3638        // is not a multiple of 32, so it falls through to the runtime shift.
3639        let ops_generic = vec![
3640            WasmOp::LocalGet(0),
3641            WasmOp::I64ExtendI32S,
3642            WasmOp::I64Const(7),
3643            WasmOp::I64ShrU,
3644            WasmOp::I32WrapI64,
3645        ];
3646        let func_generic = backend
3647            .compile_function("generic_shr", &ops_generic, &config)
3648            .unwrap();
3649
3650        let bytes_hi32 = func_hi32.code.len();
3651        let bytes_generic = func_generic.code.len();
3652        println!(
3653            "\n[issue #94] hi32 extract: {} bytes (vs generic shift: {} bytes; saved {})",
3654            bytes_hi32,
3655            bytes_generic,
3656            bytes_generic.saturating_sub(bytes_hi32)
3657        );
3658        let hex: String = func_hi32
3659            .code
3660            .iter()
3661            .map(|b| format!("{:02x}", b))
3662            .collect::<Vec<_>>()
3663            .join(" ");
3664        println!("[issue #94] hi32 bytes: {}", hex);
3665        // We expect the optimized form to be at least 30 bytes smaller than
3666        // the generic 64-bit shift sequence. (Empirically: 14 vs 50 bytes.)
3667        assert!(
3668            bytes_hi32 + 30 <= bytes_generic,
3669            "issue #94: hi32 extract = {} bytes, generic shift = {} bytes; \
3670             expected optimized form to be at least 30 bytes smaller",
3671            bytes_hi32,
3672            bytes_generic,
3673        );
3674    }
3675}