Skip to main content

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, 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            let compiled = self.compile_function(&name, &func.ops, config)?;
79            functions.push(compiled);
80        }
81
82        Ok(CompilationResult {
83            functions,
84            elf: None,
85            backend_name: self.name().to_string(),
86        })
87    }
88
89    fn compile_function(
90        &self,
91        name: &str,
92        ops: &[WasmOp],
93        config: &CompileConfig,
94    ) -> Result<CompiledFunction, BackendError> {
95        let (code, relocations) =
96            compile_wasm_to_arm(ops, config).map_err(BackendError::CompilationFailed)?;
97
98        Ok(CompiledFunction {
99            name: name.to_string(),
100            code,
101            wasm_ops: ops.to_vec(),
102            relocations,
103        })
104    }
105
106    fn is_available(&self) -> bool {
107        true // Always available — it's a library backend
108    }
109}
110
111/// Count the number of function parameters by analyzing LocalGet patterns
112fn count_params(wasm_ops: &[WasmOp]) -> u32 {
113    let mut first_access: std::collections::HashMap<u32, bool> = std::collections::HashMap::new();
114    for op in wasm_ops {
115        match op {
116            WasmOp::LocalGet(idx) => {
117                first_access.entry(*idx).or_insert(true);
118            }
119            WasmOp::LocalSet(idx) | WasmOp::LocalTee(idx) => {
120                first_access.entry(*idx).or_insert(false);
121            }
122            _ => {}
123        }
124    }
125
126    first_access
127        .iter()
128        .filter_map(
129            |(&idx, &is_read_first)| {
130                if is_read_first { Some(idx + 1) } else { None }
131            },
132        )
133        .max()
134        .unwrap_or(0)
135}
136
137/// Core compilation: WASM ops → ARM machine code bytes + relocations
138///
139/// Returns (code_bytes, relocations) where relocations record BL instructions
140/// that target external symbols (e.g., `__meld_dispatch_import` for import calls).
141fn compile_wasm_to_arm(
142    wasm_ops: &[WasmOp],
143    config: &CompileConfig,
144) -> Result<(Vec<u8>, Vec<CodeRelocation>), String> {
145    let num_params = count_params(wasm_ops);
146
147    let bounds_config = match config.effective_safety_bounds() {
148        SafetyBounds::None => BoundsCheckConfig::None,
149        SafetyBounds::Mpu => BoundsCheckConfig::Mpu,
150        SafetyBounds::Software => BoundsCheckConfig::Software,
151        SafetyBounds::Mask => BoundsCheckConfig::Masking,
152    };
153
154    // The non-optimized (direct) instruction-selection path. Handles f32 via
155    // VFP/FPU. Used directly when `--no-optimize` is set, and as the fallback
156    // when the optimized path declines a module (see issue #120 below).
157    let select_direct = || -> Result<Vec<ArmInstruction>, String> {
158        let db = RuleDatabase::with_standard_rules();
159        let mut selector =
160            InstructionSelector::with_bounds_check(db.rules().to_vec(), bounds_config);
161        selector.set_target(config.target.fpu, &config.target.triple);
162        if config.num_imports > 0 {
163            selector.set_num_imports(config.num_imports);
164        }
165        selector
166            .select_with_stack(wasm_ops, num_params)
167            .map_err(|e| format!("instruction selection failed: {}", e))
168    };
169
170    // Instruction selection: optimized or direct
171    let arm_instrs = if config.no_optimize {
172        select_direct()?
173    } else {
174        let opt_config = if config.loom_compat {
175            OptimizationConfig::loom_compat()
176        } else {
177            OptimizationConfig::all()
178        };
179
180        let bridge = OptimizerBridge::with_config(opt_config);
181        // `ir_to_arm` now returns `Result` — an `Err` means the optimized path
182        // hit an unmapped vreg (issue-#93-class). Treat it identically to an
183        // `optimize_full` failure: fall back to the direct selector rather
184        // than propagating, so the function still compiles correctly.
185        match bridge
186            .optimize_full(wasm_ops)
187            .and_then(|(opt_ir, _cfg, _stats)| bridge.ir_to_arm(&opt_ir, num_params as usize))
188        {
189            Ok(arm_ops) => arm_ops
190                .into_iter()
191                .map(|op| ArmInstruction {
192                    op,
193                    source_line: None,
194                })
195                .collect(),
196            // Issue #120: the optimized path declines modules it cannot lower
197            // (notably scalar f32/f64 ops — the IR has no float opcodes). Fall
198            // back to the direct instruction selector, which handles f32 via
199            // VFP/FPU. This is honest degradation: the function still compiles
200            // correctly, just without IR-level optimization.
201            Err(_) => select_direct()?,
202        }
203    };
204
205    // ISA feature gate: validate that all generated instructions are supported
206    // by the target. This catches FPU instructions on no-FPU targets, double-precision
207    // instructions on single-precision targets, etc.
208    validate_instructions(&arm_instrs, config.target.fpu, &config.target.triple)
209        .map_err(|e| format!("ISA validation failed: {}", e))?;
210
211    // Encode to binary — use Thumb-2 for Cortex-M targets
212    let use_thumb2 = matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
213
214    let encoder = if use_thumb2 {
215        ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
216    } else {
217        ArmEncoder::new_arm32()
218    };
219
220    let mut code = Vec::new();
221    let mut relocations = Vec::new();
222
223    for instr in &arm_instrs {
224        // Record a relocation for every BL: the encoder emits `bl #0` and
225        // relies on a relocation to patch the target. This covers BOTH import
226        // dispatch stubs (`__meld_*`, undefined externals) AND internal calls
227        // (`func_N`, defined in this object). Previously only `__meld_*` was
228        // recorded, so internal `BL func_N` calls were left as unpatched
229        // `bl #0` placeholders branching to a garbage address (#167).
230        if let ArmOp::Bl { label } = &instr.op {
231            relocations.push(CodeRelocation {
232                offset: code.len() as u32,
233                symbol: label.clone(),
234            });
235        }
236
237        let encoded = encoder
238            .encode(&instr.op)
239            .map_err(|e| format!("ARM encoding failed: {}", e))?;
240        code.extend_from_slice(&encoded);
241    }
242
243    Ok((code, relocations))
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249
250    #[test]
251    fn test_arm_backend_name() {
252        let backend = ArmBackend::new();
253        assert_eq!(backend.name(), "arm");
254        assert!(backend.is_available());
255    }
256
257    #[test]
258    fn test_arm_backend_capabilities() {
259        let backend = ArmBackend::new();
260        let caps = backend.capabilities();
261        assert!(!caps.produces_elf);
262        assert!(caps.supports_rule_verification);
263        assert!(!caps.is_external);
264    }
265
266    #[test]
267    fn test_compile_add_function() {
268        let backend = ArmBackend::new();
269        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
270        let config = CompileConfig::default();
271
272        let result = backend.compile_function("add", &ops, &config);
273        assert!(result.is_ok());
274
275        let func = result.unwrap();
276        assert_eq!(func.name, "add");
277        assert!(!func.code.is_empty());
278        assert_eq!(func.wasm_ops, ops);
279    }
280
281    #[test]
282    fn test_count_params() {
283        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
284        assert_eq!(count_params(&ops), 2);
285
286        let no_params = vec![WasmOp::I32Const(5), WasmOp::I32Const(3), WasmOp::I32Add];
287        assert_eq!(count_params(&no_params), 0);
288    }
289
290    #[test]
291    fn test_arm_backend_register() {
292        let mut registry = synth_core::BackendRegistry::new();
293        registry.register(Box::new(ArmBackend::new()));
294        assert!(registry.get("arm").is_some());
295        assert_eq!(registry.available().len(), 1);
296    }
297
298    #[test]
299    fn test_compile_import_call_produces_relocations() {
300        let backend = ArmBackend::new();
301        // Simulate a WASM module where func index 0 is an import.
302        // Call(0) should generate MOV R0, #0; BL __meld_dispatch_import
303        let ops = vec![WasmOp::Call(0)];
304        let config = CompileConfig {
305            num_imports: 1,
306            no_optimize: true, // Direct instruction selection to preserve Call semantics
307            ..CompileConfig::default()
308        };
309
310        let result = backend.compile_function("caller", &ops, &config);
311        assert!(result.is_ok());
312
313        let func = result.unwrap();
314        assert!(!func.code.is_empty());
315        assert_eq!(func.relocations.len(), 1);
316        assert_eq!(func.relocations[0].symbol, "__meld_dispatch_import");
317        // The BL is the second instruction (after MOV R0, #0), so offset should be > 0
318        assert!(func.relocations[0].offset > 0);
319    }
320
321    #[test]
322    fn test_compile_no_imports_no_relocations() {
323        let backend = ArmBackend::new();
324        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
325        let config = CompileConfig::default();
326
327        let func = backend.compile_function("add", &ops, &config).unwrap();
328        assert!(func.relocations.is_empty());
329    }
330
331    // ─── Phase 1 safety-bounds plumbing for ARM ──────────────────────────
332
333    #[test]
334    fn arm_safety_bounds_mpu_emits_same_code_as_none() {
335        // Mpu mode must not introduce any inline check on ARM — the MPU
336        // handles faults via hardware. The encoded bytes for an i32.load
337        // should be identical between None and Mpu.
338        let backend = ArmBackend::new();
339        let ops = vec![
340            WasmOp::LocalGet(0),
341            WasmOp::I32Load {
342                offset: 0,
343                align: 2,
344            },
345        ];
346        let cfg_none = CompileConfig {
347            no_optimize: true,
348            ..Default::default()
349        };
350        let cfg_mpu = CompileConfig {
351            no_optimize: true,
352            safety_bounds: SafetyBounds::Mpu,
353            ..Default::default()
354        };
355        let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
356        let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
357        assert_eq!(
358            n.code, m.code,
359            "Mpu and None should produce identical ARM bytes (Mpu relies on hardware)"
360        );
361    }
362
363    #[test]
364    fn arm_legacy_bounds_check_still_emits_software_check() {
365        // Legacy CLI users with `--bounds-check` should keep getting the
366        // software path even though the new SafetyBounds field defaults to None.
367        let backend = ArmBackend::new();
368        let ops = vec![
369            WasmOp::LocalGet(0),
370            WasmOp::I32Load {
371                offset: 0,
372                align: 2,
373            },
374        ];
375        let cfg_legacy = CompileConfig {
376            no_optimize: true,
377            bounds_check: true,
378            ..Default::default()
379        };
380        let cfg_software = CompileConfig {
381            no_optimize: true,
382            safety_bounds: SafetyBounds::Software,
383            ..Default::default()
384        };
385        let l = backend.compile_function("ld", &ops, &cfg_legacy).unwrap();
386        let s = backend.compile_function("ld", &ops, &cfg_software).unwrap();
387        assert_eq!(
388            l.code, s.code,
389            "--bounds-check should produce the same bytes as --safety-bounds=software"
390        );
391    }
392
393    // ========================================================================
394    // ISA feature gate tests — ensure the compiler never emits unsupported
395    // instructions for a given target
396    // ========================================================================
397
398    #[test]
399    fn test_f32_rejected_on_cortex_m3_no_fpu() {
400        let backend = ArmBackend::new();
401        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
402        let config = CompileConfig {
403            target: TargetSpec::cortex_m3(),
404            no_optimize: true,
405            ..CompileConfig::default()
406        };
407
408        let result = backend.compile_function("fadd", &ops, &config);
409        assert!(
410            result.is_err(),
411            "f32 operations should fail on Cortex-M3 (no FPU)"
412        );
413    }
414
415    #[test]
416    fn test_f32_accepted_on_cortex_m4f() {
417        let backend = ArmBackend::new();
418        let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
419        let config = CompileConfig {
420            target: TargetSpec::cortex_m4f(),
421            no_optimize: true,
422            ..CompileConfig::default()
423        };
424
425        let result = backend.compile_function("fadd", &ops, &config);
426        assert!(
427            result.is_ok(),
428            "f32 operations should succeed on Cortex-M4F, got: {:?}",
429            result.unwrap_err()
430        );
431    }
432
433    #[test]
434    fn test_i32_works_on_all_targets() {
435        let backend = ArmBackend::new();
436        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
437
438        // Cortex-M3 (no FPU)
439        let config_m3 = CompileConfig {
440            target: TargetSpec::cortex_m3(),
441            no_optimize: true,
442            ..CompileConfig::default()
443        };
444        assert!(
445            backend.compile_function("add", &ops, &config_m3).is_ok(),
446            "i32 ops should work on Cortex-M3"
447        );
448
449        // Cortex-M4F (single FPU)
450        let config_m4f = CompileConfig {
451            target: TargetSpec::cortex_m4f(),
452            no_optimize: true,
453            ..CompileConfig::default()
454        };
455        assert!(
456            backend.compile_function("add", &ops, &config_m4f).is_ok(),
457            "i32 ops should work on Cortex-M4F"
458        );
459
460        // Cortex-M7DP (double FPU)
461        let config_m7dp = CompileConfig {
462            target: TargetSpec::cortex_m7dp(),
463            no_optimize: true,
464            ..CompileConfig::default()
465        };
466        assert!(
467            backend.compile_function("add", &ops, &config_m7dp).is_ok(),
468            "i32 ops should work on Cortex-M7DP"
469        );
470    }
471
472    #[test]
473    fn test_f32_rejected_on_cortex_m4_no_fpu() {
474        // Cortex-M4 (without F suffix) has no FPU
475        let backend = ArmBackend::new();
476        let ops = vec![WasmOp::F32Const(1.5), WasmOp::F32Const(2.5), WasmOp::F32Mul];
477        let config = CompileConfig {
478            target: TargetSpec::cortex_m4(),
479            no_optimize: true,
480            ..CompileConfig::default()
481        };
482
483        let result = backend.compile_function("fmul", &ops, &config);
484        assert!(
485            result.is_err(),
486            "f32 operations should fail on Cortex-M4 (no FPU)"
487        );
488    }
489
490    // ========================================================================
491    // Issue #120 — f32 ops in the optimized lowering path
492    //
493    // `OptimizerBridge::wasm_to_ir` has no handlers for f32/f64 ops, so a
494    // value-producing float op fell through to `Opcode::Nop`, leaving a
495    // downstream consumer with an unmapped vreg and tripping the PR #101
496    // defensive panic in `ir_to_arm`. Customer reproducer: `compiler_builtins
497    // float::div` and `gale_compute_ipi_mask` in the `falcon-rate-component`
498    // module.
499    //
500    // Fix: `optimize_full` declines float modules with a typed `Err`;
501    // `compile_wasm_to_arm` falls back to the non-optimized `select_with_stack`
502    // path, which handles f32 via VFP/FPU. These tests use the *default*
503    // (optimized) config — `no_optimize` is NOT set — which is the exact
504    // configuration that panicked pre-fix.
505    // ========================================================================
506
507    /// Pre-fix: this panicked with "vreg vN has no assigned ARM register and
508    /// no spill slot" inside `ir_to_arm`. Post-fix: the optimized path declines
509    /// the module and the backend falls back to direct selection, producing a
510    /// non-empty f32.div lowering on a Cortex-M4F.
511    #[test]
512    fn test_issue120_f32_div_compiles_via_optimized_default() {
513        let backend = ArmBackend::new();
514        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
515        let config = CompileConfig {
516            target: TargetSpec::cortex_m4f(),
517            // no_optimize NOT set — this exercises the optimized path that
518            // panicked in issue #120, then the fallback to direct selection.
519            ..CompileConfig::default()
520        };
521
522        let result = backend.compile_function("fdiv", &ops, &config);
523        assert!(
524            result.is_ok(),
525            "f32.div must compile on Cortex-M4F via the optimized->direct \
526             fallback (issue #120), got: {:?}",
527            result.as_ref().err()
528        );
529        assert!(
530            !result.unwrap().code.is_empty(),
531            "f32.div must produce non-empty machine code"
532        );
533    }
534
535    /// A spread of f32 ops, all through the optimized (default) config, must
536    /// compile via the fallback on an FPU target without panicking.
537    #[test]
538    fn test_issue120_assorted_f32_ops_compile_via_optimized_default() {
539        let backend = ArmBackend::new();
540        let config = CompileConfig {
541            target: TargetSpec::cortex_m4f(),
542            ..CompileConfig::default()
543        };
544
545        let cases: Vec<(&str, Vec<WasmOp>)> = vec![
546            (
547                "fadd",
548                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Add],
549            ),
550            (
551                "fmul",
552                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Mul],
553            ),
554            (
555                "fsub",
556                vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Sub],
557            ),
558        ];
559
560        for (name, ops) in cases {
561            let result = backend.compile_function(name, &ops, &config);
562            assert!(
563                result.is_ok(),
564                "{name} must compile via the optimized->direct fallback \
565                 (issue #120), got: {:?}",
566                result.as_ref().err()
567            );
568            assert!(
569                !result.unwrap().code.is_empty(),
570                "{name} must produce non-empty machine code"
571            );
572        }
573    }
574
575    /// The fallback must still honor the ISA feature gate: f32 on a no-FPU
576    /// target must fail cleanly (not panic) even on the optimized path.
577    #[test]
578    fn test_issue120_f32_div_rejected_on_no_fpu_via_optimized() {
579        let backend = ArmBackend::new();
580        let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
581        let config = CompileConfig {
582            target: TargetSpec::cortex_m3(),
583            ..CompileConfig::default()
584        };
585
586        let result = backend.compile_function("fdiv", &ops, &config);
587        assert!(
588            result.is_err(),
589            "f32.div must be rejected on Cortex-M3 (no FPU), not panic"
590        );
591    }
592
593    /// Issue #94: end-to-end byte-size check for the canonical u64-packed
594    /// FFI-return hi32 extract pattern. Compiles two near-identical
595    /// functions — one with the optimized shift-by-32, one with a generic
596    /// shift-by-7 — and asserts the optimized form is meaningfully smaller.
597    #[test]
598    fn test_issue94_hi32_extract_is_smaller_than_generic_shift() {
599        let backend = ArmBackend::new();
600        let config = CompileConfig {
601            target: TargetSpec::cortex_m4f(),
602            ..CompileConfig::default()
603        };
604
605        // Optimized path: `(local.get 0) >>> 32; wrap_i64`
606        let ops_hi32 = vec![
607            WasmOp::LocalGet(0), // i64 param in R0:R1
608            WasmOp::I64Const(32),
609            WasmOp::I64ShrU,
610            WasmOp::I32WrapI64,
611        ];
612        let func_hi32 = backend
613            .compile_function("hi32_extract", &ops_hi32, &config)
614            .unwrap();
615
616        // Generic path: `(local.get 0) >>> 7; wrap_i64` — same shape, but the
617        // shift amount is not a multiple of 32, so it falls through to the
618        // 38-byte runtime shift.
619        let ops_generic = vec![
620            WasmOp::LocalGet(0),
621            WasmOp::I64Const(7),
622            WasmOp::I64ShrU,
623            WasmOp::I32WrapI64,
624        ];
625        let func_generic = backend
626            .compile_function("generic_shr", &ops_generic, &config)
627            .unwrap();
628
629        let bytes_hi32 = func_hi32.code.len();
630        let bytes_generic = func_generic.code.len();
631        println!(
632            "\n[issue #94] hi32 extract: {} bytes (vs generic shift: {} bytes; saved {})",
633            bytes_hi32,
634            bytes_generic,
635            bytes_generic.saturating_sub(bytes_hi32)
636        );
637        let hex: String = func_hi32
638            .code
639            .iter()
640            .map(|b| format!("{:02x}", b))
641            .collect::<Vec<_>>()
642            .join(" ");
643        println!("[issue #94] hi32 bytes: {}", hex);
644        // We expect the optimized form to be at least 30 bytes smaller than
645        // the generic 64-bit shift sequence. (Empirically: 14 vs 50 bytes.)
646        assert!(
647            bytes_hi32 + 30 <= bytes_generic,
648            "issue #94: hi32 extract = {} bytes, generic shift = {} bytes; \
649             expected optimized form to be at least 30 bytes smaller",
650            bytes_hi32,
651            bytes_generic,
652        );
653    }
654}