1use 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
19pub 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 }
109}
110
111fn 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
137fn 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 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.set_func_arg_counts(
168 config.func_arg_counts.clone(),
169 config.type_arg_counts.clone(),
170 );
171 selector.set_relocatable(config.relocatable);
175 selector
176 .select_with_stack(wasm_ops, num_params)
177 .map_err(|e| format!("instruction selection failed: {}", e))
178 };
179
180 let arm_instrs = if config.no_optimize || config.relocatable {
189 select_direct()?
190 } else {
191 let opt_config = if config.loom_compat {
192 OptimizationConfig::loom_compat()
193 } else {
194 OptimizationConfig::all()
195 };
196
197 let mut bridge = OptimizerBridge::with_config(opt_config);
198 bridge.set_num_imports(config.num_imports);
202 match bridge
207 .optimize_full(wasm_ops)
208 .and_then(|(opt_ir, _cfg, _stats)| bridge.ir_to_arm(&opt_ir, num_params as usize))
209 {
210 Ok(arm_ops) => arm_ops
211 .into_iter()
212 .map(|op| ArmInstruction {
213 op,
214 source_line: None,
215 })
216 .collect(),
217 Err(_) => select_direct()?,
223 }
224 };
225
226 validate_instructions(&arm_instrs, config.target.fpu, &config.target.triple)
230 .map_err(|e| format!("ISA validation failed: {}", e))?;
231
232 let use_thumb2 = matches!(config.target.isa, IsaVariant::Thumb2 | IsaVariant::Thumb);
234
235 let encoder = if use_thumb2 {
236 ArmEncoder::new_thumb2_with_fpu(config.target.fpu)
237 } else {
238 ArmEncoder::new_arm32()
239 };
240
241 let mut code = Vec::new();
242 let mut relocations = Vec::new();
243
244 for instr in &arm_instrs {
245 if let ArmOp::Bl { label } = &instr.op {
252 relocations.push(CodeRelocation {
253 offset: code.len() as u32,
254 symbol: label.clone(),
255 });
256 }
257
258 let encoded = encoder
259 .encode(&instr.op)
260 .map_err(|e| format!("ARM encoding failed: {}", e))?;
261 code.extend_from_slice(&encoded);
262 }
263
264 Ok((code, relocations))
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270
271 #[test]
272 fn test_arm_backend_name() {
273 let backend = ArmBackend::new();
274 assert_eq!(backend.name(), "arm");
275 assert!(backend.is_available());
276 }
277
278 #[test]
279 fn test_arm_backend_capabilities() {
280 let backend = ArmBackend::new();
281 let caps = backend.capabilities();
282 assert!(!caps.produces_elf);
283 assert!(caps.supports_rule_verification);
284 assert!(!caps.is_external);
285 }
286
287 #[test]
288 fn test_compile_add_function() {
289 let backend = ArmBackend::new();
290 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
291 let config = CompileConfig::default();
292
293 let result = backend.compile_function("add", &ops, &config);
294 assert!(result.is_ok());
295
296 let func = result.unwrap();
297 assert_eq!(func.name, "add");
298 assert!(!func.code.is_empty());
299 assert_eq!(func.wasm_ops, ops);
300 }
301
302 #[test]
303 fn test_count_params() {
304 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
305 assert_eq!(count_params(&ops), 2);
306
307 let no_params = vec![WasmOp::I32Const(5), WasmOp::I32Const(3), WasmOp::I32Add];
308 assert_eq!(count_params(&no_params), 0);
309 }
310
311 #[test]
312 fn test_arm_backend_register() {
313 let mut registry = synth_core::BackendRegistry::new();
314 registry.register(Box::new(ArmBackend::new()));
315 assert!(registry.get("arm").is_some());
316 assert_eq!(registry.available().len(), 1);
317 }
318
319 #[test]
320 fn test_compile_import_call_produces_relocations() {
321 let backend = ArmBackend::new();
322 let ops = vec![WasmOp::Call(0)];
325 let config = CompileConfig {
326 num_imports: 1,
327 no_optimize: true, ..CompileConfig::default()
329 };
330
331 let result = backend.compile_function("caller", &ops, &config);
332 assert!(result.is_ok());
333
334 let func = result.unwrap();
335 assert!(!func.code.is_empty());
336 assert_eq!(func.relocations.len(), 1);
337 assert_eq!(func.relocations[0].symbol, "__meld_dispatch_import");
338 assert!(func.relocations[0].offset > 0);
340 }
341
342 #[test]
348 fn test_compile_relocatable_import_uses_direct_func_symbol_197() {
349 let backend = ArmBackend::new();
350 let ops = vec![WasmOp::Call(0)]; let config = CompileConfig {
352 num_imports: 1,
353 relocatable: true,
354 ..CompileConfig::default()
355 };
356
357 let func = backend
358 .compile_function("caller", &ops, &config)
359 .expect("relocatable import call compiles");
360
361 assert_eq!(func.relocations.len(), 1);
362 assert_eq!(
363 func.relocations[0].symbol, "func_0",
364 "#197: relocatable import must relocate against func_0 (→ field name), not Meld dispatch"
365 );
366 }
367
368 #[test]
369 fn test_compile_no_imports_no_relocations() {
370 let backend = ArmBackend::new();
371 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
372 let config = CompileConfig::default();
373
374 let func = backend.compile_function("add", &ops, &config).unwrap();
375 assert!(func.relocations.is_empty());
376 }
377
378 #[test]
385 fn test_compile_internal_call_produces_relocation_167() {
386 let backend = ArmBackend::new();
387 let ops = vec![WasmOp::Call(2)];
389 let config = CompileConfig {
390 num_imports: 1,
391 no_optimize: true,
392 ..CompileConfig::default()
393 };
394
395 let func = backend
396 .compile_function("caller", &ops, &config)
397 .expect("internal call compiles");
398
399 assert_eq!(
400 func.relocations.len(),
401 1,
402 "an internal call must emit exactly one relocation (#167)"
403 );
404 assert_eq!(
405 func.relocations[0].symbol, "func_2",
406 "internal call must relocate against the callee's func_{{index}} symbol (#167)"
407 );
408 }
409
410 #[test]
413 fn arm_safety_bounds_mpu_emits_same_code_as_none() {
414 let backend = ArmBackend::new();
418 let ops = vec![
419 WasmOp::LocalGet(0),
420 WasmOp::I32Load {
421 offset: 0,
422 align: 2,
423 },
424 ];
425 let cfg_none = CompileConfig {
426 no_optimize: true,
427 ..Default::default()
428 };
429 let cfg_mpu = CompileConfig {
430 no_optimize: true,
431 safety_bounds: SafetyBounds::Mpu,
432 ..Default::default()
433 };
434 let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
435 let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
436 assert_eq!(
437 n.code, m.code,
438 "Mpu and None should produce identical ARM bytes (Mpu relies on hardware)"
439 );
440 }
441
442 #[test]
443 fn arm_legacy_bounds_check_still_emits_software_check() {
444 let backend = ArmBackend::new();
447 let ops = vec![
448 WasmOp::LocalGet(0),
449 WasmOp::I32Load {
450 offset: 0,
451 align: 2,
452 },
453 ];
454 let cfg_legacy = CompileConfig {
455 no_optimize: true,
456 bounds_check: true,
457 ..Default::default()
458 };
459 let cfg_software = CompileConfig {
460 no_optimize: true,
461 safety_bounds: SafetyBounds::Software,
462 ..Default::default()
463 };
464 let l = backend.compile_function("ld", &ops, &cfg_legacy).unwrap();
465 let s = backend.compile_function("ld", &ops, &cfg_software).unwrap();
466 assert_eq!(
467 l.code, s.code,
468 "--bounds-check should produce the same bytes as --safety-bounds=software"
469 );
470 }
471
472 #[test]
478 fn test_f32_rejected_on_cortex_m3_no_fpu() {
479 let backend = ArmBackend::new();
480 let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
481 let config = CompileConfig {
482 target: TargetSpec::cortex_m3(),
483 no_optimize: true,
484 ..CompileConfig::default()
485 };
486
487 let result = backend.compile_function("fadd", &ops, &config);
488 assert!(
489 result.is_err(),
490 "f32 operations should fail on Cortex-M3 (no FPU)"
491 );
492 }
493
494 #[test]
495 fn test_f32_accepted_on_cortex_m4f() {
496 let backend = ArmBackend::new();
497 let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
498 let config = CompileConfig {
499 target: TargetSpec::cortex_m4f(),
500 no_optimize: true,
501 ..CompileConfig::default()
502 };
503
504 let result = backend.compile_function("fadd", &ops, &config);
505 assert!(
506 result.is_ok(),
507 "f32 operations should succeed on Cortex-M4F, got: {:?}",
508 result.unwrap_err()
509 );
510 }
511
512 #[test]
513 fn test_i32_works_on_all_targets() {
514 let backend = ArmBackend::new();
515 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
516
517 let config_m3 = CompileConfig {
519 target: TargetSpec::cortex_m3(),
520 no_optimize: true,
521 ..CompileConfig::default()
522 };
523 assert!(
524 backend.compile_function("add", &ops, &config_m3).is_ok(),
525 "i32 ops should work on Cortex-M3"
526 );
527
528 let config_m4f = CompileConfig {
530 target: TargetSpec::cortex_m4f(),
531 no_optimize: true,
532 ..CompileConfig::default()
533 };
534 assert!(
535 backend.compile_function("add", &ops, &config_m4f).is_ok(),
536 "i32 ops should work on Cortex-M4F"
537 );
538
539 let config_m7dp = CompileConfig {
541 target: TargetSpec::cortex_m7dp(),
542 no_optimize: true,
543 ..CompileConfig::default()
544 };
545 assert!(
546 backend.compile_function("add", &ops, &config_m7dp).is_ok(),
547 "i32 ops should work on Cortex-M7DP"
548 );
549 }
550
551 #[test]
552 fn test_f32_rejected_on_cortex_m4_no_fpu() {
553 let backend = ArmBackend::new();
555 let ops = vec![WasmOp::F32Const(1.5), WasmOp::F32Const(2.5), WasmOp::F32Mul];
556 let config = CompileConfig {
557 target: TargetSpec::cortex_m4(),
558 no_optimize: true,
559 ..CompileConfig::default()
560 };
561
562 let result = backend.compile_function("fmul", &ops, &config);
563 assert!(
564 result.is_err(),
565 "f32 operations should fail on Cortex-M4 (no FPU)"
566 );
567 }
568
569 #[test]
591 fn test_issue120_f32_div_compiles_via_optimized_default() {
592 let backend = ArmBackend::new();
593 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
594 let config = CompileConfig {
595 target: TargetSpec::cortex_m4f(),
596 ..CompileConfig::default()
599 };
600
601 let result = backend.compile_function("fdiv", &ops, &config);
602 assert!(
603 result.is_ok(),
604 "f32.div must compile on Cortex-M4F via the optimized->direct \
605 fallback (issue #120), got: {:?}",
606 result.as_ref().err()
607 );
608 assert!(
609 !result.unwrap().code.is_empty(),
610 "f32.div must produce non-empty machine code"
611 );
612 }
613
614 #[test]
617 fn test_issue120_assorted_f32_ops_compile_via_optimized_default() {
618 let backend = ArmBackend::new();
619 let config = CompileConfig {
620 target: TargetSpec::cortex_m4f(),
621 ..CompileConfig::default()
622 };
623
624 let cases: Vec<(&str, Vec<WasmOp>)> = vec![
625 (
626 "fadd",
627 vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Add],
628 ),
629 (
630 "fmul",
631 vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Mul],
632 ),
633 (
634 "fsub",
635 vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Sub],
636 ),
637 ];
638
639 for (name, ops) in cases {
640 let result = backend.compile_function(name, &ops, &config);
641 assert!(
642 result.is_ok(),
643 "{name} must compile via the optimized->direct fallback \
644 (issue #120), got: {:?}",
645 result.as_ref().err()
646 );
647 assert!(
648 !result.unwrap().code.is_empty(),
649 "{name} must produce non-empty machine code"
650 );
651 }
652 }
653
654 #[test]
657 fn test_issue120_f32_div_rejected_on_no_fpu_via_optimized() {
658 let backend = ArmBackend::new();
659 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
660 let config = CompileConfig {
661 target: TargetSpec::cortex_m3(),
662 ..CompileConfig::default()
663 };
664
665 let result = backend.compile_function("fdiv", &ops, &config);
666 assert!(
667 result.is_err(),
668 "f32.div must be rejected on Cortex-M3 (no FPU), not panic"
669 );
670 }
671
672 #[test]
677 fn test_issue94_hi32_extract_is_smaller_than_generic_shift() {
678 let backend = ArmBackend::new();
679 let config = CompileConfig {
680 target: TargetSpec::cortex_m4f(),
681 ..CompileConfig::default()
682 };
683
684 let ops_hi32 = vec![
686 WasmOp::LocalGet(0), WasmOp::I64Const(32),
688 WasmOp::I64ShrU,
689 WasmOp::I32WrapI64,
690 ];
691 let func_hi32 = backend
692 .compile_function("hi32_extract", &ops_hi32, &config)
693 .unwrap();
694
695 let ops_generic = vec![
699 WasmOp::LocalGet(0),
700 WasmOp::I64Const(7),
701 WasmOp::I64ShrU,
702 WasmOp::I32WrapI64,
703 ];
704 let func_generic = backend
705 .compile_function("generic_shr", &ops_generic, &config)
706 .unwrap();
707
708 let bytes_hi32 = func_hi32.code.len();
709 let bytes_generic = func_generic.code.len();
710 println!(
711 "\n[issue #94] hi32 extract: {} bytes (vs generic shift: {} bytes; saved {})",
712 bytes_hi32,
713 bytes_generic,
714 bytes_generic.saturating_sub(bytes_hi32)
715 );
716 let hex: String = func_hi32
717 .code
718 .iter()
719 .map(|b| format!("{:02x}", b))
720 .collect::<Vec<_>>()
721 .join(" ");
722 println!("[issue #94] hi32 bytes: {}", hex);
723 assert!(
726 bytes_hi32 + 30 <= bytes_generic,
727 "issue #94: hi32 extract = {} bytes, generic shift = {} bytes; \
728 expected optimized form to be at least 30 bytes smaller",
729 bytes_hi32,
730 bytes_generic,
731 );
732 }
733}