1 //===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "jit"
17 #include "JITDwarfEmitter.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/CodeGen/MachineCodeEmitter.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/JITMemoryManager.h"
28 #include "llvm/ExecutionEngine/GenericValue.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetJITInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/MutexGuard.h"
35 #include "llvm/System/Disassembler.h"
36 #include "llvm/System/Memory.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/Statistic.h"
47 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
48 STATISTIC(NumRelos, "Number of relocations applied");
49 static JIT *TheJIT = 0;
52 //===----------------------------------------------------------------------===//
53 // JIT lazy compilation code.
56 class JITResolverState {
58 /// FunctionToStubMap - Keep track of the stub created for a particular
59 /// function so that we can reuse them if necessary.
60 std::map<Function*, void*> FunctionToStubMap;
62 /// StubToFunctionMap - Keep track of the function that each stub
64 std::map<void*, Function*> StubToFunctionMap;
66 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
67 /// particular GlobalVariable so that we can reuse them if necessary.
68 std::map<GlobalValue*, void*> GlobalToIndirectSymMap;
71 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
72 assert(locked.holds(TheJIT->lock));
73 return FunctionToStubMap;
76 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
77 assert(locked.holds(TheJIT->lock));
78 return StubToFunctionMap;
81 std::map<GlobalValue*, void*>&
82 getGlobalToIndirectSymMap(const MutexGuard& locked) {
83 assert(locked.holds(TheJIT->lock));
84 return GlobalToIndirectSymMap;
88 /// JITResolver - Keep track of, and resolve, call sites for functions that
89 /// have not yet been compiled.
91 /// LazyResolverFn - The target lazy resolver function that we actually
92 /// rewrite instructions to use.
93 TargetJITInfo::LazyResolverFn LazyResolverFn;
95 JITResolverState state;
97 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
98 /// external functions.
99 std::map<void*, void*> ExternalFnToStubMap;
101 /// revGOTMap - map addresses to indexes in the GOT
102 std::map<void*, unsigned> revGOTMap;
103 unsigned nextGOTIndex;
105 static JITResolver *TheJITResolver;
107 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
110 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
111 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
112 TheJITResolver = this;
119 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
120 /// if it has already been created.
121 void *getFunctionStubIfAvailable(Function *F);
123 /// getFunctionStub - This returns a pointer to a function stub, creating
124 /// one on demand as needed. If empty is true, create a function stub
125 /// pointing at address 0, to be filled in later.
126 void *getFunctionStub(Function *F);
128 /// getExternalFunctionStub - Return a stub for the function at the
129 /// specified address, created lazily on demand.
130 void *getExternalFunctionStub(void *FnAddr);
132 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
133 /// specified GV address.
134 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
136 /// AddCallbackAtLocation - If the target is capable of rewriting an
137 /// instruction without the use of a stub, record the location of the use so
138 /// we know which function is being used at the location.
139 void *AddCallbackAtLocation(Function *F, void *Location) {
140 MutexGuard locked(TheJIT->lock);
141 /// Get the target-specific JIT resolver function.
142 state.getStubToFunctionMap(locked)[Location] = F;
143 return (void*)(intptr_t)LazyResolverFn;
146 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
147 SmallVectorImpl<void*> &Ptrs);
149 GlobalValue *invalidateStub(void *Stub);
151 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
152 /// an address. This function only manages slots, it does not manage the
153 /// contents of the slots or the memory associated with the GOT.
154 unsigned getGOTIndexForAddr(void *addr);
156 /// JITCompilerFn - This function is called to resolve a stub to a compiled
157 /// address. If the LLVM Function corresponding to the stub has not yet
158 /// been compiled, this function compiles it first.
159 static void *JITCompilerFn(void *Stub);
163 JITResolver *JITResolver::TheJITResolver = 0;
165 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
166 /// if it has already been created.
167 void *JITResolver::getFunctionStubIfAvailable(Function *F) {
168 MutexGuard locked(TheJIT->lock);
170 // If we already have a stub for this function, recycle it.
171 void *&Stub = state.getFunctionToStubMap(locked)[F];
175 /// getFunctionStub - This returns a pointer to a function stub, creating
176 /// one on demand as needed.
177 void *JITResolver::getFunctionStub(Function *F) {
178 MutexGuard locked(TheJIT->lock);
180 // If we already have a stub for this function, recycle it.
181 void *&Stub = state.getFunctionToStubMap(locked)[F];
182 if (Stub) return Stub;
184 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
185 // case we must resolve the symbol now.
186 void *Actual = TheJIT->isLazyCompilationDisabled()
187 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
189 // If this is an external declaration, attempt to resolve the address now
190 // to place in the stub.
191 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
192 Actual = TheJIT->getPointerToFunction(F);
194 // If we resolved the symbol to a null address (eg. a weak external)
195 // don't emit a stub. Return a null pointer to the application. If dlsym
196 // stubs are enabled, not being able to resolve the address is not
198 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
201 // Codegen a new stub, calling the lazy resolver or the actual address of the
202 // external function, if it was resolved.
203 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
204 *TheJIT->getCodeEmitter());
206 if (Actual != (void*)(intptr_t)LazyResolverFn) {
207 // If we are getting the stub for an external function, we really want the
208 // address of the stub in the GlobalAddressMap for the JIT, not the address
209 // of the external function.
210 TheJIT->updateGlobalMapping(F, Stub);
213 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
214 << F->getName() << "'\n";
216 // Finally, keep track of the stub-to-Function mapping so that the
217 // JITCompilerFn knows which function to compile!
218 state.getStubToFunctionMap(locked)[Stub] = F;
220 // If we are JIT'ing non-lazily but need to call a function that does not
221 // exist yet, add it to the JIT's work list so that we can fill in the stub
223 if (!Actual && TheJIT->isLazyCompilationDisabled())
224 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
225 TheJIT->addPendingFunction(F);
230 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
232 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
233 MutexGuard locked(TheJIT->lock);
235 // If we already have a stub for this global variable, recycle it.
236 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
237 if (IndirectSym) return IndirectSym;
239 // Otherwise, codegen a new indirect symbol.
240 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
241 *TheJIT->getCodeEmitter());
243 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
244 << GV->getName() << "'\n";
249 /// getExternalFunctionStub - Return a stub for the function at the
250 /// specified address, created lazily on demand.
251 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
252 // If we already have a stub for this function, recycle it.
253 void *&Stub = ExternalFnToStubMap[FnAddr];
254 if (Stub) return Stub;
256 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
257 *TheJIT->getCodeEmitter());
259 DOUT << "JIT: Stub emitted at [" << Stub
260 << "] for external function at '" << FnAddr << "'\n";
264 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
265 unsigned idx = revGOTMap[addr];
267 idx = ++nextGOTIndex;
268 revGOTMap[addr] = idx;
269 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
274 void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
275 SmallVectorImpl<void*> &Ptrs) {
276 MutexGuard locked(TheJIT->lock);
278 std::map<Function*,void*> &FM = state.getFunctionToStubMap(locked);
279 std::map<GlobalValue*,void*> &GM = state.getGlobalToIndirectSymMap(locked);
281 for (std::map<Function*,void*>::iterator i = FM.begin(), e = FM.end();
283 Function *F = i->first;
284 if (F->isDeclaration() && F->hasExternalLinkage()) {
285 GVs.push_back(i->first);
286 Ptrs.push_back(i->second);
289 for (std::map<GlobalValue*,void*>::iterator i = GM.begin(), e = GM.end();
291 GVs.push_back(i->first);
292 Ptrs.push_back(i->second);
296 GlobalValue *JITResolver::invalidateStub(void *Stub) {
297 MutexGuard locked(TheJIT->lock);
299 std::map<Function*,void*> &FM = state.getFunctionToStubMap(locked);
300 std::map<void*,Function*> &SM = state.getStubToFunctionMap(locked);
301 std::map<GlobalValue*,void*> &GM = state.getGlobalToIndirectSymMap(locked);
303 // Look up the cheap way first, to see if it's a function stub we are
304 // invalidating. If so, remove it from both the forward and reverse maps.
305 if (SM.find(Stub) != SM.end()) {
306 Function *F = SM[Stub];
312 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
313 for (std::map<GlobalValue*,void*>::iterator i = GM.begin(), e = GM.end();
315 if (i->second != Stub)
317 GlobalValue *GV = i->first;
322 // Lastly, check to see if it's in the ExternalFnToStubMap.
323 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
324 e = ExternalFnToStubMap.end(); i != e; ++i) {
325 if (i->second != Stub)
327 ExternalFnToStubMap.erase(i);
334 /// JITCompilerFn - This function is called when a lazy compilation stub has
335 /// been entered. It looks up which function this stub corresponds to, compiles
336 /// it if necessary, then returns the resultant function pointer.
337 void *JITResolver::JITCompilerFn(void *Stub) {
338 JITResolver &JR = *TheJITResolver;
344 // Only lock for getting the Function. The call getPointerToFunction made
345 // in this function might trigger function materializing, which requires
346 // JIT lock to be unlocked.
347 MutexGuard locked(TheJIT->lock);
349 // The address given to us for the stub may not be exactly right, it might be
350 // a little bit after the stub. As such, use upper_bound to find it.
351 std::map<void*, Function*>::iterator I =
352 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
353 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
354 "This is not a known stub!");
356 ActualPtr = I->first;
359 // If we have already code generated the function, just return the address.
360 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
363 // Otherwise we don't have it, do lazy compilation now.
365 // If lazy compilation is disabled, emit a useful error message and abort.
366 if (TheJIT->isLazyCompilationDisabled()) {
367 cerr << "LLVM JIT requested to do lazy compilation of function '"
368 << F->getName() << "' when lazy compiles are disabled!\n";
372 // We might like to remove the stub from the StubToFunction map.
373 // We can't do that! Multiple threads could be stuck, waiting to acquire the
374 // lock above. As soon as the 1st function finishes compiling the function,
375 // the next one will be released, and needs to be able to find the function
377 //JR.state.getStubToFunctionMap(locked).erase(I);
379 DOUT << "JIT: Lazily resolving function '" << F->getName()
380 << "' In stub ptr = " << Stub << " actual ptr = "
381 << ActualPtr << "\n";
383 Result = TheJIT->getPointerToFunction(F);
386 // Reacquire the lock to erase the stub in the map.
387 MutexGuard locked(TheJIT->lock);
389 // We don't need to reuse this stub in the future, as F is now compiled.
390 JR.state.getFunctionToStubMap(locked).erase(F);
392 // FIXME: We could rewrite all references to this stub if we knew them.
394 // What we will do is set the compiled function address to map to the
395 // same GOT entry as the stub so that later clients may update the GOT
396 // if they see it still using the stub address.
397 // Note: this is done so the Resolver doesn't have to manage GOT memory
398 // Do this without allocating map space if the target isn't using a GOT
399 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
400 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
405 //===----------------------------------------------------------------------===//
406 // Function Index Support
408 // On MacOS we generate an index of currently JIT'd functions so that
409 // performance tools can determine a symbol name and accurate code range for a
410 // PC value. Because performance tools are generally asynchronous, the code
411 // below is written with the hope that it could be interrupted at any time and
412 // have useful answers. However, we don't go crazy with atomic operations, we
413 // just do a "reasonable effort".
415 #define ENABLE_JIT_SYMBOL_TABLE 0
418 /// JitSymbolEntry - Each function that is JIT compiled results in one of these
419 /// being added to an array of symbols. This indicates the name of the function
420 /// as well as the address range it occupies. This allows the client to map
421 /// from a PC value to the name of the function.
422 struct JitSymbolEntry {
423 const char *FnName; // FnName - a strdup'd string.
429 struct JitSymbolTable {
430 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
431 /// pointer is not used right now, but might be used in the future. Consider
432 /// it reserved for future use.
433 JitSymbolTable *NextPtr;
435 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
436 /// 'NumSymbols' symbols are valid.
437 JitSymbolEntry *Symbols;
439 /// NumSymbols - This indicates the number entries in the Symbols array that
443 /// NumAllocated - This indicates the amount of space we have in the Symbols
444 /// array. This is a private field that should not be read by external tools.
445 unsigned NumAllocated;
448 #if ENABLE_JIT_SYMBOL_TABLE
449 JitSymbolTable *__jitSymbolTable;
452 static void AddFunctionToSymbolTable(const char *FnName,
453 void *FnStart, intptr_t FnSize) {
454 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
455 JitSymbolTable **SymTabPtrPtr = 0;
456 #if !ENABLE_JIT_SYMBOL_TABLE
459 SymTabPtrPtr = &__jitSymbolTable;
462 // If this is the first entry in the symbol table, add the JitSymbolTable
464 if (*SymTabPtrPtr == 0) {
465 JitSymbolTable *New = new JitSymbolTable();
469 New->NumAllocated = 0;
473 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
475 // If we have space in the table, reallocate the table.
476 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
477 // If we don't have space, reallocate the table.
478 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
479 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
480 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
482 // Copy the old entries over.
483 memcpy(NewSymbols, OldSymbols, SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
485 // Swap the new symbols in, delete the old ones.
486 SymTabPtr->Symbols = NewSymbols;
487 SymTabPtr->NumAllocated = NewSize;
488 delete [] OldSymbols;
491 // Otherwise, we have enough space, just tack it onto the end of the array.
492 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
493 Entry.FnName = strdup(FnName);
494 Entry.FnStart = FnStart;
495 Entry.FnSize = FnSize;
496 ++SymTabPtr->NumSymbols;
499 static void RemoveFunctionFromSymbolTable(void *FnStart) {
500 assert(FnStart && "Invalid function pointer");
501 JitSymbolTable **SymTabPtrPtr = 0;
502 #if !ENABLE_JIT_SYMBOL_TABLE
505 SymTabPtrPtr = &__jitSymbolTable;
508 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
509 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
511 // Scan the table to find its index. The table is not sorted, so do a linear
514 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
515 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
517 // Once we have an index, we know to nuke this entry, overwrite it with the
518 // entry at the end of the array, making the last entry redundant.
519 const char *OldName = Symbols[Index].FnName;
520 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
521 free((void*)OldName);
523 // Drop the number of symbols in the table.
524 --SymTabPtr->NumSymbols;
526 // Finally, if we deleted the final symbol, deallocate the table itself.
527 if (SymTabPtr->NumSymbols != 0)
535 //===----------------------------------------------------------------------===//
539 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
540 /// used to output functions to memory for execution.
541 class JITEmitter : public MachineCodeEmitter {
542 JITMemoryManager *MemMgr;
544 // When outputting a function stub in the context of some other function, we
545 // save BufferBegin/BufferEnd/CurBufferPtr here.
546 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
548 /// Relocations - These are the relocations that the function needs, as
550 std::vector<MachineRelocation> Relocations;
552 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
553 /// It is filled in by the StartMachineBasicBlock callback and queried by
554 /// the getMachineBasicBlockAddress callback.
555 std::vector<uintptr_t> MBBLocations;
557 /// ConstantPool - The constant pool for the current function.
559 MachineConstantPool *ConstantPool;
561 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
563 void *ConstantPoolBase;
565 /// ConstPoolAddresses - Addresses of individual constant pool entries.
567 SmallVector<uintptr_t, 8> ConstPoolAddresses;
569 /// JumpTable - The jump tables for the current function.
571 MachineJumpTableInfo *JumpTable;
573 /// JumpTableBase - A pointer to the first entry in the jump table.
577 /// Resolver - This contains info about the currently resolved functions.
578 JITResolver Resolver;
580 /// DE - The dwarf emitter for the jit.
583 /// LabelLocations - This vector is a mapping from Label ID's to their
585 std::vector<uintptr_t> LabelLocations;
587 /// MMI - Machine module info for exception informations
588 MachineModuleInfo* MMI;
590 // GVSet - a set to keep track of which globals have been seen
591 SmallPtrSet<const GlobalVariable*, 8> GVSet;
593 // CurFn - The llvm function being emitted. Only valid during
595 const Function *CurFn;
597 // CurFnStubUses - For a given Function, a vector of stubs that it
598 // references. This facilitates the JIT detecting that a stub is no
599 // longer used, so that it may be deallocated.
600 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
602 // StubFnRefs - For a given pointer to a stub, a set of Functions which
603 // reference the stub. When the count of a stub's references drops to zero,
604 // the stub is unused.
605 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
607 // ExtFnStubs - A map of external function names to stubs which have entries
608 // in the JITResolver's ExternalFnToStubMap.
609 StringMap<void *> ExtFnStubs;
612 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit), CurFn(0) {
613 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
614 if (jit.getJITInfo().needsGOT()) {
615 MemMgr->AllocateGOT();
616 DOUT << "JIT is managing a GOT\n";
619 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
623 if (ExceptionHandling) delete DE;
626 /// classof - Methods for support type inquiry through isa, cast, and
629 static inline bool classof(const JITEmitter*) { return true; }
630 static inline bool classof(const MachineCodeEmitter*) { return true; }
632 JITResolver &getJITResolver() { return Resolver; }
634 virtual void startFunction(MachineFunction &F);
635 virtual bool finishFunction(MachineFunction &F);
637 void emitConstantPool(MachineConstantPool *MCP);
638 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
639 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
641 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
642 unsigned Alignment = 1);
643 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
645 virtual void* finishGVStub(const GlobalValue *GV);
647 /// allocateSpace - Reserves space in the current block if any, or
648 /// allocate a new one of the given size.
649 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
651 virtual void addRelocation(const MachineRelocation &MR) {
652 Relocations.push_back(MR);
655 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
656 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
657 MBBLocations.resize((MBB->getNumber()+1)*2);
658 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
659 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
660 << (void*) getCurrentPCValue() << "]\n";
663 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
664 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
666 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
667 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
668 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
669 return MBBLocations[MBB->getNumber()];
672 /// deallocateMemForFunction - Deallocate all memory for the specified
674 void deallocateMemForFunction(Function *F);
676 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
677 /// using the stub at the specified address. Allows
678 /// deallocateMemForFunction to also remove stubs no longer referenced.
679 void AddStubToCurrentFunction(void *Stub);
681 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
682 /// MachineRelocations that reference external functions by name.
683 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
685 virtual void emitLabel(uint64_t LabelID) {
686 if (LabelLocations.size() <= LabelID)
687 LabelLocations.resize((LabelID+1)*2);
688 LabelLocations[LabelID] = getCurrentPCValue();
691 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
692 assert(LabelLocations.size() > (unsigned)LabelID &&
693 LabelLocations[LabelID] && "Label not emitted!");
694 return LabelLocations[LabelID];
697 virtual void setModuleInfo(MachineModuleInfo* Info) {
699 if (ExceptionHandling) DE->setModuleInfo(Info);
702 void setMemoryExecutable(void) {
703 MemMgr->setMemoryExecutable();
706 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
709 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
710 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
712 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
713 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
714 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
715 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
719 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
720 bool DoesntNeedStub) {
721 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
722 return TheJIT->getOrEmitGlobalVariable(GV);
724 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
725 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
727 // If we have already compiled the function, return a pointer to its body.
728 Function *F = cast<Function>(V);
730 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
731 // Return the function stub if it's already created.
732 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
734 AddStubToCurrentFunction(ResultPtr);
736 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
738 if (ResultPtr) return ResultPtr;
740 // If this is an external function pointer, we can force the JIT to
741 // 'compile' it, which really just adds it to the map. In dlsym mode,
742 // external functions are forced through a stub, regardless of reloc type.
743 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
744 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
745 return TheJIT->getPointerToFunction(F);
747 // Okay, the function has not been compiled yet, if the target callback
748 // mechanism is capable of rewriting the instruction directly, prefer to do
749 // that instead of emitting a stub. This uses the lazy resolver, so is not
750 // legal if lazy compilation is disabled.
751 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
752 return Resolver.AddCallbackAtLocation(F, Reference);
754 // Otherwise, we have to emit a stub.
755 void *StubAddr = Resolver.getFunctionStub(F);
757 // Add the stub to the current function's list of referenced stubs, so we can
758 // deallocate them if the current function is ever freed. It's possible to
759 // return null from getFunctionStub in the case of a weak extern that fails
762 AddStubToCurrentFunction(StubAddr);
767 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
769 // Make sure GV is emitted first, and create a stub containing the fully
771 void *GVAddress = getPointerToGlobal(V, Reference, true);
772 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
774 // Add the stub to the current function's list of referenced stubs, so we can
775 // deallocate them if the current function is ever freed.
776 AddStubToCurrentFunction(StubAddr);
781 void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
782 if (!TheJIT->areDlsymStubsEnabled())
785 assert(CurFn && "Stub added to current function, but current function is 0!");
787 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
788 StubsUsed.push_back(StubAddr);
790 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
791 FnRefs.insert(CurFn);
794 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
795 const TargetData *TD) {
796 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
797 if (Constants.empty()) return 0;
800 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
801 MachineConstantPoolEntry CPE = Constants[i];
802 unsigned AlignMask = CPE.getAlignment() - 1;
803 Size = (Size + AlignMask) & ~AlignMask;
804 const Type *Ty = CPE.getType();
805 Size += TD->getTypePaddedSize(Ty);
810 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
811 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
812 if (JT.empty()) return 0;
814 unsigned NumEntries = 0;
815 for (unsigned i = 0, e = JT.size(); i != e; ++i)
816 NumEntries += JT[i].MBBs.size();
818 unsigned EntrySize = MJTI->getEntrySize();
820 return NumEntries * EntrySize;
823 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
824 if (Alignment == 0) Alignment = 1;
825 // Since we do not know where the buffer will be allocated, be pessimistic.
826 return Size + Alignment;
829 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
830 /// into the running total Size.
832 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
833 const Type *ElTy = GV->getType()->getElementType();
834 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypePaddedSize(ElTy);
836 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
837 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
839 // Assume code section ends with worst possible alignment, so first
840 // variable needs maximal padding.
843 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
848 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
849 /// but are referenced from the constant; put them in GVSet and add their
850 /// size into the running total Size.
852 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
854 // If its undefined, return the garbage.
855 if (isa<UndefValue>(C))
858 // If the value is a ConstantExpr
859 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
860 Constant *Op0 = CE->getOperand(0);
861 switch (CE->getOpcode()) {
862 case Instruction::GetElementPtr:
863 case Instruction::Trunc:
864 case Instruction::ZExt:
865 case Instruction::SExt:
866 case Instruction::FPTrunc:
867 case Instruction::FPExt:
868 case Instruction::UIToFP:
869 case Instruction::SIToFP:
870 case Instruction::FPToUI:
871 case Instruction::FPToSI:
872 case Instruction::PtrToInt:
873 case Instruction::IntToPtr:
874 case Instruction::BitCast: {
875 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
878 case Instruction::Add:
879 case Instruction::Sub:
880 case Instruction::Mul:
881 case Instruction::UDiv:
882 case Instruction::SDiv:
883 case Instruction::URem:
884 case Instruction::SRem:
885 case Instruction::And:
886 case Instruction::Or:
887 case Instruction::Xor: {
888 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
889 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
893 cerr << "ConstantExpr not handled: " << *CE << "\n";
899 if (C->getType()->getTypeID() == Type::PointerTyID)
900 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
901 if (GVSet.insert(GV))
902 Size = addSizeOfGlobal(GV, Size);
907 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
908 /// but are referenced from the given initializer.
910 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
912 if (!isa<UndefValue>(Init) &&
913 !isa<ConstantVector>(Init) &&
914 !isa<ConstantAggregateZero>(Init) &&
915 !isa<ConstantArray>(Init) &&
916 !isa<ConstantStruct>(Init) &&
917 Init->getType()->isFirstClassType())
918 Size = addSizeOfGlobalsInConstantVal(Init, Size);
922 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
923 /// globals; then walk the initializers of those globals looking for more.
924 /// If their size has not been considered yet, add it into the running total
927 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
931 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
933 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
935 const TargetInstrDesc &Desc = I->getDesc();
936 const MachineInstr &MI = *I;
937 unsigned NumOps = Desc.getNumOperands();
938 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
939 const MachineOperand &MO = MI.getOperand(CurOp);
941 GlobalValue* V = MO.getGlobal();
942 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
945 // If seen in previous function, it will have an entry here.
946 if (TheJIT->getPointerToGlobalIfAvailable(GV))
948 // If seen earlier in this function, it will have an entry here.
949 // FIXME: it should be possible to combine these tables, by
950 // assuming the addresses of the new globals in this module
951 // start at 0 (or something) and adjusting them after codegen
952 // complete. Another possibility is to grab a marker bit in GV.
953 if (GVSet.insert(GV))
954 // A variable as yet unseen. Add in its size.
955 Size = addSizeOfGlobal(GV, Size);
960 DOUT << "JIT: About to look through initializers\n";
961 // Look for more globals that are referenced only from initializers.
962 // GVSet.end is computed each time because the set can grow as we go.
963 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
964 I != GVSet.end(); I++) {
965 const GlobalVariable* GV = *I;
966 if (GV->hasInitializer())
967 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
973 void JITEmitter::startFunction(MachineFunction &F) {
974 DOUT << "JIT: Starting CodeGen of Function "
975 << F.getFunction()->getName() << "\n";
977 uintptr_t ActualSize = 0;
978 // Set the memory writable, if it's not already
979 MemMgr->setMemoryWritable();
980 if (MemMgr->NeedsExactSize()) {
981 DOUT << "JIT: ExactSize\n";
982 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
983 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
984 MachineConstantPool *MCP = F.getConstantPool();
986 // Ensure the constant pool/jump table info is at least 4-byte aligned.
987 ActualSize = RoundUpToAlign(ActualSize, 16);
989 // Add the alignment of the constant pool
990 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
992 // Add the constant pool size
993 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
995 // Add the aligment of the jump table info
996 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
998 // Add the jump table size
999 ActualSize += GetJumpTableSizeInBytes(MJTI);
1001 // Add the alignment for the function
1002 ActualSize = RoundUpToAlign(ActualSize,
1003 std::max(F.getFunction()->getAlignment(), 8U));
1005 // Add the function size
1006 ActualSize += TII->GetFunctionSizeInBytes(F);
1008 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
1009 // Add the size of the globals that will be allocated after this function.
1010 // These are all the ones referenced from this function that were not
1011 // previously allocated.
1012 ActualSize += GetSizeOfGlobalsInBytes(F);
1013 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
1016 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
1018 BufferEnd = BufferBegin+ActualSize;
1020 // Ensure the constant pool/jump table info is at least 4-byte aligned.
1023 emitConstantPool(F.getConstantPool());
1024 initJumpTableInfo(F.getJumpTableInfo());
1026 // About to start emitting the machine code for the function.
1027 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
1028 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
1030 MBBLocations.clear();
1033 bool JITEmitter::finishFunction(MachineFunction &F) {
1034 if (CurBufferPtr == BufferEnd) {
1035 // FIXME: Allocate more space, then try again.
1036 cerr << "JIT: Ran out of space for generated machine code!\n";
1040 emitJumpTableInfo(F.getJumpTableInfo());
1042 // FnStart is the start of the text, not the start of the constant pool and
1043 // other per-function data.
1044 unsigned char *FnStart =
1045 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
1047 if (!Relocations.empty()) {
1048 CurFn = F.getFunction();
1049 NumRelos += Relocations.size();
1051 // Resolve the relocations to concrete pointers.
1052 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1053 MachineRelocation &MR = Relocations[i];
1054 void *ResultPtr = 0;
1055 if (!MR.letTargetResolve()) {
1056 if (MR.isExternalSymbol()) {
1057 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1059 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
1060 << ResultPtr << "]\n";
1062 // If the target REALLY wants a stub for this function, emit it now.
1063 if (!MR.doesntNeedStub()) {
1064 if (!TheJIT->areDlsymStubsEnabled()) {
1065 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1067 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1069 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1070 AddStubToCurrentFunction(Stub);
1075 } else if (MR.isGlobalValue()) {
1076 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1077 BufferBegin+MR.getMachineCodeOffset(),
1078 MR.doesntNeedStub());
1079 } else if (MR.isIndirectSymbol()) {
1080 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
1081 BufferBegin+MR.getMachineCodeOffset(),
1082 MR.doesntNeedStub());
1083 } else if (MR.isBasicBlock()) {
1084 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1085 } else if (MR.isConstantPoolIndex()) {
1086 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1088 assert(MR.isJumpTableIndex());
1089 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1092 MR.setResultPointer(ResultPtr);
1095 // if we are managing the GOT and the relocation wants an index,
1097 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
1098 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
1099 MR.setGOTIndex(idx);
1100 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
1101 DOUT << "JIT: GOT was out of date for " << ResultPtr
1102 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1104 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
1110 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
1111 Relocations.size(), MemMgr->getGOTBase());
1114 // Update the GOT entry for F to point to the new code.
1115 if (MemMgr->isManagingGOT()) {
1116 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
1117 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
1118 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
1119 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1120 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
1124 unsigned char *FnEnd = CurBufferPtr;
1126 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
1128 if (CurBufferPtr == BufferEnd) {
1129 // FIXME: Allocate more space, then try again.
1130 cerr << "JIT: Ran out of space for generated machine code!\n";
1134 BufferBegin = CurBufferPtr = 0;
1135 NumBytes += FnEnd-FnStart;
1137 // Invalidate the icache if necessary.
1138 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
1140 // Add it to the JIT symbol table if the host wants it.
1141 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
1142 FnStart, FnEnd-FnStart);
1144 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1145 << "] Function: " << F.getFunction()->getName()
1146 << ": " << (FnEnd-FnStart) << " bytes of text, "
1147 << Relocations.size() << " relocations\n";
1148 Relocations.clear();
1149 ConstPoolAddresses.clear();
1151 // Mark code region readable and executable if it's not so already.
1152 MemMgr->setMemoryExecutable();
1156 if (sys::hasDisassembler()) {
1157 DOUT << "JIT: Disassembled code:\n";
1158 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
1160 DOUT << "JIT: Binary code:\n";
1162 unsigned char* q = FnStart;
1163 for (int i = 0; q < FnEnd; q += 4, ++i) {
1167 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1168 << (long)(q - FnStart) << ": ";
1170 for (int j = 3; j >= 0; --j) {
1174 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1187 if (ExceptionHandling) {
1188 uintptr_t ActualSize = 0;
1189 SavedBufferBegin = BufferBegin;
1190 SavedBufferEnd = BufferEnd;
1191 SavedCurBufferPtr = CurBufferPtr;
1193 if (MemMgr->NeedsExactSize()) {
1194 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
1197 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1199 BufferEnd = BufferBegin+ActualSize;
1200 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
1201 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1203 BufferBegin = SavedBufferBegin;
1204 BufferEnd = SavedBufferEnd;
1205 CurBufferPtr = SavedCurBufferPtr;
1207 TheJIT->RegisterTable(FrameRegister);
1216 /// deallocateMemForFunction - Deallocate all memory for the specified
1217 /// function body. Also drop any references the function has to stubs.
1218 void JITEmitter::deallocateMemForFunction(Function *F) {
1219 MemMgr->deallocateMemForFunction(F);
1221 // If the function did not reference any stubs, return.
1222 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1225 // For each referenced stub, erase the reference to this function, and then
1226 // erase the list of referenced stubs.
1227 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1228 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1229 void *Stub = StubList[i];
1231 // If we already invalidated this stub for this function, continue.
1232 if (StubFnRefs.count(Stub) == 0)
1235 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1238 // If this function was the last reference to the stub, invalidate the stub
1239 // in the JITResolver. Were there a memory manager deallocateStub routine,
1240 // we could call that at this point too.
1241 if (FnRefs.empty()) {
1242 DOUT << "\nJIT: Invalidated Stub at [" << Stub << "]\n";
1243 StubFnRefs.erase(Stub);
1245 // Invalidate the stub. If it is a GV stub, update the JIT's global
1246 // mapping for that GV to zero, otherwise, search the string map of
1247 // external function names to stubs and remove the entry for this stub.
1248 GlobalValue *GV = Resolver.invalidateStub(Stub);
1250 TheJIT->updateGlobalMapping(GV, 0);
1252 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1253 e = ExtFnStubs.end(); i != e; ++i) {
1254 if (i->second == Stub) {
1255 ExtFnStubs.erase(i);
1262 CurFnStubUses.erase(F);
1266 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1268 return MachineCodeEmitter::allocateSpace(Size, Alignment);
1270 // create a new memory block if there is no active one.
1271 // care must be taken so that BufferBegin is invalidated when a
1273 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1274 BufferEnd = BufferBegin+Size;
1275 return CurBufferPtr;
1278 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1279 if (TheJIT->getJITInfo().hasCustomConstantPool())
1282 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1283 if (Constants.empty()) return;
1285 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1286 unsigned Align = MCP->getConstantPoolAlignment();
1287 ConstantPoolBase = allocateSpace(Size, Align);
1290 if (ConstantPoolBase == 0) return; // Buffer overflow.
1292 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1293 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1295 // Initialize the memory for all of the constant pool entries.
1296 unsigned Offset = 0;
1297 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1298 MachineConstantPoolEntry CPE = Constants[i];
1299 unsigned AlignMask = CPE.getAlignment() - 1;
1300 Offset = (Offset + AlignMask) & ~AlignMask;
1302 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1303 ConstPoolAddresses.push_back(CAddr);
1304 if (CPE.isMachineConstantPoolEntry()) {
1305 // FIXME: add support to lower machine constant pool values into bytes!
1306 cerr << "Initialize memory with machine specific constant pool entry"
1307 << " has not been implemented!\n";
1310 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1311 DOUT << "JIT: CP" << i << " at [0x"
1312 << std::hex << CAddr << std::dec << "]\n";
1314 const Type *Ty = CPE.Val.ConstVal->getType();
1315 Offset += TheJIT->getTargetData()->getTypePaddedSize(Ty);
1319 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1320 if (TheJIT->getJITInfo().hasCustomJumpTables())
1323 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1324 if (JT.empty()) return;
1326 unsigned NumEntries = 0;
1327 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1328 NumEntries += JT[i].MBBs.size();
1330 unsigned EntrySize = MJTI->getEntrySize();
1332 // Just allocate space for all the jump tables now. We will fix up the actual
1333 // MBB entries in the tables after we emit the code for each block, since then
1334 // we will know the final locations of the MBBs in memory.
1336 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1339 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1340 if (TheJIT->getJITInfo().hasCustomJumpTables())
1343 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1344 if (JT.empty() || JumpTableBase == 0) return;
1346 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1347 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1348 // For each jump table, place the offset from the beginning of the table
1349 // to the target address.
1350 int *SlotPtr = (int*)JumpTableBase;
1352 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1353 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1354 // Store the offset of the basic block for this jump table slot in the
1355 // memory we allocated for the jump table in 'initJumpTableInfo'
1356 uintptr_t Base = (uintptr_t)SlotPtr;
1357 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1358 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1359 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1363 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1365 // For each jump table, map each target in the jump table to the address of
1366 // an emitted MachineBasicBlock.
1367 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1369 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1370 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1371 // Store the address of the basic block for this jump table slot in the
1372 // memory we allocated for the jump table in 'initJumpTableInfo'
1373 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1374 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1379 void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1380 unsigned Alignment) {
1381 SavedBufferBegin = BufferBegin;
1382 SavedBufferEnd = BufferEnd;
1383 SavedCurBufferPtr = CurBufferPtr;
1385 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1386 BufferEnd = BufferBegin+StubSize+1;
1389 void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1390 unsigned StubSize) {
1391 SavedBufferBegin = BufferBegin;
1392 SavedBufferEnd = BufferEnd;
1393 SavedCurBufferPtr = CurBufferPtr;
1395 BufferBegin = CurBufferPtr = (unsigned char *)Buffer;
1396 BufferEnd = BufferBegin+StubSize+1;
1399 void *JITEmitter::finishGVStub(const GlobalValue* GV) {
1400 NumBytes += getCurrentPCOffset();
1401 std::swap(SavedBufferBegin, BufferBegin);
1402 BufferEnd = SavedBufferEnd;
1403 CurBufferPtr = SavedCurBufferPtr;
1404 return SavedBufferBegin;
1407 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1408 // in the constant pool that was last emitted with the 'emitConstantPool'
1411 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1412 assert(ConstantNum < ConstantPool->getConstants().size() &&
1413 "Invalid ConstantPoolIndex!");
1414 return ConstPoolAddresses[ConstantNum];
1417 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1418 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1420 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1421 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1422 assert(Index < JT.size() && "Invalid jump table index!");
1424 unsigned Offset = 0;
1425 unsigned EntrySize = JumpTable->getEntrySize();
1427 for (unsigned i = 0; i < Index; ++i)
1428 Offset += JT[i].MBBs.size();
1430 Offset *= EntrySize;
1432 return (uintptr_t)((char *)JumpTableBase + Offset);
1435 //===----------------------------------------------------------------------===//
1436 // Public interface to this file
1437 //===----------------------------------------------------------------------===//
1439 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1440 return new JITEmitter(jit, JMM);
1443 // getPointerToNamedFunction - This function is used as a global wrapper to
1444 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1445 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1446 // need to resolve function(s) that are being mis-codegenerated, so we need to
1447 // resolve their addresses at runtime, and this is the way to do it.
1449 void *getPointerToNamedFunction(const char *Name) {
1450 if (Function *F = TheJIT->FindFunctionNamed(Name))
1451 return TheJIT->getPointerToFunction(F);
1452 return TheJIT->getPointerToNamedFunction(Name);
1456 // getPointerToFunctionOrStub - If the specified function has been
1457 // code-gen'd, return a pointer to the function. If not, compile it, or use
1458 // a stub to implement lazy compilation if available.
1460 void *JIT::getPointerToFunctionOrStub(Function *F) {
1461 // If we have already code generated the function, just return the address.
1462 if (void *Addr = getPointerToGlobalIfAvailable(F))
1465 // Get a stub if the target supports it.
1466 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1467 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1468 return JE->getJITResolver().getFunctionStub(F);
1471 void JIT::updateFunctionStub(Function *F) {
1472 // Get the empty stub we generated earlier.
1473 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1474 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1475 void *Stub = JE->getJITResolver().getFunctionStub(F);
1477 // Tell the target jit info to rewrite the stub at the specified address,
1478 // rather than creating a new one.
1479 void *Addr = getPointerToGlobalIfAvailable(F);
1480 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1483 /// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1484 /// that were emitted during code generation.
1486 void JIT::updateDlsymStubTable() {
1487 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1488 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1490 SmallVector<GlobalValue*, 8> GVs;
1491 SmallVector<void*, 8> Ptrs;
1492 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
1494 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1496 unsigned nStubs = GVs.size() + ExtFns.size();
1498 // If there are no relocatable stubs, return.
1502 // If there are no new relocatable stubs, return.
1503 void *CurTable = JE->getMemMgr()->getDlsymTable();
1504 if (CurTable && (*(unsigned *)CurTable == nStubs))
1507 // Calculate the size of the stub info
1508 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
1510 SmallVector<unsigned, 8> Offsets;
1511 for (unsigned i = 0; i != GVs.size(); ++i) {
1512 Offsets.push_back(offset);
1513 offset += GVs[i]->getName().length() + 1;
1515 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1517 Offsets.push_back(offset);
1518 offset += strlen(i->first()) + 1;
1521 // Allocate space for the new "stub", which contains the dlsym table.
1522 JE->startGVStub(0, offset, 4);
1524 // Emit the number of records
1525 MCE->emitInt32(nStubs);
1527 // Emit the string offsets
1528 for (unsigned i = 0; i != nStubs; ++i)
1529 MCE->emitInt32(Offsets[i]);
1531 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1532 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1533 // relocation can write the relocated pointer at the appropriate place in
1535 for (unsigned i = 0; i != GVs.size(); ++i) {
1536 intptr_t Ptr = (intptr_t)Ptrs[i];
1537 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1539 if (isa<Function>(GVs[i]))
1542 if (sizeof(Ptr) == 8)
1543 MCE->emitInt64(Ptr);
1545 MCE->emitInt32(Ptr);
1547 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1549 intptr_t Ptr = (intptr_t)i->second | 1;
1551 if (sizeof(Ptr) == 8)
1552 MCE->emitInt64(Ptr);
1554 MCE->emitInt32(Ptr);
1557 // Emit the strings.
1558 for (unsigned i = 0; i != GVs.size(); ++i)
1559 MCE->emitString(GVs[i]->getName());
1560 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1562 MCE->emitString(i->first());
1564 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1565 // deallocate space for the old one, if one existed.
1566 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1569 /// freeMachineCodeForFunction - release machine code memory for given Function.
1571 void JIT::freeMachineCodeForFunction(Function *F) {
1573 // Delete translation for this from the ExecutionEngine, so it will get
1574 // retranslated next time it is used.
1575 void *OldPtr = updateGlobalMapping(F, 0);
1578 RemoveFunctionFromSymbolTable(OldPtr);
1580 // Free the actual memory for the function body and related stuff.
1581 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1582 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);