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