1use llvm_pm::inkwell;
18use llvm_pm::inkwell::context::Context;
19use llvm_pm::inkwell::values::InstructionOpcode;
20use llvm_pm::inkwell::IntPredicate;
21use llvm_pm::traits::{
22 LlvmCgsccAnalysis, LlvmCgsccPass, LlvmFunctionPass, LlvmModulePass, PreservedAnalyses,
23};
24use llvm_pm::{
25 CgsccAnalysisManager, FunctionAnalysisManager, FunctionPassManager, ModuleAnalysisManager,
26 ModulePassManager,
27};
28
29use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
30use std::sync::Arc;
31
32struct BasicBlockCountAnalysis;
43
44impl LlvmCgsccAnalysis for BasicBlockCountAnalysis {
45 type Result = u32;
46
47 fn run_analysis(
48 &self,
49 function: &inkwell::values::FunctionValue<'_>,
50 _manager: &CgsccAnalysisManager,
51 ) -> Self::Result {
52 function.count_basic_blocks()
53 }
54
55 fn id() -> *const u8 {
56 static ID: u8 = 0;
57 &ID
58 }
59}
60
61struct BasicBlockReportPass {
69 registered: Arc<AtomicBool>,
70}
71
72impl LlvmCgsccPass for BasicBlockReportPass {
73 fn run_pass(
74 &self,
75 function: &mut inkwell::values::FunctionValue<'_>,
76 manager: &CgsccAnalysisManager,
77 ) -> PreservedAnalyses {
78 if self
80 .registered
81 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
82 .is_ok()
83 {
84 manager.add_analysis(BasicBlockCountAnalysis);
85 }
86
87 let bb_count = *manager.get_result::<BasicBlockCountAnalysis>(function);
89 let name = function.get_name().to_string_lossy();
90 println!(" [CGSCC] {}: {} basic blocks", name, bb_count);
91
92 PreservedAnalyses::All
93 }
94}
95
96struct SimpleDCEPass {
109 removed: Arc<AtomicU32>,
110}
111
112fn may_have_side_effects(opcode: InstructionOpcode) -> bool {
115 matches!(
116 opcode,
117 InstructionOpcode::Store
118 | InstructionOpcode::Call
119 | InstructionOpcode::Fence
120 | InstructionOpcode::AtomicCmpXchg
121 | InstructionOpcode::AtomicRMW
122 | InstructionOpcode::Resume
123 | InstructionOpcode::LandingPad
124 | InstructionOpcode::IndirectBr
125 | InstructionOpcode::Invoke
126 | InstructionOpcode::Unreachable
127 )
128}
129
130impl LlvmFunctionPass for SimpleDCEPass {
131 fn run_pass(
132 &self,
133 function: &mut inkwell::values::FunctionValue<'_>,
134 _manager: &FunctionAnalysisManager,
135 ) -> PreservedAnalyses {
136 let mut changed = false;
137
138 for bb in function.get_basic_blocks() {
141 let dead: Vec<_> = bb
142 .get_instructions()
143 .filter(|inst| {
144 if inst.is_terminator() {
145 return false;
146 }
147 if may_have_side_effects(inst.get_opcode()) {
148 return false;
149 }
150 if inst.get_opcode() == InstructionOpcode::Alloca {
151 return false;
152 }
153 inst.get_first_use().is_none()
154 })
155 .collect();
156
157 for inst in dead {
158 inst.erase_from_basic_block();
159 self.removed.fetch_add(1, Ordering::SeqCst);
160 changed = true;
161 }
162 }
163
164 if changed {
165 PreservedAnalyses::None
166 } else {
167 PreservedAnalyses::All
168 }
169 }
170}
171
172struct DCEStatsPass {
178 label: &'static str,
179}
180
181impl LlvmModulePass for DCEStatsPass {
182 fn run_pass(
183 &self,
184 module: &mut inkwell::module::Module<'_>,
185 _manager: &ModuleAnalysisManager,
186 ) -> PreservedAnalyses {
187 println!("--- {} ---", self.label);
188 let mut total_insts = 0u32;
189 let mut total_bbs = 0u32;
190 for func in module.get_functions() {
191 if func.count_basic_blocks() == 0 {
192 continue;
193 }
194 let mut insts = 0u32;
195 for bb in func.get_basic_blocks() {
196 insts += bb.get_instructions().count() as u32;
197 }
198 let bbs = func.count_basic_blocks();
199 let name = func.get_name().to_string_lossy();
200 println!(" {}: {} BBs, {} instructions", name, bbs, insts);
201 total_insts += insts;
202 total_bbs += bbs;
203 }
204 println!(" Total: {} BBs, {} instructions", total_bbs, total_insts);
205 PreservedAnalyses::All
206 }
207}
208
209fn build_module_with_dead_code() -> inkwell::module::Module<'static> {
216 let context = Box::leak(Box::new(Context::create()));
217 let module = context.create_module("dce_demo");
218 let i32_ty = context.i32_type();
219
220 let fn_ty = i32_ty.fn_type(&[i32_ty.into(), i32_ty.into()], false);
223 let func = module.add_function("add_with_dead_code", fn_ty, None);
224 let bb = context.append_basic_block(func, "entry");
225 let b = context.create_builder();
226 b.position_at_end(bb);
227
228 let a = func.get_nth_param(0).unwrap().into_int_value();
229 let b_param = func.get_nth_param(1).unwrap().into_int_value();
230
231 let sum = b.build_int_add(a, b_param, "sum").unwrap();
233
234 let _dead_mul = b.build_int_mul(a, b_param, "dead_mul").unwrap();
236 let _dead_sub = b.build_int_sub(a, b_param, "dead_sub").unwrap();
237 let _dead_xor = b.build_xor(a, b_param, "dead_xor").unwrap();
238
239 b.build_return(Some(&sum)).unwrap();
240
241 let fn_ty2 = i32_ty.fn_type(&[i32_ty.into()], false);
244 let func2 = module.add_function("branch_with_dead_code", fn_ty2, None);
245 let entry = context.append_basic_block(func2, "entry");
246 let then_bb = context.append_basic_block(func2, "then");
247 let else_bb = context.append_basic_block(func2, "else");
248 let merge = context.append_basic_block(func2, "merge");
249 let b = context.create_builder();
250
251 b.position_at_end(entry);
252 let x = func2.get_first_param().unwrap().into_int_value();
253 let cmp = b
254 .build_int_compare(IntPredicate::SGT, x, i32_ty.const_int(10, false), "cmp")
255 .unwrap();
256 b.build_conditional_branch(cmp, then_bb, else_bb).unwrap();
257
258 b.position_at_end(then_bb);
259 let then_val = b
260 .build_int_mul(x, i32_ty.const_int(2, false), "then_val")
261 .unwrap();
262 let _dead_then = b
263 .build_int_add(x, i32_ty.const_int(99, false), "dead_then")
264 .unwrap();
265 b.build_unconditional_branch(merge).unwrap();
266
267 b.position_at_end(else_bb);
268 let else_val = b
269 .build_int_add(x, i32_ty.const_int(1, false), "else_val")
270 .unwrap();
271 let _dead_else = b
272 .build_int_sub(x, i32_ty.const_int(42, false), "dead_else")
273 .unwrap();
274 let _dead_else2 = b.build_int_mul(x, x, "dead_else2").unwrap();
275 b.build_unconditional_branch(merge).unwrap();
276
277 b.position_at_end(merge);
278 let phi = b.build_phi(i32_ty, "result").unwrap();
279 phi.add_incoming(&[(&then_val, then_bb), (&else_val, else_bb)]);
280 let result = phi.as_basic_value().into_int_value();
281 b.build_return(Some(&result)).unwrap();
282
283 module
284}
285
286fn main() -> Result<(), Box<dyn std::error::Error>> {
291 let module = build_module_with_dead_code();
292 module.verify()?;
293
294 let removed = Arc::new(AtomicU32::new(0));
295
296 {
298 let mut pm = ModulePassManager::new(None, None)?;
299 pm.add_pass(DCEStatsPass {
300 label: "Before DCE",
301 });
302 pm.add_cgscc_pass(BasicBlockReportPass {
303 registered: Arc::new(AtomicBool::new(false)),
304 });
305 pm.run(&module)?;
306 }
307
308 {
310 let mut fpm = FunctionPassManager::new(None, None)?;
311 fpm.add_pass(SimpleDCEPass {
312 removed: removed.clone(),
313 });
314 for func in module.get_functions() {
315 if func.count_basic_blocks() == 0 {
316 continue;
317 }
318 fpm.run(func)?;
319 }
320 }
321
322 module.verify()?;
323
324 {
326 let mut pm = ModulePassManager::new(None, None)?;
327 pm.add_pass(DCEStatsPass { label: "After DCE" });
328 pm.run(&module)?;
329 }
330
331 let total_removed = removed.load(Ordering::SeqCst);
332 println!("\nRemoved {} dead instructions", total_removed);
333 assert!(
334 total_removed >= 5,
335 "Expected to remove at least 5 dead instructions, got {}",
336 total_removed
337 );
338
339 println!("ok");
340 Ok(())
341}