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/JITCodeEmitter.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRelocation.h"
27 #include "llvm/ExecutionEngine/JITMemoryManager.h"
28 #include "llvm/ExecutionEngine/GenericValue.h"
29 #include "llvm/CodeGen/MachineCodeInfo.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetJITInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/MutexGuard.h"
36 #include "llvm/Support/ValueHandle.h"
37 #include "llvm/System/Disassembler.h"
38 #include "llvm/System/Memory.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/ADT/Statistic.h"
49 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
50 STATISTIC(NumRelos, "Number of relocations applied");
51 static JIT *TheJIT = 0;
54 //===----------------------------------------------------------------------===//
55 // JIT lazy compilation code.
58 class JITResolverState {
60 typedef std::map<AssertingVH<Function>, void*> FunctionToStubMapTy;
61 typedef std::map<void*, Function*> StubToFunctionMapTy;
62 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
64 /// FunctionToStubMap - Keep track of the stub created for a particular
65 /// function so that we can reuse them if necessary.
66 FunctionToStubMapTy FunctionToStubMap;
68 /// StubToFunctionMap - Keep track of the function that each stub
70 StubToFunctionMapTy StubToFunctionMap;
72 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
73 /// particular GlobalVariable so that we can reuse them if necessary.
74 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
77 FunctionToStubMapTy& getFunctionToStubMap(const MutexGuard& locked) {
78 assert(locked.holds(TheJIT->lock));
79 return FunctionToStubMap;
82 StubToFunctionMapTy& getStubToFunctionMap(const MutexGuard& locked) {
83 assert(locked.holds(TheJIT->lock));
84 return StubToFunctionMap;
87 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
88 assert(locked.holds(TheJIT->lock));
89 return GlobalToIndirectSymMap;
93 /// JITResolver - Keep track of, and resolve, call sites for functions that
94 /// have not yet been compiled.
96 typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy;
97 typedef JITResolverState::StubToFunctionMapTy StubToFunctionMapTy;
98 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
100 /// LazyResolverFn - The target lazy resolver function that we actually
101 /// rewrite instructions to use.
102 TargetJITInfo::LazyResolverFn LazyResolverFn;
104 JITResolverState state;
106 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
107 /// external functions.
108 std::map<void*, void*> ExternalFnToStubMap;
110 /// revGOTMap - map addresses to indexes in the GOT
111 std::map<void*, unsigned> revGOTMap;
112 unsigned nextGOTIndex;
114 static JITResolver *TheJITResolver;
116 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
119 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
120 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
121 TheJITResolver = this;
128 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
129 /// if it has already been created.
130 void *getFunctionStubIfAvailable(Function *F);
132 /// getFunctionStub - This returns a pointer to a function stub, creating
133 /// one on demand as needed. If empty is true, create a function stub
134 /// pointing at address 0, to be filled in later.
135 void *getFunctionStub(Function *F);
137 /// getExternalFunctionStub - Return a stub for the function at the
138 /// specified address, created lazily on demand.
139 void *getExternalFunctionStub(void *FnAddr);
141 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
142 /// specified GV address.
143 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
145 /// AddCallbackAtLocation - If the target is capable of rewriting an
146 /// instruction without the use of a stub, record the location of the use so
147 /// we know which function is being used at the location.
148 void *AddCallbackAtLocation(Function *F, void *Location) {
149 MutexGuard locked(TheJIT->lock);
150 /// Get the target-specific JIT resolver function.
151 state.getStubToFunctionMap(locked)[Location] = F;
152 return (void*)(intptr_t)LazyResolverFn;
155 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
156 SmallVectorImpl<void*> &Ptrs);
158 GlobalValue *invalidateStub(void *Stub);
160 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
161 /// an address. This function only manages slots, it does not manage the
162 /// contents of the slots or the memory associated with the GOT.
163 unsigned getGOTIndexForAddr(void *addr);
165 /// JITCompilerFn - This function is called to resolve a stub to a compiled
166 /// address. If the LLVM Function corresponding to the stub has not yet
167 /// been compiled, this function compiles it first.
168 static void *JITCompilerFn(void *Stub);
172 JITResolver *JITResolver::TheJITResolver = 0;
174 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
175 /// if it has already been created.
176 void *JITResolver::getFunctionStubIfAvailable(Function *F) {
177 MutexGuard locked(TheJIT->lock);
179 // If we already have a stub for this function, recycle it.
180 void *&Stub = state.getFunctionToStubMap(locked)[F];
184 /// getFunctionStub - This returns a pointer to a function stub, creating
185 /// one on demand as needed.
186 void *JITResolver::getFunctionStub(Function *F) {
187 MutexGuard locked(TheJIT->lock);
189 // If we already have a stub for this function, recycle it.
190 void *&Stub = state.getFunctionToStubMap(locked)[F];
191 if (Stub) return Stub;
193 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
194 // case we must resolve the symbol now.
195 void *Actual = TheJIT->isLazyCompilationDisabled()
196 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
198 // If this is an external declaration, attempt to resolve the address now
199 // to place in the stub.
200 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
201 Actual = TheJIT->getPointerToFunction(F);
203 // If we resolved the symbol to a null address (eg. a weak external)
204 // don't emit a stub. Return a null pointer to the application. If dlsym
205 // stubs are enabled, not being able to resolve the address is not
207 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
210 // Codegen a new stub, calling the lazy resolver or the actual address of the
211 // external function, if it was resolved.
212 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
213 *TheJIT->getCodeEmitter());
215 if (Actual != (void*)(intptr_t)LazyResolverFn) {
216 // If we are getting the stub for an external function, we really want the
217 // address of the stub in the GlobalAddressMap for the JIT, not the address
218 // of the external function.
219 TheJIT->updateGlobalMapping(F, Stub);
222 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
223 << F->getName() << "'\n";
225 // Finally, keep track of the stub-to-Function mapping so that the
226 // JITCompilerFn knows which function to compile!
227 state.getStubToFunctionMap(locked)[Stub] = F;
229 // If we are JIT'ing non-lazily but need to call a function that does not
230 // exist yet, add it to the JIT's work list so that we can fill in the stub
232 if (!Actual && TheJIT->isLazyCompilationDisabled())
233 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
234 TheJIT->addPendingFunction(F);
239 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
241 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
242 MutexGuard locked(TheJIT->lock);
244 // If we already have a stub for this global variable, recycle it.
245 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
246 if (IndirectSym) return IndirectSym;
248 // Otherwise, codegen a new indirect symbol.
249 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
250 *TheJIT->getCodeEmitter());
252 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
253 << GV->getName() << "'\n";
258 /// getExternalFunctionStub - Return a stub for the function at the
259 /// specified address, created lazily on demand.
260 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
261 // If we already have a stub for this function, recycle it.
262 void *&Stub = ExternalFnToStubMap[FnAddr];
263 if (Stub) return Stub;
265 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
266 *TheJIT->getCodeEmitter());
268 DOUT << "JIT: Stub emitted at [" << Stub
269 << "] for external function at '" << FnAddr << "'\n";
273 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
274 unsigned idx = revGOTMap[addr];
276 idx = ++nextGOTIndex;
277 revGOTMap[addr] = idx;
278 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
283 void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
284 SmallVectorImpl<void*> &Ptrs) {
285 MutexGuard locked(TheJIT->lock);
287 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
288 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
290 for (FunctionToStubMapTy::iterator i = FM.begin(), e = FM.end(); i != e; ++i){
291 Function *F = i->first;
292 if (F->isDeclaration() && F->hasExternalLinkage()) {
293 GVs.push_back(i->first);
294 Ptrs.push_back(i->second);
297 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
299 GVs.push_back(i->first);
300 Ptrs.push_back(i->second);
304 GlobalValue *JITResolver::invalidateStub(void *Stub) {
305 MutexGuard locked(TheJIT->lock);
307 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
308 StubToFunctionMapTy &SM = state.getStubToFunctionMap(locked);
309 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
311 // Look up the cheap way first, to see if it's a function stub we are
312 // invalidating. If so, remove it from both the forward and reverse maps.
313 if (SM.find(Stub) != SM.end()) {
314 Function *F = SM[Stub];
320 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
321 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
323 if (i->second != Stub)
325 GlobalValue *GV = i->first;
330 // Lastly, check to see if it's in the ExternalFnToStubMap.
331 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
332 e = ExternalFnToStubMap.end(); i != e; ++i) {
333 if (i->second != Stub)
335 ExternalFnToStubMap.erase(i);
342 /// JITCompilerFn - This function is called when a lazy compilation stub has
343 /// been entered. It looks up which function this stub corresponds to, compiles
344 /// it if necessary, then returns the resultant function pointer.
345 void *JITResolver::JITCompilerFn(void *Stub) {
346 JITResolver &JR = *TheJITResolver;
352 // Only lock for getting the Function. The call getPointerToFunction made
353 // in this function might trigger function materializing, which requires
354 // JIT lock to be unlocked.
355 MutexGuard locked(TheJIT->lock);
357 // The address given to us for the stub may not be exactly right, it might be
358 // a little bit after the stub. As such, use upper_bound to find it.
359 StubToFunctionMapTy::iterator I =
360 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
361 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
362 "This is not a known stub!");
364 ActualPtr = I->first;
367 // If we have already code generated the function, just return the address.
368 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
371 // Otherwise we don't have it, do lazy compilation now.
373 // If lazy compilation is disabled, emit a useful error message and abort.
374 if (TheJIT->isLazyCompilationDisabled()) {
375 cerr << "LLVM JIT requested to do lazy compilation of function '"
376 << F->getName() << "' when lazy compiles are disabled!\n";
380 // We might like to remove the stub from the StubToFunction map.
381 // We can't do that! Multiple threads could be stuck, waiting to acquire the
382 // lock above. As soon as the 1st function finishes compiling the function,
383 // the next one will be released, and needs to be able to find the function
385 //JR.state.getStubToFunctionMap(locked).erase(I);
387 DOUT << "JIT: Lazily resolving function '" << F->getName()
388 << "' In stub ptr = " << Stub << " actual ptr = "
389 << ActualPtr << "\n";
391 Result = TheJIT->getPointerToFunction(F);
394 // Reacquire the lock to erase the stub in the map.
395 MutexGuard locked(TheJIT->lock);
397 // We don't need to reuse this stub in the future, as F is now compiled.
398 JR.state.getFunctionToStubMap(locked).erase(F);
400 // FIXME: We could rewrite all references to this stub if we knew them.
402 // What we will do is set the compiled function address to map to the
403 // same GOT entry as the stub so that later clients may update the GOT
404 // if they see it still using the stub address.
405 // Note: this is done so the Resolver doesn't have to manage GOT memory
406 // Do this without allocating map space if the target isn't using a GOT
407 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
408 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
413 //===----------------------------------------------------------------------===//
414 // Function Index Support
416 // On MacOS we generate an index of currently JIT'd functions so that
417 // performance tools can determine a symbol name and accurate code range for a
418 // PC value. Because performance tools are generally asynchronous, the code
419 // below is written with the hope that it could be interrupted at any time and
420 // have useful answers. However, we don't go crazy with atomic operations, we
421 // just do a "reasonable effort".
423 #define ENABLE_JIT_SYMBOL_TABLE 0
426 /// JitSymbolEntry - Each function that is JIT compiled results in one of these
427 /// being added to an array of symbols. This indicates the name of the function
428 /// as well as the address range it occupies. This allows the client to map
429 /// from a PC value to the name of the function.
430 struct JitSymbolEntry {
431 const char *FnName; // FnName - a strdup'd string.
437 struct JitSymbolTable {
438 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
439 /// pointer is not used right now, but might be used in the future. Consider
440 /// it reserved for future use.
441 JitSymbolTable *NextPtr;
443 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
444 /// 'NumSymbols' symbols are valid.
445 JitSymbolEntry *Symbols;
447 /// NumSymbols - This indicates the number entries in the Symbols array that
451 /// NumAllocated - This indicates the amount of space we have in the Symbols
452 /// array. This is a private field that should not be read by external tools.
453 unsigned NumAllocated;
456 #if ENABLE_JIT_SYMBOL_TABLE
457 JitSymbolTable *__jitSymbolTable;
460 static void AddFunctionToSymbolTable(const char *FnName,
461 void *FnStart, intptr_t FnSize) {
462 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
463 JitSymbolTable **SymTabPtrPtr = 0;
464 #if !ENABLE_JIT_SYMBOL_TABLE
467 SymTabPtrPtr = &__jitSymbolTable;
470 // If this is the first entry in the symbol table, add the JitSymbolTable
472 if (*SymTabPtrPtr == 0) {
473 JitSymbolTable *New = new JitSymbolTable();
477 New->NumAllocated = 0;
481 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
483 // If we have space in the table, reallocate the table.
484 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
485 // If we don't have space, reallocate the table.
486 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
487 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
488 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
490 // Copy the old entries over.
491 memcpy(NewSymbols, OldSymbols, SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
493 // Swap the new symbols in, delete the old ones.
494 SymTabPtr->Symbols = NewSymbols;
495 SymTabPtr->NumAllocated = NewSize;
496 delete [] OldSymbols;
499 // Otherwise, we have enough space, just tack it onto the end of the array.
500 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
501 Entry.FnName = strdup(FnName);
502 Entry.FnStart = FnStart;
503 Entry.FnSize = FnSize;
504 ++SymTabPtr->NumSymbols;
507 static void RemoveFunctionFromSymbolTable(void *FnStart) {
508 assert(FnStart && "Invalid function pointer");
509 JitSymbolTable **SymTabPtrPtr = 0;
510 #if !ENABLE_JIT_SYMBOL_TABLE
513 SymTabPtrPtr = &__jitSymbolTable;
516 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
517 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
519 // Scan the table to find its index. The table is not sorted, so do a linear
522 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
523 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
525 // Once we have an index, we know to nuke this entry, overwrite it with the
526 // entry at the end of the array, making the last entry redundant.
527 const char *OldName = Symbols[Index].FnName;
528 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
529 free((void*)OldName);
531 // Drop the number of symbols in the table.
532 --SymTabPtr->NumSymbols;
534 // Finally, if we deleted the final symbol, deallocate the table itself.
535 if (SymTabPtr->NumSymbols != 0)
543 //===----------------------------------------------------------------------===//
547 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
548 /// used to output functions to memory for execution.
549 class JITEmitter : public JITCodeEmitter {
550 JITMemoryManager *MemMgr;
552 // When outputting a function stub in the context of some other function, we
553 // save BufferBegin/BufferEnd/CurBufferPtr here.
554 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
556 /// Relocations - These are the relocations that the function needs, as
558 std::vector<MachineRelocation> Relocations;
560 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
561 /// It is filled in by the StartMachineBasicBlock callback and queried by
562 /// the getMachineBasicBlockAddress callback.
563 std::vector<uintptr_t> MBBLocations;
565 /// ConstantPool - The constant pool for the current function.
567 MachineConstantPool *ConstantPool;
569 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
571 void *ConstantPoolBase;
573 /// ConstPoolAddresses - Addresses of individual constant pool entries.
575 SmallVector<uintptr_t, 8> ConstPoolAddresses;
577 /// JumpTable - The jump tables for the current function.
579 MachineJumpTableInfo *JumpTable;
581 /// JumpTableBase - A pointer to the first entry in the jump table.
585 /// Resolver - This contains info about the currently resolved functions.
586 JITResolver Resolver;
588 /// DE - The dwarf emitter for the jit.
591 /// LabelLocations - This vector is a mapping from Label ID's to their
593 std::vector<uintptr_t> LabelLocations;
595 /// MMI - Machine module info for exception informations
596 MachineModuleInfo* MMI;
598 // GVSet - a set to keep track of which globals have been seen
599 SmallPtrSet<const GlobalVariable*, 8> GVSet;
601 // CurFn - The llvm function being emitted. Only valid during
603 const Function *CurFn;
605 // CurFnStubUses - For a given Function, a vector of stubs that it
606 // references. This facilitates the JIT detecting that a stub is no
607 // longer used, so that it may be deallocated.
608 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
610 // StubFnRefs - For a given pointer to a stub, a set of Functions which
611 // reference the stub. When the count of a stub's references drops to zero,
612 // the stub is unused.
613 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
615 // ExtFnStubs - A map of external function names to stubs which have entries
616 // in the JITResolver's ExternalFnToStubMap.
617 StringMap<void *> ExtFnStubs;
619 // MCI - A pointer to a MachineCodeInfo object to update with information.
620 MachineCodeInfo *MCI;
623 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit), CurFn(0), MCI(0) {
624 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
625 if (jit.getJITInfo().needsGOT()) {
626 MemMgr->AllocateGOT();
627 DOUT << "JIT is managing a GOT\n";
630 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
634 if (ExceptionHandling) delete DE;
637 /// classof - Methods for support type inquiry through isa, cast, and
640 static inline bool classof(const JITEmitter*) { return true; }
641 static inline bool classof(const MachineCodeEmitter*) { return true; }
643 JITResolver &getJITResolver() { return Resolver; }
645 virtual void startFunction(MachineFunction &F);
646 virtual bool finishFunction(MachineFunction &F);
648 void emitConstantPool(MachineConstantPool *MCP);
649 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
650 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
652 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
653 unsigned Alignment = 1);
654 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
656 virtual void* finishGVStub(const GlobalValue *GV);
658 /// allocateSpace - Reserves space in the current block if any, or
659 /// allocate a new one of the given size.
660 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
662 virtual void addRelocation(const MachineRelocation &MR) {
663 Relocations.push_back(MR);
666 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
667 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
668 MBBLocations.resize((MBB->getNumber()+1)*2);
669 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
670 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
671 << (void*) getCurrentPCValue() << "]\n";
674 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
675 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
677 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
678 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
679 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
680 return MBBLocations[MBB->getNumber()];
683 /// deallocateMemForFunction - Deallocate all memory for the specified
685 void deallocateMemForFunction(Function *F);
687 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
688 /// using the stub at the specified address. Allows
689 /// deallocateMemForFunction to also remove stubs no longer referenced.
690 void AddStubToCurrentFunction(void *Stub);
692 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
693 /// MachineRelocations that reference external functions by name.
694 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
696 virtual void emitLabel(uint64_t LabelID) {
697 if (LabelLocations.size() <= LabelID)
698 LabelLocations.resize((LabelID+1)*2);
699 LabelLocations[LabelID] = getCurrentPCValue();
702 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
703 assert(LabelLocations.size() > (unsigned)LabelID &&
704 LabelLocations[LabelID] && "Label not emitted!");
705 return LabelLocations[LabelID];
708 virtual void setModuleInfo(MachineModuleInfo* Info) {
710 if (ExceptionHandling) DE->setModuleInfo(Info);
713 void setMemoryExecutable(void) {
714 MemMgr->setMemoryExecutable();
717 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
719 void setMachineCodeInfo(MachineCodeInfo *mci) {
724 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
725 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
727 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
728 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
729 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
730 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
734 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
735 bool DoesntNeedStub) {
736 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
737 return TheJIT->getOrEmitGlobalVariable(GV);
739 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
740 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
742 // If we have already compiled the function, return a pointer to its body.
743 Function *F = cast<Function>(V);
745 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
746 // Return the function stub if it's already created.
747 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
749 AddStubToCurrentFunction(ResultPtr);
751 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
753 if (ResultPtr) return ResultPtr;
755 // If this is an external function pointer, we can force the JIT to
756 // 'compile' it, which really just adds it to the map. In dlsym mode,
757 // external functions are forced through a stub, regardless of reloc type.
758 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
759 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
760 return TheJIT->getPointerToFunction(F);
762 // Okay, the function has not been compiled yet, if the target callback
763 // mechanism is capable of rewriting the instruction directly, prefer to do
764 // that instead of emitting a stub. This uses the lazy resolver, so is not
765 // legal if lazy compilation is disabled.
766 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
767 return Resolver.AddCallbackAtLocation(F, Reference);
769 // Otherwise, we have to emit a stub.
770 void *StubAddr = Resolver.getFunctionStub(F);
772 // Add the stub to the current function's list of referenced stubs, so we can
773 // deallocate them if the current function is ever freed. It's possible to
774 // return null from getFunctionStub in the case of a weak extern that fails
777 AddStubToCurrentFunction(StubAddr);
782 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
784 // Make sure GV is emitted first, and create a stub containing the fully
786 void *GVAddress = getPointerToGlobal(V, Reference, true);
787 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
789 // Add the stub to the current function's list of referenced stubs, so we can
790 // deallocate them if the current function is ever freed.
791 AddStubToCurrentFunction(StubAddr);
796 void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
797 if (!TheJIT->areDlsymStubsEnabled())
800 assert(CurFn && "Stub added to current function, but current function is 0!");
802 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
803 StubsUsed.push_back(StubAddr);
805 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
806 FnRefs.insert(CurFn);
809 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
810 const TargetData *TD) {
811 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
812 if (Constants.empty()) return 0;
815 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
816 MachineConstantPoolEntry CPE = Constants[i];
817 unsigned AlignMask = CPE.getAlignment() - 1;
818 Size = (Size + AlignMask) & ~AlignMask;
819 const Type *Ty = CPE.getType();
820 Size += TD->getTypeAllocSize(Ty);
825 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
826 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
827 if (JT.empty()) return 0;
829 unsigned NumEntries = 0;
830 for (unsigned i = 0, e = JT.size(); i != e; ++i)
831 NumEntries += JT[i].MBBs.size();
833 unsigned EntrySize = MJTI->getEntrySize();
835 return NumEntries * EntrySize;
838 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
839 if (Alignment == 0) Alignment = 1;
840 // Since we do not know where the buffer will be allocated, be pessimistic.
841 return Size + Alignment;
844 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
845 /// into the running total Size.
847 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
848 const Type *ElTy = GV->getType()->getElementType();
849 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
851 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
852 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
854 // Assume code section ends with worst possible alignment, so first
855 // variable needs maximal padding.
858 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
863 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
864 /// but are referenced from the constant; put them in GVSet and add their
865 /// size into the running total Size.
867 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
869 // If its undefined, return the garbage.
870 if (isa<UndefValue>(C))
873 // If the value is a ConstantExpr
874 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
875 Constant *Op0 = CE->getOperand(0);
876 switch (CE->getOpcode()) {
877 case Instruction::GetElementPtr:
878 case Instruction::Trunc:
879 case Instruction::ZExt:
880 case Instruction::SExt:
881 case Instruction::FPTrunc:
882 case Instruction::FPExt:
883 case Instruction::UIToFP:
884 case Instruction::SIToFP:
885 case Instruction::FPToUI:
886 case Instruction::FPToSI:
887 case Instruction::PtrToInt:
888 case Instruction::IntToPtr:
889 case Instruction::BitCast: {
890 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
893 case Instruction::Add:
894 case Instruction::FAdd:
895 case Instruction::Sub:
896 case Instruction::FSub:
897 case Instruction::Mul:
898 case Instruction::FMul:
899 case Instruction::UDiv:
900 case Instruction::SDiv:
901 case Instruction::URem:
902 case Instruction::SRem:
903 case Instruction::And:
904 case Instruction::Or:
905 case Instruction::Xor: {
906 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
907 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
911 cerr << "ConstantExpr not handled: " << *CE << "\n";
917 if (C->getType()->getTypeID() == Type::PointerTyID)
918 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
919 if (GVSet.insert(GV))
920 Size = addSizeOfGlobal(GV, Size);
925 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
926 /// but are referenced from the given initializer.
928 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
930 if (!isa<UndefValue>(Init) &&
931 !isa<ConstantVector>(Init) &&
932 !isa<ConstantAggregateZero>(Init) &&
933 !isa<ConstantArray>(Init) &&
934 !isa<ConstantStruct>(Init) &&
935 Init->getType()->isFirstClassType())
936 Size = addSizeOfGlobalsInConstantVal(Init, Size);
940 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
941 /// globals; then walk the initializers of those globals looking for more.
942 /// If their size has not been considered yet, add it into the running total
945 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
949 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
951 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
953 const TargetInstrDesc &Desc = I->getDesc();
954 const MachineInstr &MI = *I;
955 unsigned NumOps = Desc.getNumOperands();
956 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
957 const MachineOperand &MO = MI.getOperand(CurOp);
959 GlobalValue* V = MO.getGlobal();
960 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
963 // If seen in previous function, it will have an entry here.
964 if (TheJIT->getPointerToGlobalIfAvailable(GV))
966 // If seen earlier in this function, it will have an entry here.
967 // FIXME: it should be possible to combine these tables, by
968 // assuming the addresses of the new globals in this module
969 // start at 0 (or something) and adjusting them after codegen
970 // complete. Another possibility is to grab a marker bit in GV.
971 if (GVSet.insert(GV))
972 // A variable as yet unseen. Add in its size.
973 Size = addSizeOfGlobal(GV, Size);
978 DOUT << "JIT: About to look through initializers\n";
979 // Look for more globals that are referenced only from initializers.
980 // GVSet.end is computed each time because the set can grow as we go.
981 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
982 I != GVSet.end(); I++) {
983 const GlobalVariable* GV = *I;
984 if (GV->hasInitializer())
985 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
991 void JITEmitter::startFunction(MachineFunction &F) {
992 DOUT << "JIT: Starting CodeGen of Function "
993 << F.getFunction()->getName() << "\n";
995 uintptr_t ActualSize = 0;
996 // Set the memory writable, if it's not already
997 MemMgr->setMemoryWritable();
998 if (MemMgr->NeedsExactSize()) {
999 DOUT << "JIT: ExactSize\n";
1000 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
1001 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
1002 MachineConstantPool *MCP = F.getConstantPool();
1004 // Ensure the constant pool/jump table info is at least 4-byte aligned.
1005 ActualSize = RoundUpToAlign(ActualSize, 16);
1007 // Add the alignment of the constant pool
1008 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
1010 // Add the constant pool size
1011 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1013 // Add the aligment of the jump table info
1014 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
1016 // Add the jump table size
1017 ActualSize += GetJumpTableSizeInBytes(MJTI);
1019 // Add the alignment for the function
1020 ActualSize = RoundUpToAlign(ActualSize,
1021 std::max(F.getFunction()->getAlignment(), 8U));
1023 // Add the function size
1024 ActualSize += TII->GetFunctionSizeInBytes(F);
1026 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
1027 // Add the size of the globals that will be allocated after this function.
1028 // These are all the ones referenced from this function that were not
1029 // previously allocated.
1030 ActualSize += GetSizeOfGlobalsInBytes(F);
1031 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
1034 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
1036 BufferEnd = BufferBegin+ActualSize;
1038 // Ensure the constant pool/jump table info is at least 4-byte aligned.
1041 emitConstantPool(F.getConstantPool());
1042 initJumpTableInfo(F.getJumpTableInfo());
1044 // About to start emitting the machine code for the function.
1045 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
1046 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
1048 MBBLocations.clear();
1051 bool JITEmitter::finishFunction(MachineFunction &F) {
1052 if (CurBufferPtr == BufferEnd) {
1053 // FIXME: Allocate more space, then try again.
1054 cerr << "JIT: Ran out of space for generated machine code!\n";
1058 emitJumpTableInfo(F.getJumpTableInfo());
1060 // FnStart is the start of the text, not the start of the constant pool and
1061 // other per-function data.
1063 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
1065 // FnEnd is the end of the function's machine code.
1066 uint8_t *FnEnd = CurBufferPtr;
1068 if (!Relocations.empty()) {
1069 CurFn = F.getFunction();
1070 NumRelos += Relocations.size();
1072 // Resolve the relocations to concrete pointers.
1073 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1074 MachineRelocation &MR = Relocations[i];
1075 void *ResultPtr = 0;
1076 if (!MR.letTargetResolve()) {
1077 if (MR.isExternalSymbol()) {
1078 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1080 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
1081 << ResultPtr << "]\n";
1083 // If the target REALLY wants a stub for this function, emit it now.
1084 if (!MR.doesntNeedStub()) {
1085 if (!TheJIT->areDlsymStubsEnabled()) {
1086 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1088 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1090 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1091 AddStubToCurrentFunction(Stub);
1096 } else if (MR.isGlobalValue()) {
1097 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1098 BufferBegin+MR.getMachineCodeOffset(),
1099 MR.doesntNeedStub());
1100 } else if (MR.isIndirectSymbol()) {
1101 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
1102 BufferBegin+MR.getMachineCodeOffset(),
1103 MR.doesntNeedStub());
1104 } else if (MR.isBasicBlock()) {
1105 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1106 } else if (MR.isConstantPoolIndex()) {
1107 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1109 assert(MR.isJumpTableIndex());
1110 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1113 MR.setResultPointer(ResultPtr);
1116 // if we are managing the GOT and the relocation wants an index,
1118 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
1119 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
1120 MR.setGOTIndex(idx);
1121 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
1122 DOUT << "JIT: GOT was out of date for " << ResultPtr
1123 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1125 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
1131 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
1132 Relocations.size(), MemMgr->getGOTBase());
1135 // Update the GOT entry for F to point to the new code.
1136 if (MemMgr->isManagingGOT()) {
1137 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
1138 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
1139 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
1140 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1141 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
1145 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1146 // global variables that were referenced in the relocations.
1147 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
1149 if (CurBufferPtr == BufferEnd) {
1150 // FIXME: Allocate more space, then try again.
1151 cerr << "JIT: Ran out of space for generated machine code!\n";
1155 BufferBegin = CurBufferPtr = 0;
1156 NumBytes += FnEnd-FnStart;
1158 // Invalidate the icache if necessary.
1159 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
1161 // Add it to the JIT symbol table if the host wants it.
1162 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
1163 FnStart, FnEnd-FnStart);
1165 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1166 << "] Function: " << F.getFunction()->getName()
1167 << ": " << (FnEnd-FnStart) << " bytes of text, "
1168 << Relocations.size() << " relocations\n";
1171 MCI->setAddress(FnStart);
1172 MCI->setSize(FnEnd-FnStart);
1175 Relocations.clear();
1176 ConstPoolAddresses.clear();
1178 // Mark code region readable and executable if it's not so already.
1179 MemMgr->setMemoryExecutable();
1183 if (sys::hasDisassembler()) {
1184 DOUT << "JIT: Disassembled code:\n";
1185 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
1187 DOUT << "JIT: Binary code:\n";
1189 uint8_t* q = FnStart;
1190 for (int i = 0; q < FnEnd; q += 4, ++i) {
1194 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1195 << (long)(q - FnStart) << ": ";
1197 for (int j = 3; j >= 0; --j) {
1201 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1214 if (ExceptionHandling) {
1215 uintptr_t ActualSize = 0;
1216 SavedBufferBegin = BufferBegin;
1217 SavedBufferEnd = BufferEnd;
1218 SavedCurBufferPtr = CurBufferPtr;
1220 if (MemMgr->NeedsExactSize()) {
1221 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
1224 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1226 BufferEnd = BufferBegin+ActualSize;
1227 uint8_t* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
1228 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1230 BufferBegin = SavedBufferBegin;
1231 BufferEnd = SavedBufferEnd;
1232 CurBufferPtr = SavedCurBufferPtr;
1234 TheJIT->RegisterTable(FrameRegister);
1243 /// deallocateMemForFunction - Deallocate all memory for the specified
1244 /// function body. Also drop any references the function has to stubs.
1245 void JITEmitter::deallocateMemForFunction(Function *F) {
1246 MemMgr->deallocateMemForFunction(F);
1248 // If the function did not reference any stubs, return.
1249 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1252 // For each referenced stub, erase the reference to this function, and then
1253 // erase the list of referenced stubs.
1254 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1255 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1256 void *Stub = StubList[i];
1258 // If we already invalidated this stub for this function, continue.
1259 if (StubFnRefs.count(Stub) == 0)
1262 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1265 // If this function was the last reference to the stub, invalidate the stub
1266 // in the JITResolver. Were there a memory manager deallocateStub routine,
1267 // we could call that at this point too.
1268 if (FnRefs.empty()) {
1269 DOUT << "\nJIT: Invalidated Stub at [" << Stub << "]\n";
1270 StubFnRefs.erase(Stub);
1272 // Invalidate the stub. If it is a GV stub, update the JIT's global
1273 // mapping for that GV to zero, otherwise, search the string map of
1274 // external function names to stubs and remove the entry for this stub.
1275 GlobalValue *GV = Resolver.invalidateStub(Stub);
1277 TheJIT->updateGlobalMapping(GV, 0);
1279 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1280 e = ExtFnStubs.end(); i != e; ++i) {
1281 if (i->second == Stub) {
1282 ExtFnStubs.erase(i);
1289 CurFnStubUses.erase(F);
1293 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1295 return JITCodeEmitter::allocateSpace(Size, Alignment);
1297 // create a new memory block if there is no active one.
1298 // care must be taken so that BufferBegin is invalidated when a
1300 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1301 BufferEnd = BufferBegin+Size;
1302 return CurBufferPtr;
1305 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1306 if (TheJIT->getJITInfo().hasCustomConstantPool())
1309 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1310 if (Constants.empty()) return;
1312 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1313 unsigned Align = MCP->getConstantPoolAlignment();
1314 ConstantPoolBase = allocateSpace(Size, Align);
1317 if (ConstantPoolBase == 0) return; // Buffer overflow.
1319 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1320 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1322 // Initialize the memory for all of the constant pool entries.
1323 unsigned Offset = 0;
1324 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1325 MachineConstantPoolEntry CPE = Constants[i];
1326 unsigned AlignMask = CPE.getAlignment() - 1;
1327 Offset = (Offset + AlignMask) & ~AlignMask;
1329 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1330 ConstPoolAddresses.push_back(CAddr);
1331 if (CPE.isMachineConstantPoolEntry()) {
1332 // FIXME: add support to lower machine constant pool values into bytes!
1333 cerr << "Initialize memory with machine specific constant pool entry"
1334 << " has not been implemented!\n";
1337 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1338 DOUT << "JIT: CP" << i << " at [0x"
1339 << std::hex << CAddr << std::dec << "]\n";
1341 const Type *Ty = CPE.Val.ConstVal->getType();
1342 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
1346 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1347 if (TheJIT->getJITInfo().hasCustomJumpTables())
1350 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1351 if (JT.empty()) return;
1353 unsigned NumEntries = 0;
1354 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1355 NumEntries += JT[i].MBBs.size();
1357 unsigned EntrySize = MJTI->getEntrySize();
1359 // Just allocate space for all the jump tables now. We will fix up the actual
1360 // MBB entries in the tables after we emit the code for each block, since then
1361 // we will know the final locations of the MBBs in memory.
1363 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1366 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1367 if (TheJIT->getJITInfo().hasCustomJumpTables())
1370 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1371 if (JT.empty() || JumpTableBase == 0) return;
1373 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1374 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1375 // For each jump table, place the offset from the beginning of the table
1376 // to the target address.
1377 int *SlotPtr = (int*)JumpTableBase;
1379 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1380 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1381 // Store the offset of the basic block for this jump table slot in the
1382 // memory we allocated for the jump table in 'initJumpTableInfo'
1383 uintptr_t Base = (uintptr_t)SlotPtr;
1384 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1385 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1386 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1390 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1392 // For each jump table, map each target in the jump table to the address of
1393 // an emitted MachineBasicBlock.
1394 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1396 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1397 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1398 // Store the address of the basic block for this jump table slot in the
1399 // memory we allocated for the jump table in 'initJumpTableInfo'
1400 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1401 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1406 void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1407 unsigned Alignment) {
1408 SavedBufferBegin = BufferBegin;
1409 SavedBufferEnd = BufferEnd;
1410 SavedCurBufferPtr = CurBufferPtr;
1412 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1413 BufferEnd = BufferBegin+StubSize+1;
1416 void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1417 unsigned StubSize) {
1418 SavedBufferBegin = BufferBegin;
1419 SavedBufferEnd = BufferEnd;
1420 SavedCurBufferPtr = CurBufferPtr;
1422 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1423 BufferEnd = BufferBegin+StubSize+1;
1426 void *JITEmitter::finishGVStub(const GlobalValue* GV) {
1427 NumBytes += getCurrentPCOffset();
1428 std::swap(SavedBufferBegin, BufferBegin);
1429 BufferEnd = SavedBufferEnd;
1430 CurBufferPtr = SavedCurBufferPtr;
1431 return SavedBufferBegin;
1434 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1435 // in the constant pool that was last emitted with the 'emitConstantPool'
1438 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1439 assert(ConstantNum < ConstantPool->getConstants().size() &&
1440 "Invalid ConstantPoolIndex!");
1441 return ConstPoolAddresses[ConstantNum];
1444 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1445 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1447 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1448 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1449 assert(Index < JT.size() && "Invalid jump table index!");
1451 unsigned Offset = 0;
1452 unsigned EntrySize = JumpTable->getEntrySize();
1454 for (unsigned i = 0; i < Index; ++i)
1455 Offset += JT[i].MBBs.size();
1457 Offset *= EntrySize;
1459 return (uintptr_t)((char *)JumpTableBase + Offset);
1462 //===----------------------------------------------------------------------===//
1463 // Public interface to this file
1464 //===----------------------------------------------------------------------===//
1466 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1467 return new JITEmitter(jit, JMM);
1470 // getPointerToNamedFunction - This function is used as a global wrapper to
1471 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1472 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1473 // need to resolve function(s) that are being mis-codegenerated, so we need to
1474 // resolve their addresses at runtime, and this is the way to do it.
1476 void *getPointerToNamedFunction(const char *Name) {
1477 if (Function *F = TheJIT->FindFunctionNamed(Name))
1478 return TheJIT->getPointerToFunction(F);
1479 return TheJIT->getPointerToNamedFunction(Name);
1483 // getPointerToFunctionOrStub - If the specified function has been
1484 // code-gen'd, return a pointer to the function. If not, compile it, or use
1485 // a stub to implement lazy compilation if available.
1487 void *JIT::getPointerToFunctionOrStub(Function *F) {
1488 // If we have already code generated the function, just return the address.
1489 if (void *Addr = getPointerToGlobalIfAvailable(F))
1492 // Get a stub if the target supports it.
1493 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1494 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1495 return JE->getJITResolver().getFunctionStub(F);
1498 void JIT::registerMachineCodeInfo(MachineCodeInfo *mc) {
1499 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1500 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1502 JE->setMachineCodeInfo(mc);
1505 void JIT::updateFunctionStub(Function *F) {
1506 // Get the empty stub we generated earlier.
1507 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1508 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1509 void *Stub = JE->getJITResolver().getFunctionStub(F);
1511 // Tell the target jit info to rewrite the stub at the specified address,
1512 // rather than creating a new one.
1513 void *Addr = getPointerToGlobalIfAvailable(F);
1514 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1517 /// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1518 /// that were emitted during code generation.
1520 void JIT::updateDlsymStubTable() {
1521 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1522 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1524 SmallVector<GlobalValue*, 8> GVs;
1525 SmallVector<void*, 8> Ptrs;
1526 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
1528 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1530 unsigned nStubs = GVs.size() + ExtFns.size();
1532 // If there are no relocatable stubs, return.
1536 // If there are no new relocatable stubs, return.
1537 void *CurTable = JE->getMemMgr()->getDlsymTable();
1538 if (CurTable && (*(unsigned *)CurTable == nStubs))
1541 // Calculate the size of the stub info
1542 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
1544 SmallVector<unsigned, 8> Offsets;
1545 for (unsigned i = 0; i != GVs.size(); ++i) {
1546 Offsets.push_back(offset);
1547 offset += GVs[i]->getName().length() + 1;
1549 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1551 Offsets.push_back(offset);
1552 offset += strlen(i->first()) + 1;
1555 // Allocate space for the new "stub", which contains the dlsym table.
1556 JE->startGVStub(0, offset, 4);
1558 // Emit the number of records
1559 JE->emitInt32(nStubs);
1561 // Emit the string offsets
1562 for (unsigned i = 0; i != nStubs; ++i)
1563 JE->emitInt32(Offsets[i]);
1565 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1566 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1567 // relocation can write the relocated pointer at the appropriate place in
1569 for (unsigned i = 0; i != GVs.size(); ++i) {
1570 intptr_t Ptr = (intptr_t)Ptrs[i];
1571 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1573 if (isa<Function>(GVs[i]))
1576 if (sizeof(Ptr) == 8)
1581 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1583 intptr_t Ptr = (intptr_t)i->second | 1;
1585 if (sizeof(Ptr) == 8)
1591 // Emit the strings.
1592 for (unsigned i = 0; i != GVs.size(); ++i)
1593 JE->emitString(GVs[i]->getName());
1594 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1596 JE->emitString(i->first());
1598 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1599 // deallocate space for the old one, if one existed.
1600 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1603 /// freeMachineCodeForFunction - release machine code memory for given Function.
1605 void JIT::freeMachineCodeForFunction(Function *F) {
1607 // Delete translation for this from the ExecutionEngine, so it will get
1608 // retranslated next time it is used.
1609 void *OldPtr = updateGlobalMapping(F, 0);
1612 RemoveFunctionFromSymbolTable(OldPtr);
1614 // Free the actual memory for the function body and related stuff.
1615 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1616 cast<JITEmitter>(JCE)->deallocateMemForFunction(F);