从c程序调用LLVM Jit

Dam*_*ien 22 jit llvm llvm-ir

我已经在llvm.org上使用在线编译器生成了一个bc文件,我想知道是否可以从ac或c ++程序加载这个bc文件,用llvm jit执行bc文件中的IR(以编程方式在c程序),并得到结果.

我怎么能做到这一点?

小智 23

这里有一些基于Nathan Howell的工作代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

一个奇怪的是没有最终的包含,ee是NULL.离奇.

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


Nat*_*ell 15

这应该(或多或少)使用LLVM 2.6.看起来在SVN中有一些辅助函数可以在bitcode文件之上创建一个惰性ModuleProvider.我没有尝试过编译它,只是将我的一个JIT应用程序中的一些位粘在一起.

#include <string>
#include <memory>

#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;
    auto_ptr<MemoryBuffer> buffer(MemoryBuffer::getFile("bitcode.bc"));
    auto_ptr<Module> module(ParseBitcodeFile(buffer.get(), context, &error));
    auto_ptr<ModuleProvider> mp(new ExistingModuleProvider(module));
    module.release();

    auto_ptr<ExecutionEngine> ee(ExecutionEngine::createJIT(mp.get(), &error));
    mp.release();

    Function* func = ee->getFunction("foo");

    typedef void (*PFN)();
    PFN pfn = reinterpret_cast<PFN>(ee->getPointerToFunction(func));
    pfn();
}
Run Code Online (Sandbox Code Playgroud)


Ric*_*ton -3

从命令行,您可以使用 LLVM 程序 lli 来运行 bc 文件。如果文件采用 LLVM 汇编语言,则必须先对其运行 llvm-as 以创建二进制位码文件。

使用 C 语言很容易做到这一点。我建议您查看大量的 LLVM 文档: http: //llvm.org/docs

LLVM irc 频道(该页面上有一个链接)充满了知识渊博的人,他们愿意回答问题。

抱歉间接回答。我广泛使用 LLVM,但我不仅仅在时间编译中直接生成代码。