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