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