2014-11-24 29 views
5

我試圖使用LLVM C API實現一個簡單的JIT編譯器。到目前爲止,我沒有生成IR代碼並執行它的問題,即:直到我開始處理對象並重新創建它們。LLVM API:正確的方式來創建/處置

我基本上想要做的就是在發動機不再使用的時候清理JIT的資源。什麼我基本上試圖做的是這樣的:

while (true) 
{ 
    // Initialize module & builder 
    InitializeCore(GetGlobalPassRegistry()); 
    module = ModuleCreateWithName(some_unique_name); 
    builder = CreateBuilder(); 

    // Initialize target & execution engine 
    InitializeNativeTarget(); 
    engine = CreateExecutionEngineForModule(...); 
    passmgr = CreateFunctionPassManagerForModule(module); 
    AddTargetData(GetExecutionEngineTargetData(engine), passmgr); 
    InitializeFunctionPassManager(passmgr); 

    // [... my fancy JIT code ...] --** Will give a serious error the second iteration 

    // Destroy 
    DisposePassManager(passmgr); 
    DisposeExecutionEngine(engine); 
    DisposeBuilder(builder); 
    // DisposeModule(module); //--> Commented out: Deleted by execution engine 

    Shutdown(); 
} 

然而,這似乎並沒有被正確的工作:循環,我得到一個非常糟糕的錯誤的第二次迭代...

所以總結一下:破壞和重新創建LLVM API的正確方法是什麼?

+0

我想,你應該先刪除模塊。 – arrowd 2014-11-25 06:20:13

+0

@arrowdodger在我看來,這是不可能的。執行引擎引用模塊並執行「刪除」。儘管我身體中的每一根纖維都希望將其刪除,但如果你這樣做,你的程序肯定會發生段錯誤。 – atlaste 2014-11-25 09:16:48

+0

嘗試將'InitializeNativeTarget()'移出循環,然後。 – arrowd 2014-11-25 09:18:39

回答

3

將此發送爲答案,因爲代碼太長。如果可能並且沒有其他限制,請嘗試像這樣使用LLVM。我很肯定循環內的Shutdown()是這裏的罪魁禍首。我不認爲外面也會讓Builder受傷。這很好地反映了我在JIT中使用LLVM的方式。

InitializeCore(GetGlobalPassRegistry()); 
InitializeNativeTarget(); 
builder = CreateBuilder(); 

while (true) 
{ 
    // Initialize module & builder 

    module = ModuleCreateWithName(some_unique_name); 


    // Initialize target & execution engine 
    engine = CreateExecutionEngineForModule(...); 
    passmgr = CreateFunctionPassManagerForModule(module); 
    AddTargetData(GetExecutionEngineTargetData(engine), passmgr); 
    InitializeFunctionPassManager(passmgr); 

    // [... my fancy JIT code ...] --** Will give a serious error the second iteration 

    // Destroy 
    DisposePassManager(passmgr); 
    DisposeExecutionEngine(engine);    
} 
DisposeBuilder(builder); 
Shutdown(); 
+0

謝謝,我要說一說,讓我們來看看發生了什麼,我注意到你不會銷燬模塊,是故意的嗎? – atlaste 2014-11-27 12:34:01

+0

我已經完成了一些配置,看起來泄漏已經全部消失了。幾個重要的指針:總是處置執行引擎,否則你得到一個主要的內存泄漏,並且一定要處理你傳遞給LLVM函數的所有通用值(包括函數返回值),結合你的解決方案,這對我有用。將您的答案作爲正確的解決方案。 – atlaste 2014-11-27 13:36:11

+0

是的,因爲我發現了痛苦的(段錯誤)方式,所以該模塊由執行引擎擁有,並被刪除。 – antipattern 2014-11-27 14:32:46