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/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/CodeGen/JITCodeEmitter.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/GenericValue.h"
28 #include "llvm/ExecutionEngine/JITEventListener.h"
29 #include "llvm/ExecutionEngine/JITMemoryManager.h"
30 #include "llvm/CodeGen/MachineCodeInfo.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Target/TargetJITInfo.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MutexGuard.h"
38 #include "llvm/Support/ValueHandle.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/System/Disassembler.h"
41 #include "llvm/System/Memory.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/ADT/SmallPtrSet.h"
44 #include "llvm/ADT/SmallVector.h"
45 #include "llvm/ADT/Statistic.h"
52 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
53 STATISTIC(NumRelos, "Number of relocations applied");
54 static JIT *TheJIT = 0;
57 //===----------------------------------------------------------------------===//
58 // JIT lazy compilation code.
61 class JITResolverState {
63 typedef std::map<AssertingVH<Function>, void*> FunctionToStubMapTy;
64 typedef std::map<void*, Function*> StubToFunctionMapTy;
65 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
67 /// FunctionToStubMap - Keep track of the stub created for a particular
68 /// function so that we can reuse them if necessary.
69 FunctionToStubMapTy FunctionToStubMap;
71 /// StubToFunctionMap - Keep track of the function that each stub
73 StubToFunctionMapTy StubToFunctionMap;
75 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
76 /// particular GlobalVariable so that we can reuse them if necessary.
77 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
80 FunctionToStubMapTy& getFunctionToStubMap(const MutexGuard& locked) {
81 assert(locked.holds(TheJIT->lock));
82 return FunctionToStubMap;
85 StubToFunctionMapTy& getStubToFunctionMap(const MutexGuard& locked) {
86 assert(locked.holds(TheJIT->lock));
87 return StubToFunctionMap;
90 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
91 assert(locked.holds(TheJIT->lock));
92 return GlobalToIndirectSymMap;
96 /// JITResolver - Keep track of, and resolve, call sites for functions that
97 /// have not yet been compiled.
99 typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy;
100 typedef JITResolverState::StubToFunctionMapTy StubToFunctionMapTy;
101 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
103 /// LazyResolverFn - The target lazy resolver function that we actually
104 /// rewrite instructions to use.
105 TargetJITInfo::LazyResolverFn LazyResolverFn;
107 JITResolverState state;
109 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
110 /// external functions.
111 std::map<void*, void*> ExternalFnToStubMap;
113 /// revGOTMap - map addresses to indexes in the GOT
114 std::map<void*, unsigned> revGOTMap;
115 unsigned nextGOTIndex;
117 static JITResolver *TheJITResolver;
119 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
122 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
123 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
124 TheJITResolver = this;
131 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
132 /// if it has already been created.
133 void *getFunctionStubIfAvailable(Function *F);
135 /// getFunctionStub - This returns a pointer to a function stub, creating
136 /// one on demand as needed. If empty is true, create a function stub
137 /// pointing at address 0, to be filled in later.
138 void *getFunctionStub(Function *F);
140 /// getExternalFunctionStub - Return a stub for the function at the
141 /// specified address, created lazily on demand.
142 void *getExternalFunctionStub(void *FnAddr);
144 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
145 /// specified GV address.
146 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
148 /// AddCallbackAtLocation - If the target is capable of rewriting an
149 /// instruction without the use of a stub, record the location of the use so
150 /// we know which function is being used at the location.
151 void *AddCallbackAtLocation(Function *F, void *Location) {
152 MutexGuard locked(TheJIT->lock);
153 /// Get the target-specific JIT resolver function.
154 state.getStubToFunctionMap(locked)[Location] = F;
155 return (void*)(intptr_t)LazyResolverFn;
158 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
159 SmallVectorImpl<void*> &Ptrs);
161 GlobalValue *invalidateStub(void *Stub);
163 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
164 /// an address. This function only manages slots, it does not manage the
165 /// contents of the slots or the memory associated with the GOT.
166 unsigned getGOTIndexForAddr(void *addr);
168 /// JITCompilerFn - This function is called to resolve a stub to a compiled
169 /// address. If the LLVM Function corresponding to the stub has not yet
170 /// been compiled, this function compiles it first.
171 static void *JITCompilerFn(void *Stub);
175 JITResolver *JITResolver::TheJITResolver = 0;
177 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
178 /// if it has already been created.
179 void *JITResolver::getFunctionStubIfAvailable(Function *F) {
180 MutexGuard locked(TheJIT->lock);
182 // If we already have a stub for this function, recycle it.
183 void *&Stub = state.getFunctionToStubMap(locked)[F];
187 /// getFunctionStub - This returns a pointer to a function stub, creating
188 /// one on demand as needed.
189 void *JITResolver::getFunctionStub(Function *F) {
190 MutexGuard locked(TheJIT->lock);
192 // If we already have a stub for this function, recycle it.
193 void *&Stub = state.getFunctionToStubMap(locked)[F];
194 if (Stub) return Stub;
196 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
197 // case we must resolve the symbol now.
198 void *Actual = TheJIT->isLazyCompilationDisabled()
199 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
201 // If this is an external declaration, attempt to resolve the address now
202 // to place in the stub.
203 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
204 Actual = TheJIT->getPointerToFunction(F);
206 // If we resolved the symbol to a null address (eg. a weak external)
207 // don't emit a stub. Return a null pointer to the application. If dlsym
208 // stubs are enabled, not being able to resolve the address is not
210 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
213 // Codegen a new stub, calling the lazy resolver or the actual address of the
214 // external function, if it was resolved.
215 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
216 *TheJIT->getCodeEmitter());
218 if (Actual != (void*)(intptr_t)LazyResolverFn) {
219 // If we are getting the stub for an external function, we really want the
220 // address of the stub in the GlobalAddressMap for the JIT, not the address
221 // of the external function.
222 TheJIT->updateGlobalMapping(F, Stub);
225 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
226 << F->getName() << "'\n";
228 // Finally, keep track of the stub-to-Function mapping so that the
229 // JITCompilerFn knows which function to compile!
230 state.getStubToFunctionMap(locked)[Stub] = F;
232 // If we are JIT'ing non-lazily but need to call a function that does not
233 // exist yet, add it to the JIT's work list so that we can fill in the stub
235 if (!Actual && TheJIT->isLazyCompilationDisabled())
236 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
237 TheJIT->addPendingFunction(F);
242 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
244 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
245 MutexGuard locked(TheJIT->lock);
247 // If we already have a stub for this global variable, recycle it.
248 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
249 if (IndirectSym) return IndirectSym;
251 // Otherwise, codegen a new indirect symbol.
252 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
253 *TheJIT->getCodeEmitter());
255 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
256 << GV->getName() << "'\n";
261 /// getExternalFunctionStub - Return a stub for the function at the
262 /// specified address, created lazily on demand.
263 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
264 // If we already have a stub for this function, recycle it.
265 void *&Stub = ExternalFnToStubMap[FnAddr];
266 if (Stub) return Stub;
268 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
269 *TheJIT->getCodeEmitter());
271 DOUT << "JIT: Stub emitted at [" << Stub
272 << "] for external function at '" << FnAddr << "'\n";
276 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
277 unsigned idx = revGOTMap[addr];
279 idx = ++nextGOTIndex;
280 revGOTMap[addr] = idx;
281 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
286 void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
287 SmallVectorImpl<void*> &Ptrs) {
288 MutexGuard locked(TheJIT->lock);
290 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
291 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
293 for (FunctionToStubMapTy::iterator i = FM.begin(), e = FM.end(); i != e; ++i){
294 Function *F = i->first;
295 if (F->isDeclaration() && F->hasExternalLinkage()) {
296 GVs.push_back(i->first);
297 Ptrs.push_back(i->second);
300 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
302 GVs.push_back(i->first);
303 Ptrs.push_back(i->second);
307 GlobalValue *JITResolver::invalidateStub(void *Stub) {
308 MutexGuard locked(TheJIT->lock);
310 FunctionToStubMapTy &FM = state.getFunctionToStubMap(locked);
311 StubToFunctionMapTy &SM = state.getStubToFunctionMap(locked);
312 GlobalToIndirectSymMapTy &GM = state.getGlobalToIndirectSymMap(locked);
314 // Look up the cheap way first, to see if it's a function stub we are
315 // invalidating. If so, remove it from both the forward and reverse maps.
316 if (SM.find(Stub) != SM.end()) {
317 Function *F = SM[Stub];
323 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
324 for (GlobalToIndirectSymMapTy::iterator i = GM.begin(), e = GM.end();
326 if (i->second != Stub)
328 GlobalValue *GV = i->first;
333 // Lastly, check to see if it's in the ExternalFnToStubMap.
334 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
335 e = ExternalFnToStubMap.end(); i != e; ++i) {
336 if (i->second != Stub)
338 ExternalFnToStubMap.erase(i);
345 /// JITCompilerFn - This function is called when a lazy compilation stub has
346 /// been entered. It looks up which function this stub corresponds to, compiles
347 /// it if necessary, then returns the resultant function pointer.
348 void *JITResolver::JITCompilerFn(void *Stub) {
349 JITResolver &JR = *TheJITResolver;
355 // Only lock for getting the Function. The call getPointerToFunction made
356 // in this function might trigger function materializing, which requires
357 // JIT lock to be unlocked.
358 MutexGuard locked(TheJIT->lock);
360 // The address given to us for the stub may not be exactly right, it might be
361 // a little bit after the stub. As such, use upper_bound to find it.
362 StubToFunctionMapTy::iterator I =
363 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
364 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
365 "This is not a known stub!");
367 ActualPtr = I->first;
370 // If we have already code generated the function, just return the address.
371 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
374 // Otherwise we don't have it, do lazy compilation now.
376 // If lazy compilation is disabled, emit a useful error message and abort.
377 if (TheJIT->isLazyCompilationDisabled()) {
378 llvm_report_error("LLVM JIT requested to do lazy compilation of function '"
379 + F->getName() + "' when lazy compiles are disabled!");
382 // We might like to remove the stub from the StubToFunction map.
383 // We can't do that! Multiple threads could be stuck, waiting to acquire the
384 // lock above. As soon as the 1st function finishes compiling the function,
385 // the next one will be released, and needs to be able to find the function
387 //JR.state.getStubToFunctionMap(locked).erase(I);
389 DOUT << "JIT: Lazily resolving function '" << F->getName()
390 << "' In stub ptr = " << Stub << " actual ptr = "
391 << ActualPtr << "\n";
393 Result = TheJIT->getPointerToFunction(F);
396 // Reacquire the lock to erase the stub in the map.
397 MutexGuard locked(TheJIT->lock);
399 // We don't need to reuse this stub in the future, as F is now compiled.
400 JR.state.getFunctionToStubMap(locked).erase(F);
402 // FIXME: We could rewrite all references to this stub if we knew them.
404 // What we will do is set the compiled function address to map to the
405 // same GOT entry as the stub so that later clients may update the GOT
406 // if they see it still using the stub address.
407 // Note: this is done so the Resolver doesn't have to manage GOT memory
408 // Do this without allocating map space if the target isn't using a GOT
409 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
410 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
415 //===----------------------------------------------------------------------===//
419 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
420 /// used to output functions to memory for execution.
421 class JITEmitter : public JITCodeEmitter {
422 JITMemoryManager *MemMgr;
424 // When outputting a function stub in the context of some other function, we
425 // save BufferBegin/BufferEnd/CurBufferPtr here.
426 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
428 /// Relocations - These are the relocations that the function needs, as
430 std::vector<MachineRelocation> Relocations;
432 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
433 /// It is filled in by the StartMachineBasicBlock callback and queried by
434 /// the getMachineBasicBlockAddress callback.
435 std::vector<uintptr_t> MBBLocations;
437 /// ConstantPool - The constant pool for the current function.
439 MachineConstantPool *ConstantPool;
441 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
443 void *ConstantPoolBase;
445 /// ConstPoolAddresses - Addresses of individual constant pool entries.
447 SmallVector<uintptr_t, 8> ConstPoolAddresses;
449 /// JumpTable - The jump tables for the current function.
451 MachineJumpTableInfo *JumpTable;
453 /// JumpTableBase - A pointer to the first entry in the jump table.
457 /// Resolver - This contains info about the currently resolved functions.
458 JITResolver Resolver;
460 /// DE - The dwarf emitter for the jit.
463 /// LabelLocations - This vector is a mapping from Label ID's to their
465 std::vector<uintptr_t> LabelLocations;
467 /// MMI - Machine module info for exception informations
468 MachineModuleInfo* MMI;
470 // GVSet - a set to keep track of which globals have been seen
471 SmallPtrSet<const GlobalVariable*, 8> GVSet;
473 // CurFn - The llvm function being emitted. Only valid during
475 const Function *CurFn;
477 // CurFnStubUses - For a given Function, a vector of stubs that it
478 // references. This facilitates the JIT detecting that a stub is no
479 // longer used, so that it may be deallocated.
480 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
482 // StubFnRefs - For a given pointer to a stub, a set of Functions which
483 // reference the stub. When the count of a stub's references drops to zero,
484 // the stub is unused.
485 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
487 // ExtFnStubs - A map of external function names to stubs which have entries
488 // in the JITResolver's ExternalFnToStubMap.
489 StringMap<void *> ExtFnStubs;
492 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit), CurFn(0) {
493 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
494 if (jit.getJITInfo().needsGOT()) {
495 MemMgr->AllocateGOT();
496 DOUT << "JIT is managing a GOT\n";
499 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
503 if (ExceptionHandling) delete DE;
506 /// classof - Methods for support type inquiry through isa, cast, and
509 static inline bool classof(const JITEmitter*) { return true; }
510 static inline bool classof(const MachineCodeEmitter*) { return true; }
512 JITResolver &getJITResolver() { return Resolver; }
514 virtual void startFunction(MachineFunction &F);
515 virtual bool finishFunction(MachineFunction &F);
517 void emitConstantPool(MachineConstantPool *MCP);
518 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
519 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
521 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
522 unsigned Alignment = 1);
523 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
525 virtual void* finishGVStub(const GlobalValue *GV);
527 /// allocateSpace - Reserves space in the current block if any, or
528 /// allocate a new one of the given size.
529 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
531 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
532 /// this method does not allocate memory in the current output buffer,
533 /// because a global may live longer than the current function.
534 virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
536 virtual void addRelocation(const MachineRelocation &MR) {
537 Relocations.push_back(MR);
540 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
541 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
542 MBBLocations.resize((MBB->getNumber()+1)*2);
543 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
544 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
545 << (void*) getCurrentPCValue() << "]\n";
548 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
549 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
551 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
552 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
553 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
554 return MBBLocations[MBB->getNumber()];
557 /// deallocateMemForFunction - Deallocate all memory for the specified
559 void deallocateMemForFunction(Function *F);
561 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
562 /// using the stub at the specified address. Allows
563 /// deallocateMemForFunction to also remove stubs no longer referenced.
564 void AddStubToCurrentFunction(void *Stub);
566 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
567 /// MachineRelocations that reference external functions by name.
568 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
570 virtual void emitLabel(uint64_t LabelID) {
571 if (LabelLocations.size() <= LabelID)
572 LabelLocations.resize((LabelID+1)*2);
573 LabelLocations[LabelID] = getCurrentPCValue();
576 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
577 assert(LabelLocations.size() > (unsigned)LabelID &&
578 LabelLocations[LabelID] && "Label not emitted!");
579 return LabelLocations[LabelID];
582 virtual void setModuleInfo(MachineModuleInfo* Info) {
584 if (ExceptionHandling) DE->setModuleInfo(Info);
587 void setMemoryExecutable(void) {
588 MemMgr->setMemoryExecutable();
591 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
594 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
595 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
597 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
598 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
599 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
600 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
604 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
605 bool DoesntNeedStub) {
606 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
607 return TheJIT->getOrEmitGlobalVariable(GV);
609 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
610 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
612 // If we have already compiled the function, return a pointer to its body.
613 Function *F = cast<Function>(V);
615 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
616 // Return the function stub if it's already created.
617 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
619 AddStubToCurrentFunction(ResultPtr);
621 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
623 if (ResultPtr) return ResultPtr;
625 // If this is an external function pointer, we can force the JIT to
626 // 'compile' it, which really just adds it to the map. In dlsym mode,
627 // external functions are forced through a stub, regardless of reloc type.
628 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
629 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
630 return TheJIT->getPointerToFunction(F);
632 // Okay, the function has not been compiled yet, if the target callback
633 // mechanism is capable of rewriting the instruction directly, prefer to do
634 // that instead of emitting a stub. This uses the lazy resolver, so is not
635 // legal if lazy compilation is disabled.
636 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
637 return Resolver.AddCallbackAtLocation(F, Reference);
639 // Otherwise, we have to emit a stub.
640 void *StubAddr = Resolver.getFunctionStub(F);
642 // Add the stub to the current function's list of referenced stubs, so we can
643 // deallocate them if the current function is ever freed. It's possible to
644 // return null from getFunctionStub in the case of a weak extern that fails
647 AddStubToCurrentFunction(StubAddr);
652 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
654 // Make sure GV is emitted first, and create a stub containing the fully
656 void *GVAddress = getPointerToGlobal(V, Reference, true);
657 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
659 // Add the stub to the current function's list of referenced stubs, so we can
660 // deallocate them if the current function is ever freed.
661 AddStubToCurrentFunction(StubAddr);
666 void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
667 if (!TheJIT->areDlsymStubsEnabled())
670 assert(CurFn && "Stub added to current function, but current function is 0!");
672 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
673 StubsUsed.push_back(StubAddr);
675 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
676 FnRefs.insert(CurFn);
679 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
680 const TargetData *TD) {
681 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
682 if (Constants.empty()) return 0;
685 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
686 MachineConstantPoolEntry CPE = Constants[i];
687 unsigned AlignMask = CPE.getAlignment() - 1;
688 Size = (Size + AlignMask) & ~AlignMask;
689 const Type *Ty = CPE.getType();
690 Size += TD->getTypeAllocSize(Ty);
695 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
696 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
697 if (JT.empty()) return 0;
699 unsigned NumEntries = 0;
700 for (unsigned i = 0, e = JT.size(); i != e; ++i)
701 NumEntries += JT[i].MBBs.size();
703 unsigned EntrySize = MJTI->getEntrySize();
705 return NumEntries * EntrySize;
708 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
709 if (Alignment == 0) Alignment = 1;
710 // Since we do not know where the buffer will be allocated, be pessimistic.
711 return Size + Alignment;
714 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
715 /// into the running total Size.
717 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
718 const Type *ElTy = GV->getType()->getElementType();
719 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypeAllocSize(ElTy);
721 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
722 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
724 // Assume code section ends with worst possible alignment, so first
725 // variable needs maximal padding.
728 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
733 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
734 /// but are referenced from the constant; put them in GVSet and add their
735 /// size into the running total Size.
737 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
739 // If its undefined, return the garbage.
740 if (isa<UndefValue>(C))
743 // If the value is a ConstantExpr
744 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
745 Constant *Op0 = CE->getOperand(0);
746 switch (CE->getOpcode()) {
747 case Instruction::GetElementPtr:
748 case Instruction::Trunc:
749 case Instruction::ZExt:
750 case Instruction::SExt:
751 case Instruction::FPTrunc:
752 case Instruction::FPExt:
753 case Instruction::UIToFP:
754 case Instruction::SIToFP:
755 case Instruction::FPToUI:
756 case Instruction::FPToSI:
757 case Instruction::PtrToInt:
758 case Instruction::IntToPtr:
759 case Instruction::BitCast: {
760 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
763 case Instruction::Add:
764 case Instruction::FAdd:
765 case Instruction::Sub:
766 case Instruction::FSub:
767 case Instruction::Mul:
768 case Instruction::FMul:
769 case Instruction::UDiv:
770 case Instruction::SDiv:
771 case Instruction::URem:
772 case Instruction::SRem:
773 case Instruction::And:
774 case Instruction::Or:
775 case Instruction::Xor: {
776 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
777 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
782 raw_string_ostream Msg(msg);
783 Msg << "ConstantExpr not handled: " << *CE;
784 llvm_report_error(Msg.str());
789 if (C->getType()->getTypeID() == Type::PointerTyID)
790 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
791 if (GVSet.insert(GV))
792 Size = addSizeOfGlobal(GV, Size);
797 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
798 /// but are referenced from the given initializer.
800 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
802 if (!isa<UndefValue>(Init) &&
803 !isa<ConstantVector>(Init) &&
804 !isa<ConstantAggregateZero>(Init) &&
805 !isa<ConstantArray>(Init) &&
806 !isa<ConstantStruct>(Init) &&
807 Init->getType()->isFirstClassType())
808 Size = addSizeOfGlobalsInConstantVal(Init, Size);
812 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
813 /// globals; then walk the initializers of those globals looking for more.
814 /// If their size has not been considered yet, add it into the running total
817 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
821 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
823 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
825 const TargetInstrDesc &Desc = I->getDesc();
826 const MachineInstr &MI = *I;
827 unsigned NumOps = Desc.getNumOperands();
828 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
829 const MachineOperand &MO = MI.getOperand(CurOp);
831 GlobalValue* V = MO.getGlobal();
832 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
835 // If seen in previous function, it will have an entry here.
836 if (TheJIT->getPointerToGlobalIfAvailable(GV))
838 // If seen earlier in this function, it will have an entry here.
839 // FIXME: it should be possible to combine these tables, by
840 // assuming the addresses of the new globals in this module
841 // start at 0 (or something) and adjusting them after codegen
842 // complete. Another possibility is to grab a marker bit in GV.
843 if (GVSet.insert(GV))
844 // A variable as yet unseen. Add in its size.
845 Size = addSizeOfGlobal(GV, Size);
850 DOUT << "JIT: About to look through initializers\n";
851 // Look for more globals that are referenced only from initializers.
852 // GVSet.end is computed each time because the set can grow as we go.
853 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
854 I != GVSet.end(); I++) {
855 const GlobalVariable* GV = *I;
856 if (GV->hasInitializer())
857 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
863 void JITEmitter::startFunction(MachineFunction &F) {
864 DOUT << "JIT: Starting CodeGen of Function "
865 << F.getFunction()->getName() << "\n";
867 uintptr_t ActualSize = 0;
868 // Set the memory writable, if it's not already
869 MemMgr->setMemoryWritable();
870 if (MemMgr->NeedsExactSize()) {
871 DOUT << "JIT: ExactSize\n";
872 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
873 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
874 MachineConstantPool *MCP = F.getConstantPool();
876 // Ensure the constant pool/jump table info is at least 4-byte aligned.
877 ActualSize = RoundUpToAlign(ActualSize, 16);
879 // Add the alignment of the constant pool
880 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
882 // Add the constant pool size
883 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
885 // Add the aligment of the jump table info
886 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
888 // Add the jump table size
889 ActualSize += GetJumpTableSizeInBytes(MJTI);
891 // Add the alignment for the function
892 ActualSize = RoundUpToAlign(ActualSize,
893 std::max(F.getFunction()->getAlignment(), 8U));
895 // Add the function size
896 ActualSize += TII->GetFunctionSizeInBytes(F);
898 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
899 // Add the size of the globals that will be allocated after this function.
900 // These are all the ones referenced from this function that were not
901 // previously allocated.
902 ActualSize += GetSizeOfGlobalsInBytes(F);
903 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
906 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
908 BufferEnd = BufferBegin+ActualSize;
910 // Ensure the constant pool/jump table info is at least 4-byte aligned.
913 emitConstantPool(F.getConstantPool());
914 initJumpTableInfo(F.getJumpTableInfo());
916 // About to start emitting the machine code for the function.
917 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
918 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
920 MBBLocations.clear();
923 bool JITEmitter::finishFunction(MachineFunction &F) {
924 if (CurBufferPtr == BufferEnd) {
925 // FIXME: Allocate more space, then try again.
926 llvm_report_error("JIT: Ran out of space for generated machine code!");
929 emitJumpTableInfo(F.getJumpTableInfo());
931 // FnStart is the start of the text, not the start of the constant pool and
932 // other per-function data.
934 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
936 // FnEnd is the end of the function's machine code.
937 uint8_t *FnEnd = CurBufferPtr;
939 if (!Relocations.empty()) {
940 CurFn = F.getFunction();
941 NumRelos += Relocations.size();
943 // Resolve the relocations to concrete pointers.
944 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
945 MachineRelocation &MR = Relocations[i];
947 if (!MR.letTargetResolve()) {
948 if (MR.isExternalSymbol()) {
949 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
951 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
952 << ResultPtr << "]\n";
954 // If the target REALLY wants a stub for this function, emit it now.
955 if (!MR.doesntNeedStub()) {
956 if (!TheJIT->areDlsymStubsEnabled()) {
957 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
959 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
961 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
962 AddStubToCurrentFunction(Stub);
967 } else if (MR.isGlobalValue()) {
968 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
969 BufferBegin+MR.getMachineCodeOffset(),
970 MR.doesntNeedStub());
971 } else if (MR.isIndirectSymbol()) {
972 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
973 BufferBegin+MR.getMachineCodeOffset(),
974 MR.doesntNeedStub());
975 } else if (MR.isBasicBlock()) {
976 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
977 } else if (MR.isConstantPoolIndex()) {
978 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
980 assert(MR.isJumpTableIndex());
981 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
984 MR.setResultPointer(ResultPtr);
987 // if we are managing the GOT and the relocation wants an index,
989 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
990 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
992 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
993 DOUT << "JIT: GOT was out of date for " << ResultPtr
994 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
996 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
1002 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
1003 Relocations.size(), MemMgr->getGOTBase());
1006 // Update the GOT entry for F to point to the new code.
1007 if (MemMgr->isManagingGOT()) {
1008 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
1009 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
1010 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
1011 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1012 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
1016 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1017 // global variables that were referenced in the relocations.
1018 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
1020 if (CurBufferPtr == BufferEnd) {
1021 // FIXME: Allocate more space, then try again.
1022 llvm_report_error("JIT: Ran out of space for generated machine code!");
1025 BufferBegin = CurBufferPtr = 0;
1026 NumBytes += FnEnd-FnStart;
1028 // Invalidate the icache if necessary.
1029 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
1031 JITEvent_EmittedFunctionDetails Details;
1032 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
1035 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1036 << "] Function: " << F.getFunction()->getName()
1037 << ": " << (FnEnd-FnStart) << " bytes of text, "
1038 << Relocations.size() << " relocations\n";
1040 Relocations.clear();
1041 ConstPoolAddresses.clear();
1043 // Mark code region readable and executable if it's not so already.
1044 MemMgr->setMemoryExecutable();
1048 if (sys::hasDisassembler()) {
1049 DOUT << "JIT: Disassembled code:\n";
1050 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
1052 DOUT << "JIT: Binary code:\n";
1054 uint8_t* q = FnStart;
1055 for (int i = 0; q < FnEnd; q += 4, ++i) {
1059 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1060 << (long)(q - FnStart) << ": ";
1062 for (int j = 3; j >= 0; --j) {
1066 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1079 if (ExceptionHandling) {
1080 uintptr_t ActualSize = 0;
1081 SavedBufferBegin = BufferBegin;
1082 SavedBufferEnd = BufferEnd;
1083 SavedCurBufferPtr = CurBufferPtr;
1085 if (MemMgr->NeedsExactSize()) {
1086 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
1089 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1091 BufferEnd = BufferBegin+ActualSize;
1092 uint8_t* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
1093 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1095 BufferBegin = SavedBufferBegin;
1096 BufferEnd = SavedBufferEnd;
1097 CurBufferPtr = SavedCurBufferPtr;
1099 TheJIT->RegisterTable(FrameRegister);
1108 /// deallocateMemForFunction - Deallocate all memory for the specified
1109 /// function body. Also drop any references the function has to stubs.
1110 void JITEmitter::deallocateMemForFunction(Function *F) {
1111 MemMgr->deallocateMemForFunction(F);
1113 // If the function did not reference any stubs, return.
1114 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1117 // For each referenced stub, erase the reference to this function, and then
1118 // erase the list of referenced stubs.
1119 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1120 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1121 void *Stub = StubList[i];
1123 // If we already invalidated this stub for this function, continue.
1124 if (StubFnRefs.count(Stub) == 0)
1127 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1130 // If this function was the last reference to the stub, invalidate the stub
1131 // in the JITResolver. Were there a memory manager deallocateStub routine,
1132 // we could call that at this point too.
1133 if (FnRefs.empty()) {
1134 DOUT << "\nJIT: Invalidated Stub at [" << Stub << "]\n";
1135 StubFnRefs.erase(Stub);
1137 // Invalidate the stub. If it is a GV stub, update the JIT's global
1138 // mapping for that GV to zero, otherwise, search the string map of
1139 // external function names to stubs and remove the entry for this stub.
1140 GlobalValue *GV = Resolver.invalidateStub(Stub);
1142 TheJIT->updateGlobalMapping(GV, 0);
1144 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1145 e = ExtFnStubs.end(); i != e; ++i) {
1146 if (i->second == Stub) {
1147 ExtFnStubs.erase(i);
1154 CurFnStubUses.erase(F);
1158 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1160 return JITCodeEmitter::allocateSpace(Size, Alignment);
1162 // create a new memory block if there is no active one.
1163 // care must be taken so that BufferBegin is invalidated when a
1165 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1166 BufferEnd = BufferBegin+Size;
1167 return CurBufferPtr;
1170 void* JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1171 // Delegate this call through the memory manager.
1172 return MemMgr->allocateGlobal(Size, Alignment);
1175 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1176 if (TheJIT->getJITInfo().hasCustomConstantPool())
1179 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1180 if (Constants.empty()) return;
1182 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1183 unsigned Align = MCP->getConstantPoolAlignment();
1184 ConstantPoolBase = allocateSpace(Size, Align);
1187 if (ConstantPoolBase == 0) return; // Buffer overflow.
1189 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1190 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1192 // Initialize the memory for all of the constant pool entries.
1193 unsigned Offset = 0;
1194 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1195 MachineConstantPoolEntry CPE = Constants[i];
1196 unsigned AlignMask = CPE.getAlignment() - 1;
1197 Offset = (Offset + AlignMask) & ~AlignMask;
1199 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1200 ConstPoolAddresses.push_back(CAddr);
1201 if (CPE.isMachineConstantPoolEntry()) {
1202 // FIXME: add support to lower machine constant pool values into bytes!
1203 llvm_report_error("Initialize memory with machine specific constant pool"
1204 "entry has not been implemented!");
1206 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1207 DOUT << "JIT: CP" << i << " at [0x"
1208 << std::hex << CAddr << std::dec << "]\n";
1210 const Type *Ty = CPE.Val.ConstVal->getType();
1211 Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
1215 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1216 if (TheJIT->getJITInfo().hasCustomJumpTables())
1219 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1220 if (JT.empty()) return;
1222 unsigned NumEntries = 0;
1223 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1224 NumEntries += JT[i].MBBs.size();
1226 unsigned EntrySize = MJTI->getEntrySize();
1228 // Just allocate space for all the jump tables now. We will fix up the actual
1229 // MBB entries in the tables after we emit the code for each block, since then
1230 // we will know the final locations of the MBBs in memory.
1232 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1235 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1236 if (TheJIT->getJITInfo().hasCustomJumpTables())
1239 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1240 if (JT.empty() || JumpTableBase == 0) return;
1242 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1243 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1244 // For each jump table, place the offset from the beginning of the table
1245 // to the target address.
1246 int *SlotPtr = (int*)JumpTableBase;
1248 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1249 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1250 // Store the offset of the basic block for this jump table slot in the
1251 // memory we allocated for the jump table in 'initJumpTableInfo'
1252 uintptr_t Base = (uintptr_t)SlotPtr;
1253 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1254 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1255 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1259 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1261 // For each jump table, map each target in the jump table to the address of
1262 // an emitted MachineBasicBlock.
1263 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1265 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1266 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1267 // Store the address of the basic block for this jump table slot in the
1268 // memory we allocated for the jump table in 'initJumpTableInfo'
1269 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1270 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1275 void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1276 unsigned Alignment) {
1277 SavedBufferBegin = BufferBegin;
1278 SavedBufferEnd = BufferEnd;
1279 SavedCurBufferPtr = CurBufferPtr;
1281 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1282 BufferEnd = BufferBegin+StubSize+1;
1285 void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1286 unsigned StubSize) {
1287 SavedBufferBegin = BufferBegin;
1288 SavedBufferEnd = BufferEnd;
1289 SavedCurBufferPtr = CurBufferPtr;
1291 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1292 BufferEnd = BufferBegin+StubSize+1;
1295 void *JITEmitter::finishGVStub(const GlobalValue* GV) {
1296 NumBytes += getCurrentPCOffset();
1297 std::swap(SavedBufferBegin, BufferBegin);
1298 BufferEnd = SavedBufferEnd;
1299 CurBufferPtr = SavedCurBufferPtr;
1300 return SavedBufferBegin;
1303 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1304 // in the constant pool that was last emitted with the 'emitConstantPool'
1307 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1308 assert(ConstantNum < ConstantPool->getConstants().size() &&
1309 "Invalid ConstantPoolIndex!");
1310 return ConstPoolAddresses[ConstantNum];
1313 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1314 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1316 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1317 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1318 assert(Index < JT.size() && "Invalid jump table index!");
1320 unsigned Offset = 0;
1321 unsigned EntrySize = JumpTable->getEntrySize();
1323 for (unsigned i = 0; i < Index; ++i)
1324 Offset += JT[i].MBBs.size();
1326 Offset *= EntrySize;
1328 return (uintptr_t)((char *)JumpTableBase + Offset);
1331 //===----------------------------------------------------------------------===//
1332 // Public interface to this file
1333 //===----------------------------------------------------------------------===//
1335 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1336 return new JITEmitter(jit, JMM);
1339 // getPointerToNamedFunction - This function is used as a global wrapper to
1340 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1341 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1342 // need to resolve function(s) that are being mis-codegenerated, so we need to
1343 // resolve their addresses at runtime, and this is the way to do it.
1345 void *getPointerToNamedFunction(const char *Name) {
1346 if (Function *F = TheJIT->FindFunctionNamed(Name))
1347 return TheJIT->getPointerToFunction(F);
1348 return TheJIT->getPointerToNamedFunction(Name);
1352 // getPointerToFunctionOrStub - If the specified function has been
1353 // code-gen'd, return a pointer to the function. If not, compile it, or use
1354 // a stub to implement lazy compilation if available.
1356 void *JIT::getPointerToFunctionOrStub(Function *F) {
1357 // If we have already code generated the function, just return the address.
1358 if (void *Addr = getPointerToGlobalIfAvailable(F))
1361 // Get a stub if the target supports it.
1362 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1363 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1364 return JE->getJITResolver().getFunctionStub(F);
1367 void JIT::updateFunctionStub(Function *F) {
1368 // Get the empty stub we generated earlier.
1369 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1370 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1371 void *Stub = JE->getJITResolver().getFunctionStub(F);
1373 // Tell the target jit info to rewrite the stub at the specified address,
1374 // rather than creating a new one.
1375 void *Addr = getPointerToGlobalIfAvailable(F);
1376 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1379 /// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1380 /// that were emitted during code generation.
1382 void JIT::updateDlsymStubTable() {
1383 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1384 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1386 SmallVector<GlobalValue*, 8> GVs;
1387 SmallVector<void*, 8> Ptrs;
1388 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
1390 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1392 unsigned nStubs = GVs.size() + ExtFns.size();
1394 // If there are no relocatable stubs, return.
1398 // If there are no new relocatable stubs, return.
1399 void *CurTable = JE->getMemMgr()->getDlsymTable();
1400 if (CurTable && (*(unsigned *)CurTable == nStubs))
1403 // Calculate the size of the stub info
1404 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
1406 SmallVector<unsigned, 8> Offsets;
1407 for (unsigned i = 0; i != GVs.size(); ++i) {
1408 Offsets.push_back(offset);
1409 offset += GVs[i]->getName().length() + 1;
1411 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1413 Offsets.push_back(offset);
1414 offset += strlen(i->first()) + 1;
1417 // Allocate space for the new "stub", which contains the dlsym table.
1418 JE->startGVStub(0, offset, 4);
1420 // Emit the number of records
1421 JE->emitInt32(nStubs);
1423 // Emit the string offsets
1424 for (unsigned i = 0; i != nStubs; ++i)
1425 JE->emitInt32(Offsets[i]);
1427 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1428 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1429 // relocation can write the relocated pointer at the appropriate place in
1431 for (unsigned i = 0; i != GVs.size(); ++i) {
1432 intptr_t Ptr = (intptr_t)Ptrs[i];
1433 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1435 if (isa<Function>(GVs[i]))
1438 if (sizeof(Ptr) == 8)
1443 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1445 intptr_t Ptr = (intptr_t)i->second | 1;
1447 if (sizeof(Ptr) == 8)
1453 // Emit the strings.
1454 for (unsigned i = 0; i != GVs.size(); ++i)
1455 JE->emitString(GVs[i]->getName());
1456 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1458 JE->emitString(i->first());
1460 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1461 // deallocate space for the old one, if one existed.
1462 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1465 /// freeMachineCodeForFunction - release machine code memory for given Function.
1467 void JIT::freeMachineCodeForFunction(Function *F) {
1469 // Delete translation for this from the ExecutionEngine, so it will get
1470 // retranslated next time it is used.
1471 void *OldPtr = updateGlobalMapping(F, 0);
1474 TheJIT->NotifyFreeingMachineCode(*F, OldPtr);
1476 // Free the actual memory for the function body and related stuff.
1477 assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
1478 cast<JITEmitter>(JCE)->deallocateMemForFunction(F);