622215b7a7b8119b266a64297ea30a38a77e6e14
[oota-llvm.git] / lib / ExecutionEngine / JIT / VM.cpp
1 //===-- VM.cpp - LLVM Just in Time Compiler -------------------------------===//
2 //
3 // This tool implements a just-in-time compiler for LLVM, allowing direct
4 // execution of LLVM bytecode in an efficient manner.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "VM.h"
9 #include "llvm/Target/TargetMachine.h"
10 #include "llvm/CodeGen/MachineCodeEmitter.h"
11 #include "llvm/Function.h"
12
13 VM::~VM() {
14   delete MCE;
15   delete &TM;
16 }
17
18 /// setupPassManager - Initialize the VM PassManager object with all of the
19 /// passes needed for the target to generate code.
20 ///
21 void VM::setupPassManager() {
22   // Compile LLVM Code down to machine code in the intermediate representation
23   if (TM.addPassesToJITCompile(PM)) {
24     std::cerr << "lli: target '" << TM.getName()
25               << "' doesn't support JIT compilation!\n";
26     abort();
27   }
28
29   // Turn the machine code intermediate representation into bytes in memory that
30   // may be executed.
31   //
32   if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
33     std::cerr << "lli: target '" << TM.getName()
34               << "' doesn't support machine code emission!\n";
35     abort();
36   }
37 }
38
39 /// getPointerToFunction - This method is used to get the address of the
40 /// specified function, compiling it if neccesary.
41 ///
42 void *VM::getPointerToFunction(Function *F) {
43   void *&Addr = GlobalAddress[F];   // Function already code gen'd
44   if (Addr) return Addr;
45
46   // Make sure we read in the function if it exists in this Module
47   MP->materializeFunction(F);
48
49   if (F->isExternal())
50     return Addr = getPointerToNamedFunction(F->getName());
51
52   static bool isAlreadyCodeGenerating = false;
53   assert(!isAlreadyCodeGenerating && "ERROR: RECURSIVE COMPILATION DETECTED!");
54
55   // JIT the function
56   isAlreadyCodeGenerating = true;
57   PM.run(*F);
58   isAlreadyCodeGenerating = false;
59
60   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
61   return Addr;
62 }