且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

LLVM插入内部函数Cos

更新时间:2023-01-20 22:36:24

我建议你使用 IRBuilder ,它简化了LLVM内部的IR生成过程。 :

  std :: vector< Type *> arg_type; 
arg_type.push_back(Type :: getFloatTy(getGlobalContext ());
函数* fun = Intrinsic :: getDeclaration(F.getParent(),Intrinsic :: cos,arg_type);
IRBuilder> Builder(& I);
Builder.CreateCall(fun,args);


I am trying to insert intrinsic cos() function call to LLVM pass. My code in a FunctionPass:

std::vector<Type *> arg_type;
arg_type.push_back(Type::getFloatTy(getGlobalContext()));
Function *fun = Intrinsic::getDeclaration(F.getParent(), Intrinsic::cos, arg_type);
CallInst* callInst = CallInst::Create(fun, args, Twine("cos"), (Instruction *)&I);

When I leave out last line generated IR is:

define i32 @main() nounwind uwtable {
entry:
...
}

declare float @llvm.cos.f32(float) nounwind readonly

, but with CallInst included all i get is:

0  opt                0x000000000094f4bf
1  opt                0x000000000094f9c9
2  libpthread.so.0    0x00007fb92b652cb0
3  opt                0x00000000008be244 llvm::Instruction::Instruction(llvm::Type*, unsigned int, llvm::Use*, unsigned int, llvm::Instruction*) + 148
4  LLVMObfuscation.so 0x00007fb92a66c52f
5  LLVMObfuscation.so 0x00007fb92a66c9a5
6  LLVMObfuscation.so 0x00007fb92a66df21
7  opt                0x00000000008e921f llvm::FPPassManager::runOnFunction(llvm::Function&) + 591
8  opt                0x00000000008e9293 llvm::FPPassManager::runOnModule(llvm::Module&) + 51
9  opt                0x00000000008e8f34 llvm::MPPassManager::runOnModule(llvm::Module&) + 532
10 opt                0x00000000008ea4fb llvm::PassManagerImpl::run(llvm::Module&) + 171
11 opt                0x0000000000496208 main + 4104
12 libc.so.6          0x00007fb92a89376d __libc_start_main + 237
13 opt                0x000000000049cfe5

What else do I need to do ? I think i do not need to define this function in module.

args sent to function is defined this way:

std::vector<Value *> args;
args.push_back(fp);

where fp is previously inserted Instruction:

Instruction *fp = BinaryOperator::Create(Instruction::FSub, ...

Variable I is inst_iterator, but i am doing this outside for cycle.

Thank you.

I advice you to use IRBuilder. It simplifies IR generation inside LLVM pass. In your case you can use it like that:

std::vector<Type *> arg_type;
arg_type.push_back(Type::getFloatTy(getGlobalContext()));
Function *fun = Intrinsic::getDeclaration(F.getParent(), Intrinsic::cos, arg_type);
IRBuilder<> Builder(&I);
Builder.CreateCall(fun, args);