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
166 .select_with_stack(wasm_ops, num_params)
167 .map_err(|e| format!("instruction selection failed: {}", e))
168 };
169
170 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 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 Err(_) => select_direct()?,
202 }
203 };
204
205 validate_instructions(&arm_instrs, config.target.fpu, &config.target.triple)
209 .map_err(|e| format!("ISA validation failed: {}", e))?;
210
211 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 if let ArmOp::Bl { label } = &instr.op
227 && label.starts_with("__meld_")
228 {
229 relocations.push(CodeRelocation {
230 offset: code.len() as u32,
231 symbol: label.clone(),
232 });
233 }
234
235 let encoded = encoder
236 .encode(&instr.op)
237 .map_err(|e| format!("ARM encoding failed: {}", e))?;
238 code.extend_from_slice(&encoded);
239 }
240
241 Ok((code, relocations))
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 #[test]
249 fn test_arm_backend_name() {
250 let backend = ArmBackend::new();
251 assert_eq!(backend.name(), "arm");
252 assert!(backend.is_available());
253 }
254
255 #[test]
256 fn test_arm_backend_capabilities() {
257 let backend = ArmBackend::new();
258 let caps = backend.capabilities();
259 assert!(!caps.produces_elf);
260 assert!(caps.supports_rule_verification);
261 assert!(!caps.is_external);
262 }
263
264 #[test]
265 fn test_compile_add_function() {
266 let backend = ArmBackend::new();
267 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
268 let config = CompileConfig::default();
269
270 let result = backend.compile_function("add", &ops, &config);
271 assert!(result.is_ok());
272
273 let func = result.unwrap();
274 assert_eq!(func.name, "add");
275 assert!(!func.code.is_empty());
276 assert_eq!(func.wasm_ops, ops);
277 }
278
279 #[test]
280 fn test_count_params() {
281 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
282 assert_eq!(count_params(&ops), 2);
283
284 let no_params = vec![WasmOp::I32Const(5), WasmOp::I32Const(3), WasmOp::I32Add];
285 assert_eq!(count_params(&no_params), 0);
286 }
287
288 #[test]
289 fn test_arm_backend_register() {
290 let mut registry = synth_core::BackendRegistry::new();
291 registry.register(Box::new(ArmBackend::new()));
292 assert!(registry.get("arm").is_some());
293 assert_eq!(registry.available().len(), 1);
294 }
295
296 #[test]
297 fn test_compile_import_call_produces_relocations() {
298 let backend = ArmBackend::new();
299 let ops = vec![WasmOp::Call(0)];
302 let config = CompileConfig {
303 num_imports: 1,
304 no_optimize: true, ..CompileConfig::default()
306 };
307
308 let result = backend.compile_function("caller", &ops, &config);
309 assert!(result.is_ok());
310
311 let func = result.unwrap();
312 assert!(!func.code.is_empty());
313 assert_eq!(func.relocations.len(), 1);
314 assert_eq!(func.relocations[0].symbol, "__meld_dispatch_import");
315 assert!(func.relocations[0].offset > 0);
317 }
318
319 #[test]
320 fn test_compile_no_imports_no_relocations() {
321 let backend = ArmBackend::new();
322 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
323 let config = CompileConfig::default();
324
325 let func = backend.compile_function("add", &ops, &config).unwrap();
326 assert!(func.relocations.is_empty());
327 }
328
329 #[test]
332 fn arm_safety_bounds_mpu_emits_same_code_as_none() {
333 let backend = ArmBackend::new();
337 let ops = vec![
338 WasmOp::LocalGet(0),
339 WasmOp::I32Load {
340 offset: 0,
341 align: 2,
342 },
343 ];
344 let cfg_none = CompileConfig {
345 no_optimize: true,
346 ..Default::default()
347 };
348 let cfg_mpu = CompileConfig {
349 no_optimize: true,
350 safety_bounds: SafetyBounds::Mpu,
351 ..Default::default()
352 };
353 let n = backend.compile_function("ld", &ops, &cfg_none).unwrap();
354 let m = backend.compile_function("ld", &ops, &cfg_mpu).unwrap();
355 assert_eq!(
356 n.code, m.code,
357 "Mpu and None should produce identical ARM bytes (Mpu relies on hardware)"
358 );
359 }
360
361 #[test]
362 fn arm_legacy_bounds_check_still_emits_software_check() {
363 let backend = ArmBackend::new();
366 let ops = vec![
367 WasmOp::LocalGet(0),
368 WasmOp::I32Load {
369 offset: 0,
370 align: 2,
371 },
372 ];
373 let cfg_legacy = CompileConfig {
374 no_optimize: true,
375 bounds_check: true,
376 ..Default::default()
377 };
378 let cfg_software = CompileConfig {
379 no_optimize: true,
380 safety_bounds: SafetyBounds::Software,
381 ..Default::default()
382 };
383 let l = backend.compile_function("ld", &ops, &cfg_legacy).unwrap();
384 let s = backend.compile_function("ld", &ops, &cfg_software).unwrap();
385 assert_eq!(
386 l.code, s.code,
387 "--bounds-check should produce the same bytes as --safety-bounds=software"
388 );
389 }
390
391 #[test]
397 fn test_f32_rejected_on_cortex_m3_no_fpu() {
398 let backend = ArmBackend::new();
399 let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
400 let config = CompileConfig {
401 target: TargetSpec::cortex_m3(),
402 no_optimize: true,
403 ..CompileConfig::default()
404 };
405
406 let result = backend.compile_function("fadd", &ops, &config);
407 assert!(
408 result.is_err(),
409 "f32 operations should fail on Cortex-M3 (no FPU)"
410 );
411 }
412
413 #[test]
414 fn test_f32_accepted_on_cortex_m4f() {
415 let backend = ArmBackend::new();
416 let ops = vec![WasmOp::F32Const(1.0), WasmOp::F32Const(2.0), WasmOp::F32Add];
417 let config = CompileConfig {
418 target: TargetSpec::cortex_m4f(),
419 no_optimize: true,
420 ..CompileConfig::default()
421 };
422
423 let result = backend.compile_function("fadd", &ops, &config);
424 assert!(
425 result.is_ok(),
426 "f32 operations should succeed on Cortex-M4F, got: {:?}",
427 result.unwrap_err()
428 );
429 }
430
431 #[test]
432 fn test_i32_works_on_all_targets() {
433 let backend = ArmBackend::new();
434 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::I32Add];
435
436 let config_m3 = CompileConfig {
438 target: TargetSpec::cortex_m3(),
439 no_optimize: true,
440 ..CompileConfig::default()
441 };
442 assert!(
443 backend.compile_function("add", &ops, &config_m3).is_ok(),
444 "i32 ops should work on Cortex-M3"
445 );
446
447 let config_m4f = CompileConfig {
449 target: TargetSpec::cortex_m4f(),
450 no_optimize: true,
451 ..CompileConfig::default()
452 };
453 assert!(
454 backend.compile_function("add", &ops, &config_m4f).is_ok(),
455 "i32 ops should work on Cortex-M4F"
456 );
457
458 let config_m7dp = CompileConfig {
460 target: TargetSpec::cortex_m7dp(),
461 no_optimize: true,
462 ..CompileConfig::default()
463 };
464 assert!(
465 backend.compile_function("add", &ops, &config_m7dp).is_ok(),
466 "i32 ops should work on Cortex-M7DP"
467 );
468 }
469
470 #[test]
471 fn test_f32_rejected_on_cortex_m4_no_fpu() {
472 let backend = ArmBackend::new();
474 let ops = vec![WasmOp::F32Const(1.5), WasmOp::F32Const(2.5), WasmOp::F32Mul];
475 let config = CompileConfig {
476 target: TargetSpec::cortex_m4(),
477 no_optimize: true,
478 ..CompileConfig::default()
479 };
480
481 let result = backend.compile_function("fmul", &ops, &config);
482 assert!(
483 result.is_err(),
484 "f32 operations should fail on Cortex-M4 (no FPU)"
485 );
486 }
487
488 #[test]
510 fn test_issue120_f32_div_compiles_via_optimized_default() {
511 let backend = ArmBackend::new();
512 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
513 let config = CompileConfig {
514 target: TargetSpec::cortex_m4f(),
515 ..CompileConfig::default()
518 };
519
520 let result = backend.compile_function("fdiv", &ops, &config);
521 assert!(
522 result.is_ok(),
523 "f32.div must compile on Cortex-M4F via the optimized->direct \
524 fallback (issue #120), got: {:?}",
525 result.as_ref().err()
526 );
527 assert!(
528 !result.unwrap().code.is_empty(),
529 "f32.div must produce non-empty machine code"
530 );
531 }
532
533 #[test]
536 fn test_issue120_assorted_f32_ops_compile_via_optimized_default() {
537 let backend = ArmBackend::new();
538 let config = CompileConfig {
539 target: TargetSpec::cortex_m4f(),
540 ..CompileConfig::default()
541 };
542
543 let cases: Vec<(&str, Vec<WasmOp>)> = vec![
544 (
545 "fadd",
546 vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Add],
547 ),
548 (
549 "fmul",
550 vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Mul],
551 ),
552 (
553 "fsub",
554 vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Sub],
555 ),
556 ];
557
558 for (name, ops) in cases {
559 let result = backend.compile_function(name, &ops, &config);
560 assert!(
561 result.is_ok(),
562 "{name} must compile via the optimized->direct fallback \
563 (issue #120), got: {:?}",
564 result.as_ref().err()
565 );
566 assert!(
567 !result.unwrap().code.is_empty(),
568 "{name} must produce non-empty machine code"
569 );
570 }
571 }
572
573 #[test]
576 fn test_issue120_f32_div_rejected_on_no_fpu_via_optimized() {
577 let backend = ArmBackend::new();
578 let ops = vec![WasmOp::LocalGet(0), WasmOp::LocalGet(1), WasmOp::F32Div];
579 let config = CompileConfig {
580 target: TargetSpec::cortex_m3(),
581 ..CompileConfig::default()
582 };
583
584 let result = backend.compile_function("fdiv", &ops, &config);
585 assert!(
586 result.is_err(),
587 "f32.div must be rejected on Cortex-M3 (no FPU), not panic"
588 );
589 }
590
591 #[test]
596 fn test_issue94_hi32_extract_is_smaller_than_generic_shift() {
597 let backend = ArmBackend::new();
598 let config = CompileConfig {
599 target: TargetSpec::cortex_m4f(),
600 ..CompileConfig::default()
601 };
602
603 let ops_hi32 = vec![
605 WasmOp::LocalGet(0), WasmOp::I64Const(32),
607 WasmOp::I64ShrU,
608 WasmOp::I32WrapI64,
609 ];
610 let func_hi32 = backend
611 .compile_function("hi32_extract", &ops_hi32, &config)
612 .unwrap();
613
614 let ops_generic = vec![
618 WasmOp::LocalGet(0),
619 WasmOp::I64Const(7),
620 WasmOp::I64ShrU,
621 WasmOp::I32WrapI64,
622 ];
623 let func_generic = backend
624 .compile_function("generic_shr", &ops_generic, &config)
625 .unwrap();
626
627 let bytes_hi32 = func_hi32.code.len();
628 let bytes_generic = func_generic.code.len();
629 println!(
630 "\n[issue #94] hi32 extract: {} bytes (vs generic shift: {} bytes; saved {})",
631 bytes_hi32,
632 bytes_generic,
633 bytes_generic.saturating_sub(bytes_hi32)
634 );
635 let hex: String = func_hi32
636 .code
637 .iter()
638 .map(|b| format!("{:02x}", b))
639 .collect::<Vec<_>>()
640 .join(" ");
641 println!("[issue #94] hi32 bytes: {}", hex);
642 assert!(
645 bytes_hi32 + 30 <= bytes_generic,
646 "issue #94: hi32 extract = {} bytes, generic shift = {} bytes; \
647 expected optimized form to be at least 30 bytes smaller",
648 bytes_hi32,
649 bytes_generic,
650 );
651 }
652}