Change indirect-globals to use a dedicated allocIndirectGV. This lets us
[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 #define DEBUG_TYPE "jit"
16 #include "JIT.h"
17 #include "JITDebugRegisterer.h"
18 #include "JITDwarfEmitter.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Module.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/CodeGen/JITCodeEmitter.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRelocation.h"
29 #include "llvm/ExecutionEngine/GenericValue.h"
30 #include "llvm/ExecutionEngine/JITEventListener.h"
31 #include "llvm/ExecutionEngine/JITMemoryManager.h"
32 #include "llvm/CodeGen/MachineCodeInfo.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetJITInfo.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MutexGuard.h"
40 #include "llvm/Support/ValueHandle.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/System/Disassembler.h"
43 #include "llvm/System/Memory.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/ADT/DenseMap.h"
46 #include "llvm/ADT/SmallPtrSet.h"
47 #include "llvm/ADT/SmallVector.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/ADT/ValueMap.h"
50 #include <algorithm>
51 #ifndef NDEBUG
52 #include <iomanip>
53 #endif
54 using namespace llvm;
55
56 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
57 STATISTIC(NumRelos, "Number of relocations applied");
58 STATISTIC(NumRetries, "Number of retries with more memory");
59 static JIT *TheJIT = 0;
60
61
62 //===----------------------------------------------------------------------===//
63 // JIT lazy compilation code.
64 //
65 namespace {
66   class JITEmitter;
67   class JITResolverState;
68
69   template<typename ValueTy>
70   struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
71     typedef JITResolverState *ExtraData;
72     static void onRAUW(JITResolverState *, Value *Old, Value *New) {
73       assert(false && "The JIT doesn't know how to handle a"
74              " RAUW on a value it has emitted.");
75     }
76   };
77
78   struct CallSiteValueMapConfig : public NoRAUWValueMapConfig<Function*> {
79     typedef JITResolverState *ExtraData;
80     static void onDelete(JITResolverState *JRS, Function *F);
81   };
82
83   class JITResolverState {
84   public:
85     typedef ValueMap<Function*, void*, NoRAUWValueMapConfig<Function*> >
86       FunctionToLazyStubMapTy;
87     typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
88     typedef ValueMap<Function *, SmallPtrSet<void*, 1>,
89                      CallSiteValueMapConfig> FunctionToCallSitesMapTy;
90     typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
91   private:
92     /// FunctionToLazyStubMap - Keep track of the lazy stub created for a
93     /// particular function so that we can reuse them if necessary.
94     FunctionToLazyStubMapTy FunctionToLazyStubMap;
95
96     /// CallSiteToFunctionMap - Keep track of the function that each lazy call
97     /// site corresponds to, and vice versa.
98     CallSiteToFunctionMapTy CallSiteToFunctionMap;
99     FunctionToCallSitesMapTy FunctionToCallSitesMap;
100
101     /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
102     /// particular GlobalVariable so that we can reuse them if necessary.
103     GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
104
105   public:
106     JITResolverState() : FunctionToLazyStubMap(this),
107                          FunctionToCallSitesMap(this) {}
108
109     FunctionToLazyStubMapTy& getFunctionToLazyStubMap(
110       const MutexGuard& locked) {
111       assert(locked.holds(TheJIT->lock));
112       return FunctionToLazyStubMap;
113     }
114
115     GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
116       assert(locked.holds(TheJIT->lock));
117       return GlobalToIndirectSymMap;
118     }
119
120     pair<void *, Function *> LookupFunctionFromCallSite(
121         const MutexGuard &locked, void *CallSite) const {
122       assert(locked.holds(TheJIT->lock));
123
124       // The address given to us for the stub may not be exactly right, it might be
125       // a little bit after the stub.  As such, use upper_bound to find it.
126       CallSiteToFunctionMapTy::const_iterator I =
127         CallSiteToFunctionMap.upper_bound(CallSite);
128       assert(I != CallSiteToFunctionMap.begin() &&
129              "This is not a known call site!");
130       --I;
131       return *I;
132     }
133
134     void AddCallSite(const MutexGuard &locked, void *CallSite, Function *F) {
135       assert(locked.holds(TheJIT->lock));
136
137       bool Inserted = CallSiteToFunctionMap.insert(
138           std::make_pair(CallSite, F)).second;
139       (void)Inserted;
140       assert(Inserted && "Pair was already in CallSiteToFunctionMap");
141       FunctionToCallSitesMap[F].insert(CallSite);
142     }
143
144     // Returns the Function of the stub if a stub was erased, or NULL if there
145     // was no stub.  This function uses the call-site->function map to find a
146     // relevant function, but asserts that only stubs and not other call sites
147     // will be passed in.
148     Function *EraseStub(const MutexGuard &locked, void *Stub) {
149       CallSiteToFunctionMapTy::iterator C2F_I =
150         CallSiteToFunctionMap.find(Stub);
151       if (C2F_I == CallSiteToFunctionMap.end()) {
152         // Not a stub.
153         return NULL;
154       }
155
156       Function *const F = C2F_I->second;
157 #ifndef NDEBUG
158       void *RealStub = FunctionToLazyStubMap.lookup(F);
159       assert(RealStub == Stub &&
160              "Call-site that wasn't a stub pass in to EraseStub");
161 #endif
162       FunctionToLazyStubMap.erase(F);
163       CallSiteToFunctionMap.erase(C2F_I);
164
165       // Remove the stub from the function->call-sites map, and remove the whole
166       // entry from the map if that was the last call site.
167       FunctionToCallSitesMapTy::iterator F2C_I = FunctionToCallSitesMap.find(F);
168       assert(F2C_I != FunctionToCallSitesMap.end() &&
169              "FunctionToCallSitesMap broken");
170       bool Erased = F2C_I->second.erase(Stub);
171       (void)Erased;
172       assert(Erased && "FunctionToCallSitesMap broken");
173       if (F2C_I->second.empty())
174         FunctionToCallSitesMap.erase(F2C_I);
175
176       return F;
177     }
178
179     void EraseAllCallSites(const MutexGuard &locked, Function *F) {
180       assert(locked.holds(TheJIT->lock));
181       EraseAllCallSitesPrelocked(F);
182     }
183     void EraseAllCallSitesPrelocked(Function *F) {
184       FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
185       if (F2C == FunctionToCallSitesMap.end())
186         return;
187       for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
188              E = F2C->second.end(); I != E; ++I) {
189         bool Erased = CallSiteToFunctionMap.erase(*I);
190         (void)Erased;
191         assert(Erased && "Missing call site->function mapping");
192       }
193       FunctionToCallSitesMap.erase(F2C);
194     }
195   };
196
197   /// JITResolver - Keep track of, and resolve, call sites for functions that
198   /// have not yet been compiled.
199   class JITResolver {
200     typedef JITResolverState::FunctionToLazyStubMapTy FunctionToLazyStubMapTy;
201     typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
202     typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
203
204     /// LazyResolverFn - The target lazy resolver function that we actually
205     /// rewrite instructions to use.
206     TargetJITInfo::LazyResolverFn LazyResolverFn;
207
208     JITResolverState state;
209
210     /// ExternalFnToStubMap - This is the equivalent of FunctionToLazyStubMap
211     /// for external functions.  TODO: Of course, external functions don't need
212     /// a lazy stub.  It's actually here to make it more likely that far calls
213     /// succeed, but no single stub can guarantee that.  I'll remove this in a
214     /// subsequent checkin when I actually fix far calls.
215     std::map<void*, void*> ExternalFnToStubMap;
216
217     /// revGOTMap - map addresses to indexes in the GOT
218     std::map<void*, unsigned> revGOTMap;
219     unsigned nextGOTIndex;
220
221     JITEmitter &JE;
222
223     static JITResolver *TheJITResolver;
224   public:
225     explicit JITResolver(JIT &jit, JITEmitter &je) : nextGOTIndex(0), JE(je) {
226       TheJIT = &jit;
227
228       LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
229       assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
230       TheJITResolver = this;
231     }
232
233     ~JITResolver() {
234       TheJITResolver = 0;
235     }
236
237     /// getLazyFunctionStubIfAvailable - This returns a pointer to a function's
238     /// lazy-compilation stub if it has already been created.
239     void *getLazyFunctionStubIfAvailable(Function *F);
240
241     /// getLazyFunctionStub - This returns a pointer to a function's
242     /// lazy-compilation stub, creating one on demand as needed.
243     void *getLazyFunctionStub(Function *F);
244
245     /// getExternalFunctionStub - Return a stub for the function at the
246     /// specified address, created lazily on demand.
247     void *getExternalFunctionStub(void *FnAddr);
248
249     /// getGlobalValueIndirectSym - Return an indirect symbol containing the
250     /// specified GV address.
251     void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
252
253     void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
254                            SmallVectorImpl<void*> &Ptrs);
255
256     GlobalValue *invalidateStub(void *Stub);
257
258     /// getGOTIndexForAddress - Return a new or existing index in the GOT for
259     /// an address.  This function only manages slots, it does not manage the
260     /// contents of the slots or the memory associated with the GOT.
261     unsigned getGOTIndexForAddr(void *addr);
262
263     /// JITCompilerFn - This function is called to resolve a stub to a compiled
264     /// address.  If the LLVM Function corresponding to the stub has not yet
265     /// been compiled, this function compiles it first.
266     static void *JITCompilerFn(void *Stub);
267   };
268
269   /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
270   /// used to output functions to memory for execution.
271   class JITEmitter : public JITCodeEmitter {
272     JITMemoryManager *MemMgr;
273
274     // When outputting a function stub in the context of some other function, we
275     // save BufferBegin/BufferEnd/CurBufferPtr here.
276     uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
277
278     // When reattempting to JIT a function after running out of space, we store
279     // the estimated size of the function we're trying to JIT here, so we can
280     // ask the memory manager for at least this much space.  When we
281     // successfully emit the function, we reset this back to zero.
282     uintptr_t SizeEstimate;
283
284     /// Relocations - These are the relocations that the function needs, as
285     /// emitted.
286     std::vector<MachineRelocation> Relocations;
287
288     /// MBBLocations - This vector is a mapping from MBB ID's to their address.
289     /// It is filled in by the StartMachineBasicBlock callback and queried by
290     /// the getMachineBasicBlockAddress callback.
291     std::vector<uintptr_t> MBBLocations;
292
293     /// ConstantPool - The constant pool for the current function.
294     ///
295     MachineConstantPool *ConstantPool;
296
297     /// ConstantPoolBase - A pointer to the first entry in the constant pool.
298     ///
299     void *ConstantPoolBase;
300
301     /// ConstPoolAddresses - Addresses of individual constant pool entries.
302     ///
303     SmallVector<uintptr_t, 8> ConstPoolAddresses;
304
305     /// JumpTable - The jump tables for the current function.
306     ///
307     MachineJumpTableInfo *JumpTable;
308
309     /// JumpTableBase - A pointer to the first entry in the jump table.
310     ///
311     void *JumpTableBase;
312
313     /// Resolver - This contains info about the currently resolved functions.
314     JITResolver Resolver;
315
316     /// DE - The dwarf emitter for the jit.
317     OwningPtr<JITDwarfEmitter> DE;
318
319     /// DR - The debug registerer for the jit.
320     OwningPtr<JITDebugRegisterer> DR;
321
322     /// LabelLocations - This vector is a mapping from Label ID's to their
323     /// address.
324     std::vector<uintptr_t> LabelLocations;
325
326     /// MMI - Machine module info for exception informations
327     MachineModuleInfo* MMI;
328
329     // GVSet - a set to keep track of which globals have been seen
330     SmallPtrSet<const GlobalVariable*, 8> GVSet;
331
332     // CurFn - The llvm function being emitted.  Only valid during
333     // finishFunction().
334     const Function *CurFn;
335
336     /// Information about emitted code, which is passed to the
337     /// JITEventListeners.  This is reset in startFunction and used in
338     /// finishFunction.
339     JITEvent_EmittedFunctionDetails EmissionDetails;
340
341     struct EmittedCode {
342       void *FunctionBody;  // Beginning of the function's allocation.
343       void *Code;  // The address the function's code actually starts at.
344       void *ExceptionTable;
345       EmittedCode() : FunctionBody(0), Code(0), ExceptionTable(0) {}
346     };
347     struct EmittedFunctionConfig : public ValueMapConfig<const Function*> {
348       typedef JITEmitter *ExtraData;
349       static void onDelete(JITEmitter *, const Function*);
350       static void onRAUW(JITEmitter *, const Function*, const Function*);
351     };
352     ValueMap<const Function *, EmittedCode,
353              EmittedFunctionConfig> EmittedFunctions;
354
355     // CurFnStubUses - For a given Function, a vector of stubs that it
356     // references.  This facilitates the JIT detecting that a stub is no
357     // longer used, so that it may be deallocated.
358     DenseMap<AssertingVH<const Function>, SmallVector<void*, 1> > CurFnStubUses;
359
360     // StubFnRefs - For a given pointer to a stub, a set of Functions which
361     // reference the stub.  When the count of a stub's references drops to zero,
362     // the stub is unused.
363     DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
364
365     DebugLocTuple PrevDLT;
366
367   public:
368     JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
369       : SizeEstimate(0), Resolver(jit, *this), MMI(0), CurFn(0),
370           EmittedFunctions(this) {
371       MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
372       if (jit.getJITInfo().needsGOT()) {
373         MemMgr->AllocateGOT();
374         DEBUG(errs() << "JIT is managing a GOT\n");
375       }
376
377       if (DwarfExceptionHandling || JITEmitDebugInfo) {
378         DE.reset(new JITDwarfEmitter(jit));
379       }
380       if (JITEmitDebugInfo) {
381         DR.reset(new JITDebugRegisterer(TM));
382       }
383     }
384     ~JITEmitter() {
385       delete MemMgr;
386     }
387
388     /// classof - Methods for support type inquiry through isa, cast, and
389     /// dyn_cast:
390     ///
391     static inline bool classof(const JITEmitter*) { return true; }
392     static inline bool classof(const MachineCodeEmitter*) { return true; }
393
394     JITResolver &getJITResolver() { return Resolver; }
395
396     virtual void startFunction(MachineFunction &F);
397     virtual bool finishFunction(MachineFunction &F);
398
399     void emitConstantPool(MachineConstantPool *MCP);
400     void initJumpTableInfo(MachineJumpTableInfo *MJTI);
401     void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
402
403     void startGVStub(const GlobalValue* GV,
404                      unsigned StubSize, unsigned Alignment = 1);
405     void startGVStub(void *Buffer, unsigned StubSize);
406     void finishGVStub();
407     virtual void *allocIndirectGV(const GlobalValue *GV,
408                                   const uint8_t *Buffer, size_t Size,
409                                   unsigned Alignment);
410
411     /// allocateSpace - Reserves space in the current block if any, or
412     /// allocate a new one of the given size.
413     virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
414
415     /// allocateGlobal - Allocate memory for a global.  Unlike allocateSpace,
416     /// this method does not allocate memory in the current output buffer,
417     /// because a global may live longer than the current function.
418     virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
419
420     virtual void addRelocation(const MachineRelocation &MR) {
421       Relocations.push_back(MR);
422     }
423
424     virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
425       if (MBBLocations.size() <= (unsigned)MBB->getNumber())
426         MBBLocations.resize((MBB->getNumber()+1)*2);
427       MBBLocations[MBB->getNumber()] = getCurrentPCValue();
428       DEBUG(errs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
429                    << (void*) getCurrentPCValue() << "]\n");
430     }
431
432     virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
433     virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
434
435     virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
436       assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
437              MBBLocations[MBB->getNumber()] && "MBB not emitted!");
438       return MBBLocations[MBB->getNumber()];
439     }
440
441     /// retryWithMoreMemory - Log a retry and deallocate all memory for the
442     /// given function.  Increase the minimum allocation size so that we get
443     /// more memory next time.
444     void retryWithMoreMemory(MachineFunction &F);
445
446     /// deallocateMemForFunction - Deallocate all memory for the specified
447     /// function body.
448     void deallocateMemForFunction(const Function *F);
449
450     /// AddStubToCurrentFunction - Mark the current function being JIT'd as
451     /// using the stub at the specified address. Allows
452     /// deallocateMemForFunction to also remove stubs no longer referenced.
453     void AddStubToCurrentFunction(void *Stub);
454
455     virtual void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn);
456
457     virtual void emitLabel(uint64_t LabelID) {
458       if (LabelLocations.size() <= LabelID)
459         LabelLocations.resize((LabelID+1)*2);
460       LabelLocations[LabelID] = getCurrentPCValue();
461     }
462
463     virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
464       assert(LabelLocations.size() > (unsigned)LabelID &&
465              LabelLocations[LabelID] && "Label not emitted!");
466       return LabelLocations[LabelID];
467     }
468
469     virtual void setModuleInfo(MachineModuleInfo* Info) {
470       MMI = Info;
471       if (DE.get()) DE->setModuleInfo(Info);
472     }
473
474     void setMemoryExecutable() {
475       MemMgr->setMemoryExecutable();
476     }
477
478     JITMemoryManager *getMemMgr() const { return MemMgr; }
479
480   private:
481     void *getPointerToGlobal(GlobalValue *GV, void *Reference,
482                              bool MayNeedFarStub);
483     void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference);
484     unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
485     unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
486     unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
487     unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
488   };
489 }
490
491 JITResolver *JITResolver::TheJITResolver = 0;
492
493 void CallSiteValueMapConfig::onDelete(JITResolverState *JRS, Function *F) {
494   JRS->EraseAllCallSitesPrelocked(F);
495 }
496
497 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function stub
498 /// if it has already been created.
499 void *JITResolver::getLazyFunctionStubIfAvailable(Function *F) {
500   MutexGuard locked(TheJIT->lock);
501
502   // If we already have a stub for this function, recycle it.
503   return state.getFunctionToLazyStubMap(locked).lookup(F);
504 }
505
506 /// getFunctionStub - This returns a pointer to a function stub, creating
507 /// one on demand as needed.
508 void *JITResolver::getLazyFunctionStub(Function *F) {
509   MutexGuard locked(TheJIT->lock);
510
511   // If we already have a lazy stub for this function, recycle it.
512   void *&Stub = state.getFunctionToLazyStubMap(locked)[F];
513   if (Stub) return Stub;
514
515   // Call the lazy resolver function if we are JIT'ing lazily.  Otherwise we
516   // must resolve the symbol now.
517   void *Actual = TheJIT->isCompilingLazily()
518     ? (void *)(intptr_t)LazyResolverFn : (void *)0;
519
520   // If this is an external declaration, attempt to resolve the address now
521   // to place in the stub.
522   if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
523     Actual = TheJIT->getPointerToFunction(F);
524
525     // If we resolved the symbol to a null address (eg. a weak external)
526     // don't emit a stub. Return a null pointer to the application.
527     if (!Actual) return 0;
528   }
529
530   TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
531   JE.startGVStub(F, SL.Size, SL.Alignment);
532   // Codegen a new stub, calling the lazy resolver or the actual address of the
533   // external function, if it was resolved.
534   Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual, JE);
535   JE.finishGVStub();
536
537   if (Actual != (void*)(intptr_t)LazyResolverFn) {
538     // If we are getting the stub for an external function, we really want the
539     // address of the stub in the GlobalAddressMap for the JIT, not the address
540     // of the external function.
541     TheJIT->updateGlobalMapping(F, Stub);
542   }
543
544   DEBUG(errs() << "JIT: Lazy stub emitted at [" << Stub << "] for function '"
545         << F->getName() << "'\n");
546
547   // Finally, keep track of the stub-to-Function mapping so that the
548   // JITCompilerFn knows which function to compile!
549   state.AddCallSite(locked, Stub, F);
550
551   // If we are JIT'ing non-lazily but need to call a function that does not
552   // exist yet, add it to the JIT's work list so that we can fill in the stub
553   // address later.
554   if (!Actual && !TheJIT->isCompilingLazily())
555     if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
556       TheJIT->addPendingFunction(F);
557
558   return Stub;
559 }
560
561 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
562 /// GV address.
563 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
564   MutexGuard locked(TheJIT->lock);
565
566   // If we already have a stub for this global variable, recycle it.
567   void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
568   if (IndirectSym) return IndirectSym;
569
570   // Otherwise, codegen a new indirect symbol.
571   IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
572                                                                 JE);
573
574   DEBUG(errs() << "JIT: Indirect symbol emitted at [" << IndirectSym
575         << "] for GV '" << GV->getName() << "'\n");
576
577   return IndirectSym;
578 }
579
580 /// getExternalFunctionStub - Return a stub for the function at the
581 /// specified address, created lazily on demand.
582 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
583   // If we already have a stub for this function, recycle it.
584   void *&Stub = ExternalFnToStubMap[FnAddr];
585   if (Stub) return Stub;
586
587   TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
588   JE.startGVStub(0, SL.Size, SL.Alignment);
589   Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr, JE);
590   JE.finishGVStub();
591
592   DEBUG(errs() << "JIT: Stub emitted at [" << Stub
593                << "] for external function at '" << FnAddr << "'\n");
594   return Stub;
595 }
596
597 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
598   unsigned idx = revGOTMap[addr];
599   if (!idx) {
600     idx = ++nextGOTIndex;
601     revGOTMap[addr] = idx;
602     DEBUG(errs() << "JIT: Adding GOT entry " << idx << " for addr ["
603                  << addr << "]\n");
604   }
605   return idx;
606 }
607
608 void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
609                                     SmallVectorImpl<void*> &Ptrs) {
610   MutexGuard locked(TheJIT->lock);
611
612   const FunctionToLazyStubMapTy &FM = state.getFunctionToLazyStubMap(locked);
613   GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
614
615   for (FunctionToLazyStubMapTy::const_iterator i = FM.begin(), e = FM.end();
616        i != e; ++i){
617     Function *F = i->first;
618     if (F->isDeclaration() && F->hasExternalLinkage()) {
619       GVs.push_back(i->first);
620       Ptrs.push_back(i->second);
621     }
622   }
623   for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
624        i != e; ++i) {
625     GVs.push_back(i->first);
626     Ptrs.push_back(i->second);
627   }
628 }
629
630 GlobalValue *JITResolver::invalidateStub(void *Stub) {
631   MutexGuard locked(TheJIT->lock);
632
633   GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
634
635   // Look up the cheap way first, to see if it's a function stub we are
636   // invalidating.  If so, remove it from both the forward and reverse maps.
637   if (Function *F = state.EraseStub(locked, Stub)) {
638     return F;
639   }
640
641   // Otherwise, it might be an indirect symbol stub.  Find it and remove it.
642   for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
643        i != e; ++i) {
644     if (i->second != Stub)
645       continue;
646     GlobalValue *GV = i->first;
647     GM.erase(i);
648     return GV;
649   }
650
651   // Lastly, check to see if it's in the ExternalFnToStubMap.
652   for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
653        e = ExternalFnToStubMap.end(); i != e; ++i) {
654     if (i->second != Stub)
655       continue;
656     ExternalFnToStubMap.erase(i);
657     break;
658   }
659
660   return 0;
661 }
662
663 /// JITCompilerFn - This function is called when a lazy compilation stub has
664 /// been entered.  It looks up which function this stub corresponds to, compiles
665 /// it if necessary, then returns the resultant function pointer.
666 void *JITResolver::JITCompilerFn(void *Stub) {
667   JITResolver &JR = *TheJITResolver;
668
669   Function* F = 0;
670   void* ActualPtr = 0;
671
672   {
673     // Only lock for getting the Function. The call getPointerToFunction made
674     // in this function might trigger function materializing, which requires
675     // JIT lock to be unlocked.
676     MutexGuard locked(TheJIT->lock);
677
678     // The address given to us for the stub may not be exactly right, it might
679     // be a little bit after the stub.  As such, use upper_bound to find it.
680     pair<void*, Function*> I =
681       JR.state.LookupFunctionFromCallSite(locked, Stub);
682     F = I.second;
683     ActualPtr = I.first;
684   }
685
686   // If we have already code generated the function, just return the address.
687   void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
688
689   if (!Result) {
690     // Otherwise we don't have it, do lazy compilation now.
691
692     // If lazy compilation is disabled, emit a useful error message and abort.
693     if (!TheJIT->isCompilingLazily()) {
694       llvm_report_error("LLVM JIT requested to do lazy compilation of function '"
695                         + F->getName() + "' when lazy compiles are disabled!");
696     }
697
698     DEBUG(errs() << "JIT: Lazily resolving function '" << F->getName()
699           << "' In stub ptr = " << Stub << " actual ptr = "
700           << ActualPtr << "\n");
701
702     Result = TheJIT->getPointerToFunction(F);
703   }
704
705   // Reacquire the lock to update the GOT map.
706   MutexGuard locked(TheJIT->lock);
707
708   // We might like to remove the call site from the CallSiteToFunction map, but
709   // we can't do that! Multiple threads could be stuck, waiting to acquire the
710   // lock above. As soon as the 1st function finishes compiling the function,
711   // the next one will be released, and needs to be able to find the function it
712   // needs to call.
713
714   // FIXME: We could rewrite all references to this stub if we knew them.
715
716   // What we will do is set the compiled function address to map to the
717   // same GOT entry as the stub so that later clients may update the GOT
718   // if they see it still using the stub address.
719   // Note: this is done so the Resolver doesn't have to manage GOT memory
720   // Do this without allocating map space if the target isn't using a GOT
721   if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
722     JR.revGOTMap[Result] = JR.revGOTMap[Stub];
723
724   return Result;
725 }
726
727 //===----------------------------------------------------------------------===//
728 // JITEmitter code.
729 //
730 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
731                                      bool MayNeedFarStub) {
732   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
733     return TheJIT->getOrEmitGlobalVariable(GV);
734
735   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
736     return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
737
738   // If we have already compiled the function, return a pointer to its body.
739   Function *F = cast<Function>(V);
740
741   void *FnStub = Resolver.getLazyFunctionStubIfAvailable(F);
742   if (FnStub) {
743     // Return the function stub if it's already created.  We do this first so
744     // that we're returning the same address for the function as any previous
745     // call.  TODO: Yes, this is wrong. The lazy stub isn't guaranteed to be
746     // close enough to call.
747     AddStubToCurrentFunction(FnStub);
748     return FnStub;
749   }
750
751   // If we know the target can handle arbitrary-distance calls, try to
752   // return a direct pointer.
753   if (!MayNeedFarStub) {
754     // If we have code, go ahead and return that.
755     void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
756     if (ResultPtr) return ResultPtr;
757
758     // If this is an external function pointer, we can force the JIT to
759     // 'compile' it, which really just adds it to the map.
760     if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
761       return TheJIT->getPointerToFunction(F);
762   }
763
764   // Otherwise, we may need a to emit a stub, and, conservatively, we
765   // always do so.
766   void *StubAddr = Resolver.getLazyFunctionStub(F);
767
768   // Add the stub to the current function's list of referenced stubs, so we can
769   // deallocate them if the current function is ever freed.  It's possible to
770   // return null from getLazyFunctionStub in the case of a weak extern that
771   // fails to resolve.
772   if (StubAddr)
773     AddStubToCurrentFunction(StubAddr);
774
775   return StubAddr;
776 }
777
778 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference) {
779   // Make sure GV is emitted first, and create a stub containing the fully
780   // resolved address.
781   void *GVAddress = getPointerToGlobal(V, Reference, false);
782   void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
783
784   // Add the stub to the current function's list of referenced stubs, so we can
785   // deallocate them if the current function is ever freed.
786   AddStubToCurrentFunction(StubAddr);
787
788   return StubAddr;
789 }
790
791 void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
792   assert(CurFn && "Stub added to current function, but current function is 0!");
793
794   SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
795   StubsUsed.push_back(StubAddr);
796
797   SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
798   FnRefs.insert(CurFn);
799 }
800
801 void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
802   if (!DL.isUnknown()) {
803     DebugLocTuple CurDLT = EmissionDetails.MF->getDebugLocTuple(DL);
804
805     if (BeforePrintingInsn) {
806       if (CurDLT.Scope != 0 && PrevDLT != CurDLT) {
807         JITEvent_EmittedFunctionDetails::LineStart NextLine;
808         NextLine.Address = getCurrentPCValue();
809         NextLine.Loc = DL;
810         EmissionDetails.LineStarts.push_back(NextLine);
811       }
812
813       PrevDLT = CurDLT;
814     }
815   }
816 }
817
818 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
819                                            const TargetData *TD) {
820   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
821   if (Constants.empty()) return 0;
822
823   unsigned Size = 0;
824   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
825     MachineConstantPoolEntry CPE = Constants[i];
826     unsigned AlignMask = CPE.getAlignment() - 1;
827     Size = (Size + AlignMask) & ~AlignMask;
828     const Type *Ty = CPE.getType();
829     Size += TD->getTypeAllocSize(Ty);
830   }
831   return Size;
832 }
833
834 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
835   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
836   if (JT.empty()) return 0;
837
838   unsigned NumEntries = 0;
839   for (unsigned i = 0, e = JT.size(); i != e; ++i)
840     NumEntries += JT[i].MBBs.size();
841
842   unsigned EntrySize = MJTI->getEntrySize();
843
844   return NumEntries * EntrySize;
845 }
846
847 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
848   if (Alignment == 0) Alignment = 1;
849   // Since we do not know where the buffer will be allocated, be pessimistic.
850   return Size + Alignment;
851 }
852
853 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
854 /// into the running total Size.
855
856 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
857   const Type *ElTy = GV->getType()->getElementType();
858   size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
859   size_t GVAlign =
860       (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
861   DEBUG(errs() << "JIT: Adding in size " << GVSize << " alignment " << GVAlign);
862   DEBUG(GV->dump());
863   // Assume code section ends with worst possible alignment, so first
864   // variable needs maximal padding.
865   if (Size==0)
866     Size = 1;
867   Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
868   Size += GVSize;
869   return Size;
870 }
871
872 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
873 /// but are referenced from the constant; put them in GVSet and add their
874 /// size into the running total Size.
875
876 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
877                                               unsigned Size) {
878   // If its undefined, return the garbage.
879   if (isa<UndefValue>(C))
880     return Size;
881
882   // If the value is a ConstantExpr
883   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
884     Constant *Op0 = CE->getOperand(0);
885     switch (CE->getOpcode()) {
886     case Instruction::GetElementPtr:
887     case Instruction::Trunc:
888     case Instruction::ZExt:
889     case Instruction::SExt:
890     case Instruction::FPTrunc:
891     case Instruction::FPExt:
892     case Instruction::UIToFP:
893     case Instruction::SIToFP:
894     case Instruction::FPToUI:
895     case Instruction::FPToSI:
896     case Instruction::PtrToInt:
897     case Instruction::IntToPtr:
898     case Instruction::BitCast: {
899       Size = addSizeOfGlobalsInConstantVal(Op0, Size);
900       break;
901     }
902     case Instruction::Add:
903     case Instruction::FAdd:
904     case Instruction::Sub:
905     case Instruction::FSub:
906     case Instruction::Mul:
907     case Instruction::FMul:
908     case Instruction::UDiv:
909     case Instruction::SDiv:
910     case Instruction::URem:
911     case Instruction::SRem:
912     case Instruction::And:
913     case Instruction::Or:
914     case Instruction::Xor: {
915       Size = addSizeOfGlobalsInConstantVal(Op0, Size);
916       Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
917       break;
918     }
919     default: {
920        std::string msg;
921        raw_string_ostream Msg(msg);
922        Msg << "ConstantExpr not handled: " << *CE;
923        llvm_report_error(Msg.str());
924     }
925     }
926   }
927
928   if (C->getType()->getTypeID() == Type::PointerTyID)
929     if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
930       if (GVSet.insert(GV))
931         Size = addSizeOfGlobal(GV, Size);
932
933   return Size;
934 }
935
936 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
937 /// but are referenced from the given initializer.
938
939 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
940                                               unsigned Size) {
941   if (!isa<UndefValue>(Init) &&
942       !isa<ConstantVector>(Init) &&
943       !isa<ConstantAggregateZero>(Init) &&
944       !isa<ConstantArray>(Init) &&
945       !isa<ConstantStruct>(Init) &&
946       Init->getType()->isFirstClassType())
947     Size = addSizeOfGlobalsInConstantVal(Init, Size);
948   return Size;
949 }
950
951 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
952 /// globals; then walk the initializers of those globals looking for more.
953 /// If their size has not been considered yet, add it into the running total
954 /// Size.
955
956 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
957   unsigned Size = 0;
958   GVSet.clear();
959
960   for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
961        MBB != E; ++MBB) {
962     for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
963          I != E; ++I) {
964       const TargetInstrDesc &Desc = I->getDesc();
965       const MachineInstr &MI = *I;
966       unsigned NumOps = Desc.getNumOperands();
967       for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
968         const MachineOperand &MO = MI.getOperand(CurOp);
969         if (MO.isGlobal()) {
970           GlobalValue* V = MO.getGlobal();
971           const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
972           if (!GV)
973             continue;
974           // If seen in previous function, it will have an entry here.
975           if (TheJIT->getPointerToGlobalIfAvailable(GV))
976             continue;
977           // If seen earlier in this function, it will have an entry here.
978           // FIXME: it should be possible to combine these tables, by
979           // assuming the addresses of the new globals in this module
980           // start at 0 (or something) and adjusting them after codegen
981           // complete.  Another possibility is to grab a marker bit in GV.
982           if (GVSet.insert(GV))
983             // A variable as yet unseen.  Add in its size.
984             Size = addSizeOfGlobal(GV, Size);
985         }
986       }
987     }
988   }
989   DEBUG(errs() << "JIT: About to look through initializers\n");
990   // Look for more globals that are referenced only from initializers.
991   // GVSet.end is computed each time because the set can grow as we go.
992   for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
993        I != GVSet.end(); I++) {
994     const GlobalVariable* GV = *I;
995     if (GV->hasInitializer())
996       Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
997   }
998
999   return Size;
1000 }
1001
1002 void JITEmitter::startFunction(MachineFunction &F) {
1003   DEBUG(errs() << "JIT: Starting CodeGen of Function "
1004         << F.getFunction()->getName() << "\n");
1005
1006   uintptr_t ActualSize = 0;
1007   // Set the memory writable, if it's not already
1008   MemMgr->setMemoryWritable();
1009   if (MemMgr->NeedsExactSize()) {
1010     DEBUG(errs() << "JIT: ExactSize\n");
1011     const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
1012     MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
1013     MachineConstantPool *MCP = F.getConstantPool();
1014
1015     // Ensure the constant pool/jump table info is at least 4-byte aligned.
1016     ActualSize = RoundUpToAlign(ActualSize, 16);
1017
1018     // Add the alignment of the constant pool
1019     ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
1020
1021     // Add the constant pool size
1022     ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1023
1024     // Add the aligment of the jump table info
1025     ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
1026
1027     // Add the jump table size
1028     ActualSize += GetJumpTableSizeInBytes(MJTI);
1029
1030     // Add the alignment for the function
1031     ActualSize = RoundUpToAlign(ActualSize,
1032                                 std::max(F.getFunction()->getAlignment(), 8U));
1033
1034     // Add the function size
1035     ActualSize += TII->GetFunctionSizeInBytes(F);
1036
1037     DEBUG(errs() << "JIT: ActualSize before globals " << ActualSize << "\n");
1038     // Add the size of the globals that will be allocated after this function.
1039     // These are all the ones referenced from this function that were not
1040     // previously allocated.
1041     ActualSize += GetSizeOfGlobalsInBytes(F);
1042     DEBUG(errs() << "JIT: ActualSize after globals " << ActualSize << "\n");
1043   } else if (SizeEstimate > 0) {
1044     // SizeEstimate will be non-zero on reallocation attempts.
1045     ActualSize = SizeEstimate;
1046   }
1047
1048   BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
1049                                                          ActualSize);
1050   BufferEnd = BufferBegin+ActualSize;
1051   EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
1052
1053   // Ensure the constant pool/jump table info is at least 4-byte aligned.
1054   emitAlignment(16);
1055
1056   emitConstantPool(F.getConstantPool());
1057   initJumpTableInfo(F.getJumpTableInfo());
1058
1059   // About to start emitting the machine code for the function.
1060   emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
1061   TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
1062   EmittedFunctions[F.getFunction()].Code = CurBufferPtr;
1063
1064   MBBLocations.clear();
1065
1066   EmissionDetails.MF = &F;
1067   EmissionDetails.LineStarts.clear();
1068 }
1069
1070 bool JITEmitter::finishFunction(MachineFunction &F) {
1071   if (CurBufferPtr == BufferEnd) {
1072     // We must call endFunctionBody before retrying, because
1073     // deallocateMemForFunction requires it.
1074     MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
1075     retryWithMoreMemory(F);
1076     return true;
1077   }
1078
1079   emitJumpTableInfo(F.getJumpTableInfo());
1080
1081   // FnStart is the start of the text, not the start of the constant pool and
1082   // other per-function data.
1083   uint8_t *FnStart =
1084     (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
1085
1086   // FnEnd is the end of the function's machine code.
1087   uint8_t *FnEnd = CurBufferPtr;
1088
1089   if (!Relocations.empty()) {
1090     CurFn = F.getFunction();
1091     NumRelos += Relocations.size();
1092
1093     // Resolve the relocations to concrete pointers.
1094     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1095       MachineRelocation &MR = Relocations[i];
1096       void *ResultPtr = 0;
1097       if (!MR.letTargetResolve()) {
1098         if (MR.isExternalSymbol()) {
1099           ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1100                                                         false);
1101           DEBUG(errs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
1102                        << ResultPtr << "]\n");
1103
1104           // If the target REALLY wants a stub for this function, emit it now.
1105           if (MR.mayNeedFarStub()) {
1106             ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1107           }
1108         } else if (MR.isGlobalValue()) {
1109           ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1110                                          BufferBegin+MR.getMachineCodeOffset(),
1111                                          MR.mayNeedFarStub());
1112         } else if (MR.isIndirectSymbol()) {
1113           ResultPtr = getPointerToGVIndirectSym(
1114               MR.getGlobalValue(), BufferBegin+MR.getMachineCodeOffset());
1115         } else if (MR.isBasicBlock()) {
1116           ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1117         } else if (MR.isConstantPoolIndex()) {
1118           ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1119         } else {
1120           assert(MR.isJumpTableIndex());
1121           ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1122         }
1123
1124         MR.setResultPointer(ResultPtr);
1125       }
1126
1127       // if we are managing the GOT and the relocation wants an index,
1128       // give it one
1129       if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
1130         unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
1131         MR.setGOTIndex(idx);
1132         if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
1133           DEBUG(errs() << "JIT: GOT was out of date for " << ResultPtr
1134                        << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1135                        << "\n");
1136           ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
1137         }
1138       }
1139     }
1140
1141     CurFn = 0;
1142     TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
1143                                   Relocations.size(), MemMgr->getGOTBase());
1144   }
1145
1146   // Update the GOT entry for F to point to the new code.
1147   if (MemMgr->isManagingGOT()) {
1148     unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
1149     if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
1150       DEBUG(errs() << "JIT: GOT was out of date for " << (void*)BufferBegin
1151                    << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1152                    << "\n");
1153       ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
1154     }
1155   }
1156
1157   // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1158   // global variables that were referenced in the relocations.
1159   MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
1160
1161   if (CurBufferPtr == BufferEnd) {
1162     retryWithMoreMemory(F);
1163     return true;
1164   } else {
1165     // Now that we've succeeded in emitting the function, reset the
1166     // SizeEstimate back down to zero.
1167     SizeEstimate = 0;
1168   }
1169
1170   BufferBegin = CurBufferPtr = 0;
1171   NumBytes += FnEnd-FnStart;
1172
1173   // Invalidate the icache if necessary.
1174   sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
1175
1176   TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
1177                                 EmissionDetails);
1178
1179   DEBUG(errs() << "JIT: Finished CodeGen of [" << (void*)FnStart
1180         << "] Function: " << F.getFunction()->getName()
1181         << ": " << (FnEnd-FnStart) << " bytes of text, "
1182         << Relocations.size() << " relocations\n");
1183
1184   Relocations.clear();
1185   ConstPoolAddresses.clear();
1186
1187   // Mark code region readable and executable if it's not so already.
1188   MemMgr->setMemoryExecutable();
1189
1190   DEBUG(
1191     if (sys::hasDisassembler()) {
1192       errs() << "JIT: Disassembled code:\n";
1193       errs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
1194                                        (uintptr_t)FnStart);
1195     } else {
1196       errs() << "JIT: Binary code:\n";
1197       uint8_t* q = FnStart;
1198       for (int i = 0; q < FnEnd; q += 4, ++i) {
1199         if (i == 4)
1200           i = 0;
1201         if (i == 0)
1202           errs() << "JIT: " << (long)(q - FnStart) << ": ";
1203         bool Done = false;
1204         for (int j = 3; j >= 0; --j) {
1205           if (q + j >= FnEnd)
1206             Done = true;
1207           else
1208             errs() << (unsigned short)q[j];
1209         }
1210         if (Done)
1211           break;
1212         errs() << ' ';
1213         if (i == 3)
1214           errs() << '\n';
1215       }
1216       errs()<< '\n';
1217     }
1218         );
1219
1220   if (DwarfExceptionHandling || JITEmitDebugInfo) {
1221     uintptr_t ActualSize = 0;
1222     SavedBufferBegin = BufferBegin;
1223     SavedBufferEnd = BufferEnd;
1224     SavedCurBufferPtr = CurBufferPtr;
1225
1226     if (MemMgr->NeedsExactSize()) {
1227       ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
1228     }
1229
1230     BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1231                                                              ActualSize);
1232     BufferEnd = BufferBegin+ActualSize;
1233     EmittedFunctions[F.getFunction()].ExceptionTable = BufferBegin;
1234     uint8_t *EhStart;
1235     uint8_t *FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd,
1236                                                 EhStart);
1237     MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1238                               FrameRegister);
1239     uint8_t *EhEnd = CurBufferPtr;
1240     BufferBegin = SavedBufferBegin;
1241     BufferEnd = SavedBufferEnd;
1242     CurBufferPtr = SavedCurBufferPtr;
1243
1244     if (DwarfExceptionHandling) {
1245       TheJIT->RegisterTable(FrameRegister);
1246     }
1247
1248     if (JITEmitDebugInfo) {
1249       DebugInfo I;
1250       I.FnStart = FnStart;
1251       I.FnEnd = FnEnd;
1252       I.EhStart = EhStart;
1253       I.EhEnd = EhEnd;
1254       DR->RegisterFunction(F.getFunction(), I);
1255     }
1256   }
1257
1258   if (MMI)
1259     MMI->EndFunction();
1260
1261   return false;
1262 }
1263
1264 void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
1265   DEBUG(errs() << "JIT: Ran out of space for native code.  Reattempting.\n");
1266   Relocations.clear();  // Clear the old relocations or we'll reapply them.
1267   ConstPoolAddresses.clear();
1268   ++NumRetries;
1269   deallocateMemForFunction(F.getFunction());
1270   // Try again with at least twice as much free space.
1271   SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
1272 }
1273
1274 /// deallocateMemForFunction - Deallocate all memory for the specified
1275 /// function body.  Also drop any references the function has to stubs.
1276 /// May be called while the Function is being destroyed inside ~Value().
1277 void JITEmitter::deallocateMemForFunction(const Function *F) {
1278   ValueMap<const Function *, EmittedCode, EmittedFunctionConfig>::iterator
1279     Emitted = EmittedFunctions.find(F);
1280   if (Emitted != EmittedFunctions.end()) {
1281     MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
1282     MemMgr->deallocateExceptionTable(Emitted->second.ExceptionTable);
1283     TheJIT->NotifyFreeingMachineCode(Emitted->second.Code);
1284
1285     EmittedFunctions.erase(Emitted);
1286   }
1287
1288   // TODO: Do we need to unregister exception handling information from libgcc
1289   // here?
1290
1291   if (JITEmitDebugInfo) {
1292     DR->UnregisterFunction(F);
1293   }
1294
1295   // If the function did not reference any stubs, return.
1296   if (CurFnStubUses.find(F) == CurFnStubUses.end())
1297     return;
1298
1299   // For each referenced stub, erase the reference to this function, and then
1300   // erase the list of referenced stubs.
1301   SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1302   for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1303     void *Stub = StubList[i];
1304
1305     // If we already invalidated this stub for this function, continue.
1306     if (StubFnRefs.count(Stub) == 0)
1307       continue;
1308
1309     SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1310     FnRefs.erase(F);
1311
1312     // If this function was the last reference to the stub, invalidate the stub
1313     // in the JITResolver.  Were there a memory manager deallocateStub routine,
1314     // we could call that at this point too.
1315     if (FnRefs.empty()) {
1316       DEBUG(errs() << "\nJIT: Invalidated Stub at [" << Stub << "]\n");
1317       StubFnRefs.erase(Stub);
1318
1319       // Invalidate the stub.  If it is a GV stub, update the JIT's global
1320       // mapping for that GV to zero.
1321       GlobalValue *GV = Resolver.invalidateStub(Stub);
1322       if (GV) {
1323         TheJIT->updateGlobalMapping(GV, 0);
1324       }
1325     }
1326   }
1327   CurFnStubUses.erase(F);
1328 }
1329
1330
1331 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1332   if (BufferBegin)
1333     return JITCodeEmitter::allocateSpace(Size, Alignment);
1334
1335   // create a new memory block if there is no active one.
1336   // care must be taken so that BufferBegin is invalidated when a
1337   // block is trimmed
1338   BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1339   BufferEnd = BufferBegin+Size;
1340   return CurBufferPtr;
1341 }
1342
1343 void* JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1344   // Delegate this call through the memory manager.
1345   return MemMgr->allocateGlobal(Size, Alignment);
1346 }
1347
1348 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1349   if (TheJIT->getJITInfo().hasCustomConstantPool())
1350     return;
1351
1352   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1353   if (Constants.empty()) return;
1354
1355   unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1356   unsigned Align = MCP->getConstantPoolAlignment();
1357   ConstantPoolBase = allocateSpace(Size, Align);
1358   ConstantPool = MCP;
1359
1360   if (ConstantPoolBase == 0) return;  // Buffer overflow.
1361
1362   DEBUG(errs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1363                << "] (size: " << Size << ", alignment: " << Align << ")\n");
1364
1365   // Initialize the memory for all of the constant pool entries.
1366   unsigned Offset = 0;
1367   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1368     MachineConstantPoolEntry CPE = Constants[i];
1369     unsigned AlignMask = CPE.getAlignment() - 1;
1370     Offset = (Offset + AlignMask) & ~AlignMask;
1371
1372     uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1373     ConstPoolAddresses.push_back(CAddr);
1374     if (CPE.isMachineConstantPoolEntry()) {
1375       // FIXME: add support to lower machine constant pool values into bytes!
1376       llvm_report_error("Initialize memory with machine specific constant pool"
1377                         "entry has not been implemented!");
1378     }
1379     TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1380     DEBUG(errs() << "JIT:   CP" << i << " at [0x";
1381           errs().write_hex(CAddr) << "]\n");
1382
1383     const Type *Ty = CPE.Val.ConstVal->getType();
1384     Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
1385   }
1386 }
1387
1388 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1389   if (TheJIT->getJITInfo().hasCustomJumpTables())
1390     return;
1391
1392   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1393   if (JT.empty()) return;
1394
1395   unsigned NumEntries = 0;
1396   for (unsigned i = 0, e = JT.size(); i != e; ++i)
1397     NumEntries += JT[i].MBBs.size();
1398
1399   unsigned EntrySize = MJTI->getEntrySize();
1400
1401   // Just allocate space for all the jump tables now.  We will fix up the actual
1402   // MBB entries in the tables after we emit the code for each block, since then
1403   // we will know the final locations of the MBBs in memory.
1404   JumpTable = MJTI;
1405   JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1406 }
1407
1408 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1409   if (TheJIT->getJITInfo().hasCustomJumpTables())
1410     return;
1411
1412   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1413   if (JT.empty() || JumpTableBase == 0) return;
1414
1415   if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1416     assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1417     // For each jump table, place the offset from the beginning of the table
1418     // to the target address.
1419     int *SlotPtr = (int*)JumpTableBase;
1420
1421     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1422       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1423       // Store the offset of the basic block for this jump table slot in the
1424       // memory we allocated for the jump table in 'initJumpTableInfo'
1425       uintptr_t Base = (uintptr_t)SlotPtr;
1426       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1427         uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1428         *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1429       }
1430     }
1431   } else {
1432     assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1433
1434     // For each jump table, map each target in the jump table to the address of
1435     // an emitted MachineBasicBlock.
1436     intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1437
1438     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1439       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1440       // Store the address of the basic block for this jump table slot in the
1441       // memory we allocated for the jump table in 'initJumpTableInfo'
1442       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1443         *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1444     }
1445   }
1446 }
1447
1448 void JITEmitter::startGVStub(const GlobalValue* GV,
1449                              unsigned StubSize, unsigned Alignment) {
1450   SavedBufferBegin = BufferBegin;
1451   SavedBufferEnd = BufferEnd;
1452   SavedCurBufferPtr = CurBufferPtr;
1453
1454   BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1455   BufferEnd = BufferBegin+StubSize+1;
1456 }
1457
1458 void JITEmitter::startGVStub(void *Buffer, unsigned StubSize) {
1459   SavedBufferBegin = BufferBegin;
1460   SavedBufferEnd = BufferEnd;
1461   SavedCurBufferPtr = CurBufferPtr;
1462
1463   BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1464   BufferEnd = BufferBegin+StubSize+1;
1465 }
1466
1467 void JITEmitter::finishGVStub() {
1468   assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
1469   NumBytes += getCurrentPCOffset();
1470   BufferBegin = SavedBufferBegin;
1471   BufferEnd = SavedBufferEnd;
1472   CurBufferPtr = SavedCurBufferPtr;
1473 }
1474
1475 void *JITEmitter::allocIndirectGV(const GlobalValue *GV,
1476                                   const uint8_t *Buffer, size_t Size,
1477                                   unsigned Alignment) {
1478   uint8_t *IndGV = MemMgr->allocateStub(GV, Size, Alignment);
1479   memcpy(IndGV, Buffer, Size);
1480   return IndGV;
1481 }
1482
1483 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1484 // in the constant pool that was last emitted with the 'emitConstantPool'
1485 // method.
1486 //
1487 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1488   assert(ConstantNum < ConstantPool->getConstants().size() &&
1489          "Invalid ConstantPoolIndex!");
1490   return ConstPoolAddresses[ConstantNum];
1491 }
1492
1493 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1494 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1495 //
1496 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1497   const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1498   assert(Index < JT.size() && "Invalid jump table index!");
1499
1500   unsigned Offset = 0;
1501   unsigned EntrySize = JumpTable->getEntrySize();
1502
1503   for (unsigned i = 0; i < Index; ++i)
1504     Offset += JT[i].MBBs.size();
1505
1506    Offset *= EntrySize;
1507
1508   return (uintptr_t)((char *)JumpTableBase + Offset);
1509 }
1510
1511 void JITEmitter::EmittedFunctionConfig::onDelete(
1512   JITEmitter *Emitter, const Function *F) {
1513   Emitter->deallocateMemForFunction(F);
1514 }
1515 void JITEmitter::EmittedFunctionConfig::onRAUW(
1516   JITEmitter *, const Function*, const Function*) {
1517   llvm_unreachable("The JIT doesn't know how to handle a"
1518                    " RAUW on a value it has emitted.");
1519 }
1520
1521
1522 //===----------------------------------------------------------------------===//
1523 //  Public interface to this file
1524 //===----------------------------------------------------------------------===//
1525
1526 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1527                                    TargetMachine &tm) {
1528   return new JITEmitter(jit, JMM, tm);
1529 }
1530
1531 // getPointerToNamedFunction - This function is used as a global wrapper to
1532 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1533 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1534 // need to resolve function(s) that are being mis-codegenerated, so we need to
1535 // resolve their addresses at runtime, and this is the way to do it.
1536 extern "C" {
1537   void *getPointerToNamedFunction(const char *Name) {
1538     if (Function *F = TheJIT->FindFunctionNamed(Name))
1539       return TheJIT->getPointerToFunction(F);
1540     return TheJIT->getPointerToNamedFunction(Name);
1541   }
1542 }
1543
1544 // getPointerToFunctionOrStub - If the specified function has been
1545 // code-gen'd, return a pointer to the function.  If not, compile it, or use
1546 // a stub to implement lazy compilation if available.
1547 //
1548 void *JIT::getPointerToFunctionOrStub(Function *F) {
1549   // If we have already code generated the function, just return the address.
1550   if (void *Addr = getPointerToGlobalIfAvailable(F))
1551     return Addr;
1552
1553   // Get a stub if the target supports it.
1554   assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1555   JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1556   return JE->getJITResolver().getLazyFunctionStub(F);
1557 }
1558
1559 void JIT::updateFunctionStub(Function *F) {
1560   // Get the empty stub we generated earlier.
1561   assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1562   JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1563   void *Stub = JE->getJITResolver().getLazyFunctionStub(F);
1564   void *Addr = getPointerToGlobalIfAvailable(F);
1565
1566   // Tell the target jit info to rewrite the stub at the specified address,
1567   // rather than creating a new one.
1568   TargetJITInfo::StubLayout layout = getJITInfo().getStubLayout();
1569   JE->startGVStub(Stub, layout.Size);
1570   getJITInfo().emitFunctionStub(F, Addr, *getCodeEmitter());
1571   JE->finishGVStub();
1572 }
1573
1574 /// freeMachineCodeForFunction - release machine code memory for given Function.
1575 ///
1576 void JIT::freeMachineCodeForFunction(Function *F) {
1577   // Delete translation for this from the ExecutionEngine, so it will get
1578   // retranslated next time it is used.
1579   updateGlobalMapping(F, 0);
1580
1581   // Free the actual memory for the function body and related stuff.
1582   assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1583   cast<JITEmitter>(JCE)->deallocateMemForFunction(F);
1584 }