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/Target/TargetInstrInfo.h"
36 #include "llvm/ADT/Statistic.h"
40 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
41 STATISTIC(NumRelos, "Number of relocations applied");
42 static JIT *TheJIT = 0;
45 //===----------------------------------------------------------------------===//
46 // JIT lazy compilation code.
49 class JITResolverState {
51 /// FunctionToStubMap - Keep track of the stub created for a particular
52 /// function so that we can reuse them if necessary.
53 std::map<Function*, void*> FunctionToStubMap;
55 /// StubToFunctionMap - Keep track of the function that each stub
57 std::map<void*, Function*> StubToFunctionMap;
59 /// GlobalToLazyPtrMap - Keep track of the lazy pointer created for a
60 /// particular GlobalVariable so that we can reuse them if necessary.
61 std::map<GlobalValue*, void*> GlobalToLazyPtrMap;
64 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
65 assert(locked.holds(TheJIT->lock));
66 return FunctionToStubMap;
69 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
70 assert(locked.holds(TheJIT->lock));
71 return StubToFunctionMap;
74 std::map<GlobalValue*, void*>&
75 getGlobalToLazyPtrMap(const MutexGuard& locked) {
76 assert(locked.holds(TheJIT->lock));
77 return GlobalToLazyPtrMap;
81 /// JITResolver - Keep track of, and resolve, call sites for functions that
82 /// have not yet been compiled.
84 /// LazyResolverFn - The target lazy resolver function that we actually
85 /// rewrite instructions to use.
86 TargetJITInfo::LazyResolverFn LazyResolverFn;
88 JITResolverState state;
90 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
91 /// external functions.
92 std::map<void*, void*> ExternalFnToStubMap;
94 //map addresses to indexes in the GOT
95 std::map<void*, unsigned> revGOTMap;
96 unsigned nextGOTIndex;
98 static JITResolver *TheJITResolver;
100 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
103 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
104 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
105 TheJITResolver = this;
112 /// getFunctionStub - This returns a pointer to a function stub, creating
113 /// one on demand as needed.
114 void *getFunctionStub(Function *F);
116 /// getExternalFunctionStub - Return a stub for the function at the
117 /// specified address, created lazily on demand.
118 void *getExternalFunctionStub(void *FnAddr);
120 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
122 void *getGlobalValueLazyPtr(GlobalValue *V, void *GVAddress);
124 /// AddCallbackAtLocation - If the target is capable of rewriting an
125 /// instruction without the use of a stub, record the location of the use so
126 /// we know which function is being used at the location.
127 void *AddCallbackAtLocation(Function *F, void *Location) {
128 MutexGuard locked(TheJIT->lock);
129 /// Get the target-specific JIT resolver function.
130 state.getStubToFunctionMap(locked)[Location] = F;
131 return (void*)(intptr_t)LazyResolverFn;
134 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
135 /// an address. This function only manages slots, it does not manage the
136 /// contents of the slots or the memory associated with the GOT.
137 unsigned getGOTIndexForAddr(void *addr);
139 /// JITCompilerFn - This function is called to resolve a stub to a compiled
140 /// address. If the LLVM Function corresponding to the stub has not yet
141 /// been compiled, this function compiles it first.
142 static void *JITCompilerFn(void *Stub);
146 JITResolver *JITResolver::TheJITResolver = 0;
148 /// getFunctionStub - This returns a pointer to a function stub, creating
149 /// one on demand as needed.
150 void *JITResolver::getFunctionStub(Function *F) {
151 MutexGuard locked(TheJIT->lock);
153 // If we already have a stub for this function, recycle it.
154 void *&Stub = state.getFunctionToStubMap(locked)[F];
155 if (Stub) return Stub;
157 // Call the lazy resolver function unless we already KNOW it is an external
158 // function, in which case we just skip the lazy resolution step.
159 void *Actual = (void*)(intptr_t)LazyResolverFn;
160 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
161 Actual = TheJIT->getPointerToFunction(F);
163 // Otherwise, codegen a new stub. For now, the stub will call the lazy
164 // resolver function.
165 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
166 *TheJIT->getCodeEmitter());
168 if (Actual != (void*)(intptr_t)LazyResolverFn) {
169 // If we are getting the stub for an external function, we really want the
170 // address of the stub in the GlobalAddressMap for the JIT, not the address
171 // of the external function.
172 TheJIT->updateGlobalMapping(F, Stub);
175 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
176 << F->getName() << "'\n";
178 // Finally, keep track of the stub-to-Function mapping so that the
179 // JITCompilerFn knows which function to compile!
180 state.getStubToFunctionMap(locked)[Stub] = F;
184 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
186 void *JITResolver::getGlobalValueLazyPtr(GlobalValue *GV, void *GVAddress) {
187 MutexGuard locked(TheJIT->lock);
189 // If we already have a stub for this global variable, recycle it.
190 void *&LazyPtr = state.getGlobalToLazyPtrMap(locked)[GV];
191 if (LazyPtr) return LazyPtr;
193 // Otherwise, codegen a new lazy pointer.
194 LazyPtr = TheJIT->getJITInfo().emitGlobalValueLazyPtr(GV, GVAddress,
195 *TheJIT->getCodeEmitter());
197 DOUT << "JIT: Stub emitted at [" << LazyPtr << "] for GV '"
198 << GV->getName() << "'\n";
203 /// getExternalFunctionStub - Return a stub for the function at the
204 /// specified address, created lazily on demand.
205 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
206 // If we already have a stub for this function, recycle it.
207 void *&Stub = ExternalFnToStubMap[FnAddr];
208 if (Stub) return Stub;
210 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
211 *TheJIT->getCodeEmitter());
213 DOUT << "JIT: Stub emitted at [" << Stub
214 << "] for external function at '" << FnAddr << "'\n";
218 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
219 unsigned idx = revGOTMap[addr];
221 idx = ++nextGOTIndex;
222 revGOTMap[addr] = idx;
223 DOUT << "Adding GOT entry " << idx << " for addr " << addr << "\n";
228 /// JITCompilerFn - This function is called when a lazy compilation stub has
229 /// been entered. It looks up which function this stub corresponds to, compiles
230 /// it if necessary, then returns the resultant function pointer.
231 void *JITResolver::JITCompilerFn(void *Stub) {
232 JITResolver &JR = *TheJITResolver;
234 MutexGuard locked(TheJIT->lock);
236 // The address given to us for the stub may not be exactly right, it might be
237 // a little bit after the stub. As such, use upper_bound to find it.
238 std::map<void*, Function*>::iterator I =
239 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
240 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
241 "This is not a known stub!");
242 Function *F = (--I)->second;
244 // If we have already code generated the function, just return the address.
245 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
248 // Otherwise we don't have it, do lazy compilation now.
250 // If lazy compilation is disabled, emit a useful error message and abort.
251 if (TheJIT->isLazyCompilationDisabled()) {
252 cerr << "LLVM JIT requested to do lazy compilation of function '"
253 << F->getName() << "' when lazy compiles are disabled!\n";
257 // We might like to remove the stub from the StubToFunction map.
258 // We can't do that! Multiple threads could be stuck, waiting to acquire the
259 // lock above. As soon as the 1st function finishes compiling the function,
260 // the next one will be released, and needs to be able to find the function
262 //JR.state.getStubToFunctionMap(locked).erase(I);
264 DOUT << "JIT: Lazily resolving function '" << F->getName()
265 << "' In stub ptr = " << Stub << " actual ptr = "
268 Result = TheJIT->getPointerToFunction(F);
271 // We don't need to reuse this stub in the future, as F is now compiled.
272 JR.state.getFunctionToStubMap(locked).erase(F);
274 // FIXME: We could rewrite all references to this stub if we knew them.
276 // What we will do is set the compiled function address to map to the
277 // same GOT entry as the stub so that later clients may update the GOT
278 // if they see it still using the stub address.
279 // Note: this is done so the Resolver doesn't have to manage GOT memory
280 // Do this without allocating map space if the target isn't using a GOT
281 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
282 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
287 //===----------------------------------------------------------------------===//
288 // Function Index Support
290 // On MacOS we generate an index of currently JIT'd functions so that
291 // performance tools can determine a symbol name and accurate code range for a
292 // PC value. Because performance tools are generally asynchronous, the code
293 // below is written with the hope that it could be interrupted at any time and
294 // have useful answers. However, we don't go crazy with atomic operations, we
295 // just do a "reasonable effort".
297 #define ENABLE_JIT_SYMBOL_TABLE 0
300 /// JitSymbolEntry - Each function that is JIT compiled results in one of these
301 /// being added to an array of symbols. This indicates the name of the function
302 /// as well as the address range it occupies. This allows the client to map
303 /// from a PC value to the name of the function.
304 struct JitSymbolEntry {
305 const char *FnName; // FnName - a strdup'd string.
311 struct JitSymbolTable {
312 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
313 /// pointer is not used right now, but might be used in the future. Consider
314 /// it reserved for future use.
315 JitSymbolTable *NextPtr;
317 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
318 /// 'NumSymbols' symbols are valid.
319 JitSymbolEntry *Symbols;
321 /// NumSymbols - This indicates the number entries in the Symbols array that
325 /// NumAllocated - This indicates the amount of space we have in the Symbols
326 /// array. This is a private field that should not be read by external tools.
327 unsigned NumAllocated;
330 #if ENABLE_JIT_SYMBOL_TABLE
331 JitSymbolTable *__jitSymbolTable;
334 static void AddFunctionToSymbolTable(const char *FnName,
335 void *FnStart, intptr_t FnSize) {
336 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
337 JitSymbolTable **SymTabPtrPtr = 0;
338 #if !ENABLE_JIT_SYMBOL_TABLE
341 SymTabPtrPtr = &__jitSymbolTable;
344 // If this is the first entry in the symbol table, add the JitSymbolTable
346 if (*SymTabPtrPtr == 0) {
347 JitSymbolTable *New = new JitSymbolTable();
351 New->NumAllocated = 0;
355 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
357 // If we have space in the table, reallocate the table.
358 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
359 // If we don't have space, reallocate the table.
360 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
361 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
362 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
364 // Copy the old entries over.
365 memcpy(NewSymbols, OldSymbols,
366 SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
368 // Swap the new symbols in, delete the old ones.
369 SymTabPtr->Symbols = NewSymbols;
370 SymTabPtr->NumAllocated = NewSize;
371 delete [] OldSymbols;
374 // Otherwise, we have enough space, just tack it onto the end of the array.
375 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
376 Entry.FnName = strdup(FnName);
377 Entry.FnStart = FnStart;
378 Entry.FnSize = FnSize;
379 ++SymTabPtr->NumSymbols;
382 static void RemoveFunctionFromSymbolTable(void *FnStart) {
383 assert(FnStart && "Invalid function pointer");
384 JitSymbolTable **SymTabPtrPtr = 0;
385 #if !ENABLE_JIT_SYMBOL_TABLE
388 SymTabPtrPtr = &__jitSymbolTable;
391 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
392 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
394 // Scan the table to find its index. The table is not sorted, so do a linear
397 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
398 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
400 // Once we have an index, we know to nuke this entry, overwrite it with the
401 // entry at the end of the array, making the last entry redundant.
402 const char *OldName = Symbols[Index].FnName;
403 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
404 free((void*)OldName);
406 // Drop the number of symbols in the table.
407 --SymTabPtr->NumSymbols;
409 // Finally, if we deleted the final symbol, deallocate the table itself.
410 if (SymTabPtr->NumSymbols != 0)
418 //===----------------------------------------------------------------------===//
422 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
423 /// used to output functions to memory for execution.
424 class JITEmitter : public MachineCodeEmitter {
425 JITMemoryManager *MemMgr;
427 // When outputting a function stub in the context of some other function, we
428 // save BufferBegin/BufferEnd/CurBufferPtr here.
429 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
431 /// Relocations - These are the relocations that the function needs, as
433 std::vector<MachineRelocation> Relocations;
435 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
436 /// It is filled in by the StartMachineBasicBlock callback and queried by
437 /// the getMachineBasicBlockAddress callback.
438 std::vector<intptr_t> MBBLocations;
440 /// ConstantPool - The constant pool for the current function.
442 MachineConstantPool *ConstantPool;
444 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
446 void *ConstantPoolBase;
448 /// JumpTable - The jump tables for the current function.
450 MachineJumpTableInfo *JumpTable;
452 /// JumpTableBase - A pointer to the first entry in the jump table.
456 /// Resolver - This contains info about the currently resolved functions.
457 JITResolver Resolver;
459 /// DE - The dwarf emitter for the jit.
462 /// LabelLocations - This vector is a mapping from Label ID's to their
464 std::vector<intptr_t> LabelLocations;
466 /// MMI - Machine module info for exception informations
467 MachineModuleInfo* MMI;
470 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
471 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
472 if (jit.getJITInfo().needsGOT()) {
473 MemMgr->AllocateGOT();
474 DOUT << "JIT is managing a GOT\n";
477 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
481 if (ExceptionHandling) delete DE;
484 JITResolver &getJITResolver() { return Resolver; }
486 virtual void startFunction(MachineFunction &F);
487 virtual bool finishFunction(MachineFunction &F);
489 void emitConstantPool(MachineConstantPool *MCP);
490 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
491 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
493 virtual void startFunctionStub(const GlobalValue* F, unsigned StubSize,
494 unsigned Alignment = 1);
495 virtual void* finishFunctionStub(const GlobalValue *F);
497 virtual void addRelocation(const MachineRelocation &MR) {
498 Relocations.push_back(MR);
501 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
502 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
503 MBBLocations.resize((MBB->getNumber()+1)*2);
504 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
507 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
508 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
510 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
511 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
512 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
513 return MBBLocations[MBB->getNumber()];
516 /// deallocateMemForFunction - Deallocate all memory for the specified
518 void deallocateMemForFunction(Function *F) {
519 MemMgr->deallocateMemForFunction(F);
522 virtual void emitLabel(uint64_t LabelID) {
523 if (LabelLocations.size() <= LabelID)
524 LabelLocations.resize((LabelID+1)*2);
525 LabelLocations[LabelID] = getCurrentPCValue();
528 virtual intptr_t getLabelAddress(uint64_t LabelID) const {
529 assert(LabelLocations.size() > (unsigned)LabelID &&
530 LabelLocations[LabelID] && "Label not emitted!");
531 return LabelLocations[LabelID];
534 virtual void setModuleInfo(MachineModuleInfo* Info) {
536 if (ExceptionHandling) DE->setModuleInfo(Info);
540 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
541 void *getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
546 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
547 bool DoesntNeedStub) {
548 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
549 /// FIXME: If we straightened things out, this could actually emit the
550 /// global immediately instead of queuing it for codegen later!
551 return TheJIT->getOrEmitGlobalVariable(GV);
554 // If we have already compiled the function, return a pointer to its body.
555 Function *F = cast<Function>(V);
556 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
557 if (ResultPtr) return ResultPtr;
559 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
560 // If this is an external function pointer, we can force the JIT to
561 // 'compile' it, which really just adds it to the map.
563 return TheJIT->getPointerToFunction(F);
565 return Resolver.getFunctionStub(F);
568 // Okay, the function has not been compiled yet, if the target callback
569 // mechanism is capable of rewriting the instruction directly, prefer to do
570 // that instead of emitting a stub.
572 return Resolver.AddCallbackAtLocation(F, Reference);
574 // Otherwise, we have to emit a lazy resolving stub.
575 return Resolver.getFunctionStub(F);
578 void *JITEmitter::getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
579 bool DoesntNeedStub) {
580 // Make sure GV is emitted first.
581 // FIXME: For now, if the GV is an external function we force the JIT to
582 // compile it so the lazy pointer will contain the fully resolved address.
583 void *GVAddress = getPointerToGlobal(V, Reference, true);
584 return Resolver.getGlobalValueLazyPtr(V, GVAddress);
587 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
588 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
589 if (Constants.empty()) return 0;
591 MachineConstantPoolEntry CPE = Constants.back();
592 unsigned Size = CPE.Offset;
593 const Type *Ty = CPE.isMachineConstantPoolEntry()
594 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
595 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
599 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
600 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
601 if (JT.empty()) return 0;
603 unsigned NumEntries = 0;
604 for (unsigned i = 0, e = JT.size(); i != e; ++i)
605 NumEntries += JT[i].MBBs.size();
607 unsigned EntrySize = MJTI->getEntrySize();
609 return NumEntries * EntrySize;
612 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
613 if (Alignment == 0) Alignment = 1;
614 // Since we do not know where the buffer will be allocated, be pessimistic.
615 return Size + Alignment;
618 void JITEmitter::startFunction(MachineFunction &F) {
619 uintptr_t ActualSize = 0;
620 if (MemMgr->NeedsExactSize()) {
621 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
622 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
623 MachineConstantPool *MCP = F.getConstantPool();
625 // Ensure the constant pool/jump table info is at least 4-byte aligned.
626 ActualSize = RoundUpToAlign(ActualSize, 16);
628 // Add the alignment of the constant pool
629 ActualSize = RoundUpToAlign(ActualSize,
630 1 << MCP->getConstantPoolAlignment());
632 // Add the constant pool size
633 ActualSize += GetConstantPoolSizeInBytes(MCP);
635 // Add the aligment of the jump table info
636 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
638 // Add the jump table size
639 ActualSize += GetJumpTableSizeInBytes(MJTI);
641 // Add the alignment for the function
642 ActualSize = RoundUpToAlign(ActualSize,
643 std::max(F.getFunction()->getAlignment(), 8U));
645 // Add the function size
646 ActualSize += TII->GetFunctionSizeInBytes(F);
649 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
651 BufferEnd = BufferBegin+ActualSize;
653 // Ensure the constant pool/jump table info is at least 4-byte aligned.
656 emitConstantPool(F.getConstantPool());
657 initJumpTableInfo(F.getJumpTableInfo());
659 // About to start emitting the machine code for the function.
660 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
661 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
663 MBBLocations.clear();
666 bool JITEmitter::finishFunction(MachineFunction &F) {
667 if (CurBufferPtr == BufferEnd) {
668 // FIXME: Allocate more space, then try again.
669 cerr << "JIT: Ran out of space for generated machine code!\n";
673 emitJumpTableInfo(F.getJumpTableInfo());
675 // FnStart is the start of the text, not the start of the constant pool and
676 // other per-function data.
677 unsigned char *FnStart =
678 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
679 unsigned char *FnEnd = CurBufferPtr;
681 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
682 NumBytes += FnEnd-FnStart;
684 if (!Relocations.empty()) {
685 NumRelos += Relocations.size();
687 // Resolve the relocations to concrete pointers.
688 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
689 MachineRelocation &MR = Relocations[i];
692 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
694 // If the target REALLY wants a stub for this function, emit it now.
695 if (!MR.doesntNeedStub())
696 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
697 } else if (MR.isGlobalValue()) {
698 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
699 BufferBegin+MR.getMachineCodeOffset(),
700 MR.doesntNeedStub());
701 } else if (MR.isGlobalValueLazyPtr()) {
702 ResultPtr = getPointerToGVLazyPtr(MR.getGlobalValue(),
703 BufferBegin+MR.getMachineCodeOffset(),
704 MR.doesntNeedStub());
705 } else if (MR.isBasicBlock()) {
706 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
707 } else if (MR.isConstantPoolIndex()) {
708 ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
710 assert(MR.isJumpTableIndex());
711 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
714 MR.setResultPointer(ResultPtr);
716 // if we are managing the GOT and the relocation wants an index,
718 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
719 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
721 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
722 DOUT << "GOT was out of date for " << ResultPtr
723 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
725 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
730 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
731 Relocations.size(), MemMgr->getGOTBase());
734 // Update the GOT entry for F to point to the new code.
735 if (MemMgr->isManagingGOT()) {
736 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
737 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
738 DOUT << "GOT was out of date for " << (void*)BufferBegin
739 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
740 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
744 // Invalidate the icache if necessary.
745 TheJIT->getJITInfo().InvalidateInstructionCache(FnStart, FnEnd-FnStart);
747 // Add it to the JIT symbol table if the host wants it.
748 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
749 FnStart, FnEnd-FnStart);
751 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
752 << "] Function: " << F.getFunction()->getName()
753 << ": " << (FnEnd-FnStart) << " bytes of text, "
754 << Relocations.size() << " relocations\n";
758 if (sys::hasDisassembler())
759 DOUT << "Disassembled code:\n"
760 << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
762 if (ExceptionHandling) {
763 uintptr_t ActualSize = 0;
764 SavedBufferBegin = BufferBegin;
765 SavedBufferEnd = BufferEnd;
766 SavedCurBufferPtr = CurBufferPtr;
768 if (MemMgr->NeedsExactSize()) {
769 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
772 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
774 BufferEnd = BufferBegin+ActualSize;
775 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
776 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
778 BufferBegin = SavedBufferBegin;
779 BufferEnd = SavedBufferEnd;
780 CurBufferPtr = SavedCurBufferPtr;
782 TheJIT->RegisterTable(FrameRegister);
789 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
790 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
791 if (Constants.empty()) return;
793 MachineConstantPoolEntry CPE = Constants.back();
794 unsigned Size = CPE.Offset;
795 const Type *Ty = CPE.isMachineConstantPoolEntry()
796 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
797 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
799 unsigned Align = 1 << MCP->getConstantPoolAlignment();
800 ConstantPoolBase = allocateSpace(Size, Align);
803 if (ConstantPoolBase == 0) return; // Buffer overflow.
805 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
806 << "] (size: " << Size << ", alignment: " << Align << ")\n";
808 // Initialize the memory for all of the constant pool entries.
809 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
810 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
811 if (Constants[i].isMachineConstantPoolEntry()) {
812 // FIXME: add support to lower machine constant pool values into bytes!
813 cerr << "Initialize memory with machine specific constant pool entry"
814 << " has not been implemented!\n";
817 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
818 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
822 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
823 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
824 if (JT.empty()) return;
826 unsigned NumEntries = 0;
827 for (unsigned i = 0, e = JT.size(); i != e; ++i)
828 NumEntries += JT[i].MBBs.size();
830 unsigned EntrySize = MJTI->getEntrySize();
832 // Just allocate space for all the jump tables now. We will fix up the actual
833 // MBB entries in the tables after we emit the code for each block, since then
834 // we will know the final locations of the MBBs in memory.
836 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
839 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
840 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
841 if (JT.empty() || JumpTableBase == 0) return;
843 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
844 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
845 // For each jump table, place the offset from the beginning of the table
846 // to the target address.
847 int *SlotPtr = (int*)JumpTableBase;
849 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
850 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
851 // Store the offset of the basic block for this jump table slot in the
852 // memory we allocated for the jump table in 'initJumpTableInfo'
853 intptr_t Base = (intptr_t)SlotPtr;
854 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
855 intptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
856 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
860 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
862 // For each jump table, map each target in the jump table to the address of
863 // an emitted MachineBasicBlock.
864 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
866 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
867 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
868 // Store the address of the basic block for this jump table slot in the
869 // memory we allocated for the jump table in 'initJumpTableInfo'
870 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
871 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
876 void JITEmitter::startFunctionStub(const GlobalValue* F, unsigned StubSize,
877 unsigned Alignment) {
878 SavedBufferBegin = BufferBegin;
879 SavedBufferEnd = BufferEnd;
880 SavedCurBufferPtr = CurBufferPtr;
882 BufferBegin = CurBufferPtr = MemMgr->allocateStub(F, StubSize, Alignment);
883 BufferEnd = BufferBegin+StubSize+1;
886 void *JITEmitter::finishFunctionStub(const GlobalValue* F) {
887 NumBytes += getCurrentPCOffset();
888 std::swap(SavedBufferBegin, BufferBegin);
889 BufferEnd = SavedBufferEnd;
890 CurBufferPtr = SavedCurBufferPtr;
891 return SavedBufferBegin;
894 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
895 // in the constant pool that was last emitted with the 'emitConstantPool'
898 intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
899 assert(ConstantNum < ConstantPool->getConstants().size() &&
900 "Invalid ConstantPoolIndex!");
901 return (intptr_t)ConstantPoolBase +
902 ConstantPool->getConstants()[ConstantNum].Offset;
905 // getJumpTableEntryAddress - Return the address of the JumpTable with index
906 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
908 intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
909 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
910 assert(Index < JT.size() && "Invalid jump table index!");
913 unsigned EntrySize = JumpTable->getEntrySize();
915 for (unsigned i = 0; i < Index; ++i)
916 Offset += JT[i].MBBs.size();
920 return (intptr_t)((char *)JumpTableBase + Offset);
923 //===----------------------------------------------------------------------===//
924 // Public interface to this file
925 //===----------------------------------------------------------------------===//
927 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
928 return new JITEmitter(jit, JMM);
931 // getPointerToNamedFunction - This function is used as a global wrapper to
932 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
933 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
934 // need to resolve function(s) that are being mis-codegenerated, so we need to
935 // resolve their addresses at runtime, and this is the way to do it.
937 void *getPointerToNamedFunction(const char *Name) {
938 if (Function *F = TheJIT->FindFunctionNamed(Name))
939 return TheJIT->getPointerToFunction(F);
940 return TheJIT->getPointerToNamedFunction(Name);
944 // getPointerToFunctionOrStub - If the specified function has been
945 // code-gen'd, return a pointer to the function. If not, compile it, or use
946 // a stub to implement lazy compilation if available.
948 void *JIT::getPointerToFunctionOrStub(Function *F) {
949 // If we have already code generated the function, just return the address.
950 if (void *Addr = getPointerToGlobalIfAvailable(F))
953 // Get a stub if the target supports it.
954 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
955 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
956 return JE->getJITResolver().getFunctionStub(F);
959 /// freeMachineCodeForFunction - release machine code memory for given Function.
961 void JIT::freeMachineCodeForFunction(Function *F) {
963 // Delete translation for this from the ExecutionEngine, so it will get
964 // retranslated next time it is used.
965 void *OldPtr = updateGlobalMapping(F, 0);
968 RemoveFunctionFromSymbolTable(OldPtr);
970 // Free the actual memory for the function body and related stuff.
971 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
972 static_cast<JITEmitter*>(MCE)->deallocateMemForFunction(F);