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 "JITDebugRegisterer.h"
18 #include "JITDwarfEmitter.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Module.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/CodeGen/JITCodeEmitter.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRelocation.h"
29 #include "llvm/ExecutionEngine/GenericValue.h"
30 #include "llvm/ExecutionEngine/JITEventListener.h"
31 #include "llvm/ExecutionEngine/JITMemoryManager.h"
32 #include "llvm/CodeGen/MachineCodeInfo.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetJITInfo.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MutexGuard.h"
40 #include "llvm/Support/ValueHandle.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/System/Disassembler.h"
43 #include "llvm/System/Memory.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/ADT/SmallPtrSet.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/ADT/Statistic.h"
54 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
55 STATISTIC(NumRelos, "Number of relocations applied");
56 STATISTIC(NumRetries, "Number of retries with more memory");
57 static JIT *TheJIT = 0;
60 //===----------------------------------------------------------------------===//
61 // JIT lazy compilation code.
64 class JITResolverState {
66 typedef std::map<AssertingVH<Function>, void*> FunctionToStubMapTy;
67 typedef std::map<void*, Function*> StubToFunctionMapTy;
68 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
70 /// FunctionToStubMap - Keep track of the stub created for a particular
71 /// function so that we can reuse them if necessary.
72 FunctionToStubMapTy FunctionToStubMap;
74 /// StubToFunctionMap - Keep track of the function that each stub
76 StubToFunctionMapTy StubToFunctionMap;
78 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
79 /// particular GlobalVariable so that we can reuse them if necessary.
80 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
83 FunctionToStubMapTy& getFunctionToStubMap(const MutexGuard& locked) {
84 assert(locked.holds(TheJIT->lock));
85 return FunctionToStubMap;
88 StubToFunctionMapTy& getStubToFunctionMap(const MutexGuard& locked) {
89 assert(locked.holds(TheJIT->lock));
90 return StubToFunctionMap;
93 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
94 assert(locked.holds(TheJIT->lock));
95 return GlobalToIndirectSymMap;
99 /// JITResolver - Keep track of, and resolve, call sites for functions that
100 /// have not yet been compiled.
102 typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy;
103 typedef JITResolverState::StubToFunctionMapTy StubToFunctionMapTy;
104 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
106 /// LazyResolverFn - The target lazy resolver function that we actually
107 /// rewrite instructions to use.
108 TargetJITInfo::LazyResolverFn LazyResolverFn;
110 JITResolverState state;
112 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
113 /// external functions.
114 std::map<void*, void*> ExternalFnToStubMap;
116 /// revGOTMap - map addresses to indexes in the GOT
117 std::map<void*, unsigned> revGOTMap;
118 unsigned nextGOTIndex;
120 static JITResolver *TheJITResolver;
122 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
125 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
126 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
127 TheJITResolver = this;
134 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
135 /// if it has already been created.
136 void *getFunctionStubIfAvailable(Function *F);
138 /// getFunctionStub - This returns a pointer to a function stub, creating
139 /// one on demand as needed. If empty is true, create a function stub
140 /// pointing at address 0, to be filled in later.
141 void *getFunctionStub(Function *F);
143 /// getExternalFunctionStub - Return a stub for the function at the
144 /// specified address, created lazily on demand.
145 void *getExternalFunctionStub(void *FnAddr);
147 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
148 /// specified GV address.
149 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
151 /// AddCallbackAtLocation - If the target is capable of rewriting an
152 /// instruction without the use of a stub, record the location of the use so
153 /// we know which function is being used at the location.
154 void *AddCallbackAtLocation(Function *F, void *Location) {
155 MutexGuard locked(TheJIT->lock);
156 /// Get the target-specific JIT resolver function.
157 state.getStubToFunctionMap(locked)[Location] = F;
158 return (void*)(intptr_t)LazyResolverFn;
161 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
162 SmallVectorImpl<void*> &Ptrs);
164 GlobalValue *invalidateStub(void *Stub);
166 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
167 /// an address. This function only manages slots, it does not manage the
168 /// contents of the slots or the memory associated with the GOT.
169 unsigned getGOTIndexForAddr(void *addr);
171 /// JITCompilerFn - This function is called to resolve a stub to a compiled
172 /// address. If the LLVM Function corresponding to the stub has not yet
173 /// been compiled, this function compiles it first.
174 static void *JITCompilerFn(void *Stub);
178 JITResolver *JITResolver::TheJITResolver = 0;
180 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
181 /// if it has already been created.
182 void *JITResolver::getFunctionStubIfAvailable(Function *F) {
183 MutexGuard locked(TheJIT->lock);
185 // If we already have a stub for this function, recycle it.
186 void *&Stub = state.getFunctionToStubMap(locked)[F];
190 /// getFunctionStub - This returns a pointer to a function stub, creating
191 /// one on demand as needed.
192 void *JITResolver::getFunctionStub(Function *F) {
193 MutexGuard locked(TheJIT->lock);
195 // If we already have a stub for this function, recycle it.
196 void *&Stub = state.getFunctionToStubMap(locked)[F];
197 if (Stub) return Stub;
199 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
200 // case we must resolve the symbol now.
201 void *Actual = TheJIT->isLazyCompilationDisabled()
202 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
204 // If this is an external declaration, attempt to resolve the address now
205 // to place in the stub.
206 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
207 Actual = TheJIT->getPointerToFunction(F);
209 // If we resolved the symbol to a null address (eg. a weak external)
210 // don't emit a stub. Return a null pointer to the application. If dlsym
211 // stubs are enabled, not being able to resolve the address is not
213 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
216 // Codegen a new stub, calling the lazy resolver or the actual address of the
217 // external function, if it was resolved.
218 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
219 *TheJIT->getCodeEmitter());
221 if (Actual != (void*)(intptr_t)LazyResolverFn) {
222 // If we are getting the stub for an external function, we really want the
223 // address of the stub in the GlobalAddressMap for the JIT, not the address
224 // of the external function.
225 TheJIT->updateGlobalMapping(F, Stub);
228 DEBUG(errs() << "JIT: Stub emitted at [" << Stub << "] for function '"
229 << F->getName() << "'\n");
231 // Finally, keep track of the stub-to-Function mapping so that the
232 // JITCompilerFn knows which function to compile!
233 state.getStubToFunctionMap(locked)[Stub] = F;
235 // If we are JIT'ing non-lazily but need to call a function that does not
236 // exist yet, add it to the JIT's work list so that we can fill in the stub
238 if (!Actual && TheJIT->isLazyCompilationDisabled())
239 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
240 TheJIT->addPendingFunction(F);
245 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
247 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
248 MutexGuard locked(TheJIT->lock);
250 // If we already have a stub for this global variable, recycle it.
251 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
252 if (IndirectSym) return IndirectSym;
254 // Otherwise, codegen a new indirect symbol.
255 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
256 *TheJIT->getCodeEmitter());
258 DEBUG(errs() << "JIT: Indirect symbol emitted at [" << IndirectSym
259 << "] for GV '" << GV->getName() << "'\n");
264 /// getExternalFunctionStub - Return a stub for the function at the
265 /// specified address, created lazily on demand.
266 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
267 // If we already have a stub for this function, recycle it.
268 void *&Stub = ExternalFnToStubMap[FnAddr];
269 if (Stub) return Stub;
271 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
272 *TheJIT->getCodeEmitter());
274 DEBUG(errs() << "JIT: Stub emitted at [" << Stub
275 << "] for external function at '" << FnAddr << "'\n");
279 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
280 unsigned idx = revGOTMap[addr];
282 idx = ++nextGOTIndex;
283 revGOTMap[addr] = idx;
284 DEBUG(errs() << "JIT: Adding GOT entry " << idx << " for addr ["
290 void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
291 SmallVectorImpl<void*> &Ptrs) {
292 MutexGuard locked(TheJIT->lock);
294 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
295 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
297 for (FunctionToStubMapTy::iterator i = FM.begin(), e = FM.end(); i != e; ++i){
298 Function *F = i->first;
299 if (F->isDeclaration() && F->hasExternalLinkage()) {
300 GVs.push_back(i->first);
301 Ptrs.push_back(i->second);
304 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
306 GVs.push_back(i->first);
307 Ptrs.push_back(i->second);
311 GlobalValue *JITResolver::invalidateStub(void *Stub) {
312 MutexGuard locked(TheJIT->lock);
314 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
315 StubToFunctionMapTy &SM = state.getStubToFunctionMap(locked);
316 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
318 // Look up the cheap way first, to see if it's a function stub we are
319 // invalidating. If so, remove it from both the forward and reverse maps.
320 if (SM.find(Stub) != SM.end()) {
321 Function *F = SM[Stub];
327 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
328 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
330 if (i->second != Stub)
332 GlobalValue *GV = i->first;
337 // Lastly, check to see if it's in the ExternalFnToStubMap.
338 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
339 e = ExternalFnToStubMap.end(); i != e; ++i) {
340 if (i->second != Stub)
342 ExternalFnToStubMap.erase(i);
349 /// JITCompilerFn - This function is called when a lazy compilation stub has
350 /// been entered. It looks up which function this stub corresponds to, compiles
351 /// it if necessary, then returns the resultant function pointer.
352 void *JITResolver::JITCompilerFn(void *Stub) {
353 JITResolver &JR = *TheJITResolver;
359 // Only lock for getting the Function. The call getPointerToFunction made
360 // in this function might trigger function materializing, which requires
361 // JIT lock to be unlocked.
362 MutexGuard locked(TheJIT->lock);
364 // The address given to us for the stub may not be exactly right, it might be
365 // a little bit after the stub. As such, use upper_bound to find it.
366 StubToFunctionMapTy::iterator I =
367 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
368 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
369 "This is not a known stub!");
371 ActualPtr = I->first;
374 // If we have already code generated the function, just return the address.
375 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
378 // Otherwise we don't have it, do lazy compilation now.
380 // If lazy compilation is disabled, emit a useful error message and abort.
381 if (TheJIT->isLazyCompilationDisabled()) {
382 llvm_report_error("LLVM JIT requested to do lazy compilation of function '"
383 + F->getName() + "' when lazy compiles are disabled!");
386 // We might like to remove the stub from the StubToFunction map.
387 // We can't do that! Multiple threads could be stuck, waiting to acquire the
388 // lock above. As soon as the 1st function finishes compiling the function,
389 // the next one will be released, and needs to be able to find the function
391 //JR.state.getStubToFunctionMap(locked).erase(I);
393 DEBUG(errs() << "JIT: Lazily resolving function '" << F->getName()
394 << "' In stub ptr = " << Stub << " actual ptr = "
395 << ActualPtr << "\n");
397 Result = TheJIT->getPointerToFunction(F);
400 // Reacquire the lock to erase the stub in the map.
401 MutexGuard locked(TheJIT->lock);
403 // We don't need to reuse this stub in the future, as F is now compiled.
404 JR.state.getFunctionToStubMap(locked).erase(F);
406 // FIXME: We could rewrite all references to this stub if we knew them.
408 // What we will do is set the compiled function address to map to the
409 // same GOT entry as the stub so that later clients may update the GOT
410 // if they see it still using the stub address.
411 // Note: this is done so the Resolver doesn't have to manage GOT memory
412 // Do this without allocating map space if the target isn't using a GOT
413 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
414 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
419 //===----------------------------------------------------------------------===//
423 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
424 /// used to output functions to memory for execution.
425 class JITEmitter : public JITCodeEmitter {
426 JITMemoryManager *MemMgr;
428 // When outputting a function stub in the context of some other function, we
429 // save BufferBegin/BufferEnd/CurBufferPtr here.
430 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
432 // When reattempting to JIT a function after running out of space, we store
433 // the estimated size of the function we're trying to JIT here, so we can
434 // ask the memory manager for at least this much space. When we
435 // successfully emit the function, we reset this back to zero.
436 uintptr_t SizeEstimate;
438 /// Relocations - These are the relocations that the function needs, as
440 std::vector<MachineRelocation> Relocations;
442 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
443 /// It is filled in by the StartMachineBasicBlock callback and queried by
444 /// the getMachineBasicBlockAddress callback.
445 std::vector<uintptr_t> MBBLocations;
447 /// ConstantPool - The constant pool for the current function.
449 MachineConstantPool *ConstantPool;
451 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
453 void *ConstantPoolBase;
455 /// ConstPoolAddresses - Addresses of individual constant pool entries.
457 SmallVector<uintptr_t, 8> ConstPoolAddresses;
459 /// JumpTable - The jump tables for the current function.
461 MachineJumpTableInfo *JumpTable;
463 /// JumpTableBase - A pointer to the first entry in the jump table.
467 /// Resolver - This contains info about the currently resolved functions.
468 JITResolver Resolver;
470 /// DE - The dwarf emitter for the jit.
471 OwningPtr<JITDwarfEmitter> DE;
473 /// DR - The debug registerer for the jit.
474 OwningPtr<JITDebugRegisterer> DR;
476 /// LabelLocations - This vector is a mapping from Label ID's to their
478 std::vector<uintptr_t> LabelLocations;
480 /// MMI - Machine module info for exception informations
481 MachineModuleInfo* MMI;
483 // GVSet - a set to keep track of which globals have been seen
484 SmallPtrSet<const GlobalVariable*, 8> GVSet;
486 // CurFn - The llvm function being emitted. Only valid during
488 const Function *CurFn;
490 /// Information about emitted code, which is passed to the
491 /// JITEventListeners. This is reset in startFunction and used in
493 JITEvent_EmittedFunctionDetails EmissionDetails;
495 // CurFnStubUses - For a given Function, a vector of stubs that it
496 // references. This facilitates the JIT detecting that a stub is no
497 // longer used, so that it may be deallocated.
498 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
500 // StubFnRefs - For a given pointer to a stub, a set of Functions which
501 // reference the stub. When the count of a stub's references drops to zero,
502 // the stub is unused.
503 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
505 // ExtFnStubs - A map of external function names to stubs which have entries
506 // in the JITResolver's ExternalFnToStubMap.
507 StringMap<void *> ExtFnStubs;
509 DebugLocTuple PrevDLT;
512 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
513 : SizeEstimate(0), Resolver(jit), MMI(0), CurFn(0) {
514 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
515 if (jit.getJITInfo().needsGOT()) {
516 MemMgr->AllocateGOT();
517 DEBUG(errs() << "JIT is managing a GOT\n");
520 if (DwarfExceptionHandling || JITEmitDebugInfo) {
521 DE.reset(new JITDwarfEmitter(jit));
523 if (JITEmitDebugInfo) {
524 DR.reset(new JITDebugRegisterer(TM));
531 /// classof - Methods for support type inquiry through isa, cast, and
534 static inline bool classof(const JITEmitter*) { return true; }
535 static inline bool classof(const MachineCodeEmitter*) { return true; }
537 JITResolver &getJITResolver() { return Resolver; }
539 virtual void startFunction(MachineFunction &F);
540 virtual bool finishFunction(MachineFunction &F);
542 void emitConstantPool(MachineConstantPool *MCP);
543 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
544 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
546 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
547 unsigned Alignment = 1);
548 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
550 virtual void* finishGVStub(const GlobalValue *GV);
552 /// allocateSpace - Reserves space in the current block if any, or
553 /// allocate a new one of the given size.
554 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
556 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
557 /// this method does not allocate memory in the current output buffer,
558 /// because a global may live longer than the current function.
559 virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
561 virtual void addRelocation(const MachineRelocation &MR) {
562 Relocations.push_back(MR);
565 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
566 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
567 MBBLocations.resize((MBB->getNumber()+1)*2);
568 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
569 DEBUG(errs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
570 << (void*) getCurrentPCValue() << "]\n");
573 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
574 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
576 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
577 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
578 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
579 return MBBLocations[MBB->getNumber()];
582 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
583 /// given function. Increase the minimum allocation size so that we get
584 /// more memory next time.
585 void retryWithMoreMemory(MachineFunction &F);
587 /// deallocateMemForFunction - Deallocate all memory for the specified
589 void deallocateMemForFunction(const Function *F);
591 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
592 /// using the stub at the specified address. Allows
593 /// deallocateMemForFunction to also remove stubs no longer referenced.
594 void AddStubToCurrentFunction(void *Stub);
596 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
597 /// MachineRelocations that reference external functions by name.
598 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
600 virtual void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn);
602 virtual void emitLabel(uint64_t LabelID) {
603 if (LabelLocations.size() <= LabelID)
604 LabelLocations.resize((LabelID+1)*2);
605 LabelLocations[LabelID] = getCurrentPCValue();
608 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
609 assert(LabelLocations.size() > (unsigned)LabelID &&
610 LabelLocations[LabelID] && "Label not emitted!");
611 return LabelLocations[LabelID];
614 virtual void setModuleInfo(MachineModuleInfo* Info) {
616 if (DE.get()) DE->setModuleInfo(Info);
619 void setMemoryExecutable() {
620 MemMgr->setMemoryExecutable();
623 JITMemoryManager *getMemMgr() const { return MemMgr; }
626 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
627 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
629 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
630 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
631 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
632 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
636 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
637 bool DoesntNeedStub) {
638 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
639 return TheJIT->getOrEmitGlobalVariable(GV);
641 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
642 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
644 // If we have already compiled the function, return a pointer to its body.
645 Function *F = cast<Function>(V);
647 if (!DoesntNeedStub) {
648 // Return the function stub if it's already created.
649 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
651 AddStubToCurrentFunction(ResultPtr);
653 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
655 if (ResultPtr) return ResultPtr;
657 // If this is an external function pointer, we can force the JIT to
658 // 'compile' it, which really just adds it to the map. In dlsym mode,
659 // external functions are forced through a stub, regardless of reloc type.
660 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
661 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
662 return TheJIT->getPointerToFunction(F);
664 // Okay, the function has not been compiled yet, if the target callback
665 // mechanism is capable of rewriting the instruction directly, prefer to do
666 // that instead of emitting a stub. This uses the lazy resolver, so is not
667 // legal if lazy compilation is disabled.
668 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
669 return Resolver.AddCallbackAtLocation(F, Reference);
671 // Otherwise, we have to emit a stub.
672 void *StubAddr = Resolver.getFunctionStub(F);
674 // Add the stub to the current function's list of referenced stubs, so we can
675 // deallocate them if the current function is ever freed. It's possible to
676 // return null from getFunctionStub in the case of a weak extern that fails
679 AddStubToCurrentFunction(StubAddr);
684 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
686 // Make sure GV is emitted first, and create a stub containing the fully
688 void *GVAddress = getPointerToGlobal(V, Reference, true);
689 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
691 // Add the stub to the current function's list of referenced stubs, so we can
692 // deallocate them if the current function is ever freed.
693 AddStubToCurrentFunction(StubAddr);
698 void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
699 if (!TheJIT->areDlsymStubsEnabled())
702 assert(CurFn && "Stub added to current function, but current function is 0!");
704 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
705 StubsUsed.push_back(StubAddr);
707 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
708 FnRefs.insert(CurFn);
711 void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
712 if (!DL.isUnknown()) {
713 DebugLocTuple CurDLT = EmissionDetails.MF->getDebugLocTuple(DL);
715 if (BeforePrintingInsn) {
716 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT) {
717 JITEvent_EmittedFunctionDetails::LineStart NextLine;
718 NextLine.Address = getCurrentPCValue();
720 EmissionDetails.LineStarts.push_back(NextLine);
728 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
729 const TargetData *TD) {
730 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
731 if (Constants.empty()) return 0;
734 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
735 MachineConstantPoolEntry CPE = Constants[i];
736 unsigned AlignMask = CPE.getAlignment() - 1;
737 Size = (Size + AlignMask) & ~AlignMask;
738 const Type *Ty = CPE.getType();
739 Size += TD->getTypeAllocSize(Ty);
744 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
745 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
746 if (JT.empty()) return 0;
748 unsigned NumEntries = 0;
749 for (unsigned i = 0, e = JT.size(); i != e; ++i)
750 NumEntries += JT[i].MBBs.size();
752 unsigned EntrySize = MJTI->getEntrySize();
754 return NumEntries * EntrySize;
757 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
758 if (Alignment == 0) Alignment = 1;
759 // Since we do not know where the buffer will be allocated, be pessimistic.
760 return Size + Alignment;
763 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
764 /// into the running total Size.
766 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
767 const Type *ElTy = GV->getType()->getElementType();
768 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
770 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
771 DEBUG(errs() << "JIT: Adding in size " << GVSize << " alignment " << GVAlign);
773 // Assume code section ends with worst possible alignment, so first
774 // variable needs maximal padding.
777 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
782 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
783 /// but are referenced from the constant; put them in GVSet and add their
784 /// size into the running total Size.
786 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
788 // If its undefined, return the garbage.
789 if (isa<UndefValue>(C))
792 // If the value is a ConstantExpr
793 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
794 Constant *Op0 = CE->getOperand(0);
795 switch (CE->getOpcode()) {
796 case Instruction::GetElementPtr:
797 case Instruction::Trunc:
798 case Instruction::ZExt:
799 case Instruction::SExt:
800 case Instruction::FPTrunc:
801 case Instruction::FPExt:
802 case Instruction::UIToFP:
803 case Instruction::SIToFP:
804 case Instruction::FPToUI:
805 case Instruction::FPToSI:
806 case Instruction::PtrToInt:
807 case Instruction::IntToPtr:
808 case Instruction::BitCast: {
809 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
812 case Instruction::Add:
813 case Instruction::FAdd:
814 case Instruction::Sub:
815 case Instruction::FSub:
816 case Instruction::Mul:
817 case Instruction::FMul:
818 case Instruction::UDiv:
819 case Instruction::SDiv:
820 case Instruction::URem:
821 case Instruction::SRem:
822 case Instruction::And:
823 case Instruction::Or:
824 case Instruction::Xor: {
825 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
826 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
831 raw_string_ostream Msg(msg);
832 Msg << "ConstantExpr not handled: " << *CE;
833 llvm_report_error(Msg.str());
838 if (C->getType()->getTypeID() == Type::PointerTyID)
839 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
840 if (GVSet.insert(GV))
841 Size = addSizeOfGlobal(GV, Size);
846 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
847 /// but are referenced from the given initializer.
849 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
851 if (!isa<UndefValue>(Init) &&
852 !isa<ConstantVector>(Init) &&
853 !isa<ConstantAggregateZero>(Init) &&
854 !isa<ConstantArray>(Init) &&
855 !isa<ConstantStruct>(Init) &&
856 Init->getType()->isFirstClassType())
857 Size = addSizeOfGlobalsInConstantVal(Init, Size);
861 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
862 /// globals; then walk the initializers of those globals looking for more.
863 /// If their size has not been considered yet, add it into the running total
866 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
870 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
872 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
874 const TargetInstrDesc &Desc = I->getDesc();
875 const MachineInstr &MI = *I;
876 unsigned NumOps = Desc.getNumOperands();
877 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
878 const MachineOperand &MO = MI.getOperand(CurOp);
880 GlobalValue* V = MO.getGlobal();
881 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
884 // If seen in previous function, it will have an entry here.
885 if (TheJIT->getPointerToGlobalIfAvailable(GV))
887 // If seen earlier in this function, it will have an entry here.
888 // FIXME: it should be possible to combine these tables, by
889 // assuming the addresses of the new globals in this module
890 // start at 0 (or something) and adjusting them after codegen
891 // complete. Another possibility is to grab a marker bit in GV.
892 if (GVSet.insert(GV))
893 // A variable as yet unseen. Add in its size.
894 Size = addSizeOfGlobal(GV, Size);
899 DEBUG(errs() << "JIT: About to look through initializers\n");
900 // Look for more globals that are referenced only from initializers.
901 // GVSet.end is computed each time because the set can grow as we go.
902 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
903 I != GVSet.end(); I++) {
904 const GlobalVariable* GV = *I;
905 if (GV->hasInitializer())
906 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
912 void JITEmitter::startFunction(MachineFunction &F) {
913 DEBUG(errs() << "JIT: Starting CodeGen of Function "
914 << F.getFunction()->getName() << "\n");
916 uintptr_t ActualSize = 0;
917 // Set the memory writable, if it's not already
918 MemMgr->setMemoryWritable();
919 if (MemMgr->NeedsExactSize()) {
920 DEBUG(errs() << "JIT: ExactSize\n");
921 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
922 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
923 MachineConstantPool *MCP = F.getConstantPool();
925 // Ensure the constant pool/jump table info is at least 4-byte aligned.
926 ActualSize = RoundUpToAlign(ActualSize, 16);
928 // Add the alignment of the constant pool
929 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
931 // Add the constant pool size
932 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
934 // Add the aligment of the jump table info
935 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
937 // Add the jump table size
938 ActualSize += GetJumpTableSizeInBytes(MJTI);
940 // Add the alignment for the function
941 ActualSize = RoundUpToAlign(ActualSize,
942 std::max(F.getFunction()->getAlignment(), 8U));
944 // Add the function size
945 ActualSize += TII->GetFunctionSizeInBytes(F);
947 DEBUG(errs() << "JIT: ActualSize before globals " << ActualSize << "\n");
948 // Add the size of the globals that will be allocated after this function.
949 // These are all the ones referenced from this function that were not
950 // previously allocated.
951 ActualSize += GetSizeOfGlobalsInBytes(F);
952 DEBUG(errs() << "JIT: ActualSize after globals " << ActualSize << "\n");
953 } else if (SizeEstimate > 0) {
954 // SizeEstimate will be non-zero on reallocation attempts.
955 ActualSize = SizeEstimate;
958 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
960 BufferEnd = BufferBegin+ActualSize;
962 // Ensure the constant pool/jump table info is at least 4-byte aligned.
965 emitConstantPool(F.getConstantPool());
966 initJumpTableInfo(F.getJumpTableInfo());
968 // About to start emitting the machine code for the function.
969 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
970 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
972 MBBLocations.clear();
974 EmissionDetails.MF = &F;
975 EmissionDetails.LineStarts.clear();
978 bool JITEmitter::finishFunction(MachineFunction &F) {
979 if (CurBufferPtr == BufferEnd) {
980 // We must call endFunctionBody before retrying, because
981 // deallocateMemForFunction requires it.
982 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
983 retryWithMoreMemory(F);
987 emitJumpTableInfo(F.getJumpTableInfo());
989 // FnStart is the start of the text, not the start of the constant pool and
990 // other per-function data.
992 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
994 // FnEnd is the end of the function's machine code.
995 uint8_t *FnEnd = CurBufferPtr;
997 if (!Relocations.empty()) {
998 CurFn = F.getFunction();
999 NumRelos += Relocations.size();
1001 // Resolve the relocations to concrete pointers.
1002 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1003 MachineRelocation &MR = Relocations[i];
1004 void *ResultPtr = 0;
1005 if (!MR.letTargetResolve()) {
1006 if (MR.isExternalSymbol()) {
1007 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1009 DEBUG(errs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
1010 << ResultPtr << "]\n");
1012 // If the target REALLY wants a stub for this function, emit it now.
1013 if (!MR.doesntNeedStub()) {
1014 if (!TheJIT->areDlsymStubsEnabled()) {
1015 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1017 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1019 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1020 AddStubToCurrentFunction(Stub);
1025 } else if (MR.isGlobalValue()) {
1026 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1027 BufferBegin+MR.getMachineCodeOffset(),
1028 MR.doesntNeedStub());
1029 } else if (MR.isIndirectSymbol()) {
1030 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
1031 BufferBegin+MR.getMachineCodeOffset(),
1032 MR.doesntNeedStub());
1033 } else if (MR.isBasicBlock()) {
1034 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1035 } else if (MR.isConstantPoolIndex()) {
1036 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1038 assert(MR.isJumpTableIndex());
1039 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1042 MR.setResultPointer(ResultPtr);
1045 // if we are managing the GOT and the relocation wants an index,
1047 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
1048 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
1049 MR.setGOTIndex(idx);
1050 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
1051 DEBUG(errs() << "JIT: GOT was out of date for " << ResultPtr
1052 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1054 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
1060 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
1061 Relocations.size(), MemMgr->getGOTBase());
1064 // Update the GOT entry for F to point to the new code.
1065 if (MemMgr->isManagingGOT()) {
1066 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
1067 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
1068 DEBUG(errs() << "JIT: GOT was out of date for " << (void*)BufferBegin
1069 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1071 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
1075 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1076 // global variables that were referenced in the relocations.
1077 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
1079 if (CurBufferPtr == BufferEnd) {
1080 retryWithMoreMemory(F);
1083 // Now that we've succeeded in emitting the function, reset the
1084 // SizeEstimate back down to zero.
1088 BufferBegin = CurBufferPtr = 0;
1089 NumBytes += FnEnd-FnStart;
1091 // Invalidate the icache if necessary.
1092 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
1094 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
1097 DEBUG(errs() << "JIT: Finished CodeGen of [" << (void*)FnStart
1098 << "] Function: " << F.getFunction()->getName()
1099 << ": " << (FnEnd-FnStart) << " bytes of text, "
1100 << Relocations.size() << " relocations\n");
1102 Relocations.clear();
1103 ConstPoolAddresses.clear();
1105 // Mark code region readable and executable if it's not so already.
1106 MemMgr->setMemoryExecutable();
1109 if (sys::hasDisassembler()) {
1110 errs() << "JIT: Disassembled code:\n";
1111 errs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
1112 (uintptr_t)FnStart);
1114 errs() << "JIT: Binary code:\n";
1115 uint8_t* q = FnStart;
1116 for (int i = 0; q < FnEnd; q += 4, ++i) {
1120 errs() << "JIT: " << (long)(q - FnStart) << ": ";
1122 for (int j = 3; j >= 0; --j) {
1126 errs() << (unsigned short)q[j];
1138 if (DwarfExceptionHandling || JITEmitDebugInfo) {
1139 uintptr_t ActualSize = 0;
1140 SavedBufferBegin = BufferBegin;
1141 SavedBufferEnd = BufferEnd;
1142 SavedCurBufferPtr = CurBufferPtr;
1144 if (MemMgr->NeedsExactSize()) {
1145 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
1148 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1150 BufferEnd = BufferBegin+ActualSize;
1152 uint8_t *FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd,
1154 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1156 uint8_t *EhEnd = CurBufferPtr;
1157 BufferBegin = SavedBufferBegin;
1158 BufferEnd = SavedBufferEnd;
1159 CurBufferPtr = SavedCurBufferPtr;
1161 if (DwarfExceptionHandling) {
1162 TheJIT->RegisterTable(FrameRegister);
1165 if (JITEmitDebugInfo) {
1167 I.FnStart = FnStart;
1169 I.EhStart = EhStart;
1171 DR->RegisterFunction(F.getFunction(), I);
1181 void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
1182 DEBUG(errs() << "JIT: Ran out of space for native code. Reattempting.\n");
1183 Relocations.clear(); // Clear the old relocations or we'll reapply them.
1184 ConstPoolAddresses.clear();
1186 deallocateMemForFunction(F.getFunction());
1187 // Try again with at least twice as much free space.
1188 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
1191 /// deallocateMemForFunction - Deallocate all memory for the specified
1192 /// function body. Also drop any references the function has to stubs.
1193 void JITEmitter::deallocateMemForFunction(const Function *F) {
1194 MemMgr->deallocateMemForFunction(F);
1196 // TODO: Do we need to unregister exception handling information from libgcc
1199 if (JITEmitDebugInfo) {
1200 DR->UnregisterFunction(F);
1203 // If the function did not reference any stubs, return.
1204 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1207 // For each referenced stub, erase the reference to this function, and then
1208 // erase the list of referenced stubs.
1209 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1210 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1211 void *Stub = StubList[i];
1213 // If we already invalidated this stub for this function, continue.
1214 if (StubFnRefs.count(Stub) == 0)
1217 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1220 // If this function was the last reference to the stub, invalidate the stub
1221 // in the JITResolver. Were there a memory manager deallocateStub routine,
1222 // we could call that at this point too.
1223 if (FnRefs.empty()) {
1224 DEBUG(errs() << "\nJIT: Invalidated Stub at [" << Stub << "]\n");
1225 StubFnRefs.erase(Stub);
1227 // Invalidate the stub. If it is a GV stub, update the JIT's global
1228 // mapping for that GV to zero, otherwise, search the string map of
1229 // external function names to stubs and remove the entry for this stub.
1230 GlobalValue *GV = Resolver.invalidateStub(Stub);
1232 TheJIT->updateGlobalMapping(GV, 0);
1234 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1235 e = ExtFnStubs.end(); i != e; ++i) {
1236 if (i->second == Stub) {
1237 ExtFnStubs.erase(i);
1244 CurFnStubUses.erase(F);
1248 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1250 return JITCodeEmitter::allocateSpace(Size, Alignment);
1252 // create a new memory block if there is no active one.
1253 // care must be taken so that BufferBegin is invalidated when a
1255 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1256 BufferEnd = BufferBegin+Size;
1257 return CurBufferPtr;
1260 void* JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1261 // Delegate this call through the memory manager.
1262 return MemMgr->allocateGlobal(Size, Alignment);
1265 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1266 if (TheJIT->getJITInfo().hasCustomConstantPool())
1269 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1270 if (Constants.empty()) return;
1272 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1273 unsigned Align = MCP->getConstantPoolAlignment();
1274 ConstantPoolBase = allocateSpace(Size, Align);
1277 if (ConstantPoolBase == 0) return; // Buffer overflow.
1279 DEBUG(errs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1280 << "] (size: " << Size << ", alignment: " << Align << ")\n");
1282 // Initialize the memory for all of the constant pool entries.
1283 unsigned Offset = 0;
1284 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1285 MachineConstantPoolEntry CPE = Constants[i];
1286 unsigned AlignMask = CPE.getAlignment() - 1;
1287 Offset = (Offset + AlignMask) & ~AlignMask;
1289 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1290 ConstPoolAddresses.push_back(CAddr);
1291 if (CPE.isMachineConstantPoolEntry()) {
1292 // FIXME: add support to lower machine constant pool values into bytes!
1293 llvm_report_error("Initialize memory with machine specific constant pool"
1294 "entry has not been implemented!");
1296 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1297 DEBUG(errs() << "JIT: CP" << i << " at [0x";
1298 errs().write_hex(CAddr) << "]\n");
1300 const Type *Ty = CPE.Val.ConstVal->getType();
1301 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
1305 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1306 if (TheJIT->getJITInfo().hasCustomJumpTables())
1309 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1310 if (JT.empty()) return;
1312 unsigned NumEntries = 0;
1313 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1314 NumEntries += JT[i].MBBs.size();
1316 unsigned EntrySize = MJTI->getEntrySize();
1318 // Just allocate space for all the jump tables now. We will fix up the actual
1319 // MBB entries in the tables after we emit the code for each block, since then
1320 // we will know the final locations of the MBBs in memory.
1322 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1325 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1326 if (TheJIT->getJITInfo().hasCustomJumpTables())
1329 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1330 if (JT.empty() || JumpTableBase == 0) return;
1332 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1333 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1334 // For each jump table, place the offset from the beginning of the table
1335 // to the target address.
1336 int *SlotPtr = (int*)JumpTableBase;
1338 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1339 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1340 // Store the offset of the basic block for this jump table slot in the
1341 // memory we allocated for the jump table in 'initJumpTableInfo'
1342 uintptr_t Base = (uintptr_t)SlotPtr;
1343 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1344 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1345 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1349 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1351 // For each jump table, map each target in the jump table to the address of
1352 // an emitted MachineBasicBlock.
1353 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1355 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1356 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1357 // Store the address of the basic block for this jump table slot in the
1358 // memory we allocated for the jump table in 'initJumpTableInfo'
1359 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1360 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1365 void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1366 unsigned Alignment) {
1367 SavedBufferBegin = BufferBegin;
1368 SavedBufferEnd = BufferEnd;
1369 SavedCurBufferPtr = CurBufferPtr;
1371 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1372 BufferEnd = BufferBegin+StubSize+1;
1375 void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1376 unsigned StubSize) {
1377 SavedBufferBegin = BufferBegin;
1378 SavedBufferEnd = BufferEnd;
1379 SavedCurBufferPtr = CurBufferPtr;
1381 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1382 BufferEnd = BufferBegin+StubSize+1;
1385 void *JITEmitter::finishGVStub(const GlobalValue* GV) {
1386 NumBytes += getCurrentPCOffset();
1387 std::swap(SavedBufferBegin, BufferBegin);
1388 BufferEnd = SavedBufferEnd;
1389 CurBufferPtr = SavedCurBufferPtr;
1390 return SavedBufferBegin;
1393 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1394 // in the constant pool that was last emitted with the 'emitConstantPool'
1397 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1398 assert(ConstantNum < ConstantPool->getConstants().size() &&
1399 "Invalid ConstantPoolIndex!");
1400 return ConstPoolAddresses[ConstantNum];
1403 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1404 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1406 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1407 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1408 assert(Index < JT.size() && "Invalid jump table index!");
1410 unsigned Offset = 0;
1411 unsigned EntrySize = JumpTable->getEntrySize();
1413 for (unsigned i = 0; i < Index; ++i)
1414 Offset += JT[i].MBBs.size();
1416 Offset *= EntrySize;
1418 return (uintptr_t)((char *)JumpTableBase + Offset);
1421 //===----------------------------------------------------------------------===//
1422 // Public interface to this file
1423 //===----------------------------------------------------------------------===//
1425 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1426 TargetMachine &tm) {
1427 return new JITEmitter(jit, JMM, tm);
1430 // getPointerToNamedFunction - This function is used as a global wrapper to
1431 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1432 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1433 // need to resolve function(s) that are being mis-codegenerated, so we need to
1434 // resolve their addresses at runtime, and this is the way to do it.
1436 void *getPointerToNamedFunction(const char *Name) {
1437 if (Function *F = TheJIT->FindFunctionNamed(Name))
1438 return TheJIT->getPointerToFunction(F);
1439 return TheJIT->getPointerToNamedFunction(Name);
1443 // getPointerToFunctionOrStub - If the specified function has been
1444 // code-gen'd, return a pointer to the function. If not, compile it, or use
1445 // a stub to implement lazy compilation if available.
1447 void *JIT::getPointerToFunctionOrStub(Function *F) {
1448 // If we have already code generated the function, just return the address.
1449 if (void *Addr = getPointerToGlobalIfAvailable(F))
1452 // Get a stub if the target supports it.
1453 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1454 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1455 return JE->getJITResolver().getFunctionStub(F);
1458 void JIT::updateFunctionStub(Function *F) {
1459 // Get the empty stub we generated earlier.
1460 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1461 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1462 void *Stub = JE->getJITResolver().getFunctionStub(F);
1464 // Tell the target jit info to rewrite the stub at the specified address,
1465 // rather than creating a new one.
1466 void *Addr = getPointerToGlobalIfAvailable(F);
1467 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1470 /// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1471 /// that were emitted during code generation.
1473 void JIT::updateDlsymStubTable() {
1474 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1475 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1477 SmallVector<GlobalValue*, 8> GVs;
1478 SmallVector<void*, 8> Ptrs;
1479 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
1481 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1483 unsigned nStubs = GVs.size() + ExtFns.size();
1485 // If there are no relocatable stubs, return.
1489 // If there are no new relocatable stubs, return.
1490 void *CurTable = JE->getMemMgr()->getDlsymTable();
1491 if (CurTable && (*(unsigned *)CurTable == nStubs))
1494 // Calculate the size of the stub info
1495 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
1497 SmallVector<unsigned, 8> Offsets;
1498 for (unsigned i = 0; i != GVs.size(); ++i) {
1499 Offsets.push_back(offset);
1500 offset += GVs[i]->getName().size() + 1;
1502 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1504 Offsets.push_back(offset);
1505 offset += strlen(i->first()) + 1;
1508 // Allocate space for the new "stub", which contains the dlsym table.
1509 JE->startGVStub(0, offset, 4);
1511 // Emit the number of records
1512 JE->emitInt32(nStubs);
1514 // Emit the string offsets
1515 for (unsigned i = 0; i != nStubs; ++i)
1516 JE->emitInt32(Offsets[i]);
1518 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1519 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1520 // relocation can write the relocated pointer at the appropriate place in
1522 for (unsigned i = 0; i != GVs.size(); ++i) {
1523 intptr_t Ptr = (intptr_t)Ptrs[i];
1524 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1526 if (isa<Function>(GVs[i]))
1529 if (sizeof(Ptr) == 8)
1534 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1536 intptr_t Ptr = (intptr_t)i->second | 1;
1538 if (sizeof(Ptr) == 8)
1544 // Emit the strings.
1545 for (unsigned i = 0; i != GVs.size(); ++i)
1546 JE->emitString(GVs[i]->getName());
1547 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1549 JE->emitString(i->first());
1551 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1552 // deallocate space for the old one, if one existed.
1553 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1556 /// freeMachineCodeForFunction - release machine code memory for given Function.
1558 void JIT::freeMachineCodeForFunction(Function *F) {
1560 // Delete translation for this from the ExecutionEngine, so it will get
1561 // retranslated next time it is used.
1562 void *OldPtr = updateGlobalMapping(F, 0);
1565 TheJIT->NotifyFreeingMachineCode(*F, OldPtr);
1567 // Free the actual memory for the function body and related stuff.
1568 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1569 cast<JITEmitter>(JCE)->deallocateMemForFunction(F);