ExecutionEngine: fix JIT/MCJIT selectTarget() duplication (v2)
[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 =
56           EngineBuilder::selectTarget(M, MArch, MCPU, MAttrs, ErrorStr);
57   if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
58   TM->setCodeModel(CMM);
59
60   // If the target supports JIT code generation, create the JIT.
61   if (TargetJITInfo *TJ = TM->getJITInfo())
62     return new MCJIT(M, TM, *TJ, new MCJITMemoryManager(JMM, M), OptLevel,
63                      GVsWithCode);
64
65   if (ErrorStr)
66     *ErrorStr = "target does not support JIT code generation";
67   return 0;
68 }
69
70 MCJIT::MCJIT(Module *m, TargetMachine *tm, TargetJITInfo &tji,
71              RTDyldMemoryManager *MM, CodeGenOpt::Level OptLevel,
72              bool AllocateGVsWithCode)
73   : ExecutionEngine(m), TM(tm), MemMgr(MM), M(m), OS(Buffer), Dyld(MM) {
74
75   PM.add(new TargetData(*TM->getTargetData()));
76
77   // Turn the machine code intermediate representation into bytes in memory
78   // that may be executed.
79   if (TM->addPassesToEmitMC(PM, Ctx, OS, CodeGenOpt::Default, false)) {
80     report_fatal_error("Target does not support MC emission!");
81   }
82
83   // Initialize passes.
84   // FIXME: When we support multiple modules, we'll want to move the code
85   // gen and finalization out of the constructor here and do it more
86   // on-demand as part of getPointerToFunction().
87   PM.run(*M);
88   // Flush the output buffer so the SmallVector gets its data.
89   OS.flush();
90
91   // Load the object into the dynamic linker.
92   // FIXME: It would be nice to avoid making yet another copy.
93   MemoryBuffer *MB = MemoryBuffer::getMemBufferCopy(StringRef(Buffer.data(),
94                                                               Buffer.size()));
95   if (Dyld.loadObject(MB))
96     report_fatal_error(Dyld.getErrorString());
97   // Resolve any relocations.
98   Dyld.resolveRelocations();
99 }
100
101 MCJIT::~MCJIT() {
102   delete MemMgr;
103 }
104
105 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
106   report_fatal_error("not yet implemented");
107   return 0;
108 }
109
110 void *MCJIT::getPointerToFunction(Function *F) {
111   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
112     bool AbortOnFailure = !F->hasExternalWeakLinkage();
113     void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
114     addGlobalMapping(F, Addr);
115     return Addr;
116   }
117
118   Twine Name = TM->getMCAsmInfo()->getGlobalPrefix() + F->getName();
119   return (void*)Dyld.getSymbolAddress(Name.str());
120 }
121
122 void *MCJIT::recompileAndRelinkFunction(Function *F) {
123   report_fatal_error("not yet implemented");
124 }
125
126 void MCJIT::freeMachineCodeForFunction(Function *F) {
127   report_fatal_error("not yet implemented");
128 }
129
130 GenericValue MCJIT::runFunction(Function *F,
131                                 const std::vector<GenericValue> &ArgValues) {
132   assert(F && "Function *F was null at entry to run()");
133
134   void *FPtr = getPointerToFunction(F);
135   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
136   const FunctionType *FTy = F->getFunctionType();
137   const Type *RetTy = FTy->getReturnType();
138
139   assert((FTy->getNumParams() == ArgValues.size() ||
140           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
141          "Wrong number of arguments passed into function!");
142   assert(FTy->getNumParams() == ArgValues.size() &&
143          "This doesn't support passing arguments through varargs (yet)!");
144
145   // Handle some common cases first.  These cases correspond to common `main'
146   // prototypes.
147   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
148     switch (ArgValues.size()) {
149     case 3:
150       if (FTy->getParamType(0)->isIntegerTy(32) &&
151           FTy->getParamType(1)->isPointerTy() &&
152           FTy->getParamType(2)->isPointerTy()) {
153         int (*PF)(int, char **, const char **) =
154           (int(*)(int, char **, const char **))(intptr_t)FPtr;
155
156         // Call the function.
157         GenericValue rv;
158         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
159                                  (char **)GVTOP(ArgValues[1]),
160                                  (const char **)GVTOP(ArgValues[2])));
161         return rv;
162       }
163       break;
164     case 2:
165       if (FTy->getParamType(0)->isIntegerTy(32) &&
166           FTy->getParamType(1)->isPointerTy()) {
167         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
168
169         // Call the function.
170         GenericValue rv;
171         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
172                                  (char **)GVTOP(ArgValues[1])));
173         return rv;
174       }
175       break;
176     case 1:
177       if (FTy->getNumParams() == 1 &&
178           FTy->getParamType(0)->isIntegerTy(32)) {
179         GenericValue rv;
180         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
181         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
182         return rv;
183       }
184       break;
185     }
186   }
187
188   // Handle cases where no arguments are passed first.
189   if (ArgValues.empty()) {
190     GenericValue rv;
191     switch (RetTy->getTypeID()) {
192     default: llvm_unreachable("Unknown return type for function call!");
193     case Type::IntegerTyID: {
194       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
195       if (BitWidth == 1)
196         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
197       else if (BitWidth <= 8)
198         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
199       else if (BitWidth <= 16)
200         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
201       else if (BitWidth <= 32)
202         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
203       else if (BitWidth <= 64)
204         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
205       else
206         llvm_unreachable("Integer types > 64 bits not supported");
207       return rv;
208     }
209     case Type::VoidTyID:
210       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
211       return rv;
212     case Type::FloatTyID:
213       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
214       return rv;
215     case Type::DoubleTyID:
216       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
217       return rv;
218     case Type::X86_FP80TyID:
219     case Type::FP128TyID:
220     case Type::PPC_FP128TyID:
221       llvm_unreachable("long double not supported yet");
222       return rv;
223     case Type::PointerTyID:
224       return PTOGV(((void*(*)())(intptr_t)FPtr)());
225     }
226   }
227
228   assert("Full-featured argument passing not supported yet!");
229   return GenericValue();
230 }