use llvm_pm::inkwell;
use llvm_pm::inkwell::IntPredicate;
use llvm_pm::{
AnalysisKey, CgsccAnalysisManager, FunctionAnalysisManager, FunctionPassManager,
LlvmCgsccAnalysis, LlvmCgsccPass, LlvmFunctionAnalysis, LlvmFunctionPass, LlvmLoopAnalysis,
LlvmLoopPass, LlvmModuleAnalysis, LlvmModulePass, LoopAnalysisManager, ModuleAnalysisManager,
ModulePassManager, OptLevel, PreservedAnalyses,
};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
fn build_demo_module() -> inkwell::module::Module<'static> {
let context = Box::leak(Box::new(inkwell::context::Context::create()));
let module = context.create_module("demo");
let i32_ty = context.i32_type();
let callee_ty = i32_ty.fn_type(&[i32_ty.into()], false);
let callee = module.add_function("callee_cond", callee_ty, None);
let entry = context.append_basic_block(callee, "entry");
let then_bb = context.append_basic_block(callee, "then");
let else_bb = context.append_basic_block(callee, "else");
let merge_bb = context.append_basic_block(callee, "merge");
let b = context.create_builder();
b.position_at_end(entry);
let x = callee.get_first_param().unwrap().into_int_value();
let cmp = b
.build_int_compare(IntPredicate::SGT, x, i32_ty.const_int(10, false), "cmp")
.unwrap();
b.build_conditional_branch(cmp, then_bb, else_bb).unwrap();
b.position_at_end(then_bb);
let dec = b
.build_int_sub(x, i32_ty.const_int(1, false), "dec")
.unwrap();
b.build_unconditional_branch(merge_bb).unwrap();
b.position_at_end(else_bb);
let inc = b
.build_int_add(x, i32_ty.const_int(2, false), "inc")
.unwrap();
b.build_unconditional_branch(merge_bb).unwrap();
b.position_at_end(merge_bb);
let phi = b.build_phi(i32_ty, "r").unwrap();
phi.add_incoming(&[(&dec, then_bb), (&inc, else_bb)]);
b.build_return(Some(&phi.as_basic_value())).unwrap();
let helper_ty = i32_ty.fn_type(&[i32_ty.into()], false);
let helper = module.add_function("helper_loop", helper_ty, None);
let entry = context.append_basic_block(helper, "entry");
let cond_bb = context.append_basic_block(helper, "cond");
let body_bb = context.append_basic_block(helper, "body");
let exit_bb = context.append_basic_block(helper, "exit");
let b = context.create_builder();
b.position_at_end(entry);
let i_ptr = b.build_alloca(i32_ty, "i").unwrap();
let acc_ptr = b.build_alloca(i32_ty, "acc").unwrap();
b.build_store(i_ptr, i32_ty.const_zero()).unwrap();
b.build_store(acc_ptr, i32_ty.const_zero()).unwrap();
b.build_unconditional_branch(cond_bb).unwrap();
b.position_at_end(cond_bb);
let i = b.build_load(i32_ty, i_ptr, "i").unwrap().into_int_value();
let n = helper.get_first_param().unwrap().into_int_value();
let keep_going = b
.build_int_compare(IntPredicate::SLT, i, n, "keep_going")
.unwrap();
b.build_conditional_branch(keep_going, body_bb, exit_bb)
.unwrap();
b.position_at_end(body_bb);
let acc = b
.build_load(i32_ty, acc_ptr, "acc")
.unwrap()
.into_int_value();
let acc_next = b.build_int_add(acc, i, "acc_next").unwrap();
let i_next = b
.build_int_add(i, i32_ty.const_int(1, false), "i_next")
.unwrap();
b.build_store(acc_ptr, acc_next).unwrap();
b.build_store(i_ptr, i_next).unwrap();
b.build_unconditional_branch(cond_bb).unwrap();
b.position_at_end(exit_bb);
let acc_final = b.build_load(i32_ty, acc_ptr, "acc_final").unwrap();
b.build_return(Some(&acc_final)).unwrap();
let driver_ty = i32_ty.fn_type(&[i32_ty.into(), i32_ty.into()], false);
let driver = module.add_function("driver", driver_ty, None);
let entry = context.append_basic_block(driver, "entry");
let big_bb = context.append_basic_block(driver, "big");
let small_bb = context.append_basic_block(driver, "small");
let b = context.create_builder();
b.position_at_end(entry);
let a = driver.get_nth_param(0).unwrap().into_int_value();
let b_arg = driver.get_nth_param(1).unwrap().into_int_value();
let c1 = b
.build_call(callee, &[a.into()], "c1")
.unwrap()
.try_as_basic_value()
.left()
.unwrap()
.into_int_value();
let c2 = b
.build_call(helper, &[b_arg.into()], "c2")
.unwrap()
.try_as_basic_value()
.left()
.unwrap()
.into_int_value();
let sum = b.build_int_add(c1, c2, "sum").unwrap();
let is_big = b
.build_int_compare(
IntPredicate::SGT,
sum,
i32_ty.const_int(100, false),
"is_big",
)
.unwrap();
b.build_conditional_branch(is_big, big_bb, small_bb)
.unwrap();
b.position_at_end(big_bb);
b.build_return(Some(&sum)).unwrap();
b.position_at_end(small_bb);
let plus_one = b
.build_int_add(sum, i32_ty.const_int(1, false), "plus_one")
.unwrap();
b.build_return(Some(&plus_one)).unwrap();
module
}
struct CgsccNameLenAnalysis;
impl LlvmCgsccAnalysis for CgsccNameLenAnalysis {
type Result = usize;
fn run_analysis(
&self,
function: &inkwell::values::FunctionValue<'_>,
_manager: &CgsccAnalysisManager,
) -> Self::Result {
function.get_name().to_string_lossy().len()
}
fn id() -> AnalysisKey {
static ID: u8 = 0;
&ID
}
}
struct LoopHeaderNonNullAnalysis;
impl LlvmLoopAnalysis for LoopHeaderNonNullAnalysis {
type Result = bool;
fn run_analysis(
&self,
loop_header: llvm_pm::LLVMBasicBlockRef,
_manager: &LoopAnalysisManager,
) -> Self::Result {
!loop_header.is_null()
}
fn id() -> AnalysisKey {
static ID: u8 = 0;
&ID
}
}
struct ModulePrintPass;
impl LlvmModulePass for ModulePrintPass {
fn run_pass(
&self,
module: &mut inkwell::module::Module<'_>,
_manager: &ModuleAnalysisManager,
) -> PreservedAnalyses {
let names: Vec<String> = module
.get_functions()
.map(|f| f.get_name().to_string_lossy().to_string())
.collect();
println!("module pass: functions = {:?}", names);
PreservedAnalyses::All
}
}
struct FunctionPrintPass;
impl LlvmFunctionPass for FunctionPrintPass {
fn run_pass(
&self,
function: &mut inkwell::values::FunctionValue<'_>,
_manager: &FunctionAnalysisManager,
) -> PreservedAnalyses {
println!(
"function pass: {} ({} BBs)",
function.get_name().to_string_lossy(),
function.count_basic_blocks()
);
PreservedAnalyses::All
}
}
struct CgsccUsesAnalysisPass {
registered: Arc<AtomicBool>,
}
impl LlvmCgsccPass for CgsccUsesAnalysisPass {
fn run_pass(
&self,
function: &mut inkwell::values::FunctionValue<'_>,
manager: &CgsccAnalysisManager,
) -> PreservedAnalyses {
if self
.registered
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
.is_ok()
{
manager.add_pass(CgsccNameLenAnalysis);
}
let len = *manager.get_result::<CgsccNameLenAnalysis>(function);
println!(
"cgscc pass: function {} name_len={}",
function.get_name().to_string_lossy(),
len
);
PreservedAnalyses::All
}
}
struct LoopUsesAnalysisPass {
registered: Arc<AtomicBool>,
}
impl LlvmLoopPass for LoopUsesAnalysisPass {
fn run_pass(
&self,
loop_header: llvm_pm::LLVMBasicBlockRef,
manager: &LoopAnalysisManager,
) -> PreservedAnalyses {
if self
.registered
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
.is_ok()
{
manager.add_pass(LoopHeaderNonNullAnalysis);
}
let ok = *manager.get_result::<LoopHeaderNonNullAnalysis>(loop_header);
println!("loop pass: header_is_non_null={ok}");
PreservedAnalyses::All
}
}
struct ModuleAnalysisOnlyPass;
impl LlvmModuleAnalysis for ModuleAnalysisOnlyPass {
type Result = ();
fn run_analysis(
&self,
module: &inkwell::module::Module<'_>,
_manager: &ModuleAnalysisManager,
) -> Self::Result {
println!(
"module analysis-only pass: {}",
module.get_name().to_string_lossy()
);
}
fn id() -> AnalysisKey {
static ID: u8 = 0;
&ID
}
}
struct FunctionAnalysisOnlyPass;
impl LlvmFunctionAnalysis for FunctionAnalysisOnlyPass {
type Result = ();
fn run_analysis(
&self,
function: &inkwell::values::FunctionValue<'_>,
_manager: &FunctionAnalysisManager,
) -> Self::Result {
println!(
"function analysis-only pass: {}",
function.get_name().to_string_lossy()
);
}
fn id() -> AnalysisKey {
static ID: u8 = 0;
&ID
}
}
struct CgsccAnalysisOnlyPass;
impl LlvmCgsccAnalysis for CgsccAnalysisOnlyPass {
type Result = ();
fn run_analysis(
&self,
function: &inkwell::values::FunctionValue<'_>,
_manager: &CgsccAnalysisManager,
) -> Self::Result {
println!(
"cgscc analysis-only pass: {}",
function.get_name().to_string_lossy()
);
}
fn id() -> AnalysisKey {
static ID: u8 = 0;
&ID
}
}
struct LoopAnalysisOnlyPass;
impl LlvmLoopAnalysis for LoopAnalysisOnlyPass {
type Result = ();
fn run_analysis(
&self,
_loop_header: llvm_pm::LLVMBasicBlockRef,
_manager: &LoopAnalysisManager,
) -> Self::Result {
println!("loop analysis-only pass");
}
fn id() -> AnalysisKey {
static ID: u8 = 0;
&ID
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let module = build_demo_module();
module.verify()?;
let mut module_pm = ModulePassManager::with_opt_level(None, OptLevel::O2, None)?;
module_pm.add_analysis_pass(ModuleAnalysisOnlyPass);
module_pm.add_pass(ModulePrintPass);
module_pm.add_cgscc_analysis_pass(CgsccAnalysisOnlyPass);
module_pm.add_cgscc_pass(CgsccUsesAnalysisPass {
registered: Arc::new(AtomicBool::new(false)),
});
module_pm.run(&module)?;
let mut function_pm = FunctionPassManager::with_pipeline(
None,
"loop-simplify,loop-rotate,instcombine,simplifycfg",
None,
)?;
function_pm.add_analysis_pass(FunctionAnalysisOnlyPass);
function_pm.add_pass(FunctionPrintPass);
function_pm.add_loop_analysis_pass(LoopAnalysisOnlyPass);
function_pm.add_loop_pass(LoopUsesAnalysisPass {
registered: Arc::new(AtomicBool::new(false)),
});
for f in module.get_functions() {
if f.count_basic_blocks() == 0 {
continue;
}
function_pm.run(f)?;
}
println!("done");
Ok(())
}