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 "llvm/Constant.h"
18 #include "llvm/Module.h"
19 #include "llvm/Type.h"
20 #include "llvm/CodeGen/MachineCodeEmitter.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineRelocation.h"
25 #include "llvm/ExecutionEngine/JITMemoryManager.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetJITInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MutexGuard.h"
31 #include "llvm/System/Disassembler.h"
32 #include "llvm/ADT/Statistic.h"
36 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
37 STATISTIC(NumRelos, "Number of relocations applied");
38 static JIT *TheJIT = 0;
41 //===----------------------------------------------------------------------===//
42 // JIT lazy compilation code.
45 class JITResolverState {
47 /// FunctionToStubMap - Keep track of the stub created for a particular
48 /// function so that we can reuse them if necessary.
49 std::map<Function*, void*> FunctionToStubMap;
51 /// StubToFunctionMap - Keep track of the function that each stub
53 std::map<void*, Function*> StubToFunctionMap;
55 /// GlobalToLazyPtrMap - Keep track of the lazy pointer created for a
56 /// particular GlobalVariable so that we can reuse them if necessary.
57 std::map<GlobalValue*, void*> GlobalToLazyPtrMap;
60 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
61 assert(locked.holds(TheJIT->lock));
62 return FunctionToStubMap;
65 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
66 assert(locked.holds(TheJIT->lock));
67 return StubToFunctionMap;
70 std::map<GlobalValue*, void*>&
71 getGlobalToLazyPtrMap(const MutexGuard& locked) {
72 assert(locked.holds(TheJIT->lock));
73 return GlobalToLazyPtrMap;
77 /// JITResolver - Keep track of, and resolve, call sites for functions that
78 /// have not yet been compiled.
80 /// LazyResolverFn - The target lazy resolver function that we actually
81 /// rewrite instructions to use.
82 TargetJITInfo::LazyResolverFn LazyResolverFn;
84 JITResolverState state;
86 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
87 /// external functions.
88 std::map<void*, void*> ExternalFnToStubMap;
90 //map addresses to indexes in the GOT
91 std::map<void*, unsigned> revGOTMap;
92 unsigned nextGOTIndex;
94 static JITResolver *TheJITResolver;
96 JITResolver(JIT &jit) : nextGOTIndex(0) {
99 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
100 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
101 TheJITResolver = this;
108 /// getFunctionStub - This returns a pointer to a function stub, creating
109 /// one on demand as needed.
110 void *getFunctionStub(Function *F);
112 /// getExternalFunctionStub - Return a stub for the function at the
113 /// specified address, created lazily on demand.
114 void *getExternalFunctionStub(void *FnAddr);
116 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
118 void *getGlobalValueLazyPtr(GlobalValue *V, void *GVAddress);
120 /// AddCallbackAtLocation - If the target is capable of rewriting an
121 /// instruction without the use of a stub, record the location of the use so
122 /// we know which function is being used at the location.
123 void *AddCallbackAtLocation(Function *F, void *Location) {
124 MutexGuard locked(TheJIT->lock);
125 /// Get the target-specific JIT resolver function.
126 state.getStubToFunctionMap(locked)[Location] = F;
127 return (void*)(intptr_t)LazyResolverFn;
130 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
131 /// an address. This function only manages slots, it does not manage the
132 /// contents of the slots or the memory associated with the GOT.
133 unsigned getGOTIndexForAddr(void *addr);
135 /// JITCompilerFn - This function is called to resolve a stub to a compiled
136 /// address. If the LLVM Function corresponding to the stub has not yet
137 /// been compiled, this function compiles it first.
138 static void *JITCompilerFn(void *Stub);
142 JITResolver *JITResolver::TheJITResolver = 0;
144 #if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
146 extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
149 /// synchronizeICache - On some targets, the JIT emitted code must be
150 /// explicitly refetched to ensure correct execution.
151 static void synchronizeICache(const void *Addr, size_t len) {
152 #if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
154 sys_icache_invalidate(Addr, len);
158 /// getFunctionStub - This returns a pointer to a function stub, creating
159 /// one on demand as needed.
160 void *JITResolver::getFunctionStub(Function *F) {
161 MutexGuard locked(TheJIT->lock);
163 // If we already have a stub for this function, recycle it.
164 void *&Stub = state.getFunctionToStubMap(locked)[F];
165 if (Stub) return Stub;
167 // Call the lazy resolver function unless we already KNOW it is an external
168 // function, in which case we just skip the lazy resolution step.
169 void *Actual = (void*)(intptr_t)LazyResolverFn;
170 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
171 Actual = TheJIT->getPointerToFunction(F);
173 // Otherwise, codegen a new stub. For now, the stub will call the lazy
174 // resolver function.
175 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual,
176 *TheJIT->getCodeEmitter());
178 if (Actual != (void*)(intptr_t)LazyResolverFn) {
179 // If we are getting the stub for an external function, we really want the
180 // address of the stub in the GlobalAddressMap for the JIT, not the address
181 // of the external function.
182 TheJIT->updateGlobalMapping(F, Stub);
185 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
186 << F->getName() << "'\n";
188 // Finally, keep track of the stub-to-Function mapping so that the
189 // JITCompilerFn knows which function to compile!
190 state.getStubToFunctionMap(locked)[Stub] = F;
194 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
196 void *JITResolver::getGlobalValueLazyPtr(GlobalValue *GV, void *GVAddress) {
197 MutexGuard locked(TheJIT->lock);
199 // If we already have a stub for this global variable, recycle it.
200 void *&LazyPtr = state.getGlobalToLazyPtrMap(locked)[GV];
201 if (LazyPtr) return LazyPtr;
203 // Otherwise, codegen a new lazy pointer.
204 LazyPtr = TheJIT->getJITInfo().emitGlobalValueLazyPtr(GVAddress,
205 *TheJIT->getCodeEmitter());
207 DOUT << "JIT: Stub emitted at [" << LazyPtr << "] for GV '"
208 << GV->getName() << "'\n";
213 /// getExternalFunctionStub - Return a stub for the function at the
214 /// specified address, created lazily on demand.
215 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
216 // If we already have a stub for this function, recycle it.
217 void *&Stub = ExternalFnToStubMap[FnAddr];
218 if (Stub) return Stub;
220 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr,
221 *TheJIT->getCodeEmitter());
223 DOUT << "JIT: Stub emitted at [" << Stub
224 << "] for external function at '" << FnAddr << "'\n";
228 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
229 unsigned idx = revGOTMap[addr];
231 idx = ++nextGOTIndex;
232 revGOTMap[addr] = idx;
233 DOUT << "Adding GOT entry " << idx
234 << " for addr " << addr << "\n";
239 /// JITCompilerFn - This function is called when a lazy compilation stub has
240 /// been entered. It looks up which function this stub corresponds to, compiles
241 /// it if necessary, then returns the resultant function pointer.
242 void *JITResolver::JITCompilerFn(void *Stub) {
243 JITResolver &JR = *TheJITResolver;
245 MutexGuard locked(TheJIT->lock);
247 // The address given to us for the stub may not be exactly right, it might be
248 // a little bit after the stub. As such, use upper_bound to find it.
249 std::map<void*, Function*>::iterator I =
250 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
251 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
252 "This is not a known stub!");
253 Function *F = (--I)->second;
255 // If we have already code generated the function, just return the address.
256 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
259 // Otherwise we don't have it, do lazy compilation now.
261 // If lazy compilation is disabled, emit a useful error message and abort.
262 if (TheJIT->isLazyCompilationDisabled()) {
263 cerr << "LLVM JIT requested to do lazy compilation of function '"
264 << F->getName() << "' when lazy compiles are disabled!\n";
268 // We might like to remove the stub from the StubToFunction map.
269 // We can't do that! Multiple threads could be stuck, waiting to acquire the
270 // lock above. As soon as the 1st function finishes compiling the function,
271 // the next one will be released, and needs to be able to find the function
273 //JR.state.getStubToFunctionMap(locked).erase(I);
275 DOUT << "JIT: Lazily resolving function '" << F->getName()
276 << "' In stub ptr = " << Stub << " actual ptr = "
279 Result = TheJIT->getPointerToFunction(F);
282 // We don't need to reuse this stub in the future, as F is now compiled.
283 JR.state.getFunctionToStubMap(locked).erase(F);
285 // FIXME: We could rewrite all references to this stub if we knew them.
287 // What we will do is set the compiled function address to map to the
288 // same GOT entry as the stub so that later clients may update the GOT
289 // if they see it still using the stub address.
290 // Note: this is done so the Resolver doesn't have to manage GOT memory
291 // Do this without allocating map space if the target isn't using a GOT
292 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
293 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
299 //===----------------------------------------------------------------------===//
303 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
304 /// used to output functions to memory for execution.
305 class JITEmitter : public MachineCodeEmitter {
306 JITMemoryManager *MemMgr;
308 // When outputting a function stub in the context of some other function, we
309 // save BufferBegin/BufferEnd/CurBufferPtr here.
310 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
312 /// Relocations - These are the relocations that the function needs, as
314 std::vector<MachineRelocation> Relocations;
316 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
317 /// It is filled in by the StartMachineBasicBlock callback and queried by
318 /// the getMachineBasicBlockAddress callback.
319 std::vector<intptr_t> MBBLocations;
321 /// ConstantPool - The constant pool for the current function.
323 MachineConstantPool *ConstantPool;
325 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
327 void *ConstantPoolBase;
329 /// JumpTable - The jump tables for the current function.
331 MachineJumpTableInfo *JumpTable;
333 /// JumpTableBase - A pointer to the first entry in the jump table.
337 /// Resolver - This contains info about the currently resolved functions.
338 JITResolver Resolver;
340 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
341 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
342 if (jit.getJITInfo().needsGOT()) {
343 MemMgr->AllocateGOT();
344 DOUT << "JIT is managing a GOT\n";
351 JITResolver &getJITResolver() { return Resolver; }
353 virtual void startFunction(MachineFunction &F);
354 virtual bool finishFunction(MachineFunction &F);
356 void emitConstantPool(MachineConstantPool *MCP);
357 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
358 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
360 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1);
361 virtual void* finishFunctionStub(const Function *F);
363 virtual void addRelocation(const MachineRelocation &MR) {
364 Relocations.push_back(MR);
367 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
368 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
369 MBBLocations.resize((MBB->getNumber()+1)*2);
370 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
373 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
374 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
376 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
377 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
378 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
379 return MBBLocations[MBB->getNumber()];
382 /// deallocateMemForFunction - Deallocate all memory for the specified
384 void deallocateMemForFunction(Function *F) {
385 MemMgr->deallocateMemForFunction(F);
388 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
389 void *getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
394 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
395 bool DoesntNeedStub) {
396 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
397 /// FIXME: If we straightened things out, this could actually emit the
398 /// global immediately instead of queuing it for codegen later!
399 return TheJIT->getOrEmitGlobalVariable(GV);
402 // If we have already compiled the function, return a pointer to its body.
403 Function *F = cast<Function>(V);
404 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
405 if (ResultPtr) return ResultPtr;
407 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
408 // If this is an external function pointer, we can force the JIT to
409 // 'compile' it, which really just adds it to the map.
411 return TheJIT->getPointerToFunction(F);
413 return Resolver.getFunctionStub(F);
416 // Okay, the function has not been compiled yet, if the target callback
417 // mechanism is capable of rewriting the instruction directly, prefer to do
418 // that instead of emitting a stub.
420 return Resolver.AddCallbackAtLocation(F, Reference);
422 // Otherwise, we have to emit a lazy resolving stub.
423 return Resolver.getFunctionStub(F);
426 void *JITEmitter::getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
427 bool DoesntNeedStub) {
428 // Make sure GV is emitted first.
429 // FIXME: For now, if the GV is an external function we force the JIT to
430 // compile it so the lazy pointer will contain the fully resolved address.
431 void *GVAddress = getPointerToGlobal(V, Reference, true);
432 return Resolver.getGlobalValueLazyPtr(V, GVAddress);
436 void JITEmitter::startFunction(MachineFunction &F) {
437 uintptr_t ActualSize;
438 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
440 BufferEnd = BufferBegin+ActualSize;
442 // Ensure the constant pool/jump table info is at least 4-byte aligned.
445 emitConstantPool(F.getConstantPool());
446 initJumpTableInfo(F.getJumpTableInfo());
448 // About to start emitting the machine code for the function.
449 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
450 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
452 MBBLocations.clear();
455 bool JITEmitter::finishFunction(MachineFunction &F) {
456 if (CurBufferPtr == BufferEnd) {
457 // FIXME: Allocate more space, then try again.
458 cerr << "JIT: Ran out of space for generated machine code!\n";
462 emitJumpTableInfo(F.getJumpTableInfo());
464 // FnStart is the start of the text, not the start of the constant pool and
465 // other per-function data.
466 unsigned char *FnStart =
467 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
468 unsigned char *FnEnd = CurBufferPtr;
470 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
471 NumBytes += FnEnd-FnStart;
473 if (!Relocations.empty()) {
474 NumRelos += Relocations.size();
476 // Resolve the relocations to concrete pointers.
477 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
478 MachineRelocation &MR = Relocations[i];
481 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
483 // If the target REALLY wants a stub for this function, emit it now.
484 if (!MR.doesntNeedStub())
485 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
486 } else if (MR.isGlobalValue()) {
487 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
488 BufferBegin+MR.getMachineCodeOffset(),
489 MR.doesntNeedStub());
490 } else if (MR.isGlobalValueLazyPtr()) {
491 ResultPtr = getPointerToGVLazyPtr(MR.getGlobalValue(),
492 BufferBegin+MR.getMachineCodeOffset(),
493 MR.doesntNeedStub());
494 } else if (MR.isBasicBlock()) {
495 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
496 } else if (MR.isConstantPoolIndex()) {
497 ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
499 assert(MR.isJumpTableIndex());
500 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
503 MR.setResultPointer(ResultPtr);
505 // if we are managing the GOT and the relocation wants an index,
507 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
508 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
510 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
511 DOUT << "GOT was out of date for " << ResultPtr
512 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
514 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
519 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
520 Relocations.size(), MemMgr->getGOTBase());
523 // Update the GOT entry for F to point to the new code.
524 if (MemMgr->isManagingGOT()) {
525 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
526 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
527 DOUT << "GOT was out of date for " << (void*)BufferBegin
528 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
529 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
533 // Invalidate the icache if necessary.
534 synchronizeICache(FnStart, FnEnd-FnStart);
536 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
537 << "] Function: " << F.getFunction()->getName()
538 << ": " << (FnEnd-FnStart) << " bytes of text, "
539 << Relocations.size() << " relocations\n";
543 if (sys::hasDisassembler())
544 DOUT << "Disassembled code:\n"
545 << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
551 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
552 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
553 if (Constants.empty()) return;
555 MachineConstantPoolEntry CPE = Constants.back();
556 unsigned Size = CPE.Offset;
557 const Type *Ty = CPE.isMachineConstantPoolEntry()
558 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
559 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
561 ConstantPoolBase = allocateSpace(Size, 1 << MCP->getConstantPoolAlignment());
564 if (ConstantPoolBase == 0) return; // Buffer overflow.
566 // Initialize the memory for all of the constant pool entries.
567 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
568 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
569 if (Constants[i].isMachineConstantPoolEntry()) {
570 // FIXME: add support to lower machine constant pool values into bytes!
571 cerr << "Initialize memory with machine specific constant pool entry"
572 << " has not been implemented!\n";
575 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
579 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
580 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
581 if (JT.empty()) return;
583 unsigned NumEntries = 0;
584 for (unsigned i = 0, e = JT.size(); i != e; ++i)
585 NumEntries += JT[i].MBBs.size();
587 unsigned EntrySize = MJTI->getEntrySize();
589 // Just allocate space for all the jump tables now. We will fix up the actual
590 // MBB entries in the tables after we emit the code for each block, since then
591 // we will know the final locations of the MBBs in memory.
593 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
596 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
597 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
598 if (JT.empty() || JumpTableBase == 0) return;
600 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
601 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
602 // For each jump table, place the offset from the beginning of the table
603 // to the target address.
604 int *SlotPtr = (int*)JumpTableBase;
606 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
607 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
608 // Store the offset of the basic block for this jump table slot in the
609 // memory we allocated for the jump table in 'initJumpTableInfo'
610 intptr_t Base = (intptr_t)SlotPtr;
611 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
612 intptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
613 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
617 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
619 // For each jump table, map each target in the jump table to the address of
620 // an emitted MachineBasicBlock.
621 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
623 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
624 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
625 // Store the address of the basic block for this jump table slot in the
626 // memory we allocated for the jump table in 'initJumpTableInfo'
627 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
628 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
633 void JITEmitter::startFunctionStub(unsigned StubSize, unsigned Alignment) {
634 SavedBufferBegin = BufferBegin;
635 SavedBufferEnd = BufferEnd;
636 SavedCurBufferPtr = CurBufferPtr;
638 BufferBegin = CurBufferPtr = MemMgr->allocateStub(StubSize, Alignment);
639 BufferEnd = BufferBegin+StubSize+1;
642 void *JITEmitter::finishFunctionStub(const Function *F) {
643 NumBytes += getCurrentPCOffset();
644 std::swap(SavedBufferBegin, BufferBegin);
645 BufferEnd = SavedBufferEnd;
646 CurBufferPtr = SavedCurBufferPtr;
647 return SavedBufferBegin;
650 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
651 // in the constant pool that was last emitted with the 'emitConstantPool'
654 intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
655 assert(ConstantNum < ConstantPool->getConstants().size() &&
656 "Invalid ConstantPoolIndex!");
657 return (intptr_t)ConstantPoolBase +
658 ConstantPool->getConstants()[ConstantNum].Offset;
661 // getJumpTableEntryAddress - Return the address of the JumpTable with index
662 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
664 intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
665 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
666 assert(Index < JT.size() && "Invalid jump table index!");
669 unsigned EntrySize = JumpTable->getEntrySize();
671 for (unsigned i = 0; i < Index; ++i)
672 Offset += JT[i].MBBs.size();
676 return (intptr_t)((char *)JumpTableBase + Offset);
679 //===----------------------------------------------------------------------===//
680 // Public interface to this file
681 //===----------------------------------------------------------------------===//
683 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
684 return new JITEmitter(jit, JMM);
687 // getPointerToNamedFunction - This function is used as a global wrapper to
688 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
689 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
690 // need to resolve function(s) that are being mis-codegenerated, so we need to
691 // resolve their addresses at runtime, and this is the way to do it.
693 void *getPointerToNamedFunction(const char *Name) {
694 if (Function *F = TheJIT->FindFunctionNamed(Name))
695 return TheJIT->getPointerToFunction(F);
696 return TheJIT->getPointerToNamedFunction(Name);
700 // getPointerToFunctionOrStub - If the specified function has been
701 // code-gen'd, return a pointer to the function. If not, compile it, or use
702 // a stub to implement lazy compilation if available.
704 void *JIT::getPointerToFunctionOrStub(Function *F) {
705 // If we have already code generated the function, just return the address.
706 if (void *Addr = getPointerToGlobalIfAvailable(F))
709 // Get a stub if the target supports it.
710 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
711 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
712 return JE->getJITResolver().getFunctionStub(F);
715 /// freeMachineCodeForFunction - release machine code memory for given Function.
717 void JIT::freeMachineCodeForFunction(Function *F) {
718 // Delete translation for this from the ExecutionEngine, so it will get
719 // retranslated next time it is used.
720 updateGlobalMapping(F, 0);
722 // Free the actual memory for the function body and related stuff.
723 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
724 static_cast<JITEmitter*>(MCE)->deallocateMemForFunction(F);