使用c++api将c++回调函数转换为llvm

translating c++ callback function to llvm using c++ api

本文关键字:转换 llvm 函数 回调 c++api c++ 使用      更新时间:2023-10-16

我想使用c++api将c回调函数转换为llvm函数。我的示例c++函数如下所示。

extern "C" void bindMe(int(*compare)(const int a))
{
    llvm::LLVMContext& context = llvm::getGlobalContext();
    llvm::Module *module = new llvm::Module("top", context);
    llvm::IRBuilder<> builder(context);
    //I want to create the corresponding llvm function here which is called compareLLVM
    llvm::BasicBlock *entry = llvm::BasicBlock::Create(context, "entrypoint", compareLLVM);
    builder.SetInsertPoint(entry);
    module->dump();
}

基本上,我想将bindMe函数(一个c回调函数)的参数转换为相应的llvm函数。使用API有可能这样做吗?

我真的很感激任何想法。

感谢

compare是指向函数编译代码所在位置的指针。那里没有源代码——事实上,它甚至可能不是从C编译的——所以LLVM不能用它做太多事情,也不能将它转换为LLVM Function对象。

可以插入对该函数的调用:从该compare指针创建一个LLVM Value,将其强制转换为适当的类型,然后使用该强制转换的指针创建一条调用指令作为函数。使用API插入这样的调用看起来像:

Type* longType = Type::getInt64Ty(context);
Type* intType = Type::getInt32Ty(context);
Type* funcType = FunctionType::get(intType, intType, false);
// Insert the 'compare' value:
Constant* ptrInt = ConstantInt::get(longType, (long long)compare); 
// Convert it to the correct type:
Value* ptr = ConstantExpr::getIntToPtr(ptrInt, funcType->getPointerTo());
// Insert function call, assuming 'num' is an int32-typed
// value you have already created:
CallInst* call = builder.CreateCall(ptr, num);