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/ADT/Statistic.h"
39 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
40 STATISTIC(NumRelos, "Number of relocations applied");
41 static JIT *TheJIT = 0;
44 //===----------------------------------------------------------------------===//
45 // JIT lazy compilation code.
48 class JITResolverState {
50 /// FunctionToStubMap - Keep track of the stub created for a particular
51 /// function so that we can reuse them if necessary.
52 std::map<Function*, void*> FunctionToStubMap;
54 /// StubToFunctionMap - Keep track of the function that each stub
56 std::map<void*, Function*> StubToFunctionMap;
58 /// GlobalToLazyPtrMap - Keep track of the lazy pointer created for a
59 /// particular GlobalVariable so that we can reuse them if necessary.
60 std::map<GlobalValue*, void*> GlobalToLazyPtrMap;
63 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
64 assert(locked.holds(TheJIT->lock));
65 return FunctionToStubMap;
68 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
69 assert(locked.holds(TheJIT->lock));
70 return StubToFunctionMap;
73 std::map<GlobalValue*, void*>&
74 getGlobalToLazyPtrMap(const MutexGuard& locked) {
75 assert(locked.holds(TheJIT->lock));
76 return GlobalToLazyPtrMap;
80 /// JITResolver - Keep track of, and resolve, call sites for functions that
81 /// have not yet been compiled.
83 /// LazyResolverFn - The target lazy resolver function that we actually
84 /// rewrite instructions to use.
85 TargetJITInfo::LazyResolverFn LazyResolverFn;
87 JITResolverState state;
89 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
90 /// external functions.
91 std::map<void*, void*> ExternalFnToStubMap;
93 //map addresses to indexes in the GOT
94 std::map<void*, unsigned> revGOTMap;
95 unsigned nextGOTIndex;
97 static JITResolver *TheJITResolver;
99 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
102 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
103 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
104 TheJITResolver = this;
111 /// getFunctionStub - This returns a pointer to a function stub, creating
112 /// one on demand as needed.
113 void *getFunctionStub(Function *F);
115 /// getExternalFunctionStub - Return a stub for the function at the
116 /// specified address, created lazily on demand.
117 void *getExternalFunctionStub(void *FnAddr);
119 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
121 void *getGlobalValueLazyPtr(GlobalValue *V, void *GVAddress);
123 /// AddCallbackAtLocation - If the target is capable of rewriting an
124 /// instruction without the use of a stub, record the location of the use so
125 /// we know which function is being used at the location.
126 void *AddCallbackAtLocation(Function *F, void *Location) {
127 MutexGuard locked(TheJIT->lock);
128 /// Get the target-specific JIT resolver function.
129 state.getStubToFunctionMap(locked)[Location] = F;
130 return (void*)(intptr_t)LazyResolverFn;
133 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
134 /// an address. This function only manages slots, it does not manage the
135 /// contents of the slots or the memory associated with the GOT.
136 unsigned getGOTIndexForAddr(void *addr);
138 /// JITCompilerFn - This function is called to resolve a stub to a compiled
139 /// address. If the LLVM Function corresponding to the stub has not yet
140 /// been compiled, this function compiles it first.
141 static void *JITCompilerFn(void *Stub);
145 JITResolver *JITResolver::TheJITResolver = 0;
147 #if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
149 extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
152 /// synchronizeICache - On some targets, the JIT emitted code must be
153 /// explicitly refetched to ensure correct execution.
154 static void synchronizeICache(const void *Addr, size_t len) {
155 #if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
157 sys_icache_invalidate(Addr, len);
161 /// getFunctionStub - This returns a pointer to a function stub, creating
162 /// one on demand as needed.
163 void *JITResolver::getFunctionStub(Function *F) {
164 MutexGuard locked(TheJIT->lock);
166 // If we already have a stub for this function, recycle it.
167 void *&Stub = state.getFunctionToStubMap(locked)[F];
168 if (Stub) return Stub;
170 // Call the lazy resolver function unless we already KNOW it is an external
171 // function, in which case we just skip the lazy resolution step.
172 void *Actual = (void*)(intptr_t)LazyResolverFn;
173 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
174 Actual = TheJIT->getPointerToFunction(F);
176 // Otherwise, codegen a new stub. For now, the stub will call the lazy
177 // resolver function.
178 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual,
179 *TheJIT->getCodeEmitter());
181 if (Actual != (void*)(intptr_t)LazyResolverFn) {
182 // If we are getting the stub for an external function, we really want the
183 // address of the stub in the GlobalAddressMap for the JIT, not the address
184 // of the external function.
185 TheJIT->updateGlobalMapping(F, Stub);
188 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
189 << F->getName() << "'\n";
191 // Finally, keep track of the stub-to-Function mapping so that the
192 // JITCompilerFn knows which function to compile!
193 state.getStubToFunctionMap(locked)[Stub] = F;
197 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
199 void *JITResolver::getGlobalValueLazyPtr(GlobalValue *GV, void *GVAddress) {
200 MutexGuard locked(TheJIT->lock);
202 // If we already have a stub for this global variable, recycle it.
203 void *&LazyPtr = state.getGlobalToLazyPtrMap(locked)[GV];
204 if (LazyPtr) return LazyPtr;
206 // Otherwise, codegen a new lazy pointer.
207 LazyPtr = TheJIT->getJITInfo().emitGlobalValueLazyPtr(GVAddress,
208 *TheJIT->getCodeEmitter());
210 DOUT << "JIT: Stub emitted at [" << LazyPtr << "] for GV '"
211 << GV->getName() << "'\n";
216 /// getExternalFunctionStub - Return a stub for the function at the
217 /// specified address, created lazily on demand.
218 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
219 // If we already have a stub for this function, recycle it.
220 void *&Stub = ExternalFnToStubMap[FnAddr];
221 if (Stub) return Stub;
223 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr,
224 *TheJIT->getCodeEmitter());
226 DOUT << "JIT: Stub emitted at [" << Stub
227 << "] for external function at '" << FnAddr << "'\n";
231 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
232 unsigned idx = revGOTMap[addr];
234 idx = ++nextGOTIndex;
235 revGOTMap[addr] = idx;
236 DOUT << "Adding GOT entry " << idx
237 << " for addr " << addr << "\n";
242 /// JITCompilerFn - This function is called when a lazy compilation stub has
243 /// been entered. It looks up which function this stub corresponds to, compiles
244 /// it if necessary, then returns the resultant function pointer.
245 void *JITResolver::JITCompilerFn(void *Stub) {
246 JITResolver &JR = *TheJITResolver;
248 MutexGuard locked(TheJIT->lock);
250 // The address given to us for the stub may not be exactly right, it might be
251 // a little bit after the stub. As such, use upper_bound to find it.
252 std::map<void*, Function*>::iterator I =
253 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
254 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
255 "This is not a known stub!");
256 Function *F = (--I)->second;
258 // If we have already code generated the function, just return the address.
259 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
262 // Otherwise we don't have it, do lazy compilation now.
264 // If lazy compilation is disabled, emit a useful error message and abort.
265 if (TheJIT->isLazyCompilationDisabled()) {
266 cerr << "LLVM JIT requested to do lazy compilation of function '"
267 << F->getName() << "' when lazy compiles are disabled!\n";
271 // We might like to remove the stub from the StubToFunction map.
272 // We can't do that! Multiple threads could be stuck, waiting to acquire the
273 // lock above. As soon as the 1st function finishes compiling the function,
274 // the next one will be released, and needs to be able to find the function
276 //JR.state.getStubToFunctionMap(locked).erase(I);
278 DOUT << "JIT: Lazily resolving function '" << F->getName()
279 << "' In stub ptr = " << Stub << " actual ptr = "
282 Result = TheJIT->getPointerToFunction(F);
285 // We don't need to reuse this stub in the future, as F is now compiled.
286 JR.state.getFunctionToStubMap(locked).erase(F);
288 // FIXME: We could rewrite all references to this stub if we knew them.
290 // What we will do is set the compiled function address to map to the
291 // same GOT entry as the stub so that later clients may update the GOT
292 // if they see it still using the stub address.
293 // Note: this is done so the Resolver doesn't have to manage GOT memory
294 // Do this without allocating map space if the target isn't using a GOT
295 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
296 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
302 //===----------------------------------------------------------------------===//
306 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
307 /// used to output functions to memory for execution.
308 class JITEmitter : public MachineCodeEmitter {
309 JITMemoryManager *MemMgr;
311 // When outputting a function stub in the context of some other function, we
312 // save BufferBegin/BufferEnd/CurBufferPtr here.
313 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
315 /// Relocations - These are the relocations that the function needs, as
317 std::vector<MachineRelocation> Relocations;
319 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
320 /// It is filled in by the StartMachineBasicBlock callback and queried by
321 /// the getMachineBasicBlockAddress callback.
322 std::vector<intptr_t> MBBLocations;
324 /// ConstantPool - The constant pool for the current function.
326 MachineConstantPool *ConstantPool;
328 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
330 void *ConstantPoolBase;
332 /// JumpTable - The jump tables for the current function.
334 MachineJumpTableInfo *JumpTable;
336 /// JumpTableBase - A pointer to the first entry in the jump table.
340 /// Resolver - This contains info about the currently resolved functions.
341 JITResolver Resolver;
343 /// DE - The dwarf emitter for the jit.
346 /// LabelLocations - This vector is a mapping from Label ID's to their
348 std::vector<intptr_t> LabelLocations;
350 /// MMI - Machine module info for exception informations
351 MachineModuleInfo* MMI;
354 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
355 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
356 if (jit.getJITInfo().needsGOT()) {
357 MemMgr->AllocateGOT();
358 DOUT << "JIT is managing a GOT\n";
361 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
365 if (ExceptionHandling) delete DE;
368 JITResolver &getJITResolver() { return Resolver; }
370 virtual void startFunction(MachineFunction &F);
371 virtual bool finishFunction(MachineFunction &F);
373 void emitConstantPool(MachineConstantPool *MCP);
374 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
375 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
377 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1);
378 virtual void* finishFunctionStub(const Function *F);
380 virtual void addRelocation(const MachineRelocation &MR) {
381 Relocations.push_back(MR);
384 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
385 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
386 MBBLocations.resize((MBB->getNumber()+1)*2);
387 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
390 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
391 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
393 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
394 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
395 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
396 return MBBLocations[MBB->getNumber()];
399 /// deallocateMemForFunction - Deallocate all memory for the specified
401 void deallocateMemForFunction(Function *F) {
402 MemMgr->deallocateMemForFunction(F);
405 virtual void emitLabel(uint64_t LabelID) {
406 if (LabelLocations.size() <= LabelID)
407 LabelLocations.resize((LabelID+1)*2);
408 LabelLocations[LabelID] = getCurrentPCValue();
411 virtual intptr_t getLabelAddress(uint64_t LabelID) const {
412 assert(LabelLocations.size() > (unsigned)LabelID &&
413 LabelLocations[LabelID] && "Label not emitted!");
414 return LabelLocations[LabelID];
417 virtual void setModuleInfo(MachineModuleInfo* Info) {
419 if (ExceptionHandling) DE->setModuleInfo(Info);
423 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
424 void *getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
429 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
430 bool DoesntNeedStub) {
431 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
432 /// FIXME: If we straightened things out, this could actually emit the
433 /// global immediately instead of queuing it for codegen later!
434 return TheJIT->getOrEmitGlobalVariable(GV);
437 // If we have already compiled the function, return a pointer to its body.
438 Function *F = cast<Function>(V);
439 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
440 if (ResultPtr) return ResultPtr;
442 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
443 // If this is an external function pointer, we can force the JIT to
444 // 'compile' it, which really just adds it to the map.
446 return TheJIT->getPointerToFunction(F);
448 return Resolver.getFunctionStub(F);
451 // Okay, the function has not been compiled yet, if the target callback
452 // mechanism is capable of rewriting the instruction directly, prefer to do
453 // that instead of emitting a stub.
455 return Resolver.AddCallbackAtLocation(F, Reference);
457 // Otherwise, we have to emit a lazy resolving stub.
458 return Resolver.getFunctionStub(F);
461 void *JITEmitter::getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
462 bool DoesntNeedStub) {
463 // Make sure GV is emitted first.
464 // FIXME: For now, if the GV is an external function we force the JIT to
465 // compile it so the lazy pointer will contain the fully resolved address.
466 void *GVAddress = getPointerToGlobal(V, Reference, true);
467 return Resolver.getGlobalValueLazyPtr(V, GVAddress);
471 void JITEmitter::startFunction(MachineFunction &F) {
472 uintptr_t ActualSize;
473 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
475 BufferEnd = BufferBegin+ActualSize;
477 // Ensure the constant pool/jump table info is at least 4-byte aligned.
480 emitConstantPool(F.getConstantPool());
481 initJumpTableInfo(F.getJumpTableInfo());
483 // About to start emitting the machine code for the function.
484 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
485 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
487 MBBLocations.clear();
490 bool JITEmitter::finishFunction(MachineFunction &F) {
491 if (CurBufferPtr == BufferEnd) {
492 // FIXME: Allocate more space, then try again.
493 cerr << "JIT: Ran out of space for generated machine code!\n";
497 emitJumpTableInfo(F.getJumpTableInfo());
499 // FnStart is the start of the text, not the start of the constant pool and
500 // other per-function data.
501 unsigned char *FnStart =
502 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
503 unsigned char *FnEnd = CurBufferPtr;
505 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
506 NumBytes += FnEnd-FnStart;
508 if (!Relocations.empty()) {
509 NumRelos += Relocations.size();
511 // Resolve the relocations to concrete pointers.
512 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
513 MachineRelocation &MR = Relocations[i];
516 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
518 // If the target REALLY wants a stub for this function, emit it now.
519 if (!MR.doesntNeedStub())
520 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
521 } else if (MR.isGlobalValue()) {
522 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
523 BufferBegin+MR.getMachineCodeOffset(),
524 MR.doesntNeedStub());
525 } else if (MR.isGlobalValueLazyPtr()) {
526 ResultPtr = getPointerToGVLazyPtr(MR.getGlobalValue(),
527 BufferBegin+MR.getMachineCodeOffset(),
528 MR.doesntNeedStub());
529 } else if (MR.isBasicBlock()) {
530 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
531 } else if (MR.isConstantPoolIndex()) {
532 ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
534 assert(MR.isJumpTableIndex());
535 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
538 MR.setResultPointer(ResultPtr);
540 // if we are managing the GOT and the relocation wants an index,
542 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
543 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
545 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
546 DOUT << "GOT was out of date for " << ResultPtr
547 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
549 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
554 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
555 Relocations.size(), MemMgr->getGOTBase());
558 // Update the GOT entry for F to point to the new code.
559 if (MemMgr->isManagingGOT()) {
560 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
561 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
562 DOUT << "GOT was out of date for " << (void*)BufferBegin
563 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
564 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
568 // Invalidate the icache if necessary.
569 synchronizeICache(FnStart, FnEnd-FnStart);
571 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
572 << "] Function: " << F.getFunction()->getName()
573 << ": " << (FnEnd-FnStart) << " bytes of text, "
574 << Relocations.size() << " relocations\n";
578 if (sys::hasDisassembler())
579 DOUT << "Disassembled code:\n"
580 << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
582 if (ExceptionHandling) {
583 uintptr_t ActualSize;
584 SavedBufferBegin = BufferBegin;
585 SavedBufferEnd = BufferEnd;
586 SavedCurBufferPtr = CurBufferPtr;
588 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
590 BufferEnd = BufferBegin+ActualSize;
591 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
592 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
594 BufferBegin = SavedBufferBegin;
595 BufferEnd = SavedBufferEnd;
596 CurBufferPtr = SavedCurBufferPtr;
598 TheJIT->RegisterTable(FrameRegister);
605 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
606 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
607 if (Constants.empty()) return;
609 MachineConstantPoolEntry CPE = Constants.back();
610 unsigned Size = CPE.Offset;
611 const Type *Ty = CPE.isMachineConstantPoolEntry()
612 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
613 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
615 ConstantPoolBase = allocateSpace(Size, 1 << MCP->getConstantPoolAlignment());
618 if (ConstantPoolBase == 0) return; // Buffer overflow.
620 // Initialize the memory for all of the constant pool entries.
621 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
622 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
623 if (Constants[i].isMachineConstantPoolEntry()) {
624 // FIXME: add support to lower machine constant pool values into bytes!
625 cerr << "Initialize memory with machine specific constant pool entry"
626 << " has not been implemented!\n";
629 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
633 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
634 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
635 if (JT.empty()) return;
637 unsigned NumEntries = 0;
638 for (unsigned i = 0, e = JT.size(); i != e; ++i)
639 NumEntries += JT[i].MBBs.size();
641 unsigned EntrySize = MJTI->getEntrySize();
643 // Just allocate space for all the jump tables now. We will fix up the actual
644 // MBB entries in the tables after we emit the code for each block, since then
645 // we will know the final locations of the MBBs in memory.
647 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
650 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
651 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
652 if (JT.empty() || JumpTableBase == 0) return;
654 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
655 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
656 // For each jump table, place the offset from the beginning of the table
657 // to the target address.
658 int *SlotPtr = (int*)JumpTableBase;
660 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
661 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
662 // Store the offset of the basic block for this jump table slot in the
663 // memory we allocated for the jump table in 'initJumpTableInfo'
664 intptr_t Base = (intptr_t)SlotPtr;
665 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
666 intptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
667 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
671 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
673 // For each jump table, map each target in the jump table to the address of
674 // an emitted MachineBasicBlock.
675 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
677 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
678 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
679 // Store the address of the basic block for this jump table slot in the
680 // memory we allocated for the jump table in 'initJumpTableInfo'
681 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
682 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
687 void JITEmitter::startFunctionStub(unsigned StubSize, unsigned Alignment) {
688 SavedBufferBegin = BufferBegin;
689 SavedBufferEnd = BufferEnd;
690 SavedCurBufferPtr = CurBufferPtr;
692 BufferBegin = CurBufferPtr = MemMgr->allocateStub(StubSize, Alignment);
693 BufferEnd = BufferBegin+StubSize+1;
696 void *JITEmitter::finishFunctionStub(const Function *F) {
697 NumBytes += getCurrentPCOffset();
698 std::swap(SavedBufferBegin, BufferBegin);
699 BufferEnd = SavedBufferEnd;
700 CurBufferPtr = SavedCurBufferPtr;
701 return SavedBufferBegin;
704 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
705 // in the constant pool that was last emitted with the 'emitConstantPool'
708 intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
709 assert(ConstantNum < ConstantPool->getConstants().size() &&
710 "Invalid ConstantPoolIndex!");
711 return (intptr_t)ConstantPoolBase +
712 ConstantPool->getConstants()[ConstantNum].Offset;
715 // getJumpTableEntryAddress - Return the address of the JumpTable with index
716 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
718 intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
719 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
720 assert(Index < JT.size() && "Invalid jump table index!");
723 unsigned EntrySize = JumpTable->getEntrySize();
725 for (unsigned i = 0; i < Index; ++i)
726 Offset += JT[i].MBBs.size();
730 return (intptr_t)((char *)JumpTableBase + Offset);
733 //===----------------------------------------------------------------------===//
734 // Public interface to this file
735 //===----------------------------------------------------------------------===//
737 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
738 return new JITEmitter(jit, JMM);
741 // getPointerToNamedFunction - This function is used as a global wrapper to
742 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
743 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
744 // need to resolve function(s) that are being mis-codegenerated, so we need to
745 // resolve their addresses at runtime, and this is the way to do it.
747 void *getPointerToNamedFunction(const char *Name) {
748 if (Function *F = TheJIT->FindFunctionNamed(Name))
749 return TheJIT->getPointerToFunction(F);
750 return TheJIT->getPointerToNamedFunction(Name);
754 // getPointerToFunctionOrStub - If the specified function has been
755 // code-gen'd, return a pointer to the function. If not, compile it, or use
756 // a stub to implement lazy compilation if available.
758 void *JIT::getPointerToFunctionOrStub(Function *F) {
759 // If we have already code generated the function, just return the address.
760 if (void *Addr = getPointerToGlobalIfAvailable(F))
763 // Get a stub if the target supports it.
764 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
765 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
766 return JE->getJITResolver().getFunctionStub(F);
769 /// freeMachineCodeForFunction - release machine code memory for given Function.
771 void JIT::freeMachineCodeForFunction(Function *F) {
772 // Delete translation for this from the ExecutionEngine, so it will get
773 // retranslated next time it is used.
774 updateGlobalMapping(F, 0);
776 // Free the actual memory for the function body and related stuff.
777 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
778 static_cast<JITEmitter*>(MCE)->deallocateMemForFunction(F);