且构网

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

从C程序调用LLVM Jit

更新时间:2023-11-10 18:19:10

以下是基于Nathan Howell的一些工作代码:

Here's some working code based on Nathan Howell's:

#include <string>
#include <memory>
#include <iostream>

#include <llvm/LLVMContext.h>
#include <llvm/Target/TargetSelect.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ModuleProvider.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/ExecutionEngine/JIT.h>

using namespace std;
using namespace llvm;

int main()
{
    InitializeNativeTarget();
    llvm_start_multithreaded();
    LLVMContext context;
    string error;
    Module *m = ParseBitcodeFile(MemoryBuffer::getFile("tst.bc"), context, &error);
    ExecutionEngine *ee = ExecutionEngine::create(m);

    Function* func = ee->FindFunctionNamed("main");

    typedef void (*PFN)();
    PFN pfn = reinterpret_cast<PFN>(ee->getPointerToFunction(func));
    pfn();
    delete ee;
}

一个奇怪的地方是,如果没有最后的包含,则ee为NULL.奇怪.

One oddity was that without the final include, ee is NULL. Bizarre.

要生成我的tst.bc,我使用了 http://llvm.org/demo/index.cgi 和llvm-as命令行工具.

To generate my tst.bc, I used http://llvm.org/demo/index.cgi and the llvm-as command-line tool.