b6f90e2de05a7d5c68e61a6cd073128245ef5b80
[oota-llvm.git] / lib / ExecutionEngine / JIT / JITEmitter.cpp
1 //===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
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 // This file defines a MachineCodeEmitter object that is used by the JIT to
11 // write machine code to memory and remember where relocatable values are.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "JIT.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/JITCodeEmitter.h"
21 #include "llvm/CodeGen/MachineCodeInfo.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRelocation.h"
27 #include "llvm/ExecutionEngine/GenericValue.h"
28 #include "llvm/ExecutionEngine/JITEventListener.h"
29 #include "llvm/ExecutionEngine/JITMemoryManager.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/IR/ValueHandle.h"
37 #include "llvm/IR/ValueMap.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Disassembler.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/Memory.h"
43 #include "llvm/Support/MutexGuard.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetJITInfo.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include <algorithm>
50 #ifndef NDEBUG
51 #include <iomanip>
52 #endif
53 using namespace llvm;
54
55 #define DEBUG_TYPE "jit"
56
57 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
58 STATISTIC(NumRelos, "Number of relocations applied");
59 STATISTIC(NumRetries, "Number of retries with more memory");
60
61
62 // A declaration may stop being a declaration once it's fully read from bitcode.
63 // This function returns true if F is fully read and is still a declaration.
64 static bool isNonGhostDeclaration(const Function *F) {
65   return F->isDeclaration() && !F->isMaterializable();
66 }
67
68 //===----------------------------------------------------------------------===//
69 // JIT lazy compilation code.
70 //
71 namespace {
72   class JITEmitter;
73   class JITResolverState;
74
75   template<typename ValueTy>
76   struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
77     typedef JITResolverState *ExtraData;
78     static void onRAUW(JITResolverState *, Value *Old, Value *New) {
79       llvm_unreachable("The JIT doesn't know how to handle a"
80                        " RAUW on a value it has emitted.");
81     }
82   };
83
84   struct CallSiteValueMapConfig : public NoRAUWValueMapConfig<Function*> {
85     typedef JITResolverState *ExtraData;
86     static void onDelete(JITResolverState *JRS, Function *F);
87   };
88
89   class JITResolverState {
90   public:
91     typedef ValueMap<Function*, void*, NoRAUWValueMapConfig<Function*> >
92       FunctionToLazyStubMapTy;
93     typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
94     typedef ValueMap<Function *, SmallPtrSet<void*, 1>,
95                      CallSiteValueMapConfig> FunctionToCallSitesMapTy;
96     typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
97   private:
98     /// FunctionToLazyStubMap - Keep track of the lazy stub created for a
99     /// particular function so that we can reuse them if necessary.
100     FunctionToLazyStubMapTy FunctionToLazyStubMap;
101
102     /// CallSiteToFunctionMap - Keep track of the function that each lazy call
103     /// site corresponds to, and vice versa.
104     CallSiteToFunctionMapTy CallSiteToFunctionMap;
105     FunctionToCallSitesMapTy FunctionToCallSitesMap;
106
107     /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
108     /// particular GlobalVariable so that we can reuse them if necessary.
109     GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
110
111 #ifndef NDEBUG
112     /// Instance of the JIT this ResolverState serves.
113     JIT *TheJIT;
114 #endif
115
116   public:
117     JITResolverState(JIT *jit) : FunctionToLazyStubMap(this),
118                                  FunctionToCallSitesMap(this) {
119 #ifndef NDEBUG
120       TheJIT = jit;
121 #endif
122     }
123
124     FunctionToLazyStubMapTy& getFunctionToLazyStubMap(
125       const MutexGuard& locked) {
126       assert(locked.holds(TheJIT->lock));
127       return FunctionToLazyStubMap;
128     }
129
130     GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& lck) {
131       assert(lck.holds(TheJIT->lock));
132       return GlobalToIndirectSymMap;
133     }
134
135     std::pair<void *, Function *> LookupFunctionFromCallSite(
136         const MutexGuard &locked, void *CallSite) const {
137       assert(locked.holds(TheJIT->lock));
138
139       // The address given to us for the stub may not be exactly right, it
140       // might be a little bit after the stub.  As such, use upper_bound to
141       // find it.
142       CallSiteToFunctionMapTy::const_iterator I =
143         CallSiteToFunctionMap.upper_bound(CallSite);
144       assert(I != CallSiteToFunctionMap.begin() &&
145              "This is not a known call site!");
146       --I;
147       return *I;
148     }
149
150     void AddCallSite(const MutexGuard &locked, void *CallSite, Function *F) {
151       assert(locked.holds(TheJIT->lock));
152
153       bool Inserted = CallSiteToFunctionMap.insert(
154           std::make_pair(CallSite, F)).second;
155       (void)Inserted;
156       assert(Inserted && "Pair was already in CallSiteToFunctionMap");
157       FunctionToCallSitesMap[F].insert(CallSite);
158     }
159
160     void EraseAllCallSitesForPrelocked(Function *F);
161
162     // Erases _all_ call sites regardless of their function.  This is used to
163     // unregister the stub addresses from the StubToResolverMap in
164     // ~JITResolver().
165     void EraseAllCallSitesPrelocked();
166   };
167
168   /// JITResolver - Keep track of, and resolve, call sites for functions that
169   /// have not yet been compiled.
170   class JITResolver {
171     typedef JITResolverState::FunctionToLazyStubMapTy FunctionToLazyStubMapTy;
172     typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
173     typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
174
175     /// LazyResolverFn - The target lazy resolver function that we actually
176     /// rewrite instructions to use.
177     TargetJITInfo::LazyResolverFn LazyResolverFn;
178
179     JITResolverState state;
180
181     /// ExternalFnToStubMap - This is the equivalent of FunctionToLazyStubMap
182     /// for external functions.  TODO: Of course, external functions don't need
183     /// a lazy stub.  It's actually here to make it more likely that far calls
184     /// succeed, but no single stub can guarantee that.  I'll remove this in a
185     /// subsequent checkin when I actually fix far calls.
186     std::map<void*, void*> ExternalFnToStubMap;
187
188     /// revGOTMap - map addresses to indexes in the GOT
189     std::map<void*, unsigned> revGOTMap;
190     unsigned nextGOTIndex;
191
192     JITEmitter &JE;
193
194     /// Instance of JIT corresponding to this Resolver.
195     JIT *TheJIT;
196
197   public:
198     explicit JITResolver(JIT &jit, JITEmitter &je)
199       : state(&jit), nextGOTIndex(0), JE(je), TheJIT(&jit) {
200       LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
201     }
202
203     ~JITResolver();
204
205     /// getLazyFunctionStubIfAvailable - This returns a pointer to a function's
206     /// lazy-compilation stub if it has already been created.
207     void *getLazyFunctionStubIfAvailable(Function *F);
208
209     /// getLazyFunctionStub - This returns a pointer to a function's
210     /// lazy-compilation stub, creating one on demand as needed.
211     void *getLazyFunctionStub(Function *F);
212
213     /// getExternalFunctionStub - Return a stub for the function at the
214     /// specified address, created lazily on demand.
215     void *getExternalFunctionStub(void *FnAddr);
216
217     /// getGlobalValueIndirectSym - Return an indirect symbol containing the
218     /// specified GV address.
219     void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
220
221     /// getGOTIndexForAddress - Return a new or existing index in the GOT for
222     /// an address.  This function only manages slots, it does not manage the
223     /// contents of the slots or the memory associated with the GOT.
224     unsigned getGOTIndexForAddr(void *addr);
225
226     /// JITCompilerFn - This function is called to resolve a stub to a compiled
227     /// address.  If the LLVM Function corresponding to the stub has not yet
228     /// been compiled, this function compiles it first.
229     static void *JITCompilerFn(void *Stub);
230   };
231
232   class StubToResolverMapTy {
233     /// Map a stub address to a specific instance of a JITResolver so that
234     /// lazily-compiled functions can find the right resolver to use.
235     ///
236     /// Guarded by Lock.
237     std::map<void*, JITResolver*> Map;
238
239     /// Guards Map from concurrent accesses.
240     mutable sys::Mutex Lock;
241
242   public:
243     /// Registers a Stub to be resolved by Resolver.
244     void RegisterStubResolver(void *Stub, JITResolver *Resolver) {
245       MutexGuard guard(Lock);
246       Map.insert(std::make_pair(Stub, Resolver));
247     }
248     /// Unregisters the Stub when it's invalidated.
249     void UnregisterStubResolver(void *Stub) {
250       MutexGuard guard(Lock);
251       Map.erase(Stub);
252     }
253     /// Returns the JITResolver instance that owns the Stub.
254     JITResolver *getResolverFromStub(void *Stub) const {
255       MutexGuard guard(Lock);
256       // The address given to us for the stub may not be exactly right, it might
257       // be a little bit after the stub.  As such, use upper_bound to find it.
258       // This is the same trick as in LookupFunctionFromCallSite from
259       // JITResolverState.
260       std::map<void*, JITResolver*>::const_iterator I = Map.upper_bound(Stub);
261       assert(I != Map.begin() && "This is not a known stub!");
262       --I;
263       return I->second;
264     }
265     /// True if any stubs refer to the given resolver. Only used in an assert().
266     /// O(N)
267     bool ResolverHasStubs(JITResolver* Resolver) const {
268       MutexGuard guard(Lock);
269       for (std::map<void*, JITResolver*>::const_iterator I = Map.begin(),
270              E = Map.end(); I != E; ++I) {
271         if (I->second == Resolver)
272           return true;
273       }
274       return false;
275     }
276   };
277   /// This needs to be static so that a lazy call stub can access it with no
278   /// context except the address of the stub.
279   ManagedStatic<StubToResolverMapTy> StubToResolverMap;
280
281   /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
282   /// used to output functions to memory for execution.
283   class JITEmitter : public JITCodeEmitter {
284     JITMemoryManager *MemMgr;
285
286     // When outputting a function stub in the context of some other function, we
287     // save BufferBegin/BufferEnd/CurBufferPtr here.
288     uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
289
290     // When reattempting to JIT a function after running out of space, we store
291     // the estimated size of the function we're trying to JIT here, so we can
292     // ask the memory manager for at least this much space.  When we
293     // successfully emit the function, we reset this back to zero.
294     uintptr_t SizeEstimate;
295
296     /// Relocations - These are the relocations that the function needs, as
297     /// emitted.
298     std::vector<MachineRelocation> Relocations;
299
300     /// MBBLocations - This vector is a mapping from MBB ID's to their address.
301     /// It is filled in by the StartMachineBasicBlock callback and queried by
302     /// the getMachineBasicBlockAddress callback.
303     std::vector<uintptr_t> MBBLocations;
304
305     /// ConstantPool - The constant pool for the current function.
306     ///
307     MachineConstantPool *ConstantPool;
308
309     /// ConstantPoolBase - A pointer to the first entry in the constant pool.
310     ///
311     void *ConstantPoolBase;
312
313     /// ConstPoolAddresses - Addresses of individual constant pool entries.
314     ///
315     SmallVector<uintptr_t, 8> ConstPoolAddresses;
316
317     /// JumpTable - The jump tables for the current function.
318     ///
319     MachineJumpTableInfo *JumpTable;
320
321     /// JumpTableBase - A pointer to the first entry in the jump table.
322     ///
323     void *JumpTableBase;
324
325     /// Resolver - This contains info about the currently resolved functions.
326     JITResolver Resolver;
327
328     /// LabelLocations - This vector is a mapping from Label ID's to their
329     /// address.
330     DenseMap<MCSymbol*, uintptr_t> LabelLocations;
331
332     /// MMI - Machine module info for exception informations
333     MachineModuleInfo* MMI;
334
335     // CurFn - The llvm function being emitted.  Only valid during
336     // finishFunction().
337     const Function *CurFn;
338
339     /// Information about emitted code, which is passed to the
340     /// JITEventListeners.  This is reset in startFunction and used in
341     /// finishFunction.
342     JITEvent_EmittedFunctionDetails EmissionDetails;
343
344     struct EmittedCode {
345       void *FunctionBody;  // Beginning of the function's allocation.
346       void *Code;  // The address the function's code actually starts at.
347       void *ExceptionTable;
348       EmittedCode() : FunctionBody(nullptr), Code(nullptr),
349                       ExceptionTable(nullptr) {}
350     };
351     struct EmittedFunctionConfig : public ValueMapConfig<const Function*> {
352       typedef JITEmitter *ExtraData;
353       static void onDelete(JITEmitter *, const Function*);
354       static void onRAUW(JITEmitter *, const Function*, const Function*);
355     };
356     ValueMap<const Function *, EmittedCode,
357              EmittedFunctionConfig> EmittedFunctions;
358
359     DebugLoc PrevDL;
360
361     /// Instance of the JIT
362     JIT *TheJIT;
363
364   public:
365     JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
366       : SizeEstimate(0), Resolver(jit, *this), MMI(nullptr), CurFn(nullptr),
367         EmittedFunctions(this), TheJIT(&jit) {
368       MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
369       if (jit.getJITInfo().needsGOT()) {
370         MemMgr->AllocateGOT();
371         DEBUG(dbgs() << "JIT is managing a GOT\n");
372       }
373
374     }
375     ~JITEmitter() {
376       delete MemMgr;
377     }
378
379     JITResolver &getJITResolver() { return Resolver; }
380
381     void startFunction(MachineFunction &F) override;
382     bool finishFunction(MachineFunction &F) override;
383
384     void emitConstantPool(MachineConstantPool *MCP);
385     void initJumpTableInfo(MachineJumpTableInfo *MJTI);
386     void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
387
388     void startGVStub(const GlobalValue* GV,
389                      unsigned StubSize, unsigned Alignment = 1);
390     void startGVStub(void *Buffer, unsigned StubSize);
391     void finishGVStub();
392     void *allocIndirectGV(const GlobalValue *GV, const uint8_t *Buffer,
393                           size_t Size, unsigned Alignment) override;
394
395     /// allocateSpace - Reserves space in the current block if any, or
396     /// allocate a new one of the given size.
397     void *allocateSpace(uintptr_t Size, unsigned Alignment) override;
398
399     /// allocateGlobal - Allocate memory for a global.  Unlike allocateSpace,
400     /// this method does not allocate memory in the current output buffer,
401     /// because a global may live longer than the current function.
402     void *allocateGlobal(uintptr_t Size, unsigned Alignment) override;
403
404     void addRelocation(const MachineRelocation &MR) override {
405       Relocations.push_back(MR);
406     }
407
408     void StartMachineBasicBlock(MachineBasicBlock *MBB) override {
409       if (MBBLocations.size() <= (unsigned)MBB->getNumber())
410         MBBLocations.resize((MBB->getNumber()+1)*2);
411       MBBLocations[MBB->getNumber()] = getCurrentPCValue();
412       if (MBB->hasAddressTaken())
413         TheJIT->addPointerToBasicBlock(MBB->getBasicBlock(),
414                                        (void*)getCurrentPCValue());
415       DEBUG(dbgs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
416                    << (void*) getCurrentPCValue() << "]\n");
417     }
418
419     uintptr_t getConstantPoolEntryAddress(unsigned Entry) const override;
420     uintptr_t getJumpTableEntryAddress(unsigned Entry) const override;
421
422     uintptr_t
423     getMachineBasicBlockAddress(MachineBasicBlock *MBB) const override {
424       assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
425              MBBLocations[MBB->getNumber()] && "MBB not emitted!");
426       return MBBLocations[MBB->getNumber()];
427     }
428
429     /// retryWithMoreMemory - Log a retry and deallocate all memory for the
430     /// given function.  Increase the minimum allocation size so that we get
431     /// more memory next time.
432     void retryWithMoreMemory(MachineFunction &F);
433
434     /// deallocateMemForFunction - Deallocate all memory for the specified
435     /// function body.
436     void deallocateMemForFunction(const Function *F);
437
438     void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) override;
439
440     void emitLabel(MCSymbol *Label) override {
441       LabelLocations[Label] = getCurrentPCValue();
442     }
443
444     DenseMap<MCSymbol*, uintptr_t> *getLabelLocations() override {
445       return &LabelLocations;
446     }
447
448     uintptr_t getLabelAddress(MCSymbol *Label) const override {
449       assert(LabelLocations.count(Label) && "Label not emitted!");
450       return LabelLocations.find(Label)->second;
451     }
452
453     void setModuleInfo(MachineModuleInfo* Info) override {
454       MMI = Info;
455     }
456
457   private:
458     void *getPointerToGlobal(GlobalValue *GV, void *Reference,
459                              bool MayNeedFarStub);
460     void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference);
461   };
462 }
463
464 void CallSiteValueMapConfig::onDelete(JITResolverState *JRS, Function *F) {
465   JRS->EraseAllCallSitesForPrelocked(F);
466 }
467
468 void JITResolverState::EraseAllCallSitesForPrelocked(Function *F) {
469   FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
470   if (F2C == FunctionToCallSitesMap.end())
471     return;
472   StubToResolverMapTy &S2RMap = *StubToResolverMap;
473   for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
474          E = F2C->second.end(); I != E; ++I) {
475     S2RMap.UnregisterStubResolver(*I);
476     bool Erased = CallSiteToFunctionMap.erase(*I);
477     (void)Erased;
478     assert(Erased && "Missing call site->function mapping");
479   }
480   FunctionToCallSitesMap.erase(F2C);
481 }
482
483 void JITResolverState::EraseAllCallSitesPrelocked() {
484   StubToResolverMapTy &S2RMap = *StubToResolverMap;
485   for (CallSiteToFunctionMapTy::const_iterator
486          I = CallSiteToFunctionMap.begin(),
487          E = CallSiteToFunctionMap.end(); I != E; ++I) {
488     S2RMap.UnregisterStubResolver(I->first);
489   }
490   CallSiteToFunctionMap.clear();
491   FunctionToCallSitesMap.clear();
492 }
493
494 JITResolver::~JITResolver() {
495   // No need to lock because we're in the destructor, and state isn't shared.
496   state.EraseAllCallSitesPrelocked();
497   assert(!StubToResolverMap->ResolverHasStubs(this) &&
498          "Resolver destroyed with stubs still alive.");
499 }
500
501 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function stub
502 /// if it has already been created.
503 void *JITResolver::getLazyFunctionStubIfAvailable(Function *F) {
504   MutexGuard locked(TheJIT->lock);
505
506   // If we already have a stub for this function, recycle it.
507   return state.getFunctionToLazyStubMap(locked).lookup(F);
508 }
509
510 /// getFunctionStub - This returns a pointer to a function stub, creating
511 /// one on demand as needed.
512 void *JITResolver::getLazyFunctionStub(Function *F) {
513   MutexGuard locked(TheJIT->lock);
514
515   // If we already have a lazy stub for this function, recycle it.
516   void *&Stub = state.getFunctionToLazyStubMap(locked)[F];
517   if (Stub) return Stub;
518
519   // Call the lazy resolver function if we are JIT'ing lazily.  Otherwise we
520   // must resolve the symbol now.
521   void *Actual = TheJIT->isCompilingLazily()
522     ? (void *)(intptr_t)LazyResolverFn : (void *)nullptr;
523
524   // If this is an external declaration, attempt to resolve the address now
525   // to place in the stub.
526   if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage()) {
527     Actual = TheJIT->getPointerToFunction(F);
528
529     // If we resolved the symbol to a null address (eg. a weak external)
530     // don't emit a stub. Return a null pointer to the application.
531     if (!Actual) return nullptr;
532   }
533
534   TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
535   JE.startGVStub(F, SL.Size, SL.Alignment);
536   // Codegen a new stub, calling the lazy resolver or the actual address of the
537   // external function, if it was resolved.
538   Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual, JE);
539   JE.finishGVStub();
540
541   if (Actual != (void*)(intptr_t)LazyResolverFn) {
542     // If we are getting the stub for an external function, we really want the
543     // address of the stub in the GlobalAddressMap for the JIT, not the address
544     // of the external function.
545     TheJIT->updateGlobalMapping(F, Stub);
546   }
547
548   DEBUG(dbgs() << "JIT: Lazy stub emitted at [" << Stub << "] for function '"
549         << F->getName() << "'\n");
550
551   if (TheJIT->isCompilingLazily()) {
552     // Register this JITResolver as the one corresponding to this call site so
553     // JITCompilerFn will be able to find it.
554     StubToResolverMap->RegisterStubResolver(Stub, this);
555
556     // Finally, keep track of the stub-to-Function mapping so that the
557     // JITCompilerFn knows which function to compile!
558     state.AddCallSite(locked, Stub, F);
559   } else if (!Actual) {
560     // If we are JIT'ing non-lazily but need to call a function that does not
561     // exist yet, add it to the JIT's work list so that we can fill in the
562     // stub address later.
563     assert(!isNonGhostDeclaration(F) && !F->hasAvailableExternallyLinkage() &&
564            "'Actual' should have been set above.");
565     TheJIT->addPendingFunction(F);
566   }
567
568   return Stub;
569 }
570
571 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
572 /// GV address.
573 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
574   MutexGuard locked(TheJIT->lock);
575
576   // If we already have a stub for this global variable, recycle it.
577   void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
578   if (IndirectSym) return IndirectSym;
579
580   // Otherwise, codegen a new indirect symbol.
581   IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
582                                                                 JE);
583
584   DEBUG(dbgs() << "JIT: Indirect symbol emitted at [" << IndirectSym
585         << "] for GV '" << GV->getName() << "'\n");
586
587   return IndirectSym;
588 }
589
590 /// getExternalFunctionStub - Return a stub for the function at the
591 /// specified address, created lazily on demand.
592 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
593   // If we already have a stub for this function, recycle it.
594   void *&Stub = ExternalFnToStubMap[FnAddr];
595   if (Stub) return Stub;
596
597   TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
598   JE.startGVStub(nullptr, SL.Size, SL.Alignment);
599   Stub = TheJIT->getJITInfo().emitFunctionStub(nullptr, FnAddr, JE);
600   JE.finishGVStub();
601
602   DEBUG(dbgs() << "JIT: Stub emitted at [" << Stub
603                << "] for external function at '" << FnAddr << "'\n");
604   return Stub;
605 }
606
607 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
608   unsigned idx = revGOTMap[addr];
609   if (!idx) {
610     idx = ++nextGOTIndex;
611     revGOTMap[addr] = idx;
612     DEBUG(dbgs() << "JIT: Adding GOT entry " << idx << " for addr ["
613                  << addr << "]\n");
614   }
615   return idx;
616 }
617
618 /// JITCompilerFn - This function is called when a lazy compilation stub has
619 /// been entered.  It looks up which function this stub corresponds to, compiles
620 /// it if necessary, then returns the resultant function pointer.
621 void *JITResolver::JITCompilerFn(void *Stub) {
622   JITResolver *JR = StubToResolverMap->getResolverFromStub(Stub);
623   assert(JR && "Unable to find the corresponding JITResolver to the call site");
624
625   Function* F = nullptr;
626   void* ActualPtr = nullptr;
627
628   {
629     // Only lock for getting the Function. The call getPointerToFunction made
630     // in this function might trigger function materializing, which requires
631     // JIT lock to be unlocked.
632     MutexGuard locked(JR->TheJIT->lock);
633
634     // The address given to us for the stub may not be exactly right, it might
635     // be a little bit after the stub.  As such, use upper_bound to find it.
636     std::pair<void*, Function*> I =
637       JR->state.LookupFunctionFromCallSite(locked, Stub);
638     F = I.second;
639     ActualPtr = I.first;
640   }
641
642   // If we have already code generated the function, just return the address.
643   void *Result = JR->TheJIT->getPointerToGlobalIfAvailable(F);
644
645   if (!Result) {
646     // Otherwise we don't have it, do lazy compilation now.
647
648     // If lazy compilation is disabled, emit a useful error message and abort.
649     if (!JR->TheJIT->isCompilingLazily()) {
650       report_fatal_error("LLVM JIT requested to do lazy compilation of"
651                          " function '"
652                         + F->getName() + "' when lazy compiles are disabled!");
653     }
654
655     DEBUG(dbgs() << "JIT: Lazily resolving function '" << F->getName()
656           << "' In stub ptr = " << Stub << " actual ptr = "
657           << ActualPtr << "\n");
658     (void)ActualPtr;
659
660     Result = JR->TheJIT->getPointerToFunction(F);
661   }
662
663   // Reacquire the lock to update the GOT map.
664   MutexGuard locked(JR->TheJIT->lock);
665
666   // We might like to remove the call site from the CallSiteToFunction map, but
667   // we can't do that! Multiple threads could be stuck, waiting to acquire the
668   // lock above. As soon as the 1st function finishes compiling the function,
669   // the next one will be released, and needs to be able to find the function it
670   // needs to call.
671
672   // FIXME: We could rewrite all references to this stub if we knew them.
673
674   // What we will do is set the compiled function address to map to the
675   // same GOT entry as the stub so that later clients may update the GOT
676   // if they see it still using the stub address.
677   // Note: this is done so the Resolver doesn't have to manage GOT memory
678   // Do this without allocating map space if the target isn't using a GOT
679   if(JR->revGOTMap.find(Stub) != JR->revGOTMap.end())
680     JR->revGOTMap[Result] = JR->revGOTMap[Stub];
681
682   return Result;
683 }
684
685 //===----------------------------------------------------------------------===//
686 // JITEmitter code.
687 //
688
689 static GlobalObject *getSimpleAliasee(Constant *C) {
690   C = C->stripPointerCasts();
691   return dyn_cast<GlobalObject>(C);
692 }
693
694 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
695                                      bool MayNeedFarStub) {
696   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
697     return TheJIT->getOrEmitGlobalVariable(GV);
698
699   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
700     // We can only handle simple cases.
701     if (GlobalValue *GV = getSimpleAliasee(GA->getAliasee()))
702       return TheJIT->getPointerToGlobal(GV);
703     return nullptr;
704   }
705
706   // If we have already compiled the function, return a pointer to its body.
707   Function *F = cast<Function>(V);
708
709   void *FnStub = Resolver.getLazyFunctionStubIfAvailable(F);
710   if (FnStub) {
711     // Return the function stub if it's already created.  We do this first so
712     // that we're returning the same address for the function as any previous
713     // call.  TODO: Yes, this is wrong. The lazy stub isn't guaranteed to be
714     // close enough to call.
715     return FnStub;
716   }
717
718   // If we know the target can handle arbitrary-distance calls, try to
719   // return a direct pointer.
720   if (!MayNeedFarStub) {
721     // If we have code, go ahead and return that.
722     void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
723     if (ResultPtr) return ResultPtr;
724
725     // If this is an external function pointer, we can force the JIT to
726     // 'compile' it, which really just adds it to the map.
727     if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage())
728       return TheJIT->getPointerToFunction(F);
729   }
730
731   // Otherwise, we may need a to emit a stub, and, conservatively, we always do
732   // so.  Note that it's possible to return null from getLazyFunctionStub in the
733   // case of a weak extern that fails to resolve.
734   return Resolver.getLazyFunctionStub(F);
735 }
736
737 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference) {
738   // Make sure GV is emitted first, and create a stub containing the fully
739   // resolved address.
740   void *GVAddress = getPointerToGlobal(V, Reference, false);
741   void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
742   return StubAddr;
743 }
744
745 void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
746   if (DL.isUnknown()) return;
747   if (!BeforePrintingInsn) return;
748
749   const LLVMContext &Context = EmissionDetails.MF->getFunction()->getContext();
750
751   if (DL.getScope(Context) != nullptr && PrevDL != DL) {
752     JITEvent_EmittedFunctionDetails::LineStart NextLine;
753     NextLine.Address = getCurrentPCValue();
754     NextLine.Loc = DL;
755     EmissionDetails.LineStarts.push_back(NextLine);
756   }
757
758   PrevDL = DL;
759 }
760
761 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
762                                            const DataLayout *TD) {
763   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
764   if (Constants.empty()) return 0;
765
766   unsigned Size = 0;
767   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
768     MachineConstantPoolEntry CPE = Constants[i];
769     unsigned AlignMask = CPE.getAlignment() - 1;
770     Size = (Size + AlignMask) & ~AlignMask;
771     Type *Ty = CPE.getType();
772     Size += TD->getTypeAllocSize(Ty);
773   }
774   return Size;
775 }
776
777 void JITEmitter::startFunction(MachineFunction &F) {
778   DEBUG(dbgs() << "JIT: Starting CodeGen of Function "
779         << F.getName() << "\n");
780
781   uintptr_t ActualSize = 0;
782   // Set the memory writable, if it's not already
783   MemMgr->setMemoryWritable();
784
785   if (SizeEstimate > 0) {
786     // SizeEstimate will be non-zero on reallocation attempts.
787     ActualSize = SizeEstimate;
788   }
789
790   BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
791                                                          ActualSize);
792   BufferEnd = BufferBegin+ActualSize;
793   EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
794
795   // Ensure the constant pool/jump table info is at least 4-byte aligned.
796   emitAlignment(16);
797
798   emitConstantPool(F.getConstantPool());
799   if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
800     initJumpTableInfo(MJTI);
801
802   // About to start emitting the machine code for the function.
803   emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
804   TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
805   EmittedFunctions[F.getFunction()].Code = CurBufferPtr;
806
807   MBBLocations.clear();
808
809   EmissionDetails.MF = &F;
810   EmissionDetails.LineStarts.clear();
811 }
812
813 bool JITEmitter::finishFunction(MachineFunction &F) {
814   if (CurBufferPtr == BufferEnd) {
815     // We must call endFunctionBody before retrying, because
816     // deallocateMemForFunction requires it.
817     MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
818     retryWithMoreMemory(F);
819     return true;
820   }
821
822   if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
823     emitJumpTableInfo(MJTI);
824
825   // FnStart is the start of the text, not the start of the constant pool and
826   // other per-function data.
827   uint8_t *FnStart =
828     (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
829
830   // FnEnd is the end of the function's machine code.
831   uint8_t *FnEnd = CurBufferPtr;
832
833   if (!Relocations.empty()) {
834     CurFn = F.getFunction();
835     NumRelos += Relocations.size();
836
837     // Resolve the relocations to concrete pointers.
838     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
839       MachineRelocation &MR = Relocations[i];
840       void *ResultPtr = nullptr;
841       if (!MR.letTargetResolve()) {
842         if (MR.isExternalSymbol()) {
843           ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
844                                                         false);
845           DEBUG(dbgs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
846                        << ResultPtr << "]\n");
847
848           // If the target REALLY wants a stub for this function, emit it now.
849           if (MR.mayNeedFarStub()) {
850             ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
851           }
852         } else if (MR.isGlobalValue()) {
853           ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
854                                          BufferBegin+MR.getMachineCodeOffset(),
855                                          MR.mayNeedFarStub());
856         } else if (MR.isIndirectSymbol()) {
857           ResultPtr = getPointerToGVIndirectSym(
858               MR.getGlobalValue(), BufferBegin+MR.getMachineCodeOffset());
859         } else if (MR.isBasicBlock()) {
860           ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
861         } else if (MR.isConstantPoolIndex()) {
862           ResultPtr =
863             (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
864         } else {
865           assert(MR.isJumpTableIndex());
866           ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
867         }
868
869         MR.setResultPointer(ResultPtr);
870       }
871
872       // if we are managing the GOT and the relocation wants an index,
873       // give it one
874       if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
875         unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
876         MR.setGOTIndex(idx);
877         if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
878           DEBUG(dbgs() << "JIT: GOT was out of date for " << ResultPtr
879                        << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
880                        << "\n");
881           ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
882         }
883       }
884     }
885
886     CurFn = nullptr;
887     TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
888                                   Relocations.size(), MemMgr->getGOTBase());
889   }
890
891   // Update the GOT entry for F to point to the new code.
892   if (MemMgr->isManagingGOT()) {
893     unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
894     if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
895       DEBUG(dbgs() << "JIT: GOT was out of date for " << (void*)BufferBegin
896                    << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
897                    << "\n");
898       ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
899     }
900   }
901
902   // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
903   // global variables that were referenced in the relocations.
904   MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
905
906   if (CurBufferPtr == BufferEnd) {
907     retryWithMoreMemory(F);
908     return true;
909   } else {
910     // Now that we've succeeded in emitting the function, reset the
911     // SizeEstimate back down to zero.
912     SizeEstimate = 0;
913   }
914
915   BufferBegin = CurBufferPtr = nullptr;
916   NumBytes += FnEnd-FnStart;
917
918   // Invalidate the icache if necessary.
919   sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
920
921   TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
922                                 EmissionDetails);
923
924   // Reset the previous debug location.
925   PrevDL = DebugLoc();
926
927   DEBUG(dbgs() << "JIT: Finished CodeGen of [" << (void*)FnStart
928         << "] Function: " << F.getName()
929         << ": " << (FnEnd-FnStart) << " bytes of text, "
930         << Relocations.size() << " relocations\n");
931
932   Relocations.clear();
933   ConstPoolAddresses.clear();
934
935   // Mark code region readable and executable if it's not so already.
936   MemMgr->setMemoryExecutable();
937
938   DEBUG({
939       if (sys::hasDisassembler()) {
940         dbgs() << "JIT: Disassembled code:\n";
941         dbgs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
942                                          (uintptr_t)FnStart);
943       } else {
944         dbgs() << "JIT: Binary code:\n";
945         uint8_t* q = FnStart;
946         for (int i = 0; q < FnEnd; q += 4, ++i) {
947           if (i == 4)
948             i = 0;
949           if (i == 0)
950             dbgs() << "JIT: " << (long)(q - FnStart) << ": ";
951           bool Done = false;
952           for (int j = 3; j >= 0; --j) {
953             if (q + j >= FnEnd)
954               Done = true;
955             else
956               dbgs() << (unsigned short)q[j];
957           }
958           if (Done)
959             break;
960           dbgs() << ' ';
961           if (i == 3)
962             dbgs() << '\n';
963         }
964         dbgs()<< '\n';
965       }
966     });
967
968   if (MMI)
969     MMI->EndFunction();
970
971   return false;
972 }
973
974 void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
975   DEBUG(dbgs() << "JIT: Ran out of space for native code.  Reattempting.\n");
976   Relocations.clear();  // Clear the old relocations or we'll reapply them.
977   ConstPoolAddresses.clear();
978   ++NumRetries;
979   deallocateMemForFunction(F.getFunction());
980   // Try again with at least twice as much free space.
981   SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
982
983   for (MachineFunction::iterator MBB = F.begin(), E = F.end(); MBB != E; ++MBB){
984     if (MBB->hasAddressTaken())
985       TheJIT->clearPointerToBasicBlock(MBB->getBasicBlock());
986   }
987 }
988
989 /// deallocateMemForFunction - Deallocate all memory for the specified
990 /// function body.  Also drop any references the function has to stubs.
991 /// May be called while the Function is being destroyed inside ~Value().
992 void JITEmitter::deallocateMemForFunction(const Function *F) {
993   ValueMap<const Function *, EmittedCode, EmittedFunctionConfig>::iterator
994     Emitted = EmittedFunctions.find(F);
995   if (Emitted != EmittedFunctions.end()) {
996     MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
997     TheJIT->NotifyFreeingMachineCode(Emitted->second.Code);
998
999     EmittedFunctions.erase(Emitted);
1000   }
1001 }
1002
1003
1004 void *JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1005   if (BufferBegin)
1006     return JITCodeEmitter::allocateSpace(Size, Alignment);
1007
1008   // create a new memory block if there is no active one.
1009   // care must be taken so that BufferBegin is invalidated when a
1010   // block is trimmed
1011   BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1012   BufferEnd = BufferBegin+Size;
1013   return CurBufferPtr;
1014 }
1015
1016 void *JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1017   // Delegate this call through the memory manager.
1018   return MemMgr->allocateGlobal(Size, Alignment);
1019 }
1020
1021 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1022   if (TheJIT->getJITInfo().hasCustomConstantPool())
1023     return;
1024
1025   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1026   if (Constants.empty()) return;
1027
1028   unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getDataLayout());
1029   unsigned Align = MCP->getConstantPoolAlignment();
1030   ConstantPoolBase = allocateSpace(Size, Align);
1031   ConstantPool = MCP;
1032
1033   if (!ConstantPoolBase) return;  // Buffer overflow.
1034
1035   DEBUG(dbgs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1036                << "] (size: " << Size << ", alignment: " << Align << ")\n");
1037
1038   // Initialize the memory for all of the constant pool entries.
1039   unsigned Offset = 0;
1040   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1041     MachineConstantPoolEntry CPE = Constants[i];
1042     unsigned AlignMask = CPE.getAlignment() - 1;
1043     Offset = (Offset + AlignMask) & ~AlignMask;
1044
1045     uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1046     ConstPoolAddresses.push_back(CAddr);
1047     if (CPE.isMachineConstantPoolEntry()) {
1048       // FIXME: add support to lower machine constant pool values into bytes!
1049       report_fatal_error("Initialize memory with machine specific constant pool"
1050                         "entry has not been implemented!");
1051     }
1052     TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1053     DEBUG(dbgs() << "JIT:   CP" << i << " at [0x";
1054           dbgs().write_hex(CAddr) << "]\n");
1055
1056     Type *Ty = CPE.Val.ConstVal->getType();
1057     Offset += TheJIT->getDataLayout()->getTypeAllocSize(Ty);
1058   }
1059 }
1060
1061 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1062   if (TheJIT->getJITInfo().hasCustomJumpTables())
1063     return;
1064   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline)
1065     return;
1066
1067   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1068   if (JT.empty()) return;
1069
1070   unsigned NumEntries = 0;
1071   for (unsigned i = 0, e = JT.size(); i != e; ++i)
1072     NumEntries += JT[i].MBBs.size();
1073
1074   unsigned EntrySize = MJTI->getEntrySize(*TheJIT->getDataLayout());
1075
1076   // Just allocate space for all the jump tables now.  We will fix up the actual
1077   // MBB entries in the tables after we emit the code for each block, since then
1078   // we will know the final locations of the MBBs in memory.
1079   JumpTable = MJTI;
1080   JumpTableBase = allocateSpace(NumEntries * EntrySize,
1081                              MJTI->getEntryAlignment(*TheJIT->getDataLayout()));
1082 }
1083
1084 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1085   if (TheJIT->getJITInfo().hasCustomJumpTables())
1086     return;
1087
1088   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1089   if (JT.empty() || !JumpTableBase) return;
1090
1091
1092   switch (MJTI->getEntryKind()) {
1093   case MachineJumpTableInfo::EK_Inline:
1094     return;
1095   case MachineJumpTableInfo::EK_BlockAddress: {
1096     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1097     //     .word LBB123
1098     assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == sizeof(void*) &&
1099            "Cross JIT'ing?");
1100
1101     // For each jump table, map each target in the jump table to the address of
1102     // an emitted MachineBasicBlock.
1103     intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1104
1105     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1106       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1107       // Store the address of the basic block for this jump table slot in the
1108       // memory we allocated for the jump table in 'initJumpTableInfo'
1109       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1110         *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1111     }
1112     break;
1113   }
1114
1115   case MachineJumpTableInfo::EK_Custom32:
1116   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1117   case MachineJumpTableInfo::EK_LabelDifference32: {
1118     assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == 4&&"Cross JIT'ing?");
1119     // For each jump table, place the offset from the beginning of the table
1120     // to the target address.
1121     int *SlotPtr = (int*)JumpTableBase;
1122
1123     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1124       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1125       // Store the offset of the basic block for this jump table slot in the
1126       // memory we allocated for the jump table in 'initJumpTableInfo'
1127       uintptr_t Base = (uintptr_t)SlotPtr;
1128       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1129         uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1130         /// FIXME: USe EntryKind instead of magic "getPICJumpTableEntry" hook.
1131         *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1132       }
1133     }
1134     break;
1135   }
1136   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1137     llvm_unreachable(
1138            "JT Info emission not implemented for GPRel64BlockAddress yet.");
1139   }
1140 }
1141
1142 void JITEmitter::startGVStub(const GlobalValue* GV,
1143                              unsigned StubSize, unsigned Alignment) {
1144   SavedBufferBegin = BufferBegin;
1145   SavedBufferEnd = BufferEnd;
1146   SavedCurBufferPtr = CurBufferPtr;
1147
1148   BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1149   BufferEnd = BufferBegin+StubSize+1;
1150 }
1151
1152 void JITEmitter::startGVStub(void *Buffer, unsigned StubSize) {
1153   SavedBufferBegin = BufferBegin;
1154   SavedBufferEnd = BufferEnd;
1155   SavedCurBufferPtr = CurBufferPtr;
1156
1157   BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1158   BufferEnd = BufferBegin+StubSize+1;
1159 }
1160
1161 void JITEmitter::finishGVStub() {
1162   assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
1163   NumBytes += getCurrentPCOffset();
1164   BufferBegin = SavedBufferBegin;
1165   BufferEnd = SavedBufferEnd;
1166   CurBufferPtr = SavedCurBufferPtr;
1167 }
1168
1169 void *JITEmitter::allocIndirectGV(const GlobalValue *GV,
1170                                   const uint8_t *Buffer, size_t Size,
1171                                   unsigned Alignment) {
1172   uint8_t *IndGV = MemMgr->allocateStub(GV, Size, Alignment);
1173   memcpy(IndGV, Buffer, Size);
1174   return IndGV;
1175 }
1176
1177 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1178 // in the constant pool that was last emitted with the 'emitConstantPool'
1179 // method.
1180 //
1181 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1182   assert(ConstantNum < ConstantPool->getConstants().size() &&
1183          "Invalid ConstantPoolIndex!");
1184   return ConstPoolAddresses[ConstantNum];
1185 }
1186
1187 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1188 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1189 //
1190 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1191   const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1192   assert(Index < JT.size() && "Invalid jump table index!");
1193
1194   unsigned EntrySize = JumpTable->getEntrySize(*TheJIT->getDataLayout());
1195
1196   unsigned Offset = 0;
1197   for (unsigned i = 0; i < Index; ++i)
1198     Offset += JT[i].MBBs.size();
1199
1200    Offset *= EntrySize;
1201
1202   return (uintptr_t)((char *)JumpTableBase + Offset);
1203 }
1204
1205 void JITEmitter::EmittedFunctionConfig::onDelete(
1206   JITEmitter *Emitter, const Function *F) {
1207   Emitter->deallocateMemForFunction(F);
1208 }
1209 void JITEmitter::EmittedFunctionConfig::onRAUW(
1210   JITEmitter *, const Function*, const Function*) {
1211   llvm_unreachable("The JIT doesn't know how to handle a"
1212                    " RAUW on a value it has emitted.");
1213 }
1214
1215
1216 //===----------------------------------------------------------------------===//
1217 //  Public interface to this file
1218 //===----------------------------------------------------------------------===//
1219
1220 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1221                                    TargetMachine &tm) {
1222   return new JITEmitter(jit, JMM, tm);
1223 }
1224
1225 // getPointerToFunctionOrStub - If the specified function has been
1226 // code-gen'd, return a pointer to the function.  If not, compile it, or use
1227 // a stub to implement lazy compilation if available.
1228 //
1229 void *JIT::getPointerToFunctionOrStub(Function *F) {
1230   // If we have already code generated the function, just return the address.
1231   if (void *Addr = getPointerToGlobalIfAvailable(F))
1232     return Addr;
1233
1234   // Get a stub if the target supports it.
1235   JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1236   return JE->getJITResolver().getLazyFunctionStub(F);
1237 }
1238
1239 void JIT::updateFunctionStubUnlocked(Function *F) {
1240   // Get the empty stub we generated earlier.
1241   JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1242   void *Stub = JE->getJITResolver().getLazyFunctionStub(F);
1243   void *Addr = getPointerToGlobalIfAvailable(F);
1244   assert(Addr != Stub && "Function must have non-stub address to be updated.");
1245
1246   // Tell the target jit info to rewrite the stub at the specified address,
1247   // rather than creating a new one.
1248   TargetJITInfo::StubLayout layout = getJITInfo().getStubLayout();
1249   JE->startGVStub(Stub, layout.Size);
1250   getJITInfo().emitFunctionStub(F, Addr, *getCodeEmitter());
1251   JE->finishGVStub();
1252 }
1253
1254 /// freeMachineCodeForFunction - release machine code memory for given Function.
1255 ///
1256 void JIT::freeMachineCodeForFunction(Function *F) {
1257   // Delete translation for this from the ExecutionEngine, so it will get
1258   // retranslated next time it is used.
1259   updateGlobalMapping(F, nullptr);
1260
1261   // Free the actual memory for the function body and related stuff.
1262   static_cast<JITEmitter*>(JCE)->deallocateMemForFunction(F);
1263 }