4

如果使用外部定义的函数,我的 JIT 编译 LLVM IR 模块并调用foo其中定义的函数的程序在运行时会失败:foo

LLVM ERROR: Program used external function 'glutInit' which could not be resolved!

我的程序:

// foo1.cpp
#include <GL/glut.h>

extern "C" void foo()
{
  glutInit(0,0);
}

// foo2.cpp
#include <iostream>
#include <fstream>
#include <string>

#include <llvm/Support/raw_ostream.h>
#include <llvm/LLVMContext.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/IRReader.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/ExecutionEngine/JIT.h>
#include <llvm/ExecutionEngine/RuntimeDyld.h>

int main(int argc, char **argv)
{
  using namespace llvm;
  InitializeNativeTarget();

  LLVMContext context;
  SMDiagnostic error;

  std::ifstream ir_file("foo1.s");
  std::string ir((std::istreambuf_iterator<char>(ir_file)),
                 (std::istreambuf_iterator<char>()));

  Module *m = ParseIR(MemoryBuffer::getMemBuffer(StringRef(ir)), error, context);
  if(!m)
  {
    error.print(argv[0], errs());
  }

  ExecutionEngine *ee = ExecutionEngine::create(m);

  Function *func = ee->FindFunctionNamed("foo");
  if(func == 0)
  {
    std::cerr << "Couldn't find Function foo" << std::endl;
    std::exit(-1);
  }

  typedef void (*fcn_ptr)();
  fcn_ptr foo = reinterpret_cast<fcn_ptr>(ee->getPointerToFunction(func));
  foo();
  delete ee;

  return 0;
}

这是我构建程序的方式:

$ clang -S -emit-llvm foo1.cpp
$ g++ -rdynamic foo2.cpp `llvm-config --cxxflags` `llvm-config --libs` `llvm-config --ldflags` -lglut

输出:

$ ./a.out 
LLVM ERROR: Program used external function 'glutInit' which could not be resolved!

每当我尝试使用不在 C++ 标准库中的外部定义函数时,它都会失败并出现类似的错误(例如,, printf, malloc&free没有问题)。我究竟做错了什么?

4

2 回答 2

3

确保glutInit已链接到a.out. 如果您的主机代码(执行 JIT 的东西)没有调用它,它可能已被链接器取消。如果是这种情况,您必须添加对它的虚拟引用或使用链接器脚本/标志。

于 2014-01-16T22:40:09.190 回答
2

-Wl,-no-as-needed在之前添加命令行选项-lglut将阻止链接器删除glut库,否则它认为不需要:

$ g++ -rdynamic foo2.cpp `llvm-config --cxxflags` `llvm-config --libs` `llvm-config --ldflags` -Wl,-no-as-needed -lglut
于 2014-01-16T23:49:07.683 回答