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