Temporarily Revert "Nuke the old JIT." as it's not quite ready to
[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_H
11 #define LLVM_LIB_EXECUTIONENGINE_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(Module *M, TargetMachine *tm, RTDyldMemoryManager *MemMgr);
105
106   typedef llvm::SmallPtrSet<Module *, 4> ModulePtrSet;
107
108   class OwningModuleContainer {
109   public:
110     OwningModuleContainer() {
111     }
112     ~OwningModuleContainer() {
113       freeModulePtrSet(AddedModules);
114       freeModulePtrSet(LoadedModules);
115       freeModulePtrSet(FinalizedModules);
116     }
117
118     ModulePtrSet::iterator begin_added() { return AddedModules.begin(); }
119     ModulePtrSet::iterator end_added() { return AddedModules.end(); }
120
121     ModulePtrSet::iterator begin_loaded() { return LoadedModules.begin(); }
122     ModulePtrSet::iterator end_loaded() { return LoadedModules.end(); }
123
124     ModulePtrSet::iterator begin_finalized() { return FinalizedModules.begin(); }
125     ModulePtrSet::iterator end_finalized() { return FinalizedModules.end(); }
126
127     void addModule(Module *M) {
128       AddedModules.insert(M);
129     }
130
131     bool removeModule(Module *M) {
132       return AddedModules.erase(M) || LoadedModules.erase(M) ||
133              FinalizedModules.erase(M);
134     }
135
136     bool hasModuleBeenAddedButNotLoaded(Module *M) {
137       return AddedModules.count(M) != 0;
138     }
139
140     bool hasModuleBeenLoaded(Module *M) {
141       // If the module is in either the "loaded" or "finalized" sections it
142       // has been loaded.
143       return (LoadedModules.count(M) != 0 ) || (FinalizedModules.count(M) != 0);
144     }
145
146     bool hasModuleBeenFinalized(Module *M) {
147       return FinalizedModules.count(M) != 0;
148     }
149
150     bool ownsModule(Module* M) {
151       return (AddedModules.count(M) != 0) || (LoadedModules.count(M) != 0) ||
152              (FinalizedModules.count(M) != 0);
153     }
154
155     void markModuleAsLoaded(Module *M) {
156       // This checks against logic errors in the MCJIT implementation.
157       // This function should never be called with either a Module that MCJIT
158       // does not own or a Module that has already been loaded and/or finalized.
159       assert(AddedModules.count(M) &&
160              "markModuleAsLoaded: Module not found in AddedModules");
161
162       // Remove the module from the "Added" set.
163       AddedModules.erase(M);
164
165       // Add the Module to the "Loaded" set.
166       LoadedModules.insert(M);
167     }
168
169     void markModuleAsFinalized(Module *M) {
170       // This checks against logic errors in the MCJIT implementation.
171       // This function should never be called with either a Module that MCJIT
172       // does not own, a Module that has not been loaded or a Module that has
173       // already been finalized.
174       assert(LoadedModules.count(M) &&
175              "markModuleAsFinalized: Module not found in LoadedModules");
176
177       // Remove the module from the "Loaded" section of the list.
178       LoadedModules.erase(M);
179
180       // Add the Module to the "Finalized" section of the list by inserting it
181       // before the 'end' iterator.
182       FinalizedModules.insert(M);
183     }
184
185     void markAllLoadedModulesAsFinalized() {
186       for (ModulePtrSet::iterator I = LoadedModules.begin(),
187                                   E = LoadedModules.end();
188            I != E; ++I) {
189         Module *M = *I;
190         FinalizedModules.insert(M);
191       }
192       LoadedModules.clear();
193     }
194
195   private:
196     ModulePtrSet AddedModules;
197     ModulePtrSet LoadedModules;
198     ModulePtrSet FinalizedModules;
199
200     void freeModulePtrSet(ModulePtrSet& MPS) {
201       // Go through the module set and delete everything.
202       for (ModulePtrSet::iterator I = MPS.begin(), E = MPS.end(); I != E; ++I) {
203         Module *M = *I;
204         delete M;
205       }
206       MPS.clear();
207     }
208   };
209
210   TargetMachine *TM;
211   MCContext *Ctx;
212   LinkingMemoryManager MemMgr;
213   RuntimeDyld Dyld;
214   SmallVector<JITEventListener*, 2> EventListeners;
215
216   OwningModuleContainer OwnedModules;
217
218   SmallVector<std::unique_ptr<object::Archive>, 2> Archives;
219
220   typedef SmallVector<ObjectImage *, 2> LoadedObjectList;
221   LoadedObjectList  LoadedObjects;
222
223   // An optional ObjectCache to be notified of compiled objects and used to
224   // perform lookup of pre-compiled code to avoid re-compilation.
225   ObjectCache *ObjCache;
226
227   Function *FindFunctionNamedInModulePtrSet(const char *FnName,
228                                             ModulePtrSet::iterator I,
229                                             ModulePtrSet::iterator E);
230
231   void runStaticConstructorsDestructorsInModulePtrSet(bool isDtors,
232                                                       ModulePtrSet::iterator I,
233                                                       ModulePtrSet::iterator E);
234
235 public:
236   ~MCJIT();
237
238   /// @name ExecutionEngine interface implementation
239   /// @{
240   void addModule(Module *M) override;
241   void addObjectFile(std::unique_ptr<object::ObjectFile> O) override;
242   void addArchive(std::unique_ptr<object::Archive> O) override;
243   bool removeModule(Module *M) override;
244
245   /// FindFunctionNamed - Search all of the active modules to find the one that
246   /// defines FnName.  This is very slow operation and shouldn't be used for
247   /// general code.
248   Function *FindFunctionNamed(const char *FnName) override;
249
250   /// Sets the object manager that MCJIT should use to avoid compilation.
251   void setObjectCache(ObjectCache *manager) override;
252
253   void setProcessAllSections(bool ProcessAllSections) override {
254     Dyld.setProcessAllSections(ProcessAllSections);
255   }
256
257   void generateCodeForModule(Module *M) override;
258
259   /// finalizeObject - ensure the module is fully processed and is usable.
260   ///
261   /// It is the user-level function for completing the process of making the
262   /// object usable for execution. It should be called after sections within an
263   /// object have been relocated using mapSectionAddress.  When this method is
264   /// called the MCJIT execution engine will reapply relocations for a loaded
265   /// object.
266   /// Is it OK to finalize a set of modules, add modules and finalize again.
267   // FIXME: Do we really need both of these?
268   void finalizeObject() override;
269   virtual void finalizeModule(Module *);
270   void finalizeLoadedModules();
271
272   /// runStaticConstructorsDestructors - This method is used to execute all of
273   /// the static constructors or destructors for a program.
274   ///
275   /// \param isDtors - Run the destructors instead of constructors.
276   void runStaticConstructorsDestructors(bool isDtors) override;
277
278   void *getPointerToBasicBlock(BasicBlock *BB) override;
279
280   void *getPointerToFunction(Function *F) override;
281
282   void *recompileAndRelinkFunction(Function *F) override;
283
284   void freeMachineCodeForFunction(Function *F) override;
285
286   GenericValue runFunction(Function *F,
287                            const std::vector<GenericValue> &ArgValues) override;
288
289   /// getPointerToNamedFunction - This method returns the address of the
290   /// specified function by using the dlsym function call.  As such it is only
291   /// useful for resolving library symbols, not code generated symbols.
292   ///
293   /// If AbortOnFailure is false and no function with the given name is
294   /// found, this function silently returns a null pointer. Otherwise,
295   /// it prints a message to stderr and aborts.
296   ///
297   void *getPointerToNamedFunction(const std::string &Name,
298                                   bool AbortOnFailure = true) override;
299
300   /// mapSectionAddress - map a section to its target address space value.
301   /// Map the address of a JIT section as returned from the memory manager
302   /// to the address in the target process as the running code will see it.
303   /// This is the address which will be used for relocation resolution.
304   void mapSectionAddress(const void *LocalAddress,
305                          uint64_t TargetAddress) override {
306     Dyld.mapSectionAddress(LocalAddress, TargetAddress);
307   }
308   void RegisterJITEventListener(JITEventListener *L) override;
309   void UnregisterJITEventListener(JITEventListener *L) override;
310
311   // If successful, these function will implicitly finalize all loaded objects.
312   // To get a function address within MCJIT without causing a finalize, use
313   // getSymbolAddress.
314   uint64_t getGlobalValueAddress(const std::string &Name) override;
315   uint64_t getFunctionAddress(const std::string &Name) override;
316
317   TargetMachine *getTargetMachine() override { return TM; }
318
319   /// @}
320   /// @name (Private) Registration Interfaces
321   /// @{
322
323   static void Register() {
324     MCJITCtor = createJIT;
325   }
326
327   static ExecutionEngine *createJIT(Module *M,
328                                     std::string *ErrorStr,
329                                     RTDyldMemoryManager *MemMgr,
330                                     TargetMachine *TM);
331
332   // @}
333
334   // This is not directly exposed via the ExecutionEngine API, but it is
335   // used by the LinkingMemoryManager.
336   uint64_t getSymbolAddress(const std::string &Name,
337                           bool CheckFunctionsOnly);
338
339 protected:
340   /// emitObject -- Generate a JITed object in memory from the specified module
341   /// Currently, MCJIT only supports a single module and the module passed to
342   /// this function call is expected to be the contained module.  The module
343   /// is passed as a parameter here to prepare for multiple module support in
344   /// the future.
345   ObjectBufferStream* emitObject(Module *M);
346
347   void NotifyObjectEmitted(const ObjectImage& Obj);
348   void NotifyFreeingObject(const ObjectImage& Obj);
349
350   uint64_t getExistingSymbolAddress(const std::string &Name);
351   Module *findModuleForSymbol(const std::string &Name,
352                               bool CheckFunctionsOnly);
353 };
354
355 } // End llvm namespace
356
357 #endif