2009-12-03 123 views
22

我在llvm.org上用在線編譯器生成了一個bc文件,我想知道是否有可能從ac或C++程序加載這個bc文件,執行IR bc文​​件與llvm jit(以編程方式在c程序中),並獲得結果。從c程序中調用LLVM Jit

我該如何做到這一點?

回答

-3

從命令行,您可以使用LLVM程序lli運行一個bc文件。如果文件採用LLVM彙編語言,則必須首先運行llvm-以創建二進制位碼文件。

這是很容易從下做到這一點,我建議你看看廣泛LLVM文檔:http://llvm.org/docs

LLVM的IRC頻道,其中有一個頁面上的鏈接,到處是很有學問的人說願意回答問題。

對不起,間接的答案。我廣泛使用LLVM,但是我的確在直接生成代碼,而不僅僅是在時間上進行合成。

15

這應該(或多或少)使用LLVM 2.6。看起來SVN中還有一些輔助函數在位代碼文件的頂部創建了一個懶惰的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(); 
} 
23

下面是基於內森豪威爾的一些工作代碼:

#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。離奇。

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

+1

Doh,#包括需要強制鏈接器拉入JIT,否則將被丟棄。我會更新我的示例。 – 2010-02-03 17:00:32

+0

有沒有這樣做? – Ariel 2010-09-19 01:14:39

+1

Ariel:是的,大多數LLVM都可以從純C使用,使用LLVM自帶的綁定。請參閱http://llvm.org/docs/FAQ.html#langirgen和http://npcontemplation.blogspot.com/2008/06/secret-of-llvm-c-bindings.html – 2010-12-02 05:26:11