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