1use llvm_pm::inkwell;
2use llvm_pm::inkwell::values::AsValueRef;
3use llvm_pm::inkwell::IntPredicate;
4use llvm_pm::inkwell::OptimizationLevel;
5use llvm_pm::traits::{
6 LlvmCgsccAnalysis, LlvmCgsccPass, LlvmFunctionAnalysis, LlvmFunctionPass, LlvmLoopAnalysis,
7 LlvmLoopPass, LlvmModuleAnalysis, LlvmModulePass, PreservedAnalyses,
8};
9use llvm_pm::{
10 CgsccAnalysisManager, FunctionAnalysisManager, FunctionPassManager, LoopAnalysisManager,
11 ModuleAnalysisManager, ModulePassManager, OptLevel,
12};
13
14type AnalysisKey = *const u8;
15use llvm_pm_sys::llvm_sys::core::{
16 LLVMConstInt, LLVMGetBasicBlockParent, LLVMGetGlobalParent, LLVMGetNamedGlobal,
17 LLVMGlobalGetValueType, LLVMSetInitializer,
18};
19use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
20use std::sync::Arc;
21
22const DELTA_GLOBAL: &str = "pass_delta";
23const DELTA_MODULE: u64 = 3;
24const DELTA_FUNCTION: u64 = 5;
25const DELTA_CGSCC: u64 = 8;
26const DELTA_LOOP: u64 = 13;
27const DELTA_GLOBAL_CSTR: &[u8] = b"pass_delta\0";
28
29fn set_pass_delta(module: &inkwell::module::Module<'_>, value: u64) {
30 let i32_ty = module.get_context().i32_type();
31 let g = module
32 .get_global(DELTA_GLOBAL)
33 .expect("global pass_delta must exist");
34 g.set_initializer(&i32_ty.const_int(value, false));
35}
36
37fn get_pass_delta(module: &inkwell::module::Module<'_>) -> u64 {
38 let g = module
39 .get_global(DELTA_GLOBAL)
40 .expect("global pass_delta must exist");
41 let init = g
42 .get_initializer()
43 .expect("global pass_delta must have initializer")
44 .into_int_value();
45 init.get_zero_extended_constant()
46 .expect("initializer should be integer constant")
47}
48
49unsafe fn set_pass_delta_from_function_ref(
50 function_ref: llvm_pm::traits::LLVMValueRef,
51 value: u64,
52) {
53 let module = LLVMGetGlobalParent(function_ref);
57 assert!(!module.is_null(), "function must belong to a module");
58 let global = LLVMGetNamedGlobal(module, DELTA_GLOBAL_CSTR.as_ptr().cast());
59 assert!(
60 !global.is_null(),
61 "global pass_delta must exist in function module"
62 );
63 let ty = LLVMGlobalGetValueType(global);
64 let v = LLVMConstInt(ty, value, 0);
65 LLVMSetInitializer(global, v);
66}
67
68#[cfg(any(
69 feature = "llvm10-0",
70 feature = "llvm11-0",
71 feature = "llvm12-0",
72 feature = "llvm13-0",
73 feature = "llvm14-0"
74))]
75fn build_load_i32<'ctx>(
76 b: &inkwell::builder::Builder<'ctx>,
77 _i32_ty: inkwell::types::IntType<'ctx>,
78 ptr: inkwell::values::PointerValue<'ctx>,
79 name: &str,
80) -> inkwell::values::IntValue<'ctx> {
81 b.build_load(ptr, name).unwrap().into_int_value()
82}
83
84#[cfg(any(
85 feature = "llvm15-0",
86 feature = "llvm16-0",
87 feature = "llvm17-0",
88 feature = "llvm18-0",
89 feature = "llvm19-1",
90 feature = "llvm20-1",
91 feature = "llvm21-1",
92 feature = "llvm22-1"
93))]
94fn build_load_i32<'ctx>(
95 b: &inkwell::builder::Builder<'ctx>,
96 i32_ty: inkwell::types::IntType<'ctx>,
97 ptr: inkwell::values::PointerValue<'ctx>,
98 name: &str,
99) -> inkwell::values::IntValue<'ctx> {
100 b.build_load(i32_ty, ptr, name).unwrap().into_int_value()
101}
102
103fn build_demo_module() -> inkwell::module::Module<'static> {
104 let context = Box::leak(Box::new(inkwell::context::Context::create()));
106 let module = context.create_module("demo");
107 let i32_ty = context.i32_type();
108
109 let delta = module.add_global(i32_ty, None, DELTA_GLOBAL);
110 delta.set_initializer(&i32_ty.const_zero());
111
112 let callee_ty = i32_ty.fn_type(&[i32_ty.into()], false);
114 let callee = module.add_function("callee_cond", callee_ty, None);
115 let entry = context.append_basic_block(callee, "entry");
116 let then_bb = context.append_basic_block(callee, "then");
117 let else_bb = context.append_basic_block(callee, "else");
118 let merge_bb = context.append_basic_block(callee, "merge");
119 let b = context.create_builder();
120 b.position_at_end(entry);
121 let x = callee.get_first_param().unwrap().into_int_value();
122 let x_plus_4 = b
123 .build_int_add(x, i32_ty.const_int(4, false), "x_plus_4")
124 .unwrap();
125 let x_fold = b
126 .build_int_sub(x_plus_4, i32_ty.const_int(4, false), "x_fold")
127 .unwrap();
128 let cmp = b
129 .build_int_compare(
130 IntPredicate::SGT,
131 x_fold,
132 i32_ty.const_int(10, false),
133 "cmp",
134 )
135 .unwrap();
136 b.build_conditional_branch(cmp, then_bb, else_bb).unwrap();
137
138 b.position_at_end(then_bb);
139 let t1 = b
140 .build_int_mul(x_fold, i32_ty.const_int(2, false), "t1")
141 .unwrap();
142 let t2 = b
143 .build_int_unsigned_div(t1, i32_ty.const_int(2, false), "t2")
144 .unwrap();
145 let dec = b
146 .build_int_sub(t2, i32_ty.const_int(1, false), "dec")
147 .unwrap();
148 b.build_unconditional_branch(merge_bb).unwrap();
149
150 b.position_at_end(else_bb);
151 let e1 = b
152 .build_xor(x_fold, i32_ty.const_int(0, false), "e1")
153 .unwrap();
154 let e2 = b
155 .build_int_add(e1, i32_ty.const_int(1, false), "e2")
156 .unwrap();
157 let inc = b
158 .build_int_add(e2, i32_ty.const_int(1, false), "inc")
159 .unwrap();
160 b.build_unconditional_branch(merge_bb).unwrap();
161
162 b.position_at_end(merge_bb);
163 let phi = b.build_phi(i32_ty, "r").unwrap();
164 phi.add_incoming(&[(&dec, then_bb), (&inc, else_bb)]);
165 let r = phi.as_basic_value().into_int_value();
166 let keep = b
167 .build_int_add(r, i32_ty.const_int(0, false), "keep")
168 .unwrap();
169 b.build_return(Some(&keep)).unwrap();
170
171 let helper_ty = i32_ty.fn_type(&[i32_ty.into()], false);
173 let helper = module.add_function("helper_loop", helper_ty, None);
174 let entry = context.append_basic_block(helper, "entry");
175 let cond_bb = context.append_basic_block(helper, "cond");
176 let body_bb = context.append_basic_block(helper, "body");
177 let exit_bb = context.append_basic_block(helper, "exit");
178 let b = context.create_builder();
179 b.position_at_end(entry);
180 let i_ptr = b.build_alloca(i32_ty, "i").unwrap();
181 let acc_ptr = b.build_alloca(i32_ty, "acc").unwrap();
182 let tmp_ptr = b.build_alloca(i32_ty, "tmp").unwrap();
183 b.build_store(i_ptr, i32_ty.const_zero()).unwrap();
184 b.build_store(acc_ptr, i32_ty.const_zero()).unwrap();
185 b.build_store(tmp_ptr, i32_ty.const_int(7, false)).unwrap();
186 b.build_unconditional_branch(cond_bb).unwrap();
187
188 b.position_at_end(cond_bb);
189 let i = build_load_i32(&b, i32_ty, i_ptr, "i");
190 let n = helper.get_first_param().unwrap().into_int_value();
191 let tmp = build_load_i32(&b, i32_ty, tmp_ptr, "tmp");
192 let _noise_cmp = b
193 .build_int_compare(IntPredicate::SGE, tmp, i32_ty.const_zero(), "noise_cmp")
194 .unwrap();
195 let keep_going = b
196 .build_int_compare(IntPredicate::SLT, i, n, "keep_going")
197 .unwrap();
198 b.build_conditional_branch(keep_going, body_bb, exit_bb)
199 .unwrap();
200
201 b.position_at_end(body_bb);
202 let acc = build_load_i32(&b, i32_ty, acc_ptr, "acc");
203 let i_square = b.build_int_mul(i, i, "i_square").unwrap();
204 let folded_i = b
205 .build_int_unsigned_div(
206 b.build_int_add(i_square, i, "plus_i").unwrap(),
207 b.build_int_add(i, i32_ty.const_int(1, false), "i_plus_1")
208 .unwrap(),
209 "folded_i",
210 )
211 .unwrap();
212 let acc_next = b.build_int_add(acc, folded_i, "acc_next").unwrap();
213 let i_next = b
214 .build_int_add(i, i32_ty.const_int(1, false), "i_next")
215 .unwrap();
216 b.build_store(acc_ptr, acc_next).unwrap();
217 b.build_store(i_ptr, i_next).unwrap();
218 b.build_unconditional_branch(cond_bb).unwrap();
219
220 b.position_at_end(exit_bb);
221 let acc_final = build_load_i32(&b, i32_ty, acc_ptr, "acc_final");
222 let out = b
223 .build_int_add(acc_final, i32_ty.const_int(0, false), "out")
224 .unwrap();
225 b.build_return(Some(&out)).unwrap();
226
227 let driver_ty = i32_ty.fn_type(&[i32_ty.into(), i32_ty.into()], false);
230 let driver = module.add_function("driver", driver_ty, None);
231 let entry = context.append_basic_block(driver, "entry");
232 let big_bb = context.append_basic_block(driver, "big");
233 let small_bb = context.append_basic_block(driver, "small");
234 let b = context.create_builder();
235 b.position_at_end(entry);
236 let a = driver.get_nth_param(0).unwrap().into_int_value();
237 let b_arg = driver.get_nth_param(1).unwrap().into_int_value();
238 let c1 = {
239 let value = b
240 .build_call(callee, &[a.into()], "c1")
241 .unwrap()
242 .try_as_basic_value();
243 #[cfg(any(
244 feature = "llvm10-0",
245 feature = "llvm11-0",
246 feature = "llvm12-0",
247 feature = "llvm13-0",
248 feature = "llvm14-0",
249 feature = "llvm15-0",
250 feature = "llvm16-0",
251 feature = "llvm17-0",
252 feature = "llvm18-0"
253 ))]
254 {
255 value.left().unwrap().into_int_value()
256 }
257 #[cfg(any(
258 feature = "llvm19-1",
259 feature = "llvm20-1",
260 feature = "llvm21-1",
261 feature = "llvm22-1"
262 ))]
263 {
264 value.unwrap_basic().into_int_value()
265 }
266 };
267 let c2 = {
268 let value = b
269 .build_call(helper, &[b_arg.into()], "c2")
270 .unwrap()
271 .try_as_basic_value();
272 #[cfg(any(
273 feature = "llvm10-0",
274 feature = "llvm11-0",
275 feature = "llvm12-0",
276 feature = "llvm13-0",
277 feature = "llvm14-0",
278 feature = "llvm15-0",
279 feature = "llvm16-0",
280 feature = "llvm17-0",
281 feature = "llvm18-0"
282 ))]
283 {
284 value.left().unwrap().into_int_value()
285 }
286 #[cfg(any(
287 feature = "llvm19-1",
288 feature = "llvm20-1",
289 feature = "llvm21-1",
290 feature = "llvm22-1"
291 ))]
292 {
293 value.unwrap_basic().into_int_value()
294 }
295 };
296 let raw_sum = b.build_int_add(c1, c2, "raw_sum").unwrap();
297 let delta_loaded = build_load_i32(&b, i32_ty, delta.as_pointer_value(), "delta");
298 let adjusted = b.build_int_add(raw_sum, delta_loaded, "adjusted").unwrap();
299 let is_big = b
300 .build_int_compare(
301 IntPredicate::SGT,
302 adjusted,
303 i32_ty.const_int(100, false),
304 "is_big",
305 )
306 .unwrap();
307 b.build_conditional_branch(is_big, big_bb, small_bb)
308 .unwrap();
309
310 b.position_at_end(big_bb);
311 let big_t0 = b
312 .build_int_mul(adjusted, i32_ty.const_int(2, false), "big_t0")
313 .unwrap();
314 let big_t1 = b
315 .build_int_unsigned_div(big_t0, i32_ty.const_int(2, false), "big_t1")
316 .unwrap();
317 let big_out = b
318 .build_int_add(big_t1, i32_ty.const_int(0, false), "big_out")
319 .unwrap();
320 b.build_return(Some(&big_out)).unwrap();
321
322 b.position_at_end(small_bb);
323 let plus_one = b
324 .build_int_add(adjusted, i32_ty.const_int(1, false), "plus_one")
325 .unwrap();
326 let out = b
327 .build_int_add(plus_one, i32_ty.const_int(0, false), "small_out")
328 .unwrap();
329 b.build_return(Some(&out)).unwrap();
330
331 module
332}
333
334struct CgsccNameLenAnalysis;
335impl LlvmCgsccAnalysis for CgsccNameLenAnalysis {
336 type Result = usize;
337 fn run_analysis(
338 &self,
339 function: &inkwell::values::FunctionValue<'_>,
340 _manager: &CgsccAnalysisManager,
341 ) -> Self::Result {
342 function.get_name().to_string_lossy().len()
343 }
344 fn id() -> AnalysisKey {
345 static ID: u8 = 0;
346 &ID
347 }
348}
349
350struct LoopHeaderNonNullAnalysis;
351impl LlvmLoopAnalysis for LoopHeaderNonNullAnalysis {
352 type Result = bool;
353 fn run_analysis(
354 &self,
355 loop_header: llvm_pm::traits::LLVMBasicBlockRef,
356 _manager: &LoopAnalysisManager,
357 ) -> Self::Result {
358 !loop_header.is_null()
359 }
360 fn id() -> AnalysisKey {
361 static ID: u8 = 0;
362 &ID
363 }
364}
365
366struct ModuleStatsAnalysis;
367impl LlvmModuleAnalysis for ModuleStatsAnalysis {
368 type Result = (usize, usize);
369 fn run_analysis(
370 &self,
371 module: &inkwell::module::Module<'_>,
372 _manager: &ModuleAnalysisManager,
373 ) -> Self::Result {
374 let mut fn_count = 0usize;
375 let mut bb_count = 0usize;
376 for f in module.get_functions() {
377 fn_count += 1;
378 bb_count += f.count_basic_blocks() as usize;
379 }
380 (fn_count, bb_count)
381 }
382 fn id() -> AnalysisKey {
383 static ID: u8 = 0;
384 &ID
385 }
386}
387
388struct FunctionStatsAnalysis;
389impl LlvmFunctionAnalysis for FunctionStatsAnalysis {
390 type Result = (u32, u32);
391 fn run_analysis(
392 &self,
393 function: &inkwell::values::FunctionValue<'_>,
394 _manager: &FunctionAnalysisManager,
395 ) -> Self::Result {
396 let bbs = function.count_basic_blocks();
397 let mut insts = 0u32;
398 for bb in function.get_basic_blocks() {
399 insts += bb.get_instructions().count() as u32;
400 }
401 (bbs, insts)
402 }
403 fn id() -> AnalysisKey {
404 static ID: u8 = 0;
405 &ID
406 }
407}
408
409struct ModuleMutatePass {
410 ran: Arc<AtomicU32>,
411}
412impl LlvmModulePass for ModuleMutatePass {
413 fn run_pass(
414 &self,
415 module: &mut inkwell::module::Module<'_>,
416 _manager: &ModuleAnalysisManager,
417 ) -> PreservedAnalyses {
418 self.ran.fetch_add(1, Ordering::SeqCst);
419 set_pass_delta(module, DELTA_MODULE);
420 PreservedAnalyses::None
421 }
422}
423
424struct FunctionMutatePass {
425 ran: Arc<AtomicU32>,
426}
427impl LlvmFunctionPass for FunctionMutatePass {
428 fn run_pass(
429 &self,
430 function: &mut inkwell::values::FunctionValue<'_>,
431 _manager: &FunctionAnalysisManager,
432 ) -> PreservedAnalyses {
433 self.ran.fetch_add(1, Ordering::SeqCst);
434 if function.get_name().to_string_lossy() == "driver" {
435 unsafe { set_pass_delta_from_function_ref(function.as_value_ref(), DELTA_FUNCTION) };
437 }
438 PreservedAnalyses::None
439 }
440}
441
442struct CgsccUsesAnalysisPass {
443 ran: Arc<AtomicU32>,
444 registered: Arc<AtomicBool>,
445}
446impl LlvmCgsccPass for CgsccUsesAnalysisPass {
447 fn run_pass(
448 &self,
449 function: &mut inkwell::values::FunctionValue<'_>,
450 manager: &CgsccAnalysisManager,
451 ) -> PreservedAnalyses {
452 self.ran.fetch_add(1, Ordering::SeqCst);
453 if self
454 .registered
455 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
456 .is_ok()
457 {
458 manager.add_analysis(CgsccNameLenAnalysis);
459 }
460 let _name_len = *manager.get_result::<CgsccNameLenAnalysis>(function);
461 if function.get_name().to_string_lossy() == "driver" {
462 unsafe { set_pass_delta_from_function_ref(function.as_value_ref(), DELTA_CGSCC) };
464 }
465 PreservedAnalyses::None
466 }
467}
468
469struct LoopUsesAnalysisPass {
470 ran: Arc<AtomicU32>,
471 registered: Arc<AtomicBool>,
472}
473impl LlvmLoopPass for LoopUsesAnalysisPass {
474 fn run_pass(
475 &self,
476 loop_header: llvm_pm::traits::LLVMBasicBlockRef,
477 manager: &LoopAnalysisManager,
478 ) -> PreservedAnalyses {
479 self.ran.fetch_add(1, Ordering::SeqCst);
480 if self
481 .registered
482 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
483 .is_ok()
484 {
485 manager.add_analysis(LoopHeaderNonNullAnalysis);
486 }
487 let ok = *manager.get_result::<LoopHeaderNonNullAnalysis>(loop_header);
488 if ok {
489 let function = unsafe { LLVMGetBasicBlockParent(loop_header) };
491 assert!(!function.is_null(), "loop header must have parent function");
492 unsafe { set_pass_delta_from_function_ref(function, DELTA_LOOP) };
494 }
495 PreservedAnalyses::None
496 }
497}
498
499struct ModuleAnalysisOnlyPass;
500impl LlvmModuleAnalysis for ModuleAnalysisOnlyPass {
501 type Result = ();
502 fn run_analysis(
503 &self,
504 _module: &inkwell::module::Module<'_>,
505 _manager: &ModuleAnalysisManager,
506 ) -> Self::Result {
507 }
508 fn id() -> AnalysisKey {
509 static ID: u8 = 0;
510 &ID
511 }
512}
513
514struct FunctionAnalysisOnlyPass;
515impl LlvmFunctionAnalysis for FunctionAnalysisOnlyPass {
516 type Result = ();
517 fn run_analysis(
518 &self,
519 _function: &inkwell::values::FunctionValue<'_>,
520 _manager: &FunctionAnalysisManager,
521 ) -> Self::Result {
522 }
523 fn id() -> AnalysisKey {
524 static ID: u8 = 0;
525 &ID
526 }
527}
528
529struct CgsccAnalysisOnlyPass;
530impl LlvmCgsccAnalysis for CgsccAnalysisOnlyPass {
531 type Result = ();
532 fn run_analysis(
533 &self,
534 _function: &inkwell::values::FunctionValue<'_>,
535 _manager: &CgsccAnalysisManager,
536 ) -> Self::Result {
537 }
538 fn id() -> AnalysisKey {
539 static ID: u8 = 0;
540 &ID
541 }
542}
543
544struct LoopAnalysisOnlyPass;
545impl LlvmLoopAnalysis for LoopAnalysisOnlyPass {
546 type Result = ();
547 fn run_analysis(
548 &self,
549 _loop_header: llvm_pm::traits::LLVMBasicBlockRef,
550 _manager: &LoopAnalysisManager,
551 ) -> Self::Result {
552 }
553 fn id() -> AnalysisKey {
554 static ID: u8 = 0;
555 &ID
556 }
557}
558
559fn assert_rich_ir(module: &inkwell::module::Module<'_>) {
560 let mut min_insts = u32::MAX;
561 for f in module.get_functions() {
562 for bb in f.get_basic_blocks() {
563 let insts = bb.get_instructions().count() as u32;
564 min_insts = min_insts.min(insts);
565 }
566 }
567 assert!(
568 min_insts >= 3,
569 "expected each basic block to contain multiple instructions, min={min_insts}"
570 );
571}
572
573fn main() -> Result<(), Box<dyn std::error::Error>> {
574 let module = build_demo_module();
575 module.verify()?;
576 assert_rich_ir(&module);
577
578 let module_ran = Arc::new(AtomicU32::new(0));
579 let function_ran = Arc::new(AtomicU32::new(0));
580 let cgscc_ran = Arc::new(AtomicU32::new(0));
581 let loop_ran = Arc::new(AtomicU32::new(0));
582
583 let mut module_pm = ModulePassManager::with_opt_level(None, OptLevel::O2, None)?;
584 module_pm.add_pass((ModuleAnalysisOnlyPass).into_pass());
585 module_pm.add_pass((ModuleStatsAnalysis).into_pass());
586 module_pm.add_pass(ModuleMutatePass {
587 ran: module_ran.clone(),
588 });
589 module_pm.add_cgscc_pass((CgsccAnalysisOnlyPass).into_pass());
590 module_pm.add_cgscc_pass(CgsccUsesAnalysisPass {
591 ran: cgscc_ran.clone(),
592 registered: Arc::new(AtomicBool::new(false)),
593 });
594 module_pm.run(&module)?;
595
596 let mut function_pm = FunctionPassManager::with_pipeline(
597 None,
598 "loop-simplify,loop-rotate,instcombine,simplifycfg",
599 None,
600 )?;
601 function_pm.add_pass((FunctionAnalysisOnlyPass).into_pass());
602 function_pm.add_pass((FunctionStatsAnalysis).into_pass());
603 function_pm.add_pass(FunctionMutatePass {
604 ran: function_ran.clone(),
605 });
606 function_pm.add_loop_pass((LoopAnalysisOnlyPass).into_pass());
607 function_pm.add_loop_pass(LoopUsesAnalysisPass {
608 ran: loop_ran.clone(),
609 registered: Arc::new(AtomicBool::new(false)),
610 });
611
612 for f in module.get_functions() {
613 if f.count_basic_blocks() == 0 {
614 continue;
615 }
616 function_pm.run(f)?;
617 }
618
619 module.verify()?;
620
621 assert_eq!(
622 get_pass_delta(&module),
623 DELTA_LOOP,
624 "final delta must reflect loop-pass mutation"
625 );
626 assert!(module_ran.load(Ordering::SeqCst) >= 1);
627 assert!(function_ran.load(Ordering::SeqCst) >= 3);
628 assert!(cgscc_ran.load(Ordering::SeqCst) >= 3);
629 assert!(loop_ran.load(Ordering::SeqCst) >= 1);
630
631 let ee = module.create_jit_execution_engine(OptimizationLevel::None)?;
635 type DriverFn = unsafe extern "C" fn(i32, i32) -> i32;
636 let driver = unsafe { ee.get_function::<DriverFn>("driver") }?;
638 let got = unsafe { driver.call(12, 5) };
640 assert_eq!(got, 35, "unexpected final JIT result");
641
642 println!(
643 "ok: delta={}, module_passes={}, function_passes={}, cgscc_passes={}, loop_passes={}, driver(12,5)={}",
644 get_pass_delta(&module),
645 module_ran.load(Ordering::SeqCst),
646 function_ran.load(Ordering::SeqCst),
647 cgscc_ran.load(Ordering::SeqCst),
648 loop_ran.load(Ordering::SeqCst),
649 got
650 );
651 Ok(())
652}