如何使用LLVM C ++ API实现函数指针?

时间:2019-02-27 12:12:12

标签: llvm llvm-ir

假设我要手动将下面的代码转换为IR代码:

#include <stdio.h>
int main()
{
  int (*p)(const char *__s);  // how to implement this?
  p = puts;                   // and this?
  p("Hello World!\n");
}

我发现函数指针的IR表示是这样的:

%p = alloca i32 (i8*)*, align 8
store i32 (i8*)* @puts, i32 (i8*)** %p, align 8 

但是我不知道应该使用哪个api来生成它。

这是我实施的一部分:

#include "llvm/Support/raw_ostream.h"

int main() {
  llvm::LLVMContext context;
  llvm::IRBuilder<> builder(context);
  llvm::Module *module = new llvm::Module("top", context);

  llvm::FunctionType *functionType = llvm::FunctionType::get(builder.getInt32Ty(), false);
  llvm::Function *mainFunction = llvm::Function::Create(functionType, llvm::Function::ExternalLinkage, "main", module);

  llvm::BasicBlock *entry = llvm::BasicBlock::Create(context, "entrypoint", mainFunction);
  builder.SetInsertPoint(entry);

  llvm::Value *helloWorld = builder.CreateGlobalStringPtr("hello world\n");

  std::vector<llvm::Type *> putArgs;
  putArgs.push_back(builder.getInt8Ty()->getPointerTo());
  llvm::ArrayRef<llvm::Type *> argsRef(putArgs);
  llvm::FunctionType *putsType = llvm::FunctionType::get(builder.getInt32Ty(), argsRef, false);
  llvm::Constant *putFunction = module->getOrInsertFunction("puts", putsType);

  // code to implement function pointer
  // code to assign puts() to function pointer

  builder.CreateCall(putFunction, helloWorld);  // call the function pointer instead of the function it self
  builder.CreateRet(llvm::ConstantInt::get(builder.getInt32Ty(), 0));

  module->print(llvm::errs(), nullptr);
}

我发现llvm::Functionllvm::Value的子类,所以我猜llvm::Constant *putFunction本身就是我要寻找的函数指针,但是如何使该值在IR中表示码?更具体地说,如何使用构建器生成IR代码?

1 个答案:

答案 0 :(得分:0)

我解决了。

失踪的难题是打击:

llvm::Value *p = builder.CreateAlloca(putFunction->getType(), nullptr, "p");
builder.CreateStore(putFunction, p, false);
llvm::Value *temp = builder.CreateLoad(p);
builder.CreateCall(temp, helloWorld);

关键概念是putFunction->getType()llvm::FunctionType::get()是不同的类型,我误以为llvm::FunctionType::get()作为函数指针。