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/Constant.h"
19 #include "llvm/Module.h"
20 #include "llvm/Type.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/Target/TargetData.h"
29 #include "llvm/Target/TargetJITInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/MutexGuard.h"
34 #include "llvm/System/Disassembler.h"
35 #include "llvm/System/Memory.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/ADT/Statistic.h"
41 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
42 STATISTIC(NumRelos, "Number of relocations applied");
43 static JIT *TheJIT = 0;
46 //===----------------------------------------------------------------------===//
47 // JIT lazy compilation code.
50 class JITResolverState {
52 /// FunctionToStubMap - Keep track of the stub created for a particular
53 /// function so that we can reuse them if necessary.
54 std::map<Function*, void*> FunctionToStubMap;
56 /// StubToFunctionMap - Keep track of the function that each stub
58 std::map<void*, Function*> StubToFunctionMap;
60 /// GlobalToLazyPtrMap - Keep track of the lazy pointer created for a
61 /// particular GlobalVariable so that we can reuse them if necessary.
62 std::map<GlobalValue*, void*> GlobalToLazyPtrMap;
65 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
66 assert(locked.holds(TheJIT->lock));
67 return FunctionToStubMap;
70 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
71 assert(locked.holds(TheJIT->lock));
72 return StubToFunctionMap;
75 std::map<GlobalValue*, void*>&
76 getGlobalToLazyPtrMap(const MutexGuard& locked) {
77 assert(locked.holds(TheJIT->lock));
78 return GlobalToLazyPtrMap;
82 /// JITResolver - Keep track of, and resolve, call sites for functions that
83 /// have not yet been compiled.
85 /// LazyResolverFn - The target lazy resolver function that we actually
86 /// rewrite instructions to use.
87 TargetJITInfo::LazyResolverFn LazyResolverFn;
89 JITResolverState state;
91 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
92 /// external functions.
93 std::map<void*, void*> ExternalFnToStubMap;
95 //map addresses to indexes in the GOT
96 std::map<void*, unsigned> revGOTMap;
97 unsigned nextGOTIndex;
99 static JITResolver *TheJITResolver;
101 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
104 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
105 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
106 TheJITResolver = this;
113 /// getFunctionStub - This returns a pointer to a function stub, creating
114 /// one on demand as needed.
115 void *getFunctionStub(Function *F);
117 /// getExternalFunctionStub - Return a stub for the function at the
118 /// specified address, created lazily on demand.
119 void *getExternalFunctionStub(void *FnAddr);
121 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
123 void *getGlobalValueLazyPtr(GlobalValue *V, void *GVAddress);
125 /// AddCallbackAtLocation - If the target is capable of rewriting an
126 /// instruction without the use of a stub, record the location of the use so
127 /// we know which function is being used at the location.
128 void *AddCallbackAtLocation(Function *F, void *Location) {
129 MutexGuard locked(TheJIT->lock);
130 /// Get the target-specific JIT resolver function.
131 state.getStubToFunctionMap(locked)[Location] = F;
132 return (void*)(intptr_t)LazyResolverFn;
135 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
136 /// an address. This function only manages slots, it does not manage the
137 /// contents of the slots or the memory associated with the GOT.
138 unsigned getGOTIndexForAddr(void *addr);
140 /// JITCompilerFn - This function is called to resolve a stub to a compiled
141 /// address. If the LLVM Function corresponding to the stub has not yet
142 /// been compiled, this function compiles it first.
143 static void *JITCompilerFn(void *Stub);
147 JITResolver *JITResolver::TheJITResolver = 0;
149 /// getFunctionStub - This returns a pointer to a function stub, creating
150 /// one on demand as needed.
151 void *JITResolver::getFunctionStub(Function *F) {
152 MutexGuard locked(TheJIT->lock);
154 // If we already have a stub for this function, recycle it.
155 void *&Stub = state.getFunctionToStubMap(locked)[F];
156 if (Stub) return Stub;
158 // Call the lazy resolver function unless we already KNOW it is an external
159 // function, in which case we just skip the lazy resolution step.
160 void *Actual = (void*)(intptr_t)LazyResolverFn;
161 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
162 Actual = TheJIT->getPointerToFunction(F);
164 // Otherwise, codegen a new stub. For now, the stub will call the lazy
165 // resolver function.
166 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
167 *TheJIT->getCodeEmitter());
169 if (Actual != (void*)(intptr_t)LazyResolverFn) {
170 // If we are getting the stub for an external function, we really want the
171 // address of the stub in the GlobalAddressMap for the JIT, not the address
172 // of the external function.
173 TheJIT->updateGlobalMapping(F, Stub);
176 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
177 << F->getName() << "'\n";
179 // Finally, keep track of the stub-to-Function mapping so that the
180 // JITCompilerFn knows which function to compile!
181 state.getStubToFunctionMap(locked)[Stub] = F;
185 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
187 void *JITResolver::getGlobalValueLazyPtr(GlobalValue *GV, void *GVAddress) {
188 MutexGuard locked(TheJIT->lock);
190 // If we already have a stub for this global variable, recycle it.
191 void *&LazyPtr = state.getGlobalToLazyPtrMap(locked)[GV];
192 if (LazyPtr) return LazyPtr;
194 // Otherwise, codegen a new lazy pointer.
195 LazyPtr = TheJIT->getJITInfo().emitGlobalValueLazyPtr(GV, GVAddress,
196 *TheJIT->getCodeEmitter());
198 DOUT << "JIT: Stub emitted at [" << LazyPtr << "] for GV '"
199 << GV->getName() << "'\n";
204 /// getExternalFunctionStub - Return a stub for the function at the
205 /// specified address, created lazily on demand.
206 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
207 // If we already have a stub for this function, recycle it.
208 void *&Stub = ExternalFnToStubMap[FnAddr];
209 if (Stub) return Stub;
211 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
212 *TheJIT->getCodeEmitter());
214 DOUT << "JIT: Stub emitted at [" << Stub
215 << "] for external function at '" << FnAddr << "'\n";
219 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
220 unsigned idx = revGOTMap[addr];
222 idx = ++nextGOTIndex;
223 revGOTMap[addr] = idx;
224 DOUT << "Adding GOT entry " << idx << " for addr " << addr << "\n";
229 /// JITCompilerFn - This function is called when a lazy compilation stub has
230 /// been entered. It looks up which function this stub corresponds to, compiles
231 /// it if necessary, then returns the resultant function pointer.
232 void *JITResolver::JITCompilerFn(void *Stub) {
233 JITResolver &JR = *TheJITResolver;
235 MutexGuard locked(TheJIT->lock);
237 // The address given to us for the stub may not be exactly right, it might be
238 // a little bit after the stub. As such, use upper_bound to find it.
239 std::map<void*, Function*>::iterator I =
240 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
241 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
242 "This is not a known stub!");
243 Function *F = (--I)->second;
245 // If we have already code generated the function, just return the address.
246 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
249 // Otherwise we don't have it, do lazy compilation now.
251 // If lazy compilation is disabled, emit a useful error message and abort.
252 if (TheJIT->isLazyCompilationDisabled()) {
253 cerr << "LLVM JIT requested to do lazy compilation of function '"
254 << F->getName() << "' when lazy compiles are disabled!\n";
258 // We might like to remove the stub from the StubToFunction map.
259 // We can't do that! Multiple threads could be stuck, waiting to acquire the
260 // lock above. As soon as the 1st function finishes compiling the function,
261 // the next one will be released, and needs to be able to find the function
263 //JR.state.getStubToFunctionMap(locked).erase(I);
265 DOUT << "JIT: Lazily resolving function '" << F->getName()
266 << "' In stub ptr = " << Stub << " actual ptr = "
269 Result = TheJIT->getPointerToFunction(F);
272 // We don't need to reuse this stub in the future, as F is now compiled.
273 JR.state.getFunctionToStubMap(locked).erase(F);
275 // FIXME: We could rewrite all references to this stub if we knew them.
277 // What we will do is set the compiled function address to map to the
278 // same GOT entry as the stub so that later clients may update the GOT
279 // if they see it still using the stub address.
280 // Note: this is done so the Resolver doesn't have to manage GOT memory
281 // Do this without allocating map space if the target isn't using a GOT
282 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
283 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
288 //===----------------------------------------------------------------------===//
289 // Function Index Support
291 // On MacOS we generate an index of currently JIT'd functions so that
292 // performance tools can determine a symbol name and accurate code range for a
293 // PC value. Because performance tools are generally asynchronous, the code
294 // below is written with the hope that it could be interrupted at any time and
295 // have useful answers. However, we don't go crazy with atomic operations, we
296 // just do a "reasonable effort".
298 #define ENABLE_JIT_SYMBOL_TABLE 0
301 /// JitSymbolEntry - Each function that is JIT compiled results in one of these
302 /// being added to an array of symbols. This indicates the name of the function
303 /// as well as the address range it occupies. This allows the client to map
304 /// from a PC value to the name of the function.
305 struct JitSymbolEntry {
306 const char *FnName; // FnName - a strdup'd string.
312 struct JitSymbolTable {
313 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
314 /// pointer is not used right now, but might be used in the future. Consider
315 /// it reserved for future use.
316 JitSymbolTable *NextPtr;
318 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
319 /// 'NumSymbols' symbols are valid.
320 JitSymbolEntry *Symbols;
322 /// NumSymbols - This indicates the number entries in the Symbols array that
326 /// NumAllocated - This indicates the amount of space we have in the Symbols
327 /// array. This is a private field that should not be read by external tools.
328 unsigned NumAllocated;
331 #if ENABLE_JIT_SYMBOL_TABLE
332 JitSymbolTable *__jitSymbolTable;
335 static void AddFunctionToSymbolTable(const char *FnName,
336 void *FnStart, intptr_t FnSize) {
337 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
338 JitSymbolTable **SymTabPtrPtr = 0;
339 #if !ENABLE_JIT_SYMBOL_TABLE
342 SymTabPtrPtr = &__jitSymbolTable;
345 // If this is the first entry in the symbol table, add the JitSymbolTable
347 if (*SymTabPtrPtr == 0) {
348 JitSymbolTable *New = new JitSymbolTable();
352 New->NumAllocated = 0;
356 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
358 // If we have space in the table, reallocate the table.
359 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
360 // If we don't have space, reallocate the table.
361 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
362 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
363 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
365 // Copy the old entries over.
366 memcpy(NewSymbols, OldSymbols,
367 SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
369 // Swap the new symbols in, delete the old ones.
370 SymTabPtr->Symbols = NewSymbols;
371 SymTabPtr->NumAllocated = NewSize;
372 delete [] OldSymbols;
375 // Otherwise, we have enough space, just tack it onto the end of the array.
376 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
377 Entry.FnName = strdup(FnName);
378 Entry.FnStart = FnStart;
379 Entry.FnSize = FnSize;
380 ++SymTabPtr->NumSymbols;
383 static void RemoveFunctionFromSymbolTable(void *FnStart) {
384 assert(FnStart && "Invalid function pointer");
385 JitSymbolTable **SymTabPtrPtr = 0;
386 #if !ENABLE_JIT_SYMBOL_TABLE
389 SymTabPtrPtr = &__jitSymbolTable;
392 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
393 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
395 // Scan the table to find its index. The table is not sorted, so do a linear
398 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
399 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
401 // Once we have an index, we know to nuke this entry, overwrite it with the
402 // entry at the end of the array, making the last entry redundant.
403 const char *OldName = Symbols[Index].FnName;
404 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
405 free((void*)OldName);
407 // Drop the number of symbols in the table.
408 --SymTabPtr->NumSymbols;
410 // Finally, if we deleted the final symbol, deallocate the table itself.
411 if (SymTabPtr->NumSymbols != 0)
419 //===----------------------------------------------------------------------===//
423 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
424 /// used to output functions to memory for execution.
425 class JITEmitter : public MachineCodeEmitter {
426 JITMemoryManager *MemMgr;
428 // When outputting a function stub in the context of some other function, we
429 // save BufferBegin/BufferEnd/CurBufferPtr here.
430 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
432 /// Relocations - These are the relocations that the function needs, as
434 std::vector<MachineRelocation> Relocations;
436 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
437 /// It is filled in by the StartMachineBasicBlock callback and queried by
438 /// the getMachineBasicBlockAddress callback.
439 std::vector<intptr_t> MBBLocations;
441 /// ConstantPool - The constant pool for the current function.
443 MachineConstantPool *ConstantPool;
445 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
447 void *ConstantPoolBase;
449 /// JumpTable - The jump tables for the current function.
451 MachineJumpTableInfo *JumpTable;
453 /// JumpTableBase - A pointer to the first entry in the jump table.
457 /// Resolver - This contains info about the currently resolved functions.
458 JITResolver Resolver;
460 /// DE - The dwarf emitter for the jit.
463 /// LabelLocations - This vector is a mapping from Label ID's to their
465 std::vector<intptr_t> LabelLocations;
467 /// MMI - Machine module info for exception informations
468 MachineModuleInfo* MMI;
471 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
472 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
473 if (jit.getJITInfo().needsGOT()) {
474 MemMgr->AllocateGOT();
475 DOUT << "JIT is managing a GOT\n";
478 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
482 if (ExceptionHandling) delete DE;
485 JITResolver &getJITResolver() { return Resolver; }
487 virtual void startFunction(MachineFunction &F);
488 virtual bool finishFunction(MachineFunction &F);
490 void emitConstantPool(MachineConstantPool *MCP);
491 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
492 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
494 virtual void startFunctionStub(const GlobalValue* F, unsigned StubSize,
495 unsigned Alignment = 1);
496 virtual void* finishFunctionStub(const GlobalValue *F);
498 virtual void addRelocation(const MachineRelocation &MR) {
499 Relocations.push_back(MR);
502 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
503 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
504 MBBLocations.resize((MBB->getNumber()+1)*2);
505 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
508 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
509 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
511 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
512 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
513 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
514 return MBBLocations[MBB->getNumber()];
517 /// deallocateMemForFunction - Deallocate all memory for the specified
519 void deallocateMemForFunction(Function *F) {
520 MemMgr->deallocateMemForFunction(F);
523 virtual void emitLabel(uint64_t LabelID) {
524 if (LabelLocations.size() <= LabelID)
525 LabelLocations.resize((LabelID+1)*2);
526 LabelLocations[LabelID] = getCurrentPCValue();
529 virtual intptr_t getLabelAddress(uint64_t LabelID) const {
530 assert(LabelLocations.size() > (unsigned)LabelID &&
531 LabelLocations[LabelID] && "Label not emitted!");
532 return LabelLocations[LabelID];
535 virtual void setModuleInfo(MachineModuleInfo* Info) {
537 if (ExceptionHandling) DE->setModuleInfo(Info);
541 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
542 void *getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
547 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
548 bool DoesntNeedStub) {
549 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
550 /// FIXME: If we straightened things out, this could actually emit the
551 /// global immediately instead of queuing it for codegen later!
552 return TheJIT->getOrEmitGlobalVariable(GV);
554 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
555 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal());
557 // If we have already compiled the function, return a pointer to its body.
558 Function *F = cast<Function>(V);
559 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
560 if (ResultPtr) return ResultPtr;
562 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
563 // If this is an external function pointer, we can force the JIT to
564 // 'compile' it, which really just adds it to the map.
566 return TheJIT->getPointerToFunction(F);
568 return Resolver.getFunctionStub(F);
571 // Okay, the function has not been compiled yet, if the target callback
572 // mechanism is capable of rewriting the instruction directly, prefer to do
573 // that instead of emitting a stub.
575 return Resolver.AddCallbackAtLocation(F, Reference);
577 // Otherwise, we have to emit a lazy resolving stub.
578 return Resolver.getFunctionStub(F);
581 void *JITEmitter::getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
582 bool DoesntNeedStub) {
583 // Make sure GV is emitted first.
584 // FIXME: For now, if the GV is an external function we force the JIT to
585 // compile it so the lazy pointer will contain the fully resolved address.
586 void *GVAddress = getPointerToGlobal(V, Reference, true);
587 return Resolver.getGlobalValueLazyPtr(V, GVAddress);
590 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
591 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
592 if (Constants.empty()) return 0;
594 MachineConstantPoolEntry CPE = Constants.back();
595 unsigned Size = CPE.Offset;
596 const Type *Ty = CPE.isMachineConstantPoolEntry()
597 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
598 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
602 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
603 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
604 if (JT.empty()) return 0;
606 unsigned NumEntries = 0;
607 for (unsigned i = 0, e = JT.size(); i != e; ++i)
608 NumEntries += JT[i].MBBs.size();
610 unsigned EntrySize = MJTI->getEntrySize();
612 return NumEntries * EntrySize;
615 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
616 if (Alignment == 0) Alignment = 1;
617 // Since we do not know where the buffer will be allocated, be pessimistic.
618 return Size + Alignment;
621 void JITEmitter::startFunction(MachineFunction &F) {
622 uintptr_t ActualSize = 0;
623 if (MemMgr->NeedsExactSize()) {
624 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
625 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
626 MachineConstantPool *MCP = F.getConstantPool();
628 // Ensure the constant pool/jump table info is at least 4-byte aligned.
629 ActualSize = RoundUpToAlign(ActualSize, 16);
631 // Add the alignment of the constant pool
632 ActualSize = RoundUpToAlign(ActualSize,
633 1 << MCP->getConstantPoolAlignment());
635 // Add the constant pool size
636 ActualSize += GetConstantPoolSizeInBytes(MCP);
638 // Add the aligment of the jump table info
639 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
641 // Add the jump table size
642 ActualSize += GetJumpTableSizeInBytes(MJTI);
644 // Add the alignment for the function
645 ActualSize = RoundUpToAlign(ActualSize,
646 std::max(F.getFunction()->getAlignment(), 8U));
648 // Add the function size
649 ActualSize += TII->GetFunctionSizeInBytes(F);
652 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
654 BufferEnd = BufferBegin+ActualSize;
656 // Ensure the constant pool/jump table info is at least 4-byte aligned.
659 emitConstantPool(F.getConstantPool());
660 initJumpTableInfo(F.getJumpTableInfo());
662 // About to start emitting the machine code for the function.
663 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
664 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
666 MBBLocations.clear();
669 bool JITEmitter::finishFunction(MachineFunction &F) {
670 if (CurBufferPtr == BufferEnd) {
671 // FIXME: Allocate more space, then try again.
672 cerr << "JIT: Ran out of space for generated machine code!\n";
676 emitJumpTableInfo(F.getJumpTableInfo());
678 // FnStart is the start of the text, not the start of the constant pool and
679 // other per-function data.
680 unsigned char *FnStart =
681 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
682 unsigned char *FnEnd = CurBufferPtr;
684 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
685 NumBytes += FnEnd-FnStart;
687 if (!Relocations.empty()) {
688 NumRelos += Relocations.size();
690 // Resolve the relocations to concrete pointers.
691 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
692 MachineRelocation &MR = Relocations[i];
695 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
697 // If the target REALLY wants a stub for this function, emit it now.
698 if (!MR.doesntNeedStub())
699 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
700 } else if (MR.isGlobalValue()) {
701 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
702 BufferBegin+MR.getMachineCodeOffset(),
703 MR.doesntNeedStub());
704 } else if (MR.isGlobalValueLazyPtr()) {
705 ResultPtr = getPointerToGVLazyPtr(MR.getGlobalValue(),
706 BufferBegin+MR.getMachineCodeOffset(),
707 MR.doesntNeedStub());
708 } else if (MR.isBasicBlock()) {
709 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
710 } else if (MR.isConstantPoolIndex()) {
711 ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
713 assert(MR.isJumpTableIndex());
714 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
717 MR.setResultPointer(ResultPtr);
719 // if we are managing the GOT and the relocation wants an index,
721 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
722 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
724 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
725 DOUT << "GOT was out of date for " << ResultPtr
726 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
728 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
733 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
734 Relocations.size(), MemMgr->getGOTBase());
737 // Update the GOT entry for F to point to the new code.
738 if (MemMgr->isManagingGOT()) {
739 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
740 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
741 DOUT << "GOT was out of date for " << (void*)BufferBegin
742 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
743 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
747 // Invalidate the icache if necessary.
748 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
750 // Add it to the JIT symbol table if the host wants it.
751 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
752 FnStart, FnEnd-FnStart);
754 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
755 << "] Function: " << F.getFunction()->getName()
756 << ": " << (FnEnd-FnStart) << " bytes of text, "
757 << Relocations.size() << " relocations\n";
761 if (sys::hasDisassembler())
762 DOUT << "Disassembled code:\n"
763 << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
765 if (ExceptionHandling) {
766 uintptr_t ActualSize = 0;
767 SavedBufferBegin = BufferBegin;
768 SavedBufferEnd = BufferEnd;
769 SavedCurBufferPtr = CurBufferPtr;
771 if (MemMgr->NeedsExactSize()) {
772 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
775 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
777 BufferEnd = BufferBegin+ActualSize;
778 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
779 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
781 BufferBegin = SavedBufferBegin;
782 BufferEnd = SavedBufferEnd;
783 CurBufferPtr = SavedCurBufferPtr;
785 TheJIT->RegisterTable(FrameRegister);
792 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
793 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
794 if (Constants.empty()) return;
796 MachineConstantPoolEntry CPE = Constants.back();
797 unsigned Size = CPE.Offset;
798 const Type *Ty = CPE.isMachineConstantPoolEntry()
799 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
800 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
802 unsigned Align = 1 << MCP->getConstantPoolAlignment();
803 ConstantPoolBase = allocateSpace(Size, Align);
806 if (ConstantPoolBase == 0) return; // Buffer overflow.
808 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
809 << "] (size: " << Size << ", alignment: " << Align << ")\n";
811 // Initialize the memory for all of the constant pool entries.
812 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
813 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
814 if (Constants[i].isMachineConstantPoolEntry()) {
815 // FIXME: add support to lower machine constant pool values into bytes!
816 cerr << "Initialize memory with machine specific constant pool entry"
817 << " has not been implemented!\n";
820 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
821 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
825 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
826 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
827 if (JT.empty()) return;
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 // Just allocate space for all the jump tables now. We will fix up the actual
836 // MBB entries in the tables after we emit the code for each block, since then
837 // we will know the final locations of the MBBs in memory.
839 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
842 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
843 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
844 if (JT.empty() || JumpTableBase == 0) return;
846 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
847 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
848 // For each jump table, place the offset from the beginning of the table
849 // to the target address.
850 int *SlotPtr = (int*)JumpTableBase;
852 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
853 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
854 // Store the offset of the basic block for this jump table slot in the
855 // memory we allocated for the jump table in 'initJumpTableInfo'
856 intptr_t Base = (intptr_t)SlotPtr;
857 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
858 intptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
859 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
863 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
865 // For each jump table, map each target in the jump table to the address of
866 // an emitted MachineBasicBlock.
867 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
869 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
870 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
871 // Store the address of the basic block for this jump table slot in the
872 // memory we allocated for the jump table in 'initJumpTableInfo'
873 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
874 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
879 void JITEmitter::startFunctionStub(const GlobalValue* F, unsigned StubSize,
880 unsigned Alignment) {
881 SavedBufferBegin = BufferBegin;
882 SavedBufferEnd = BufferEnd;
883 SavedCurBufferPtr = CurBufferPtr;
885 BufferBegin = CurBufferPtr = MemMgr->allocateStub(F, StubSize, Alignment);
886 BufferEnd = BufferBegin+StubSize+1;
889 void *JITEmitter::finishFunctionStub(const GlobalValue* F) {
890 NumBytes += getCurrentPCOffset();
891 std::swap(SavedBufferBegin, BufferBegin);
892 BufferEnd = SavedBufferEnd;
893 CurBufferPtr = SavedCurBufferPtr;
894 return SavedBufferBegin;
897 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
898 // in the constant pool that was last emitted with the 'emitConstantPool'
901 intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
902 assert(ConstantNum < ConstantPool->getConstants().size() &&
903 "Invalid ConstantPoolIndex!");
904 return (intptr_t)ConstantPoolBase +
905 ConstantPool->getConstants()[ConstantNum].Offset;
908 // getJumpTableEntryAddress - Return the address of the JumpTable with index
909 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
911 intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
912 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
913 assert(Index < JT.size() && "Invalid jump table index!");
916 unsigned EntrySize = JumpTable->getEntrySize();
918 for (unsigned i = 0; i < Index; ++i)
919 Offset += JT[i].MBBs.size();
923 return (intptr_t)((char *)JumpTableBase + Offset);
926 //===----------------------------------------------------------------------===//
927 // Public interface to this file
928 //===----------------------------------------------------------------------===//
930 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
931 return new JITEmitter(jit, JMM);
934 // getPointerToNamedFunction - This function is used as a global wrapper to
935 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
936 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
937 // need to resolve function(s) that are being mis-codegenerated, so we need to
938 // resolve their addresses at runtime, and this is the way to do it.
940 void *getPointerToNamedFunction(const char *Name) {
941 if (Function *F = TheJIT->FindFunctionNamed(Name))
942 return TheJIT->getPointerToFunction(F);
943 return TheJIT->getPointerToNamedFunction(Name);
947 // getPointerToFunctionOrStub - If the specified function has been
948 // code-gen'd, return a pointer to the function. If not, compile it, or use
949 // a stub to implement lazy compilation if available.
951 void *JIT::getPointerToFunctionOrStub(Function *F) {
952 // If we have already code generated the function, just return the address.
953 if (void *Addr = getPointerToGlobalIfAvailable(F))
956 // Get a stub if the target supports it.
957 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
958 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
959 return JE->getJITResolver().getFunctionStub(F);
962 /// freeMachineCodeForFunction - release machine code memory for given Function.
964 void JIT::freeMachineCodeForFunction(Function *F) {
966 // Delete translation for this from the ExecutionEngine, so it will get
967 // retranslated next time it is used.
968 void *OldPtr = updateGlobalMapping(F, 0);
971 RemoveFunctionFromSymbolTable(OldPtr);
973 // Free the actual memory for the function body and related stuff.
974 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
975 static_cast<JITEmitter*>(MCE)->deallocateMemForFunction(F);