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