[C++] Use 'nullptr'.
[oota-llvm.git] / lib / ExecutionEngine / MCJIT / MCJIT.h
index 0d15b9afe6cdfa0fd2ebc25e754c82b8c711f82f..da1e975d4cd9dbc110d88396bb8310049424c343 100644 (file)
 #define LLVM_LIB_EXECUTIONENGINE_MCJIT_H
 
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ExecutionEngine/ExecutionEngine.h"
 #include "llvm/ExecutionEngine/ObjectCache.h"
 #include "llvm/ExecutionEngine/ObjectImage.h"
 #include "llvm/ExecutionEngine/RuntimeDyld.h"
-#include "llvm/PassManager.h"
+#include "llvm/IR/Module.h"
 
 namespace llvm {
-
 class MCJIT;
 
 // This is a helper class that the MCJIT execution engine uses for linking
@@ -31,51 +31,61 @@ public:
   LinkingMemoryManager(MCJIT *Parent, RTDyldMemoryManager *MM)
     : ParentEngine(Parent), ClientMM(MM) {}
 
-  virtual uint64_t getSymbolAddress(const std::string &Name);
+  uint64_t getSymbolAddress(const std::string &Name) override;
 
   // Functions deferred to client memory manager
-  virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
-                                       unsigned SectionID, StringRef SectionName) {
+  uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
+                               unsigned SectionID,
+                               StringRef SectionName) override {
     return ClientMM->allocateCodeSection(Size, Alignment, SectionID, SectionName);
   }
 
-  virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
-                                       unsigned SectionID, StringRef SectionName,
-                                       bool IsReadOnly) {
+  uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
+                               unsigned SectionID, StringRef SectionName,
+                               bool IsReadOnly) override {
     return ClientMM->allocateDataSection(Size, Alignment,
                                          SectionID, SectionName, IsReadOnly);
   }
 
-  virtual void notifyObjectLoaded(ExecutionEngine *EE,
-                                  const ObjectImage *Obj) {
+  void reserveAllocationSpace(uintptr_t CodeSize, uintptr_t DataSizeRO,
+                              uintptr_t DataSizeRW) override {
+    return ClientMM->reserveAllocationSpace(CodeSize, DataSizeRO, DataSizeRW);
+  }
+
+  bool needsToReserveAllocationSpace() override {
+    return ClientMM->needsToReserveAllocationSpace();
+  }
+
+  void notifyObjectLoaded(ExecutionEngine *EE,
+                          const ObjectImage *Obj) override {
     ClientMM->notifyObjectLoaded(EE, Obj);
   }
 
-  virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) {
+  void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
+                        size_t Size) override {
     ClientMM->registerEHFrames(Addr, LoadAddr, Size);
   }
 
-  virtual void deregisterEHFrames(uint8_t *Addr,
-                                  uint64_t LoadAddr,
-                                  size_t Size) {
+  void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr,
+                          size_t Size) override {
     ClientMM->deregisterEHFrames(Addr, LoadAddr, Size);
   }
 
-  virtual bool finalizeMemory(std::string *ErrMsg = 0) {
+  bool finalizeMemory(std::string *ErrMsg = nullptr) override {
     return ClientMM->finalizeMemory(ErrMsg);
   }
 
 private:
   MCJIT *ParentEngine;
-  OwningPtr<RTDyldMemoryManager> ClientMM;
+  std::unique_ptr<RTDyldMemoryManager> ClientMM;
 };
 
-// About Module states:
+// About Module states: added->loaded->finalized.
 //
 // The purpose of the "added" state is having modules in standby. (added=known
 // but not compiled). The idea is that you can add a module to provide function
 // definitions but if nothing in that module is referenced by a module in which
-// a function is executed (note the wording here because it\92s not exactly the
+// a function is executed (note the wording here because it's not exactly the
 // ideal case) then the module never gets compiled. This is sort of lazy
 // compilation.
 //
@@ -94,27 +104,108 @@ class MCJIT : public ExecutionEngine {
   MCJIT(Module *M, TargetMachine *tm, RTDyldMemoryManager *MemMgr,
         bool AllocateGVsWithCode);
 
-  enum ModuleState {
-    ModuleAdded,
-    ModuleEmitted,
-    ModuleLoading,
-    ModuleLoaded,
-    ModuleFinalizing,
-    ModuleFinalized
-  };
+  typedef llvm::SmallPtrSet<Module *, 4> ModulePtrSet;
 
-  class MCJITModuleState {
+  class OwningModuleContainer {
   public:
-    MCJITModuleState() : State(ModuleAdded) {}
-
-    MCJITModuleState & operator=(ModuleState s) { State = s; return *this; }
-    bool hasBeenEmitted() { return State != ModuleAdded; }
-    bool hasBeenLoaded() { return State != ModuleAdded &&
-                                  State != ModuleEmitted; }
-    bool hasBeenFinalized() { return State == ModuleFinalized; }
+    OwningModuleContainer() {
+    }
+    ~OwningModuleContainer() {
+      freeModulePtrSet(AddedModules);
+      freeModulePtrSet(LoadedModules);
+      freeModulePtrSet(FinalizedModules);
+    }
+
+    ModulePtrSet::iterator begin_added() { return AddedModules.begin(); }
+    ModulePtrSet::iterator end_added() { return AddedModules.end(); }
+
+    ModulePtrSet::iterator begin_loaded() { return LoadedModules.begin(); }
+    ModulePtrSet::iterator end_loaded() { return LoadedModules.end(); }
+
+    ModulePtrSet::iterator begin_finalized() { return FinalizedModules.begin(); }
+    ModulePtrSet::iterator end_finalized() { return FinalizedModules.end(); }
+
+    void addModule(Module *M) {
+      AddedModules.insert(M);
+    }
+
+    bool removeModule(Module *M) {
+      return AddedModules.erase(M) || LoadedModules.erase(M) ||
+             FinalizedModules.erase(M);
+    }
+
+    bool hasModuleBeenAddedButNotLoaded(Module *M) {
+      return AddedModules.count(M) != 0;
+    }
+
+    bool hasModuleBeenLoaded(Module *M) {
+      // If the module is in either the "loaded" or "finalized" sections it
+      // has been loaded.
+      return (LoadedModules.count(M) != 0 ) || (FinalizedModules.count(M) != 0);
+    }
+
+    bool hasModuleBeenFinalized(Module *M) {
+      return FinalizedModules.count(M) != 0;
+    }
+
+    bool ownsModule(Module* M) {
+      return (AddedModules.count(M) != 0) || (LoadedModules.count(M) != 0) ||
+             (FinalizedModules.count(M) != 0);
+    }
+
+    void markModuleAsLoaded(Module *M) {
+      // This checks against logic errors in the MCJIT implementation.
+      // This function should never be called with either a Module that MCJIT
+      // does not own or a Module that has already been loaded and/or finalized.
+      assert(AddedModules.count(M) &&
+             "markModuleAsLoaded: Module not found in AddedModules");
+
+      // Remove the module from the "Added" set.
+      AddedModules.erase(M);
+
+      // Add the Module to the "Loaded" set.
+      LoadedModules.insert(M);
+    }
+
+    void markModuleAsFinalized(Module *M) {
+      // This checks against logic errors in the MCJIT implementation.
+      // This function should never be called with either a Module that MCJIT
+      // does not own, a Module that has not been loaded or a Module that has
+      // already been finalized.
+      assert(LoadedModules.count(M) &&
+             "markModuleAsFinalized: Module not found in LoadedModules");
+
+      // Remove the module from the "Loaded" section of the list.
+      LoadedModules.erase(M);
+
+      // Add the Module to the "Finalized" section of the list by inserting it
+      // before the 'end' iterator.
+      FinalizedModules.insert(M);
+    }
+
+    void markAllLoadedModulesAsFinalized() {
+      for (ModulePtrSet::iterator I = LoadedModules.begin(),
+                                  E = LoadedModules.end();
+           I != E; ++I) {
+        Module *M = *I;
+        FinalizedModules.insert(M);
+      }
+      LoadedModules.clear();
+    }
 
   private:
-    ModuleState State;
+    ModulePtrSet AddedModules;
+    ModulePtrSet LoadedModules;
+    ModulePtrSet FinalizedModules;
+
+    void freeModulePtrSet(ModulePtrSet& MPS) {
+      // Go through the module set and delete everything.
+      for (ModulePtrSet::iterator I = MPS.begin(), E = MPS.end(); I != E; ++I) {
+        Module *M = *I;
+        delete M;
+      }
+      MPS.clear();
+    }
   };
 
   TargetMachine *TM;
@@ -123,27 +214,48 @@ class MCJIT : public ExecutionEngine {
   RuntimeDyld Dyld;
   SmallVector<JITEventListener*, 2> EventListeners;
 
-  typedef DenseMap<Module *, MCJITModuleState> ModuleStateMap;
-  ModuleStateMap  ModuleStates;
+  OwningModuleContainer OwnedModules;
+
+  SmallVector<object::Archive*, 2> Archives;
 
-  typedef DenseMap<Module *, ObjectImage *> LoadedObjectMap;
-  LoadedObjectMap  LoadedObjects;
+  typedef SmallVector<ObjectImage *, 2> LoadedObjectList;
+  LoadedObjectList  LoadedObjects;
 
   // An optional ObjectCache to be notified of compiled objects and used to
   // perform lookup of pre-compiled code to avoid re-compilation.
   ObjectCache *ObjCache;
 
+  Function *FindFunctionNamedInModulePtrSet(const char *FnName,
+                                            ModulePtrSet::iterator I,
+                                            ModulePtrSet::iterator E);
+
+  void runStaticConstructorsDestructorsInModulePtrSet(bool isDtors,
+                                                      ModulePtrSet::iterator I,
+                                                      ModulePtrSet::iterator E);
+
 public:
   ~MCJIT();
 
   /// @name ExecutionEngine interface implementation
   /// @{
-  virtual void addModule(Module *M);
+  void addModule(Module *M) override;
+  void addObjectFile(object::ObjectFile *O) override;
+  void addArchive(object::Archive *O) override;
+  bool removeModule(Module *M) override;
+
+  /// FindFunctionNamed - Search all of the active modules to find the one that
+  /// defines FnName.  This is very slow operation and shouldn't be used for
+  /// general code.
+  Function *FindFunctionNamed(const char *FnName) override;
 
   /// Sets the object manager that MCJIT should use to avoid compilation.
-  virtual void setObjectCache(ObjectCache *manager);
+  void setObjectCache(ObjectCache *manager) override;
+
+  void setProcessAllSections(bool ProcessAllSections) override {
+    Dyld.setProcessAllSections(ProcessAllSections);
+  }
 
-  virtual void generateCodeForModule(Module *M);
+  void generateCodeForModule(Module *M) override;
 
   /// finalizeObject - ensure the module is fully processed and is usable.
   ///
@@ -154,20 +266,26 @@ public:
   /// object.
   /// Is it OK to finalize a set of modules, add modules and finalize again.
   // FIXME: Do we really need both of these?
-  virtual void finalizeObject();
+  void finalizeObject() override;
   virtual void finalizeModule(Module *);
   void finalizeLoadedModules();
 
-  virtual void *getPointerToBasicBlock(BasicBlock *BB);
+  /// runStaticConstructorsDestructors - This method is used to execute all of
+  /// the static constructors or destructors for a program.
+  ///
+  /// \param isDtors - Run the destructors instead of constructors.
+  void runStaticConstructorsDestructors(bool isDtors) override;
+
+  void *getPointerToBasicBlock(BasicBlock *BB) override;
 
-  virtual void *getPointerToFunction(Function *F);
+  void *getPointerToFunction(Function *F) override;
 
-  virtual void *recompileAndRelinkFunction(Function *F);
+  void *recompileAndRelinkFunction(Function *F) override;
 
-  virtual void freeMachineCodeForFunction(Function *F);
+  void freeMachineCodeForFunction(Function *F) override;
 
-  virtual GenericValue runFunction(Function *F,
-                                   const std::vector<GenericValue> &ArgValues);
+  GenericValue runFunction(Function *F,
+                           const std::vector<GenericValue> &ArgValues) override;
 
   /// getPointerToNamedFunction - This method returns the address of the
   /// specified function by using the dlsym function call.  As such it is only
@@ -177,25 +295,27 @@ public:
   /// found, this function silently returns a null pointer. Otherwise,
   /// it prints a message to stderr and aborts.
   ///
-  virtual void *getPointerToNamedFunction(const std::string &Name,
-                                          bool AbortOnFailure = true);
+  void *getPointerToNamedFunction(const std::string &Name,
+                                  bool AbortOnFailure = true) override;
 
   /// mapSectionAddress - map a section to its target address space value.
   /// Map the address of a JIT section as returned from the memory manager
   /// to the address in the target process as the running code will see it.
   /// This is the address which will be used for relocation resolution.
-  virtual void mapSectionAddress(const void *LocalAddress,
-                                 uint64_t TargetAddress) {
+  void mapSectionAddress(const void *LocalAddress,
+                         uint64_t TargetAddress) override {
     Dyld.mapSectionAddress(LocalAddress, TargetAddress);
   }
-  virtual void RegisterJITEventListener(JITEventListener *L);
-  virtual void UnregisterJITEventListener(JITEventListener *L);
+  void RegisterJITEventListener(JITEventListener *L) override;
+  void UnregisterJITEventListener(JITEventListener *L) override;
 
   // If successful, these function will implicitly finalize all loaded objects.
   // To get a function address within MCJIT without causing a finalize, use
   // getSymbolAddress.
-  virtual uint64_t getGlobalValueAddress(const std::string &Name);
-  virtual uint64_t getFunctionAddress(const std::string &Name);
+  uint64_t getGlobalValueAddress(const std::string &Name) override;
+  uint64_t getFunctionAddress(const std::string &Name) override;
+
+  TargetMachine *getTargetMachine() override { return TM; }
 
   /// @}
   /// @name (Private) Registration Interfaces
@@ -222,7 +342,7 @@ protected:
   /// emitObject -- Generate a JITed object in memory from the specified module
   /// Currently, MCJIT only supports a single module and the module passed to
   /// this function call is expected to be the contained module.  The module
-  /// is passed as a parameter here to prepare for multiple module support in 
+  /// is passed as a parameter here to prepare for multiple module support in
   /// the future.
   ObjectBufferStream* emitObject(Module *M);