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