1mod canonicalize;
2
3pub(crate) use canonicalize::{
4 canonicalize_control_flow_targets, remove_temp_control_flow_target_labels,
5};
6use {
7 crate::{ast::AST, astnode::ASTNode},
8 sbpf_analyze::remove_dead_functions,
9 sbpf_common::instruction::Instruction,
10 sbpf_ir::{Cfg, CfgRodata, InputNode, control_flow_graph},
11 std::collections::{HashMap, HashSet},
12};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum CfgDumpStage {
16 BeforeOpt,
17 AfterOpt,
18}
19
20impl CfgDumpStage {
21 pub fn file_name(self) -> &'static str {
22 match self {
23 Self::BeforeOpt => "opt-before.dot",
24 Self::AfterOpt => "opt-after.dot",
25 }
26 }
27}
28
29pub fn optimize(ast: &mut AST) {
33 optimize_with_observer(ast, |_, _| {});
34}
35
36pub fn optimize_with_observer<F>(ast: &mut AST, mut observe: F)
40where
41 F: FnMut(CfgDumpStage, &Cfg),
42{
43 let mut cfg = cfg_for_ast(ast);
44 observe(CfgDumpStage::BeforeOpt, &cfg);
45 remove_dead_functions(&mut cfg);
46 sbpf_analyze::fix_alu32_extension(&mut cfg);
47 sbpf_analyze::fix_signed_div(&mut cfg);
48 observe(CfgDumpStage::AfterOpt, &cfg);
49 write_cfg_to_ast(ast, &cfg);
50}
51
52pub fn eliminate_unreachable_functions(ast: &mut AST) {
54 let mut cfg = cfg_for_ast(ast);
55 remove_dead_functions(&mut cfg);
56 write_cfg_to_ast(ast, &cfg);
57}
58
59pub fn fix_alu32_extension(ast: &mut AST) {
63 let mut cfg = cfg_for_ast(ast);
64 sbpf_analyze::fix_alu32_extension(&mut cfg);
65 write_cfg_to_ast(ast, &cfg);
66}
67
68pub(crate) fn cfg_for_ast(ast: &AST) -> Cfg {
71 let function_entries = function_entries(ast);
72 let entry_label = ast.nodes.iter().find_map(|node| {
73 if let ASTNode::GlobalDecl { global_decl } = node {
74 Some(global_decl.entry_label.as_str())
75 } else {
76 None
77 }
78 });
79 let nodes = ast.nodes.iter().map(|node| match node {
80 ASTNode::Label { label, .. } => InputNode::Label(label.name.as_str()),
81 ASTNode::Instruction { instruction, .. } => InputNode::Instruction(instruction),
82 _ => InputNode::Other,
83 });
84 let mut cfg = control_flow_graph(nodes, &function_entries, entry_label);
85 if !ast.rodata_nodes.is_empty() {
86 let rodata = ast.rodata_nodes.iter().filter_map(|node| {
87 let ASTNode::ROData { rodata, offset } = node else {
88 return None;
89 };
90 Some(CfgRodata::new(&rodata.name, *offset, rodata.get_size()))
91 });
92 let references = ast
93 .rodata_relocations()
94 .iter()
95 .map(|relocation| (relocation.offset, relocation.target.as_str()));
96 cfg.set_rodata(rodata, references);
97 }
98 cfg
99}
100
101pub(crate) fn write_cfg_to_ast(ast: &mut AST, cfg: &Cfg) {
109 let live: HashSet<usize> = cfg
110 .all_blocks()
111 .flat_map(|(_, block)| block.node_ids().iter().copied())
112 .collect();
113
114 let mut rewritten: HashMap<usize, Vec<Instruction>> = HashMap::new();
115 for (_, block) in cfg.all_blocks() {
116 let mut last_source = None;
117 for node in block.instructions() {
118 let Some(instruction) = node.instruction() else {
119 continue;
120 };
121 match node.source_node_id() {
122 Some(id) => {
123 rewritten.insert(id, vec![instruction.clone()]);
124 last_source = Some(id);
125 }
126 None => {
127 let id = last_source
128 .expect("inserted instructions follow a source instruction in their block");
129 rewritten
130 .get_mut(&id)
131 .expect("source instruction was recorded")
132 .push(instruction.clone());
133 }
134 }
135 }
136 }
137
138 ast.nodes = std::mem::take(&mut ast.nodes)
139 .into_iter()
140 .enumerate()
141 .flat_map(|(idx, node)| match node {
142 ASTNode::Label { .. } if !live.contains(&idx) => vec![],
143 ASTNode::Instruction { .. } => rewritten
144 .remove(&idx)
145 .unwrap_or_default()
146 .into_iter()
147 .map(|instruction| ASTNode::Instruction {
148 instruction,
149 offset: 0,
150 })
151 .collect(),
152 node => vec![node],
153 })
154 .collect();
155
156 assign_offsets(ast);
157}
158
159pub fn assign_offsets(ast: &mut AST) {
163 let mut text_offset = 0u64;
164 let mut text_size = 0u64;
165 for node in &mut ast.nodes {
166 match node {
167 ASTNode::Label { offset, .. } => *offset = text_offset,
168 ASTNode::Instruction {
169 instruction,
170 offset,
171 } => {
172 *offset = text_offset;
173 let size = instruction.get_size();
174 text_offset += size;
175 text_size += size;
176 }
177 _ => {}
178 }
179 }
180 ast.set_text_size(text_size);
181}
182
183fn function_entries(ast: &AST) -> HashSet<String> {
184 ast.function_entries().clone()
185}
186
187#[cfg(test)]
188mod tests {
189 use {
190 super::*,
191 crate::{
192 SbpfArch,
193 ast::{OptimizationConfig, build_program},
194 astnode::{GlobalDecl, Label, ROData},
195 parser::Token,
196 },
197 either::Either,
198 sbpf_common::{
199 inst_param::{Number, Register},
200 instruction::Instruction,
201 opcode::Opcode,
202 },
203 };
204
205 #[test]
206 fn test_cfg_dump_stage_file_names() {
207 assert_eq!(CfgDumpStage::BeforeOpt.file_name(), "opt-before.dot");
208 assert_eq!(CfgDumpStage::AfterOpt.file_name(), "opt-after.dot");
209 }
210
211 #[test]
212 fn test_optimizer_observer_captures_before_and_after_all_passes() {
213 let mut ast = alu32_program();
214 let mut signed_div = alu_node(Opcode::Div64Reg, 0, Some(3), None);
215 if let ASTNode::Instruction { instruction, .. } = &mut signed_div {
216 instruction.off = Some(Either::Right(sbpf_common::opcode::SIGNED_DIV_OFF));
217 }
218 ast.nodes.insert(ast.nodes.len() - 1, signed_div);
219 ast.add_function_entry("dead".to_string());
220 ast.nodes.extend([
221 label_node("dead", 0),
222 instruction_node(Opcode::Exit, None, 0, None),
223 ]);
224 assign_offsets(&mut ast);
225
226 let mut snapshots = Vec::new();
227 optimize_with_observer(&mut ast, |stage, cfg| {
228 snapshots.push((stage, cfg.clone()));
229 });
230
231 let [(before_stage, before), (after_stage, after)] = snapshots.as_slice() else {
232 panic!("expected exactly two CFG snapshots");
233 };
234 assert_eq!(*before_stage, CfgDumpStage::BeforeOpt);
235 assert_eq!(*after_stage, CfgDumpStage::AfterOpt);
236 assert!(before.functions().iter().any(|f| f.name() == "dead"));
237 assert_eq!(after.functions().len(), 1);
238 assert_eq!(after.functions()[0].name(), "entrypoint");
239
240 let instructions = |cfg: &Cfg| {
241 cfg.all_instructions()
242 .filter_map(|(_, node)| node.instruction().cloned())
243 .collect::<Vec<_>>()
244 };
245 let before = instructions(before);
246 let after = instructions(after);
247
248 assert!(!before.iter().any(|i| i.opcode == Opcode::Mov32Reg));
249 assert!(after.iter().any(|i| {
250 i.opcode == Opcode::Mov32Reg
251 && i.dst == Some(Register { n: 1 })
252 && i.src == Some(Register { n: 1 })
253 }));
254 assert!(before.iter().any(Instruction::is_signed_div_or_mod));
255 assert!(!after.iter().any(Instruction::is_signed_div_or_mod));
256 assert!(after.iter().any(|i| i.opcode == Opcode::Div64Reg));
257
258 let written_instructions: Vec<_> = ast
259 .nodes
260 .iter()
261 .filter_map(|node| match node {
262 ASTNode::Instruction { instruction, .. } => Some(instruction.clone()),
263 _ => None,
264 })
265 .collect();
266 assert_eq!(after, written_instructions);
267 }
268
269 #[test]
270 fn test_optimizer_preserves_unreachable_blocks_in_reachable_function() {
271 let mut ast = AST::new();
272 ast.add_function_entry("entrypoint".to_string());
273 ast.nodes = vec![
274 label_node("entrypoint", 0),
275 instruction_node(
276 Opcode::Ja,
277 None,
278 0,
279 Some(Either::Left("target".to_string())),
280 ),
281 instruction_node(Opcode::Mov64Imm, Some(0), 8, None),
282 label_node("target", 16),
283 instruction_node(Opcode::Exit, None, 16, None),
284 ];
285 ast.set_text_size(24);
286
287 eliminate_unreachable_functions(&mut ast);
288
289 assert_eq!(ast.nodes.len(), 5);
290 assert!(matches!(
291 &ast.nodes[1],
292 ASTNode::Instruction { instruction, offset }
293 if instruction.opcode == Opcode::Ja
294 && instruction.off == Some(Either::Left("target".to_string()))
295 && *offset == 0
296 ));
297 assert!(matches!(
298 &ast.nodes[2],
299 ASTNode::Instruction { instruction, offset }
300 if instruction.opcode == Opcode::Mov64Imm && *offset == 8
301 ));
302 assert!(matches!(
303 &ast.nodes[3],
304 ASTNode::Label { label, offset } if label.name == "target" && *offset == 16
305 ));
306 assert!(matches!(
307 &ast.nodes[4],
308 ASTNode::Instruction { instruction, offset }
309 if instruction.opcode == Opcode::Exit && *offset == 16
310 ));
311 }
312
313 #[test]
314 fn test_optimizer_removes_uncalled_function_only() {
315 let mut ast = AST::new();
316 ast.add_function_entry("entrypoint".to_string());
317 ast.add_function_entry("dead".to_string());
318 ast.add_function_entry("callee".to_string());
319 ast.nodes = vec![
320 label_node("entrypoint", 0),
321 call_node("callee", 0),
322 instruction_node(Opcode::Exit, None, 8, None),
323 label_node("dead", 16),
324 instruction_node(Opcode::Exit, None, 16, None),
325 label_node("callee", 24),
326 instruction_node(Opcode::Exit, None, 24, None),
327 ];
328 ast.set_text_size(32);
329
330 eliminate_unreachable_functions(&mut ast);
331
332 assert!(
333 !ast.nodes
334 .iter()
335 .any(|node| matches!(node, ASTNode::Label { label, .. } if label.name == "dead"))
336 );
337 assert!(
338 ast.nodes
339 .iter()
340 .any(|node| matches!(node, ASTNode::Label { label, offset }
341 if label.name == "callee" && *offset == 16))
342 );
343 assert_eq!(
344 ast.nodes
345 .iter()
346 .filter(|node| matches!(node, ASTNode::Instruction { .. }))
347 .count(),
348 3
349 );
350 }
351
352 #[test]
353 fn test_optimizer_uses_declared_entry_when_it_is_not_first() {
354 let mut ast = AST::new();
355 ast.add_function_entry("helper".to_string());
356 ast.add_function_entry("dead".to_string());
357 ast.add_function_entry("entrypoint".to_string());
358 ast.nodes = vec![
359 ASTNode::GlobalDecl {
360 global_decl: GlobalDecl {
361 entry_label: "entrypoint".to_string(),
362 span: 0..0,
363 },
364 },
365 label_node("helper", 0),
366 instruction_node(Opcode::Exit, None, 0, None),
367 label_node("dead", 8),
368 instruction_node(Opcode::Exit, None, 8, None),
369 label_node("entrypoint", 16),
370 call_node("helper", 16),
371 instruction_node(Opcode::Exit, None, 24, None),
372 ];
373 ast.set_text_size(32);
374
375 let cfg = cfg_for_ast(&ast);
376 assert_eq!(cfg.functions()[0].name(), "entrypoint");
377 assert_eq!(cfg.functions()[0].entry_block_id(), Some(2)); eliminate_unreachable_functions(&mut ast);
380
381 assert!(ast.nodes.iter().any(
382 |node| matches!(node, ASTNode::Label { label, .. } if label.name == "entrypoint")
383 ));
384 assert!(
385 ast.nodes
386 .iter()
387 .any(|node| matches!(node, ASTNode::Label { label, .. } if label.name == "helper"))
388 );
389 assert!(
390 !ast.nodes
391 .iter()
392 .any(|node| matches!(node, ASTNode::Label { label, .. } if label.name == "dead"))
393 );
394 }
395
396 #[test]
397 fn test_optimizer_preserves_function_targeted_by_rodata_relocation() {
398 let mut ast = AST::new();
399 ast.add_function_entry("entrypoint".to_string());
400 ast.add_function_entry("target".to_string());
401 ast.add_function_entry("dead".to_string());
402 ast.nodes = vec![
403 ASTNode::GlobalDecl {
404 global_decl: GlobalDecl {
405 entry_label: "entrypoint".to_string(),
406 span: 0..0,
407 },
408 },
409 label_node("entrypoint", 0),
410 instruction_node(Opcode::Exit, None, 0, None),
411 label_node("target", 8),
412 instruction_node(Opcode::Exit, None, 8, None),
413 label_node("dead", 16),
414 instruction_node(Opcode::Exit, None, 16, None),
415 ];
416 ast.rodata_nodes.push(ASTNode::ROData {
417 rodata: ROData {
418 name: "pointer".to_string(),
419 args: vec![
420 Token::Directive("quad".to_string(), 0..0),
421 Token::VectorLiteral(vec![Number::Int(0)], 0..0),
422 ],
423 span: 0..0,
424 },
425 offset: 0,
426 });
427 ast.set_text_size(24);
428 ast.set_rodata_size(8);
429 ast.add_rodata_relocation(0, "target".to_string());
430
431 eliminate_unreachable_functions(&mut ast);
432
433 assert!(ast.nodes.iter().any(
434 |node| matches!(node, ASTNode::Label { label, .. } if label.name == "entrypoint")
435 ));
436 assert!(
437 ast.nodes
438 .iter()
439 .any(|node| matches!(node, ASTNode::Label { label, .. } if label.name == "target"))
440 );
441 assert!(
442 !ast.nodes
443 .iter()
444 .any(|node| matches!(node, ASTNode::Label { label, .. } if label.name == "dead"))
445 );
446 }
447
448 #[test]
449 fn test_write_back_drops_dead_functions_and_recomputes_offsets_cumulatively() {
450 let mut ast = AST::new();
451 for name in ["entrypoint", "dead_a", "live", "dead_b", "target"] {
452 ast.add_function_entry(name.to_string());
453 }
454 ast.nodes = vec![
455 label_node("entrypoint", 0),
456 call_node("live", 0),
457 call_node("target", 8),
458 instruction_node(Opcode::Exit, None, 16, None),
459 label_node("dead_a", 24),
460 instruction_node(Opcode::Exit, None, 24, None),
461 label_node("live", 32),
462 instruction_node(Opcode::Exit, None, 32, None),
463 label_node("dead_b", 40),
464 instruction_node(Opcode::Exit, None, 40, None),
465 label_node("target", 48),
466 instruction_node(Opcode::Exit, None, 48, None),
467 ];
468 ast.set_text_size(56);
469
470 eliminate_unreachable_functions(&mut ast);
471
472 assert_eq!(
473 listing(&ast.nodes),
474 [
475 ("entrypoint:".to_string(), 0),
476 ("call".to_string(), 0),
477 ("call".to_string(), 8),
478 ("exit".to_string(), 16),
479 ("live:".to_string(), 24),
480 ("exit".to_string(), 24),
481 ("target:".to_string(), 32),
482 ("exit".to_string(), 32),
483 ]
484 );
485 }
486
487 #[test]
488 fn test_assign_offsets_recomputes_from_scratch() {
489 let mut ast = AST::new();
490 ast.nodes = vec![
491 label_node("entrypoint", 999),
492 instruction_node(Opcode::Exit, None, 999, None),
493 label_node("next", 999),
494 instruction_node(Opcode::Exit, None, 999, None),
495 ];
496
497 assign_offsets(&mut ast);
498
499 assert!(matches!(
500 &ast.nodes[0],
501 ASTNode::Label { label, offset } if label.name == "entrypoint" && *offset == 0
502 ));
503 assert!(matches!(
504 &ast.nodes[1],
505 ASTNode::Instruction { offset, .. } if *offset == 0
506 ));
507 assert!(matches!(
508 &ast.nodes[2],
509 ASTNode::Label { label, offset } if label.name == "next" && *offset == 8
510 ));
511 }
512
513 fn alu_node(opcode: Opcode, dst: u8, src: Option<u8>, imm: Option<i64>) -> ASTNode {
514 ASTNode::Instruction {
515 instruction: Instruction {
516 opcode,
517 dst: Some(Register { n: dst }),
518 src: src.map(|n| Register { n }),
519 off: None,
520 imm: imm.map(|v| Either::Right(Number::Int(v))),
521 span: 0..0,
522 },
523 offset: 0,
524 }
525 }
526
527 fn alu32_program() -> AST {
530 let mut ast = AST::new();
531 ast.add_function_entry("entrypoint".to_string());
532 ast.nodes = vec![
533 label_node("entrypoint", 0),
534 alu_node(Opcode::Add32Reg, 1, Some(2), None),
535 instruction_node(Opcode::Ja, None, 8, Some(Either::Left("done".to_string()))),
536 label_node("done", 16),
537 alu_node(Opcode::Lsh64Imm, 1, None, Some(1)),
538 alu_node(Opcode::Mov64Reg, 0, Some(1), None),
539 instruction_node(Opcode::Exit, None, 32, None),
540 ];
541 ast.set_text_size(40);
542 ast
543 }
544
545 fn listing(nodes: &[ASTNode]) -> Vec<(String, u64)> {
546 nodes
547 .iter()
548 .filter_map(|node| match node {
549 ASTNode::Label { label, offset } => Some((format!("{}:", label.name), *offset)),
550 ASTNode::Instruction {
551 instruction,
552 offset,
553 } => Some((instruction.opcode.to_string(), *offset)),
554 _ => None,
555 })
556 .collect()
557 }
558
559 #[test]
560 fn test_fix_alu32_extension_inserts_fixup_and_reassigns_offsets() {
561 let mut ast = alu32_program();
562
563 fix_alu32_extension(&mut ast);
564
565 assert_eq!(
566 listing(&ast.nodes),
567 [
568 ("entrypoint:".to_string(), 0),
569 ("add32".to_string(), 0),
570 ("mov32".to_string(), 8),
571 ("ja".to_string(), 16),
572 ("done:".to_string(), 24),
573 ("lsh64".to_string(), 24),
574 ("mov64".to_string(), 32),
575 ("exit".to_string(), 40),
576 ]
577 );
578 let ASTNode::Instruction { instruction, .. } = &ast.nodes[2] else {
579 panic!("expected the inserted instruction");
580 };
581 assert_eq!(instruction.opcode, Opcode::Mov32Reg);
582 assert_eq!(instruction.dst, Some(Register { n: 1 }));
583 assert_eq!(instruction.src, Some(Register { n: 1 }));
584 }
585
586 #[test]
587 fn test_fix_alu32_extension_narrows_copy_in_place() {
588 let mut ast = AST::new();
589 ast.add_function_entry("entrypoint".to_string());
590 ast.nodes = vec![
591 label_node("entrypoint", 0),
592 alu_node(Opcode::Add32Reg, 1, Some(2), None),
593 alu_node(Opcode::Mov64Reg, 0, Some(1), None),
594 instruction_node(Opcode::Exit, None, 16, None),
595 ];
596 ast.set_text_size(24);
597
598 fix_alu32_extension(&mut ast);
599
600 assert_eq!(
601 listing(&ast.nodes),
602 [
603 ("entrypoint:".to_string(), 0),
604 ("add32".to_string(), 0),
605 ("mov32".to_string(), 8),
606 ("exit".to_string(), 16),
607 ]
608 );
609 let ASTNode::Instruction { instruction, .. } = &ast.nodes[2] else {
610 panic!("expected the narrowed copy");
611 };
612 assert_eq!(instruction.opcode, Opcode::Mov32Reg);
613 assert_eq!(instruction.dst, Some(Register { n: 0 }));
614 assert_eq!(instruction.src, Some(Register { n: 1 }));
615 }
616
617 #[test]
618 fn test_fix_alu32_extension_promotes_in_place() {
619 let mut ast = AST::new();
620 ast.add_function_entry("entrypoint".to_string());
621 ast.nodes = vec![
622 label_node("entrypoint", 0),
623 alu_node(Opcode::Lddw, 1, None, Some(0x9000_0000)),
624 alu_node(Opcode::Sub32Imm, 1, None, Some(1)),
625 alu_node(Opcode::Mov64Reg, 0, Some(1), None),
626 instruction_node(Opcode::Exit, None, 32, None),
627 ];
628 ast.set_text_size(40);
629
630 fix_alu32_extension(&mut ast);
631
632 assert_eq!(
633 listing(&ast.nodes),
634 [
635 ("entrypoint:".to_string(), 0),
636 ("lddw".to_string(), 0),
637 ("sub64".to_string(), 16),
638 ("mov64".to_string(), 24),
639 ("exit".to_string(), 32),
640 ]
641 );
642 }
643
644 #[test]
645 fn test_fix_alu32_extension_leaves_unaffected_program_untouched() {
646 let mut ast = AST::new();
647 ast.add_function_entry("entrypoint".to_string());
648 ast.nodes = vec![
649 label_node("entrypoint", 0),
650 alu_node(Opcode::Add32Reg, 1, Some(2), None),
651 alu_node(Opcode::Mov32Reg, 0, Some(1), None),
652 instruction_node(Opcode::Exit, None, 16, None),
653 ];
654 assign_offsets(&mut ast);
655 let before = listing(&ast.nodes);
656
657 fix_alu32_extension(&mut ast);
658
659 assert_eq!(listing(&ast.nodes), before);
660 }
661
662 #[test]
663 fn test_build_program_runs_fixup_only_when_optimizing() {
664 for arch in [SbpfArch::V0, SbpfArch::V3] {
665 let disabled =
666 build_program(alu32_program(), arch, OptimizationConfig::disabled()).unwrap();
667 assert!(
668 !listing(disabled.code_section.get_nodes())
669 .iter()
670 .any(|(op, _)| op == "mov32"),
671 "{arch:?}: disabled must not rewrite"
672 );
673
674 let enabled =
675 build_program(alu32_program(), arch, OptimizationConfig::enabled()).unwrap();
676 let ops: Vec<String> = listing(enabled.code_section.get_nodes())
677 .into_iter()
678 .map(|(op, _)| op)
679 .collect();
680 assert_eq!(
681 ops,
682 [
683 "entrypoint:",
684 "add32",
685 "mov32",
686 "ja",
687 "done:",
688 "lsh64",
689 "mov64",
690 "exit"
691 ],
692 "{arch:?}"
693 );
694 }
695 }
696
697 fn label_node(name: &str, offset: u64) -> ASTNode {
698 ASTNode::Label {
699 label: Label {
700 name: name.to_string(),
701 span: 0..0,
702 },
703 offset,
704 }
705 }
706
707 fn instruction_node(
708 opcode: Opcode,
709 dst: Option<u8>,
710 offset: u64,
711 off: Option<Either<String, i16>>,
712 ) -> ASTNode {
713 ASTNode::Instruction {
714 instruction: Instruction {
715 opcode,
716 dst: dst.map(|n| Register { n }),
717 src: None,
718 off,
719 imm: None,
720 span: 0..0,
721 },
722 offset,
723 }
724 }
725
726 fn call_node(target: &str, offset: u64) -> ASTNode {
727 ASTNode::Instruction {
728 instruction: Instruction {
729 opcode: Opcode::Call,
730 dst: None,
731 src: None,
732 off: None,
733 imm: Some(Either::Left(target.to_string())),
734 span: 0..0,
735 },
736 offset,
737 }
738 }
739}