可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have generated a bc file with the online compiler on llvm.org, and I would like to know if it is possible to load this bc file from a c or c++ program, execute the IR in the bc file with the llvm jit (programmatically in the c program), and get the results.
How can I accomplish this?
回答1:
Here's some working code based on Nathan Howell's:
#include #include #include #include #include #include #include #include #include #include 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(ee->getPointerToFunction(func)); pfn(); delete ee; }
One oddity was that without the final include, ee is NULL. Bizarre.
To generate my tst.bc, I used http://llvm.org/demo/index.cgi and the llvm-as command-line tool.
回答2:
This should (more or less) work using LLVM 2.6. It looks like there are some more helper functions in SVN to create a lazy ModuleProvider on top of a bitcode file. I haven't tried compiling it though, just glued together some bits from one of my JIT applications.
#include #include #include #include #include #include #include using namespace std; using namespace llvm; int main() { InitializeNativeTarget(); llvm_start_multithreaded(); LLVMContext context; string error; auto_ptr buffer(MemoryBuffer::getFile("bitcode.bc")); auto_ptr module(ParseBitcodeFile(buffer.get(), context, &error)); auto_ptr mp(new ExistingModuleProvider(module)); module.release(); auto_ptr ee(ExecutionEngine::createJIT(mp.get(), &error)); mp.release(); Function* func = ee->getFunction("foo"); typedef void (*PFN)(); PFN pfn = reinterpret_cast(ee->getPointerToFunction(func)); pfn(); }
回答3:
From the command line, you can use the LLVM program lli to run a bc file. If the file is in LLVM assembly language, you'll have to run llvm-as on it first to create a binary bitcode file.
It is easy to do this from C. I'd recommend you look at the extensive LLVM documentation: http://llvm.org/docs
The LLVM irc channel, which has a link on that page, is full of very knowledgeable people that are willing to answer questions.
Sorry for the indirect answer. I use LLVM extensively, but I do direct code generation not just in time compliation.