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

问题描述 投票:0回答:1

假设我想手动将下面的代码转换为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代码?

llvm llvm-ir
1个回答
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()作为函数指针。

© www.soinside.com 2019 - 2024. All rights reserved.