Layer the memory manager between the JIT and the runtime Dyld.
[oota-llvm.git] / lib / ExecutionEngine / MCJIT / MCJIT.cpp
1 //===-- MCJIT.cpp - MC-based Just-in-Time Compiler --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "MCJIT.h"
11 #include "MCJITMemoryManager.h"
12 #include "llvm/DerivedTypes.h"
13 #include "llvm/Function.h"
14 #include "llvm/ExecutionEngine/GenericValue.h"
15 #include "llvm/ExecutionEngine/MCJIT.h"
16 #include "llvm/ExecutionEngine/JITMemoryManager.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/DynamicLibrary.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Target/TargetData.h"
22
23 using namespace llvm;
24
25 namespace {
26
27 static struct RegisterJIT {
28   RegisterJIT() { MCJIT::Register(); }
29 } JITRegistrator;
30
31 }
32
33 extern "C" void LLVMLinkInMCJIT() {
34 }
35
36 ExecutionEngine *MCJIT::createJIT(Module *M,
37                                   std::string *ErrorStr,
38                                   JITMemoryManager *JMM,
39                                   CodeGenOpt::Level OptLevel,
40                                   bool GVsWithCode,
41                                   CodeModel::Model CMM,
42                                   StringRef MArch,
43                                   StringRef MCPU,
44                                   const SmallVectorImpl<std::string>& MAttrs) {
45   // Try to register the program as a source of symbols to resolve against.
46   //
47   // FIXME: Don't do this here.
48   sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
49
50   // Pick a target either via -march or by guessing the native arch.
51   //
52   // FIXME: This should be lifted out of here, it isn't something which should
53   // be part of the JIT policy, rather the burden for this selection should be
54   // pushed to clients.
55   TargetMachine *TM = MCJIT::selectTarget(M, MArch, MCPU, MAttrs, ErrorStr);
56   if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
57   TM->setCodeModel(CMM);
58
59   // If the target supports JIT code generation, create the JIT.
60   if (TargetJITInfo *TJ = TM->getJITInfo())
61     return new MCJIT(M, TM, *TJ, new MCJITMemoryManager(JMM), OptLevel,
62                      GVsWithCode);
63
64   if (ErrorStr)
65     *ErrorStr = "target does not support JIT code generation";
66   return 0;
67 }
68
69 MCJIT::MCJIT(Module *m, TargetMachine *tm, TargetJITInfo &tji,
70              RTDyldMemoryManager *MM, CodeGenOpt::Level OptLevel,
71              bool AllocateGVsWithCode)
72   : ExecutionEngine(m), TM(tm), MemMgr(MM), M(m), OS(Buffer), Dyld(MM) {
73
74   PM.add(new TargetData(*TM->getTargetData()));
75
76   // Turn the machine code intermediate representation into bytes in memory
77   // that may be executed.
78   if (TM->addPassesToEmitMC(PM, Ctx, OS, CodeGenOpt::Default, false)) {
79     report_fatal_error("Target does not support MC emission!");
80   }
81
82   // Initialize passes.
83   // FIXME: When we support multiple modules, we'll want to move the code
84   // gen and finalization out of the constructor here and do it more
85   // on-demand as part of getPointerToFunction().
86   PM.run(*M);
87   // Flush the output buffer so the SmallVector gets its data.
88   OS.flush();
89
90   // Load the object into the dynamic linker.
91   // FIXME: It would be nice to avoid making yet another copy.
92   MemoryBuffer *MB = MemoryBuffer::getMemBufferCopy(StringRef(Buffer.data(),
93                                                               Buffer.size()));
94   if (Dyld.loadObject(MB))
95     report_fatal_error(Dyld.getErrorString());
96 }
97
98 MCJIT::~MCJIT() {
99   delete MemMgr;
100 }
101
102 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
103   report_fatal_error("not yet implemented");
104   return 0;
105 }
106
107 void *MCJIT::getPointerToFunction(Function *F) {
108   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
109     bool AbortOnFailure = !F->hasExternalWeakLinkage();
110     void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
111     addGlobalMapping(F, Addr);
112     return Addr;
113   }
114
115   Twine Name = TM->getMCAsmInfo()->getGlobalPrefix() + F->getName();
116   return (void*)Dyld.getSymbolAddress(Name.str());
117 }
118
119 void *MCJIT::recompileAndRelinkFunction(Function *F) {
120   report_fatal_error("not yet implemented");
121 }
122
123 void MCJIT::freeMachineCodeForFunction(Function *F) {
124   report_fatal_error("not yet implemented");
125 }
126
127 GenericValue MCJIT::runFunction(Function *F,
128                                 const std::vector<GenericValue> &ArgValues) {
129   assert(F && "Function *F was null at entry to run()");
130
131   void *FPtr = getPointerToFunction(F);
132   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
133   const FunctionType *FTy = F->getFunctionType();
134   const Type *RetTy = FTy->getReturnType();
135
136   assert((FTy->getNumParams() == ArgValues.size() ||
137           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
138          "Wrong number of arguments passed into function!");
139   assert(FTy->getNumParams() == ArgValues.size() &&
140          "This doesn't support passing arguments through varargs (yet)!");
141
142   // Handle some common cases first.  These cases correspond to common `main'
143   // prototypes.
144   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
145     switch (ArgValues.size()) {
146     case 3:
147       if (FTy->getParamType(0)->isIntegerTy(32) &&
148           FTy->getParamType(1)->isPointerTy() &&
149           FTy->getParamType(2)->isPointerTy()) {
150         int (*PF)(int, char **, const char **) =
151           (int(*)(int, char **, const char **))(intptr_t)FPtr;
152
153         // Call the function.
154         GenericValue rv;
155         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
156                                  (char **)GVTOP(ArgValues[1]),
157                                  (const char **)GVTOP(ArgValues[2])));
158         return rv;
159       }
160       break;
161     case 2:
162       if (FTy->getParamType(0)->isIntegerTy(32) &&
163           FTy->getParamType(1)->isPointerTy()) {
164         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
165
166         // Call the function.
167         GenericValue rv;
168         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
169                                  (char **)GVTOP(ArgValues[1])));
170         return rv;
171       }
172       break;
173     case 1:
174       if (FTy->getNumParams() == 1 &&
175           FTy->getParamType(0)->isIntegerTy(32)) {
176         GenericValue rv;
177         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
178         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
179         return rv;
180       }
181       break;
182     }
183   }
184
185   // Handle cases where no arguments are passed first.
186   if (ArgValues.empty()) {
187     GenericValue rv;
188     switch (RetTy->getTypeID()) {
189     default: llvm_unreachable("Unknown return type for function call!");
190     case Type::IntegerTyID: {
191       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
192       if (BitWidth == 1)
193         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
194       else if (BitWidth <= 8)
195         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
196       else if (BitWidth <= 16)
197         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
198       else if (BitWidth <= 32)
199         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
200       else if (BitWidth <= 64)
201         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
202       else
203         llvm_unreachable("Integer types > 64 bits not supported");
204       return rv;
205     }
206     case Type::VoidTyID:
207       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
208       return rv;
209     case Type::FloatTyID:
210       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
211       return rv;
212     case Type::DoubleTyID:
213       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
214       return rv;
215     case Type::X86_FP80TyID:
216     case Type::FP128TyID:
217     case Type::PPC_FP128TyID:
218       llvm_unreachable("long double not supported yet");
219       return rv;
220     case Type::PointerTyID:
221       return PTOGV(((void*(*)())(intptr_t)FPtr)());
222     }
223   }
224
225   assert("Full-featured argument passing not supported yet!");
226   return GenericValue();
227 }