LLVM API Documentation

JITEmitter.cpp

Go to the documentation of this file.
00001 //===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines a MachineCodeEmitter object that is used by the JIT to
00011 // write machine code to memory and remember where relocatable values are.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #define DEBUG_TYPE "jit"
00016 #include "JIT.h"
00017 #include "JITDwarfEmitter.h"
00018 #include "llvm/Constants.h"
00019 #include "llvm/Module.h"
00020 #include "llvm/DerivedTypes.h"
00021 #include "llvm/CodeGen/MachineCodeEmitter.h"
00022 #include "llvm/CodeGen/MachineFunction.h"
00023 #include "llvm/CodeGen/MachineConstantPool.h"
00024 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00025 #include "llvm/CodeGen/MachineModuleInfo.h"
00026 #include "llvm/CodeGen/MachineRelocation.h"
00027 #include "llvm/ExecutionEngine/JITMemoryManager.h"
00028 #include "llvm/ExecutionEngine/GenericValue.h"
00029 #include "llvm/Target/TargetData.h"
00030 #include "llvm/Target/TargetJITInfo.h"
00031 #include "llvm/Target/TargetMachine.h"
00032 #include "llvm/Target/TargetOptions.h"
00033 #include "llvm/Support/Debug.h"
00034 #include "llvm/Support/MutexGuard.h"
00035 #include "llvm/System/Disassembler.h"
00036 #include "llvm/System/Memory.h"
00037 #include "llvm/Target/TargetInstrInfo.h"
00038 #include "llvm/ADT/SmallPtrSet.h"
00039 #include "llvm/ADT/Statistic.h"
00040 #include <algorithm>
00041 #ifndef NDEBUG
00042 #include <iomanip>
00043 #endif
00044 using namespace llvm;
00045 
00046 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
00047 STATISTIC(NumRelos, "Number of relocations applied");
00048 static JIT *TheJIT = 0;
00049 
00050 
00051 //===----------------------------------------------------------------------===//
00052 // JIT lazy compilation code.
00053 //
00054 namespace {
00055   class JITResolverState {
00056   private:
00057     /// FunctionToStubMap - Keep track of the stub created for a particular
00058     /// function so that we can reuse them if necessary.
00059     std::map<Function*, void*> FunctionToStubMap;
00060 
00061     /// StubToFunctionMap - Keep track of the function that each stub
00062     /// corresponds to.
00063     std::map<void*, Function*> StubToFunctionMap;
00064 
00065     /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
00066     /// particular GlobalVariable so that we can reuse them if necessary.
00067     std::map<GlobalValue*, void*> GlobalToIndirectSymMap;
00068 
00069   public:
00070     std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
00071       assert(locked.holds(TheJIT->lock));
00072       return FunctionToStubMap;
00073     }
00074 
00075     std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
00076       assert(locked.holds(TheJIT->lock));
00077       return StubToFunctionMap;
00078     }
00079 
00080     std::map<GlobalValue*, void*>&
00081     getGlobalToIndirectSymMap(const MutexGuard& locked) {
00082       assert(locked.holds(TheJIT->lock));
00083       return GlobalToIndirectSymMap;
00084     }
00085   };
00086 
00087   /// JITResolver - Keep track of, and resolve, call sites for functions that
00088   /// have not yet been compiled.
00089   class JITResolver {
00090     /// LazyResolverFn - The target lazy resolver function that we actually
00091     /// rewrite instructions to use.
00092     TargetJITInfo::LazyResolverFn LazyResolverFn;
00093 
00094     JITResolverState state;
00095 
00096     /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
00097     /// external functions.
00098     std::map<void*, void*> ExternalFnToStubMap;
00099 
00100     //map addresses to indexes in the GOT
00101     std::map<void*, unsigned> revGOTMap;
00102     unsigned nextGOTIndex;
00103 
00104     static JITResolver *TheJITResolver;
00105   public:
00106     explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
00107       TheJIT = &jit;
00108 
00109       LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
00110       assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
00111       TheJITResolver = this;
00112     }
00113     
00114     ~JITResolver() {
00115       TheJITResolver = 0;
00116     }
00117 
00118     /// getFunctionStubIfAvailable - This returns a pointer to a function stub
00119     /// if it has already been created.
00120     void *getFunctionStubIfAvailable(Function *F);
00121 
00122     /// getFunctionStub - This returns a pointer to a function stub, creating
00123     /// one on demand as needed.
00124     void *getFunctionStub(Function *F);
00125 
00126     /// getExternalFunctionStub - Return a stub for the function at the
00127     /// specified address, created lazily on demand.
00128     void *getExternalFunctionStub(void *FnAddr);
00129 
00130     /// getGlobalValueIndirectSym - Return an indirect symbol containing the
00131     /// specified GV address.
00132     void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
00133 
00134     /// AddCallbackAtLocation - If the target is capable of rewriting an
00135     /// instruction without the use of a stub, record the location of the use so
00136     /// we know which function is being used at the location.
00137     void *AddCallbackAtLocation(Function *F, void *Location) {
00138       MutexGuard locked(TheJIT->lock);
00139       /// Get the target-specific JIT resolver function.
00140       state.getStubToFunctionMap(locked)[Location] = F;
00141       return (void*)(intptr_t)LazyResolverFn;
00142     }
00143 
00144     /// getGOTIndexForAddress - Return a new or existing index in the GOT for
00145     /// an address.  This function only manages slots, it does not manage the
00146     /// contents of the slots or the memory associated with the GOT.
00147     unsigned getGOTIndexForAddr(void *addr);
00148 
00149     /// JITCompilerFn - This function is called to resolve a stub to a compiled
00150     /// address.  If the LLVM Function corresponding to the stub has not yet
00151     /// been compiled, this function compiles it first.
00152     static void *JITCompilerFn(void *Stub);
00153   };
00154 }
00155 
00156 JITResolver *JITResolver::TheJITResolver = 0;
00157 
00158 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
00159 /// if it has already been created.
00160 void *JITResolver::getFunctionStubIfAvailable(Function *F) {
00161   MutexGuard locked(TheJIT->lock);
00162 
00163   // If we already have a stub for this function, recycle it.
00164   void *&Stub = state.getFunctionToStubMap(locked)[F];
00165   return Stub;
00166 }
00167 
00168 /// getFunctionStub - This returns a pointer to a function stub, creating
00169 /// one on demand as needed.
00170 void *JITResolver::getFunctionStub(Function *F) {
00171   MutexGuard locked(TheJIT->lock);
00172 
00173   // If we already have a stub for this function, recycle it.
00174   void *&Stub = state.getFunctionToStubMap(locked)[F];
00175   if (Stub) return Stub;
00176 
00177   // Call the lazy resolver function unless we already KNOW it is an external
00178   // function, in which case we just skip the lazy resolution step.
00179   void *Actual = (void*)(intptr_t)LazyResolverFn;
00180   if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
00181     Actual = TheJIT->getPointerToFunction(F);
00182 
00183     // If we resolved the symbol to a null address (eg. a weak external)
00184     // don't emit a stub. Return a null pointer to the application.
00185     if (!Actual) return 0;
00186   }
00187 
00188   // Otherwise, codegen a new stub.  For now, the stub will call the lazy
00189   // resolver function.
00190   Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
00191                                                *TheJIT->getCodeEmitter());
00192 
00193   if (Actual != (void*)(intptr_t)LazyResolverFn) {
00194     // If we are getting the stub for an external function, we really want the
00195     // address of the stub in the GlobalAddressMap for the JIT, not the address
00196     // of the external function.
00197     TheJIT->updateGlobalMapping(F, Stub);
00198   }
00199 
00200   DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
00201        << F->getName() << "'\n";
00202 
00203   // Finally, keep track of the stub-to-Function mapping so that the
00204   // JITCompilerFn knows which function to compile!
00205   state.getStubToFunctionMap(locked)[Stub] = F;
00206   return Stub;
00207 }
00208 
00209 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
00210 /// GV address.
00211 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
00212   MutexGuard locked(TheJIT->lock);
00213 
00214   // If we already have a stub for this global variable, recycle it.
00215   void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
00216   if (IndirectSym) return IndirectSym;
00217 
00218   // Otherwise, codegen a new indirect symbol.
00219   IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
00220                                                      *TheJIT->getCodeEmitter());
00221 
00222   DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
00223        << GV->getName() << "'\n";
00224 
00225   return IndirectSym;
00226 }
00227 
00228 /// getExternalFunctionStub - Return a stub for the function at the
00229 /// specified address, created lazily on demand.
00230 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
00231   // If we already have a stub for this function, recycle it.
00232   void *&Stub = ExternalFnToStubMap[FnAddr];
00233   if (Stub) return Stub;
00234 
00235   Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
00236                                                *TheJIT->getCodeEmitter());
00237 
00238   DOUT << "JIT: Stub emitted at [" << Stub
00239        << "] for external function at '" << FnAddr << "'\n";
00240   return Stub;
00241 }
00242 
00243 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
00244   unsigned idx = revGOTMap[addr];
00245   if (!idx) {
00246     idx = ++nextGOTIndex;
00247     revGOTMap[addr] = idx;
00248     DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
00249   }
00250   return idx;
00251 }
00252 
00253 /// JITCompilerFn - This function is called when a lazy compilation stub has
00254 /// been entered.  It looks up which function this stub corresponds to, compiles
00255 /// it if necessary, then returns the resultant function pointer.
00256 void *JITResolver::JITCompilerFn(void *Stub) {
00257   JITResolver &JR = *TheJITResolver;
00258   
00259   Function* F = 0;
00260   void* ActualPtr = 0;
00261 
00262   {
00263     // Only lock for getting the Function. The call getPointerToFunction made
00264     // in this function might trigger function materializing, which requires
00265     // JIT lock to be unlocked.
00266     MutexGuard locked(TheJIT->lock);
00267 
00268     // The address given to us for the stub may not be exactly right, it might be
00269     // a little bit after the stub.  As such, use upper_bound to find it.
00270     std::map<void*, Function*>::iterator I =
00271       JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
00272     assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
00273            "This is not a known stub!");
00274     F = (--I)->second;
00275     ActualPtr = I->first;
00276   }
00277 
00278   // If we have already code generated the function, just return the address.
00279   void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
00280   
00281   if (!Result) {
00282     // Otherwise we don't have it, do lazy compilation now.
00283     
00284     // If lazy compilation is disabled, emit a useful error message and abort.
00285     if (TheJIT->isLazyCompilationDisabled()) {
00286       cerr << "LLVM JIT requested to do lazy compilation of function '"
00287       << F->getName() << "' when lazy compiles are disabled!\n";
00288       abort();
00289     }
00290   
00291     // We might like to remove the stub from the StubToFunction map.
00292     // We can't do that! Multiple threads could be stuck, waiting to acquire the
00293     // lock above. As soon as the 1st function finishes compiling the function,
00294     // the next one will be released, and needs to be able to find the function
00295     // it needs to call.
00296     //JR.state.getStubToFunctionMap(locked).erase(I);
00297 
00298     DOUT << "JIT: Lazily resolving function '" << F->getName()
00299          << "' In stub ptr = " << Stub << " actual ptr = "
00300          << ActualPtr << "\n";
00301 
00302     Result = TheJIT->getPointerToFunction(F);
00303   }
00304   
00305   // Reacquire the lock to erase the stub in the map.
00306   MutexGuard locked(TheJIT->lock);
00307 
00308   // We don't need to reuse this stub in the future, as F is now compiled.
00309   JR.state.getFunctionToStubMap(locked).erase(F);
00310 
00311   // FIXME: We could rewrite all references to this stub if we knew them.
00312 
00313   // What we will do is set the compiled function address to map to the
00314   // same GOT entry as the stub so that later clients may update the GOT
00315   // if they see it still using the stub address.
00316   // Note: this is done so the Resolver doesn't have to manage GOT memory
00317   // Do this without allocating map space if the target isn't using a GOT
00318   if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
00319     JR.revGOTMap[Result] = JR.revGOTMap[Stub];
00320 
00321   return Result;
00322 }
00323 
00324 //===----------------------------------------------------------------------===//
00325 // Function Index Support
00326 
00327 // On MacOS we generate an index of currently JIT'd functions so that
00328 // performance tools can determine a symbol name and accurate code range for a
00329 // PC value.  Because performance tools are generally asynchronous, the code
00330 // below is written with the hope that it could be interrupted at any time and
00331 // have useful answers.  However, we don't go crazy with atomic operations, we
00332 // just do a "reasonable effort".
00333 #ifdef __APPLE__ 
00334 #define ENABLE_JIT_SYMBOL_TABLE 0
00335 #endif
00336 
00337 /// JitSymbolEntry - Each function that is JIT compiled results in one of these
00338 /// being added to an array of symbols.  This indicates the name of the function
00339 /// as well as the address range it occupies.  This allows the client to map
00340 /// from a PC value to the name of the function.
00341 struct JitSymbolEntry {
00342   const char *FnName;   // FnName - a strdup'd string.
00343   void *FnStart;
00344   intptr_t FnSize;
00345 };
00346 
00347 
00348 struct JitSymbolTable {
00349   /// NextPtr - This forms a linked list of JitSymbolTable entries.  This
00350   /// pointer is not used right now, but might be used in the future.  Consider
00351   /// it reserved for future use.
00352   JitSymbolTable *NextPtr;
00353   
00354   /// Symbols - This is an array of JitSymbolEntry entries.  Only the first
00355   /// 'NumSymbols' symbols are valid.
00356   JitSymbolEntry *Symbols;
00357   
00358   /// NumSymbols - This indicates the number entries in the Symbols array that
00359   /// are valid.
00360   unsigned NumSymbols;
00361   
00362   /// NumAllocated - This indicates the amount of space we have in the Symbols
00363   /// array.  This is a private field that should not be read by external tools.
00364   unsigned NumAllocated;
00365 };
00366 
00367 #if ENABLE_JIT_SYMBOL_TABLE 
00368 JitSymbolTable *__jitSymbolTable;
00369 #endif
00370 
00371 static void AddFunctionToSymbolTable(const char *FnName, 
00372                                      void *FnStart, intptr_t FnSize) {
00373   assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
00374   JitSymbolTable **SymTabPtrPtr = 0;
00375 #if !ENABLE_JIT_SYMBOL_TABLE
00376   return;
00377 #else
00378   SymTabPtrPtr = &__jitSymbolTable;
00379 #endif
00380   
00381   // If this is the first entry in the symbol table, add the JitSymbolTable
00382   // index.
00383   if (*SymTabPtrPtr == 0) {
00384     JitSymbolTable *New = new JitSymbolTable();
00385     New->NextPtr = 0;
00386     New->Symbols = 0;
00387     New->NumSymbols = 0;
00388     New->NumAllocated = 0;
00389     *SymTabPtrPtr = New;
00390   }
00391   
00392   JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
00393   
00394   // If we have space in the table, reallocate the table.
00395   if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
00396     // If we don't have space, reallocate the table.
00397     unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
00398     JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
00399     JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
00400     
00401     // Copy the old entries over.
00402     memcpy(NewSymbols, OldSymbols,
00403            SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
00404     
00405     // Swap the new symbols in, delete the old ones.
00406     SymTabPtr->Symbols = NewSymbols;
00407     SymTabPtr->NumAllocated = NewSize;
00408     delete [] OldSymbols;
00409   }
00410   
00411   // Otherwise, we have enough space, just tack it onto the end of the array.
00412   JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
00413   Entry.FnName = strdup(FnName);
00414   Entry.FnStart = FnStart;
00415   Entry.FnSize = FnSize;
00416   ++SymTabPtr->NumSymbols;
00417 }
00418 
00419 static void RemoveFunctionFromSymbolTable(void *FnStart) {
00420   assert(FnStart && "Invalid function pointer");
00421   JitSymbolTable **SymTabPtrPtr = 0;
00422 #if !ENABLE_JIT_SYMBOL_TABLE
00423   return;
00424 #else
00425   SymTabPtrPtr = &__jitSymbolTable;
00426 #endif
00427   
00428   JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
00429   JitSymbolEntry *Symbols = SymTabPtr->Symbols;
00430   
00431   // Scan the table to find its index.  The table is not sorted, so do a linear
00432   // scan.
00433   unsigned Index;
00434   for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
00435     assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
00436   
00437   // Once we have an index, we know to nuke this entry, overwrite it with the
00438   // entry at the end of the array, making the last entry redundant.
00439   const char *OldName = Symbols[Index].FnName;
00440   Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
00441   free((void*)OldName);
00442   
00443   // Drop the number of symbols in the table.
00444   --SymTabPtr->NumSymbols;
00445 
00446   // Finally, if we deleted the final symbol, deallocate the table itself.
00447   if (SymTabPtr->NumSymbols != 0) 
00448     return;
00449   
00450   *SymTabPtrPtr = 0;
00451   delete [] Symbols;
00452   delete SymTabPtr;
00453 }
00454 
00455 //===----------------------------------------------------------------------===//
00456 // JITEmitter code.
00457 //
00458 namespace {
00459   /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
00460   /// used to output functions to memory for execution.
00461   class JITEmitter : public MachineCodeEmitter {
00462     JITMemoryManager *MemMgr;
00463 
00464     // When outputting a function stub in the context of some other function, we
00465     // save BufferBegin/BufferEnd/CurBufferPtr here.
00466     unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
00467 
00468     /// Relocations - These are the relocations that the function needs, as
00469     /// emitted.
00470     std::vector<MachineRelocation> Relocations;
00471     
00472     /// MBBLocations - This vector is a mapping from MBB ID's to their address.
00473     /// It is filled in by the StartMachineBasicBlock callback and queried by
00474     /// the getMachineBasicBlockAddress callback.
00475     std::vector<uintptr_t> MBBLocations;
00476 
00477     /// ConstantPool - The constant pool for the current function.
00478     ///
00479     MachineConstantPool *ConstantPool;
00480 
00481     /// ConstantPoolBase - A pointer to the first entry in the constant pool.
00482     ///
00483     void *ConstantPoolBase;
00484 
00485     /// JumpTable - The jump tables for the current function.
00486     ///
00487     MachineJumpTableInfo *JumpTable;
00488     
00489     /// JumpTableBase - A pointer to the first entry in the jump table.
00490     ///
00491     void *JumpTableBase;
00492 
00493     /// Resolver - This contains info about the currently resolved functions.
00494     JITResolver Resolver;
00495     
00496     /// DE - The dwarf emitter for the jit.
00497     JITDwarfEmitter *DE;
00498 
00499     /// LabelLocations - This vector is a mapping from Label ID's to their 
00500     /// address.
00501     std::vector<uintptr_t> LabelLocations;
00502 
00503     /// MMI - Machine module info for exception informations
00504     MachineModuleInfo* MMI;
00505 
00506     // GVSet - a set to keep track of which globals have been seen
00507     SmallPtrSet<const GlobalVariable*, 8> GVSet;
00508 
00509   public:
00510     JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
00511       MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
00512       if (jit.getJITInfo().needsGOT()) {
00513         MemMgr->AllocateGOT();
00514         DOUT << "JIT is managing a GOT\n";
00515       }
00516 
00517       if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
00518     }
00519     ~JITEmitter() { 
00520       delete MemMgr;
00521       if (ExceptionHandling) delete DE;
00522     }
00523 
00524     /// classof - Methods for support type inquiry through isa, cast, and
00525     /// dyn_cast:
00526     ///
00527     static inline bool classof(const JITEmitter*) { return true; }
00528     static inline bool classof(const MachineCodeEmitter*) { return true; }
00529     
00530     JITResolver &getJITResolver() { return Resolver; }
00531 
00532     virtual void startFunction(MachineFunction &F);
00533     virtual bool finishFunction(MachineFunction &F);
00534     
00535     void emitConstantPool(MachineConstantPool *MCP);
00536     void initJumpTableInfo(MachineJumpTableInfo *MJTI);
00537     void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
00538     
00539     virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
00540                                    unsigned Alignment = 1);
00541     virtual void* finishGVStub(const GlobalValue *GV);
00542 
00543     /// allocateSpace - Reserves space in the current block if any, or
00544     /// allocate a new one of the given size.
00545     virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
00546 
00547     virtual void addRelocation(const MachineRelocation &MR) {
00548       Relocations.push_back(MR);
00549     }
00550     
00551     virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
00552       if (MBBLocations.size() <= (unsigned)MBB->getNumber())
00553         MBBLocations.resize((MBB->getNumber()+1)*2);
00554       MBBLocations[MBB->getNumber()] = getCurrentPCValue();
00555       DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
00556            << (void*) getCurrentPCValue() << "]\n";
00557     }
00558 
00559     virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
00560     virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
00561 
00562     virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
00563       assert(MBBLocations.size() > (unsigned)MBB->getNumber() && 
00564              MBBLocations[MBB->getNumber()] && "MBB not emitted!");
00565       return MBBLocations[MBB->getNumber()];
00566     }
00567 
00568     /// deallocateMemForFunction - Deallocate all memory for the specified
00569     /// function body.
00570     void deallocateMemForFunction(Function *F) {
00571       MemMgr->deallocateMemForFunction(F);
00572     }
00573     
00574     virtual void emitLabel(uint64_t LabelID) {
00575       if (LabelLocations.size() <= LabelID)
00576         LabelLocations.resize((LabelID+1)*2);
00577       LabelLocations[LabelID] = getCurrentPCValue();
00578     }
00579 
00580     virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
00581       assert(LabelLocations.size() > (unsigned)LabelID && 
00582              LabelLocations[LabelID] && "Label not emitted!");
00583       return LabelLocations[LabelID];
00584     }
00585  
00586     virtual void setModuleInfo(MachineModuleInfo* Info) {
00587       MMI = Info;
00588       if (ExceptionHandling) DE->setModuleInfo(Info);
00589     }
00590 
00591     void setMemoryExecutable(void) {
00592       MemMgr->setMemoryExecutable();
00593     }
00594 
00595   private:
00596     void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
00597     void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
00598                                     bool NoNeedStub);
00599     unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
00600     unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
00601     unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
00602     unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
00603   };
00604 }
00605 
00606 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
00607                                      bool DoesntNeedStub) {
00608   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
00609     /// FIXME: If we straightened things out, this could actually emit the
00610     /// global immediately instead of queuing it for codegen later!
00611     return TheJIT->getOrEmitGlobalVariable(GV);
00612   }
00613   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
00614     return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
00615 
00616   // If we have already compiled the function, return a pointer to its body.
00617   Function *F = cast<Function>(V);
00618   void *ResultPtr;
00619   if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
00620     // Return the function stub if it's already created.
00621     ResultPtr = Resolver.getFunctionStubIfAvailable(F);
00622   else
00623     ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
00624   if (ResultPtr) return ResultPtr;
00625 
00626   if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
00627     // If this is an external function pointer, we can force the JIT to
00628     // 'compile' it, which really just adds it to the map.
00629     if (DoesntNeedStub)
00630       return TheJIT->getPointerToFunction(F);
00631 
00632     return Resolver.getFunctionStub(F);
00633   }
00634 
00635   // Okay, the function has not been compiled yet, if the target callback
00636   // mechanism is capable of rewriting the instruction directly, prefer to do
00637   // that instead of emitting a stub.
00638   if (DoesntNeedStub)
00639     return Resolver.AddCallbackAtLocation(F, Reference);
00640 
00641   // Otherwise, we have to emit a lazy resolving stub.
00642   return Resolver.getFunctionStub(F);
00643 }
00644 
00645 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
00646                                             bool NoNeedStub) {
00647   // Make sure GV is emitted first.
00648   // FIXME: For now, if the GV is an external function we force the JIT to
00649   // compile it so the indirect symbol will contain the fully resolved address.
00650   void *GVAddress = getPointerToGlobal(V, Reference, true);
00651   return Resolver.getGlobalValueIndirectSym(V, GVAddress);
00652 }
00653 
00654 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
00655   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
00656   if (Constants.empty()) return 0;
00657 
00658   MachineConstantPoolEntry CPE = Constants.back();
00659   unsigned Size = CPE.Offset;
00660   const Type *Ty = CPE.isMachineConstantPoolEntry()
00661     ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
00662   Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
00663   return Size;
00664 }
00665 
00666 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
00667   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
00668   if (JT.empty()) return 0;
00669   
00670   unsigned NumEntries = 0;
00671   for (unsigned i = 0, e = JT.size(); i != e; ++i)
00672     NumEntries += JT[i].MBBs.size();
00673 
00674   unsigned EntrySize = MJTI->getEntrySize();
00675 
00676   return NumEntries * EntrySize;
00677 }
00678 
00679 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
00680   if (Alignment == 0) Alignment = 1;
00681   // Since we do not know where the buffer will be allocated, be pessimistic. 
00682   return Size + Alignment;
00683 }
00684 
00685 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
00686 /// into the running total Size.
00687 
00688 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
00689   const Type *ElTy = GV->getType()->getElementType();
00690   size_t GVSize = (size_t)TheJIT->getTargetData()->getTypePaddedSize(ElTy);
00691   size_t GVAlign = 
00692       (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
00693   DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
00694   DEBUG(GV->dump());
00695   // Assume code section ends with worst possible alignment, so first
00696   // variable needs maximal padding.
00697   if (Size==0)
00698     Size = 1;
00699   Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
00700   Size += GVSize;
00701   return Size;
00702 }
00703 
00704 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
00705 /// but are referenced from the constant; put them in GVSet and add their
00706 /// size into the running total Size.
00707 
00708 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C, 
00709                                               unsigned Size) {
00710   // If its undefined, return the garbage.
00711   if (isa<UndefValue>(C))
00712     return Size;
00713 
00714   // If the value is a ConstantExpr
00715   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
00716     Constant *Op0 = CE->getOperand(0);
00717     switch (CE->getOpcode()) {
00718     case Instruction::GetElementPtr:
00719     case Instruction::Trunc:
00720     case Instruction::ZExt:
00721     case Instruction::SExt:
00722     case Instruction::FPTrunc:
00723     case Instruction::FPExt:
00724     case Instruction::UIToFP:
00725     case Instruction::SIToFP:
00726     case Instruction::FPToUI:
00727     case Instruction::FPToSI:
00728     case Instruction::PtrToInt:
00729     case Instruction::IntToPtr:
00730     case Instruction::BitCast: {
00731       Size = addSizeOfGlobalsInConstantVal(Op0, Size);
00732       break;
00733     }
00734     case Instruction::Add:
00735     case Instruction::Sub:
00736     case Instruction::Mul:
00737     case Instruction::UDiv:
00738     case Instruction::SDiv:
00739     case Instruction::URem:
00740     case Instruction::SRem:
00741     case Instruction::And:
00742     case Instruction::Or:
00743     case Instruction::Xor: {
00744       Size = addSizeOfGlobalsInConstantVal(Op0, Size);
00745       Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
00746       break;
00747     }
00748     default: {
00749        cerr << "ConstantExpr not handled: " << *CE << "\n";
00750       abort();
00751     }
00752     }
00753   }
00754 
00755   if (C->getType()->getTypeID() == Type::PointerTyID)
00756     if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
00757       if (GVSet.insert(GV))
00758         Size = addSizeOfGlobal(GV, Size);
00759 
00760   return Size;
00761 }
00762 
00763 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
00764 /// but are referenced from the given initializer.
00765 
00766 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init, 
00767                                               unsigned Size) {
00768   if (!isa<UndefValue>(Init) &&
00769       !isa<ConstantVector>(Init) &&
00770       !isa<ConstantAggregateZero>(Init) &&
00771       !isa<ConstantArray>(Init) &&
00772       !isa<ConstantStruct>(Init) &&
00773       Init->getType()->isFirstClassType())
00774     Size = addSizeOfGlobalsInConstantVal(Init, Size);
00775   return Size;
00776 }
00777 
00778 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
00779 /// globals; then walk the initializers of those globals looking for more.
00780 /// If their size has not been considered yet, add it into the running total
00781 /// Size.
00782 
00783 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
00784   unsigned Size = 0;
00785   GVSet.clear();
00786 
00787   for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
00788        MBB != E; ++MBB) {
00789     for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
00790          I != E; ++I) {
00791       const TargetInstrDesc &Desc = I->getDesc();
00792       const MachineInstr &MI = *I;
00793       unsigned NumOps = Desc.getNumOperands();
00794       for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
00795         const MachineOperand &MO = MI.getOperand(CurOp);
00796         if (MO.isGlobal()) {
00797           GlobalValue* V = MO.getGlobal();
00798           const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
00799           if (!GV)
00800             continue;
00801           // If seen in previous function, it will have an entry here.
00802           if (TheJIT->getPointerToGlobalIfAvailable(GV))
00803             continue;
00804           // If seen earlier in this function, it will have an entry here.
00805           // FIXME: it should be possible to combine these tables, by
00806           // assuming the addresses of the new globals in this module
00807           // start at 0 (or something) and adjusting them after codegen
00808           // complete.  Another possibility is to grab a marker bit in GV.
00809           if (GVSet.insert(GV))
00810             // A variable as yet unseen.  Add in its size.
00811             Size = addSizeOfGlobal(GV, Size);
00812         }
00813       }
00814     }
00815   }
00816   DOUT << "JIT: About to look through initializers\n";
00817   // Look for more globals that are referenced only from initializers.
00818   // GVSet.end is computed each time because the set can grow as we go.
00819   for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin(); 
00820        I != GVSet.end(); I++) {
00821     const GlobalVariable* GV = *I;
00822     if (GV->hasInitializer())
00823       Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
00824   }
00825 
00826   return Size;
00827 }
00828 
00829 void JITEmitter::startFunction(MachineFunction &F) {
00830   DOUT << "JIT: Starting CodeGen of Function "
00831        << F.getFunction()->getName() << "\n";
00832 
00833   uintptr_t ActualSize = 0;
00834   // Set the memory writable, if it's not already
00835   MemMgr->setMemoryWritable();
00836   if (MemMgr->NeedsExactSize()) {
00837     DOUT << "JIT: ExactSize\n";
00838     const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
00839     MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
00840     MachineConstantPool *MCP = F.getConstantPool();
00841     
00842     // Ensure the constant pool/jump table info is at least 4-byte aligned.
00843     ActualSize = RoundUpToAlign(ActualSize, 16);
00844     
00845     // Add the alignment of the constant pool
00846     ActualSize = RoundUpToAlign(ActualSize, 
00847                                 1 << MCP->getConstantPoolAlignment());
00848 
00849     // Add the constant pool size
00850     ActualSize += GetConstantPoolSizeInBytes(MCP);
00851 
00852     // Add the aligment of the jump table info
00853     ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
00854 
00855     // Add the jump table size
00856     ActualSize += GetJumpTableSizeInBytes(MJTI);
00857     
00858     // Add the alignment for the function
00859     ActualSize = RoundUpToAlign(ActualSize,
00860                                 std::max(F.getFunction()->getAlignment(), 8U));
00861 
00862     // Add the function size
00863     ActualSize += TII->GetFunctionSizeInBytes(F);
00864 
00865     DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
00866     // Add the size of the globals that will be allocated after this function.
00867     // These are all the ones referenced from this function that were not
00868     // previously allocated.
00869     ActualSize += GetSizeOfGlobalsInBytes(F);
00870     DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
00871   }
00872 
00873   BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
00874                                                          ActualSize);
00875   BufferEnd = BufferBegin+ActualSize;
00876   
00877   // Ensure the constant pool/jump table info is at least 4-byte aligned.
00878   emitAlignment(16);
00879 
00880   emitConstantPool(F.getConstantPool());
00881   initJumpTableInfo(F.getJumpTableInfo());
00882 
00883   // About to start emitting the machine code for the function.
00884   emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
00885   TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
00886 
00887   MBBLocations.clear();
00888 }
00889 
00890 bool JITEmitter::finishFunction(MachineFunction &F) {
00891   if (CurBufferPtr == BufferEnd) {
00892     // FIXME: Allocate more space, then try again.
00893     cerr << "JIT: Ran out of space for generated machine code!\n";
00894     abort();
00895   }
00896   
00897   emitJumpTableInfo(F.getJumpTableInfo());
00898   
00899   // FnStart is the start of the text, not the start of the constant pool and
00900   // other per-function data.
00901   unsigned char *FnStart =
00902     (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
00903 
00904   if (!Relocations.empty()) {
00905     NumRelos += Relocations.size();
00906 
00907     // Resolve the relocations to concrete pointers.
00908     for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
00909       MachineRelocation &MR = Relocations[i];
00910       void *ResultPtr = 0;
00911       if (!MR.letTargetResolve()) {
00912         if (MR.isExternalSymbol()) {
00913           ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
00914                                                         false);
00915           DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
00916                << ResultPtr << "]\n";  
00917 
00918           // If the target REALLY wants a stub for this function, emit it now.
00919           if (!MR.doesntNeedStub())
00920             ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
00921         } else if (MR.isGlobalValue()) {
00922           ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
00923                                          BufferBegin+MR.getMachineCodeOffset(),
00924                                          MR.doesntNeedStub());
00925         } else if (MR.isIndirectSymbol()) {
00926           ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
00927                                           BufferBegin+MR.getMachineCodeOffset(),
00928                                           MR.doesntNeedStub());
00929         } else if (MR.isBasicBlock()) {
00930           ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
00931         } else if (MR.isConstantPoolIndex()) {
00932           ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
00933         } else {
00934           assert(MR.isJumpTableIndex());
00935           ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
00936         }
00937 
00938         MR.setResultPointer(ResultPtr);
00939       }
00940 
00941       // if we are managing the GOT and the relocation wants an index,
00942       // give it one
00943       if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
00944         unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
00945         MR.setGOTIndex(idx);
00946         if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
00947           DOUT << "JIT: GOT was out of date for " << ResultPtr
00948                << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
00949                << "\n";
00950           ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
00951         }
00952       }
00953     }
00954 
00955     TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
00956                                   Relocations.size(), MemMgr->getGOTBase());
00957   }
00958 
00959   // Update the GOT entry for F to point to the new code.
00960   if (MemMgr->isManagingGOT()) {
00961     unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
00962     if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
00963       DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
00964            << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
00965       ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
00966     }
00967   }
00968 
00969   unsigned char *FnEnd = CurBufferPtr;
00970 
00971   MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
00972 
00973   if (CurBufferPtr == BufferEnd) {
00974     // FIXME: Allocate more space, then try again.
00975     cerr << "JIT: Ran out of space for generated machine code!\n";
00976     abort();
00977   }
00978 
00979   BufferBegin = CurBufferPtr = 0;
00980   NumBytes += FnEnd-FnStart;
00981 
00982   // Invalidate the icache if necessary.
00983   sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
00984   
00985   // Add it to the JIT symbol table if the host wants it.
00986   AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
00987                            FnStart, FnEnd-FnStart);
00988 
00989   DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
00990        << "] Function: " << F.getFunction()->getName()
00991        << ": " << (FnEnd-FnStart) << " bytes of text, "
00992        << Relocations.size() << " relocations\n";
00993   Relocations.clear();
00994 
00995   // Mark code region readable and executable if it's not so already.
00996   MemMgr->setMemoryExecutable();
00997 
00998 #ifndef NDEBUG
00999   {
01000     if (sys::hasDisassembler()) {
01001       DOUT << "JIT: Disassembled code:\n";
01002       DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
01003     } else {
01004       DOUT << "JIT: Binary code:\n";
01005       DOUT << std::hex;
01006       unsigned char* q = FnStart;
01007       for (int i = 0; q < FnEnd; q += 4, ++i) {
01008         if (i == 4)
01009           i = 0;
01010         if (i == 0)
01011           DOUT << "JIT: " << std::setw(8) << std::setfill('0')
01012                << (long)(q - FnStart) << ": ";
01013         bool Done = false;
01014         for (int j = 3; j >= 0; --j) {
01015           if (q + j >= FnEnd)
01016             Done = true;
01017           else
01018             DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
01019         }
01020         if (Done)
01021           break;
01022         DOUT << ' ';
01023         if (i == 3)
01024           DOUT << '\n';
01025       }
01026       DOUT << std::dec;
01027       DOUT<< '\n';
01028     }
01029   }
01030 #endif
01031   if (ExceptionHandling) {
01032     uintptr_t ActualSize = 0;
01033     SavedBufferBegin = BufferBegin;
01034     SavedBufferEnd = BufferEnd;
01035     SavedCurBufferPtr = CurBufferPtr;
01036     
01037     if (MemMgr->NeedsExactSize()) {
01038       ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
01039     }
01040 
01041     BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
01042                                                              ActualSize);
01043     BufferEnd = BufferBegin+ActualSize;
01044     unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
01045     MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
01046                               FrameRegister);
01047     BufferBegin = SavedBufferBegin;
01048     BufferEnd = SavedBufferEnd;
01049     CurBufferPtr = SavedCurBufferPtr;
01050 
01051     TheJIT->RegisterTable(FrameRegister);
01052   }
01053 
01054   if (MMI)
01055     MMI->EndFunction();
01056  
01057   return false;
01058 }
01059 
01060 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
01061   if (BufferBegin)
01062     return MachineCodeEmitter::allocateSpace(Size, Alignment);
01063 
01064   // create a new memory block if there is no active one.
01065   // care must be taken so that BufferBegin is invalidated when a
01066   // block is trimmed
01067   BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
01068   BufferEnd = BufferBegin+Size;
01069   return CurBufferPtr;
01070 }
01071 
01072 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
01073   if (TheJIT->getJITInfo().hasCustomConstantPool())
01074     return;
01075 
01076   const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
01077   if (Constants.empty()) return;
01078 
01079   MachineConstantPoolEntry CPE = Constants.back();
01080   unsigned Size = CPE.Offset;
01081   const Type *Ty = CPE.isMachineConstantPoolEntry()
01082     ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
01083   Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
01084 
01085   unsigned Align = 1 << MCP->getConstantPoolAlignment();
01086   ConstantPoolBase = allocateSpace(Size, Align);
01087   ConstantPool = MCP;
01088 
01089   if (ConstantPoolBase == 0) return;  // Buffer overflow.
01090 
01091   DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
01092        << "] (size: " << Size << ", alignment: " << Align << ")\n";
01093 
01094   // Initialize the memory for all of the constant pool entries.
01095   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
01096     void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
01097     if (Constants[i].isMachineConstantPoolEntry()) {
01098       // FIXME: add support to lower machine constant pool values into bytes!
01099       cerr << "Initialize memory with machine specific constant pool entry"
01100            << " has not been implemented!\n";
01101       abort();
01102     }
01103     TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
01104     DOUT << "JIT:   CP" << i << " at [" << CAddr << "]\n";
01105   }
01106 }
01107 
01108 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
01109   if (TheJIT->getJITInfo().hasCustomJumpTables())
01110     return;
01111 
01112   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
01113   if (JT.empty()) return;
01114   
01115   unsigned NumEntries = 0;
01116   for (unsigned i = 0, e = JT.size(); i != e; ++i)
01117     NumEntries += JT[i].MBBs.size();
01118 
01119   unsigned EntrySize = MJTI->getEntrySize();
01120 
01121   // Just allocate space for all the jump tables now.  We will fix up the actual
01122   // MBB entries in the tables after we emit the code for each block, since then
01123   // we will know the final locations of the MBBs in memory.
01124   JumpTable = MJTI;
01125   JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
01126 }
01127 
01128 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
01129   if (TheJIT->getJITInfo().hasCustomJumpTables())
01130     return;
01131 
01132   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
01133   if (JT.empty() || JumpTableBase == 0) return;
01134   
01135   if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
01136     assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
01137     // For each jump table, place the offset from the beginning of the table
01138     // to the target address.
01139     int *SlotPtr = (int*)JumpTableBase;
01140 
01141     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
01142       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
01143       // Store the offset of the basic block for this jump table slot in the
01144       // memory we allocated for the jump table in 'initJumpTableInfo'
01145       uintptr_t Base = (uintptr_t)SlotPtr;
01146       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
01147         uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
01148         *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
01149       }
01150     }
01151   } else {
01152     assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
01153     
01154     // For each jump table, map each target in the jump table to the address of 
01155     // an emitted MachineBasicBlock.
01156     intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
01157 
01158     for (unsigned i = 0, e = JT.size(); i != e; ++i) {
01159       const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
01160       // Store the address of the basic block for this jump table slot in the
01161       // memory we allocated for the jump table in 'initJumpTableInfo'
01162       for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
01163         *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
01164     }
01165   }
01166 }
01167 
01168 void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
01169                              unsigned Alignment) {
01170   SavedBufferBegin = BufferBegin;
01171   SavedBufferEnd = BufferEnd;
01172   SavedCurBufferPtr = CurBufferPtr;
01173   
01174   BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
01175   BufferEnd = BufferBegin+StubSize+1;
01176 }
01177 
01178 void *JITEmitter::finishGVStub(const GlobalValue* GV) {
01179   NumBytes += getCurrentPCOffset();
01180   std::swap(SavedBufferBegin, BufferBegin);
01181   BufferEnd = SavedBufferEnd;
01182   CurBufferPtr = SavedCurBufferPtr;
01183   return SavedBufferBegin;
01184 }
01185 
01186 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
01187 // in the constant pool that was last emitted with the 'emitConstantPool'
01188 // method.
01189 //
01190 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
01191   assert(ConstantNum < ConstantPool->getConstants().size() &&
01192          "Invalid ConstantPoolIndex!");
01193   return (uintptr_t)ConstantPoolBase +
01194          ConstantPool->getConstants()[ConstantNum].Offset;
01195 }
01196 
01197 // getJumpTableEntryAddress - Return the address of the JumpTable with index
01198 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
01199 //
01200 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
01201   const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
01202   assert(Index < JT.size() && "Invalid jump table index!");
01203   
01204   unsigned Offset = 0;
01205   unsigned EntrySize = JumpTable->getEntrySize();
01206   
01207   for (unsigned i = 0; i < Index; ++i)
01208     Offset += JT[i].MBBs.size();
01209   
01210    Offset *= EntrySize;
01211   
01212   return (uintptr_t)((char *)JumpTableBase + Offset);
01213 }
01214 
01215 //===----------------------------------------------------------------------===//
01216 //  Public interface to this file
01217 //===----------------------------------------------------------------------===//
01218 
01219 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
01220   return new JITEmitter(jit, JMM);
01221 }
01222 
01223 // getPointerToNamedFunction - This function is used as a global wrapper to
01224 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
01225 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
01226 // need to resolve function(s) that are being mis-codegenerated, so we need to
01227 // resolve their addresses at runtime, and this is the way to do it.
01228 extern "C" {
01229   void *getPointerToNamedFunction(const char *Name) {
01230     if (Function *F = TheJIT->FindFunctionNamed(Name))
01231       return TheJIT->getPointerToFunction(F);
01232     return TheJIT->getPointerToNamedFunction(Name);
01233   }
01234 }
01235 
01236 // getPointerToFunctionOrStub - If the specified function has been
01237 // code-gen'd, return a pointer to the function.  If not, compile it, or use
01238 // a stub to implement lazy compilation if available.
01239 //
01240 void *JIT::getPointerToFunctionOrStub(Function *F) {
01241   // If we have already code generated the function, just return the address.
01242   if (void *Addr = getPointerToGlobalIfAvailable(F))
01243     return Addr;
01244   
01245   // Get a stub if the target supports it.
01246   assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
01247   JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
01248   return JE->getJITResolver().getFunctionStub(F);
01249 }
01250 
01251 /// freeMachineCodeForFunction - release machine code memory for given Function.
01252 ///
01253 void JIT::freeMachineCodeForFunction(Function *F) {
01254 
01255   // Delete translation for this from the ExecutionEngine, so it will get
01256   // retranslated next time it is used.
01257   void *OldPtr = updateGlobalMapping(F, 0);
01258 
01259   if (OldPtr)
01260     RemoveFunctionFromSymbolTable(OldPtr);
01261 
01262   // Free the actual memory for the function body and related stuff.
01263   assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
01264   cast<JITEmitter>(MCE)->deallocateMemForFunction(F);
01265 }
01266