blob: f2ddcf487aed5573cdc51817ac7efc2613ea21fe [file] [log] [blame]
Chris Lattner6701a862003-05-14 13:26:47 +00001//===-- VM.cpp - LLVM Just in Time Compiler -------------------------------===//
Chris Lattnerbd199fb2002-12-24 00:01:05 +00002//
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"
Chris Lattnerbd199fb2002-12-24 00:01:05 +00009#include "llvm/Function.h"
Misha Brukman0f4f7d92003-10-16 21:19:34 +000010#include "llvm/ModuleProvider.h"
11#include "llvm/CodeGen/MachineCodeEmitter.h"
12#include "llvm/Target/TargetMachine.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000013
14VM::~VM() {
15 delete MCE;
16 delete &TM;
17}
18
19/// setupPassManager - Initialize the VM PassManager object with all of the
20/// passes needed for the target to generate code.
21///
22void VM::setupPassManager() {
23 // Compile LLVM Code down to machine code in the intermediate representation
24 if (TM.addPassesToJITCompile(PM)) {
25 std::cerr << "lli: target '" << TM.getName()
26 << "' doesn't support JIT compilation!\n";
27 abort();
28 }
29
30 // Turn the machine code intermediate representation into bytes in memory that
31 // may be executed.
32 //
33 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
34 std::cerr << "lli: target '" << TM.getName()
35 << "' doesn't support machine code emission!\n";
36 abort();
37 }
38}
39
Chris Lattnerbd199fb2002-12-24 00:01:05 +000040/// getPointerToFunction - This method is used to get the address of the
41/// specified function, compiling it if neccesary.
42///
Brian Gaeke71d84782003-08-13 18:16:34 +000043void *VM::getPointerToFunction(Function *F) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +000044 void *&Addr = GlobalAddress[F]; // Function already code gen'd
45 if (Addr) return Addr;
46
Misha Brukman005e5e92003-10-14 21:37:41 +000047 // Make sure we read in the function if it exists in this Module
48 MP->materializeFunction(F);
49
Chris Lattner0d448c02003-01-13 01:00:48 +000050 if (F->isExternal())
51 return Addr = getPointerToNamedFunction(F->getName());
Chris Lattnerbd199fb2002-12-24 00:01:05 +000052
Chris Lattner66a84942003-05-08 21:08:43 +000053 static bool isAlreadyCodeGenerating = false;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +000054 assert(!isAlreadyCodeGenerating && "ERROR: RECURSIVE COMPILATION DETECTED!");
Chris Lattner66a84942003-05-08 21:08:43 +000055
Brian Gaeke71d84782003-08-13 18:16:34 +000056 // JIT the function
Chris Lattner66a84942003-05-08 21:08:43 +000057 isAlreadyCodeGenerating = true;
Brian Gaeke71d84782003-08-13 18:16:34 +000058 PM.run(*F);
Chris Lattner66a84942003-05-08 21:08:43 +000059 isAlreadyCodeGenerating = false;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000060
61 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
62 return Addr;
63}