Reinstate "Nuke the old JIT."
[oota-llvm.git] / lib / ExecutionEngine / MCJIT / MCJIT.h
1 //===-- MCJIT.h - Class definition for the MCJIT ----------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLVM_LIB_EXECUTIONENGINE_MCJIT_MCJIT_H
11 #define LLVM_LIB_EXECUTIONENGINE_MCJIT_MCJIT_H
12
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ExecutionEngine/ExecutionEngine.h"
17 #include "llvm/ExecutionEngine/ObjectCache.h"
18 #include "llvm/ExecutionEngine/ObjectImage.h"
19 #include "llvm/ExecutionEngine/RuntimeDyld.h"
20 #include "llvm/IR/Module.h"
21
22 namespace llvm {
23 class MCJIT;
24
25 // This is a helper class that the MCJIT execution engine uses for linking
26 // functions across modules that it owns.  It aggregates the memory manager
27 // that is passed in to the MCJIT constructor and defers most functionality
28 // to that object.
29 class LinkingMemoryManager : public RTDyldMemoryManager {
30 public:
31   LinkingMemoryManager(MCJIT *Parent, RTDyldMemoryManager *MM)
32     : ParentEngine(Parent), ClientMM(MM) {}
33
34   uint64_t getSymbolAddress(const std::string &Name) override;
35
36   // Functions deferred to client memory manager
37   uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
38                                unsigned SectionID,
39                                StringRef SectionName) override {
40     return ClientMM->allocateCodeSection(Size, Alignment, SectionID, SectionName);
41   }
42
43   uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
44                                unsigned SectionID, StringRef SectionName,
45                                bool IsReadOnly) override {
46     return ClientMM->allocateDataSection(Size, Alignment,
47                                          SectionID, SectionName, IsReadOnly);
48   }
49
50   void reserveAllocationSpace(uintptr_t CodeSize, uintptr_t DataSizeRO,
51                               uintptr_t DataSizeRW) override {
52     return ClientMM->reserveAllocationSpace(CodeSize, DataSizeRO, DataSizeRW);
53   }
54
55   bool needsToReserveAllocationSpace() override {
56     return ClientMM->needsToReserveAllocationSpace();
57   }
58
59   void notifyObjectLoaded(ExecutionEngine *EE,
60                           const ObjectImage *Obj) override {
61     ClientMM->notifyObjectLoaded(EE, Obj);
62   }
63
64   void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
65                         size_t Size) override {
66     ClientMM->registerEHFrames(Addr, LoadAddr, Size);
67   }
68
69   void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr,
70                           size_t Size) override {
71     ClientMM->deregisterEHFrames(Addr, LoadAddr, Size);
72   }
73
74   bool finalizeMemory(std::string *ErrMsg = nullptr) override {
75     return ClientMM->finalizeMemory(ErrMsg);
76   }
77
78 private:
79   MCJIT *ParentEngine;
80   std::unique_ptr<RTDyldMemoryManager> ClientMM;
81 };
82
83 // About Module states: added->loaded->finalized.
84 //
85 // The purpose of the "added" state is having modules in standby. (added=known
86 // but not compiled). The idea is that you can add a module to provide function
87 // definitions but if nothing in that module is referenced by a module in which
88 // a function is executed (note the wording here because it's not exactly the
89 // ideal case) then the module never gets compiled. This is sort of lazy
90 // compilation.
91 //
92 // The purpose of the "loaded" state (loaded=compiled and required sections
93 // copied into local memory but not yet ready for execution) is to have an
94 // intermediate state wherein clients can remap the addresses of sections, using
95 // MCJIT::mapSectionAddress, (in preparation for later copying to a new location
96 // or an external process) before relocations and page permissions are applied.
97 //
98 // It might not be obvious at first glance, but the "remote-mcjit" case in the
99 // lli tool does this.  In that case, the intermediate action is taken by the
100 // RemoteMemoryManager in response to the notifyObjectLoaded function being
101 // called.
102
103 class MCJIT : public ExecutionEngine {
104   MCJIT(std::unique_ptr<Module> M, TargetMachine *tm,
105         RTDyldMemoryManager *MemMgr);
106
107   typedef llvm::SmallPtrSet<Module *, 4> ModulePtrSet;
108
109   class OwningModuleContainer {
110   public:
111     OwningModuleContainer() {
112     }
113     ~OwningModuleContainer() {
114       freeModulePtrSet(AddedModules);
115       freeModulePtrSet(LoadedModules);
116       freeModulePtrSet(FinalizedModules);
117     }
118
119     ModulePtrSet::iterator begin_added() { return AddedModules.begin(); }
120     ModulePtrSet::iterator end_added() { return AddedModules.end(); }
121
122     ModulePtrSet::iterator begin_loaded() { return LoadedModules.begin(); }
123     ModulePtrSet::iterator end_loaded() { return LoadedModules.end(); }
124
125     ModulePtrSet::iterator begin_finalized() { return FinalizedModules.begin(); }
126     ModulePtrSet::iterator end_finalized() { return FinalizedModules.end(); }
127
128     void addModule(std::unique_ptr<Module> M) {
129       AddedModules.insert(M.release());
130     }
131
132     bool removeModule(Module *M) {
133       return AddedModules.erase(M) || LoadedModules.erase(M) ||
134              FinalizedModules.erase(M);
135     }
136
137     bool hasModuleBeenAddedButNotLoaded(Module *M) {
138       return AddedModules.count(M) != 0;
139     }
140
141     bool hasModuleBeenLoaded(Module *M) {
142       // If the module is in either the "loaded" or "finalized" sections it
143       // has been loaded.
144       return (LoadedModules.count(M) != 0 ) || (FinalizedModules.count(M) != 0);
145     }
146
147     bool hasModuleBeenFinalized(Module *M) {
148       return FinalizedModules.count(M) != 0;
149     }
150
151     bool ownsModule(Module* M) {
152       return (AddedModules.count(M) != 0) || (LoadedModules.count(M) != 0) ||
153              (FinalizedModules.count(M) != 0);
154     }
155
156     void markModuleAsLoaded(Module *M) {
157       // This checks against logic errors in the MCJIT implementation.
158       // This function should never be called with either a Module that MCJIT
159       // does not own or a Module that has already been loaded and/or finalized.
160       assert(AddedModules.count(M) &&
161              "markModuleAsLoaded: Module not found in AddedModules");
162
163       // Remove the module from the "Added" set.
164       AddedModules.erase(M);
165
166       // Add the Module to the "Loaded" set.
167       LoadedModules.insert(M);
168     }
169
170     void markModuleAsFinalized(Module *M) {
171       // This checks against logic errors in the MCJIT implementation.
172       // This function should never be called with either a Module that MCJIT
173       // does not own, a Module that has not been loaded or a Module that has
174       // already been finalized.
175       assert(LoadedModules.count(M) &&
176              "markModuleAsFinalized: Module not found in LoadedModules");
177
178       // Remove the module from the "Loaded" section of the list.
179       LoadedModules.erase(M);
180
181       // Add the Module to the "Finalized" section of the list by inserting it
182       // before the 'end' iterator.
183       FinalizedModules.insert(M);
184     }
185
186     void markAllLoadedModulesAsFinalized() {
187       for (ModulePtrSet::iterator I = LoadedModules.begin(),
188                                   E = LoadedModules.end();
189            I != E; ++I) {
190         Module *M = *I;
191         FinalizedModules.insert(M);
192       }
193       LoadedModules.clear();
194     }
195
196   private:
197     ModulePtrSet AddedModules;
198     ModulePtrSet LoadedModules;
199     ModulePtrSet FinalizedModules;
200
201     void freeModulePtrSet(ModulePtrSet& MPS) {
202       // Go through the module set and delete everything.
203       for (ModulePtrSet::iterator I = MPS.begin(), E = MPS.end(); I != E; ++I) {
204         Module *M = *I;
205         delete M;
206       }
207       MPS.clear();
208     }
209   };
210
211   TargetMachine *TM;
212   MCContext *Ctx;
213   LinkingMemoryManager MemMgr;
214   RuntimeDyld Dyld;
215   std::vector<JITEventListener*> EventListeners;
216
217   OwningModuleContainer OwnedModules;
218
219   SmallVector<object::OwningBinary<object::Archive>, 2> Archives;
220   SmallVector<std::unique_ptr<MemoryBuffer>, 2> Buffers;
221
222   typedef SmallVector<ObjectImage *, 2> LoadedObjectList;
223   LoadedObjectList  LoadedObjects;
224
225   // An optional ObjectCache to be notified of compiled objects and used to
226   // perform lookup of pre-compiled code to avoid re-compilation.
227   ObjectCache *ObjCache;
228
229   Function *FindFunctionNamedInModulePtrSet(const char *FnName,
230                                             ModulePtrSet::iterator I,
231                                             ModulePtrSet::iterator E);
232
233   void runStaticConstructorsDestructorsInModulePtrSet(bool isDtors,
234                                                       ModulePtrSet::iterator I,
235                                                       ModulePtrSet::iterator E);
236
237 public:
238   ~MCJIT();
239
240   /// @name ExecutionEngine interface implementation
241   /// @{
242   void addModule(std::unique_ptr<Module> M) override;
243   void addObjectFile(std::unique_ptr<object::ObjectFile> O) override;
244   void addObjectFile(object::OwningBinary<object::ObjectFile> O) override;
245   void addArchive(object::OwningBinary<object::Archive> O) override;
246   bool removeModule(Module *M) override;
247
248   /// FindFunctionNamed - Search all of the active modules to find the one that
249   /// defines FnName.  This is very slow operation and shouldn't be used for
250   /// general code.
251   Function *FindFunctionNamed(const char *FnName) override;
252
253   /// Sets the object manager that MCJIT should use to avoid compilation.
254   void setObjectCache(ObjectCache *manager) override;
255
256   void setProcessAllSections(bool ProcessAllSections) override {
257     Dyld.setProcessAllSections(ProcessAllSections);
258   }
259
260   void generateCodeForModule(Module *M) override;
261
262   /// finalizeObject - ensure the module is fully processed and is usable.
263   ///
264   /// It is the user-level function for completing the process of making the
265   /// object usable for execution. It should be called after sections within an
266   /// object have been relocated using mapSectionAddress.  When this method is
267   /// called the MCJIT execution engine will reapply relocations for a loaded
268   /// object.
269   /// Is it OK to finalize a set of modules, add modules and finalize again.
270   // FIXME: Do we really need both of these?
271   void finalizeObject() override;
272   virtual void finalizeModule(Module *);
273   void finalizeLoadedModules();
274
275   /// runStaticConstructorsDestructors - This method is used to execute all of
276   /// the static constructors or destructors for a program.
277   ///
278   /// \param isDtors - Run the destructors instead of constructors.
279   void runStaticConstructorsDestructors(bool isDtors) override;
280
281   void *getPointerToFunction(Function *F) override;
282
283   GenericValue runFunction(Function *F,
284                            const std::vector<GenericValue> &ArgValues) override;
285
286   /// getPointerToNamedFunction - This method returns the address of the
287   /// specified function by using the dlsym function call.  As such it is only
288   /// useful for resolving library symbols, not code generated symbols.
289   ///
290   /// If AbortOnFailure is false and no function with the given name is
291   /// found, this function silently returns a null pointer. Otherwise,
292   /// it prints a message to stderr and aborts.
293   ///
294   void *getPointerToNamedFunction(const std::string &Name,
295                                   bool AbortOnFailure = true) override;
296
297   /// mapSectionAddress - map a section to its target address space value.
298   /// Map the address of a JIT section as returned from the memory manager
299   /// to the address in the target process as the running code will see it.
300   /// This is the address which will be used for relocation resolution.
301   void mapSectionAddress(const void *LocalAddress,
302                          uint64_t TargetAddress) override {
303     Dyld.mapSectionAddress(LocalAddress, TargetAddress);
304   }
305   void RegisterJITEventListener(JITEventListener *L) override;
306   void UnregisterJITEventListener(JITEventListener *L) override;
307
308   // If successful, these function will implicitly finalize all loaded objects.
309   // To get a function address within MCJIT without causing a finalize, use
310   // getSymbolAddress.
311   uint64_t getGlobalValueAddress(const std::string &Name) override;
312   uint64_t getFunctionAddress(const std::string &Name) override;
313
314   TargetMachine *getTargetMachine() override { return TM; }
315
316   /// @}
317   /// @name (Private) Registration Interfaces
318   /// @{
319
320   static void Register() {
321     MCJITCtor = createJIT;
322   }
323
324   static ExecutionEngine *createJIT(std::unique_ptr<Module> M,
325                                     std::string *ErrorStr,
326                                     RTDyldMemoryManager *MemMgr,
327                                     TargetMachine *TM);
328
329   // @}
330
331   // This is not directly exposed via the ExecutionEngine API, but it is
332   // used by the LinkingMemoryManager.
333   uint64_t getSymbolAddress(const std::string &Name,
334                           bool CheckFunctionsOnly);
335
336 protected:
337   /// emitObject -- Generate a JITed object in memory from the specified module
338   /// Currently, MCJIT only supports a single module and the module passed to
339   /// this function call is expected to be the contained module.  The module
340   /// is passed as a parameter here to prepare for multiple module support in
341   /// the future.
342   ObjectBufferStream* emitObject(Module *M);
343
344   void NotifyObjectEmitted(const ObjectImage& Obj);
345   void NotifyFreeingObject(const ObjectImage& Obj);
346
347   uint64_t getExistingSymbolAddress(const std::string &Name);
348   Module *findModuleForSymbol(const std::string &Name,
349                               bool CheckFunctionsOnly);
350 };
351
352 } // End llvm namespace
353
354 #endif