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