[Orc] Move Orc code into a namespace (llvm::orc), update Kaleidoscope code.
[oota-llvm.git] / include / llvm / ExecutionEngine / Orc / ObjectLinkingLayer.h
1 //===- ObjectLinkingLayer.h - Add object files to a JIT process -*- 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 // Contains the definition for the object layer of the JIT.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_EXECUTIONENGINE_ORC_OBJECTLINKINGLAYER_H
15 #define LLVM_EXECUTIONENGINE_ORC_OBJECTLINKINGLAYER_H
16
17 #include "JITSymbol.h"
18 #include "LookasideRTDyldMM.h"
19 #include "llvm/ExecutionEngine/ExecutionEngine.h"
20 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
21 #include <list>
22 #include <memory>
23
24 namespace llvm {
25 namespace orc {
26
27 class ObjectLinkingLayerBase {
28 protected:
29
30   /// @brief Holds a set of objects to be allocated/linked as a unit in the JIT.
31   ///
32   /// An instance of this class will be created for each set of objects added
33   /// via JITObjectLayer::addObjectSet. Deleting the instance (via
34   /// removeObjectSet) frees its memory, removing all symbol definitions that
35   /// had been provided by this instance. Higher level layers are responsible
36   /// for taking any action required to handle the missing symbols.
37   class LinkedObjectSet {
38     LinkedObjectSet(const LinkedObjectSet&) = delete;
39     void operator=(const LinkedObjectSet&) = delete;
40   public:
41     LinkedObjectSet(std::unique_ptr<RTDyldMemoryManager> MM)
42         : MM(std::move(MM)), RTDyld(llvm::make_unique<RuntimeDyld>(&*this->MM)),
43           State(Raw) {}
44
45     // MSVC 2012 cannot infer a move constructor, so write it out longhand.
46     LinkedObjectSet(LinkedObjectSet &&O)
47         : MM(std::move(O.MM)), RTDyld(std::move(O.RTDyld)), State(O.State) {}
48
49     std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
50     addObject(const object::ObjectFile &Obj) {
51       return RTDyld->loadObject(Obj);
52     }
53
54     TargetAddress getSymbolAddress(StringRef Name, bool ExportedSymbolsOnly) {
55       if (ExportedSymbolsOnly)
56         return RTDyld->getExportedSymbolLoadAddress(Name);
57       return RTDyld->getSymbolLoadAddress(Name);
58     }
59
60     bool NeedsFinalization() const { return (State == Raw); }
61
62     void Finalize() {
63       State = Finalizing;
64       RTDyld->resolveRelocations();
65       RTDyld->registerEHFrames();
66       MM->finalizeMemory();
67       OwnedBuffers.clear();
68       State = Finalized;
69     }
70
71     void mapSectionAddress(const void *LocalAddress, TargetAddress TargetAddr) {
72       assert((State != Finalized) &&
73              "Attempting to remap sections for finalized objects.");
74       RTDyld->mapSectionAddress(LocalAddress, TargetAddr);
75     }
76
77     void takeOwnershipOfBuffer(std::unique_ptr<MemoryBuffer> B) {
78       OwnedBuffers.push_back(std::move(B));
79     }
80
81   private:
82     std::unique_ptr<RTDyldMemoryManager> MM;
83     std::unique_ptr<RuntimeDyld> RTDyld;
84     enum { Raw, Finalizing, Finalized } State;
85
86     // FIXME: This ownership hack only exists because RuntimeDyldELF still
87     //        wants to be able to inspect the original object when resolving
88     //        relocations. As soon as that can be fixed this should be removed.
89     std::vector<std::unique_ptr<MemoryBuffer>> OwnedBuffers;
90   };
91
92   typedef std::list<LinkedObjectSet> LinkedObjectSetListT;
93
94 public:
95   /// @brief Handle to a set of loaded objects.
96   typedef LinkedObjectSetListT::iterator ObjSetHandleT;
97
98   // Ownership hack.
99   // FIXME: Remove this as soon as RuntimeDyldELF can apply relocations without
100   //        referencing the original object.
101   template <typename OwningMBSet>
102   void takeOwnershipOfBuffers(ObjSetHandleT H, OwningMBSet MBs) {
103     for (auto &MB : MBs)
104       H->takeOwnershipOfBuffer(std::move(MB));
105   }
106
107 };
108
109 /// @brief Default (no-op) action to perform when loading objects.
110 class DoNothingOnNotifyLoaded {
111 public:
112   template <typename ObjSetT, typename LoadResult>
113   void operator()(ObjectLinkingLayerBase::ObjSetHandleT, const ObjSetT &,
114                   const LoadResult &) {}
115 };
116
117 /// @brief Bare bones object linking layer.
118 ///
119 ///   This class is intended to be used as the base layer for a JIT. It allows
120 /// object files to be loaded into memory, linked, and the addresses of their
121 /// symbols queried. All objects added to this layer can see each other's
122 /// symbols.
123 template <typename NotifyLoadedFtor = DoNothingOnNotifyLoaded>
124 class ObjectLinkingLayer : public ObjectLinkingLayerBase {
125 public:
126
127   /// @brief LoadedObjectInfo list. Contains a list of owning pointers to
128   ///        RuntimeDyld::LoadedObjectInfo instances.
129   typedef std::vector<std::unique_ptr<RuntimeDyld::LoadedObjectInfo>>
130       LoadedObjInfoList;
131
132   /// @brief Functor to create RTDyldMemoryManager instances.
133   typedef std::function<std::unique_ptr<RTDyldMemoryManager>()> CreateRTDyldMMFtor;
134
135   /// @brief Functor for receiving finalization notifications.
136   typedef std::function<void(ObjSetHandleT)> NotifyFinalizedFtor;
137
138   /// @brief Construct an ObjectLinkingLayer with the given NotifyLoaded,
139   ///        NotifyFinalized and CreateMemoryManager functors.
140   ObjectLinkingLayer(
141       CreateRTDyldMMFtor CreateMemoryManager = CreateRTDyldMMFtor(),
142       NotifyLoadedFtor NotifyLoaded = NotifyLoadedFtor(),
143       NotifyFinalizedFtor NotifyFinalized = NotifyFinalizedFtor())
144       : NotifyLoaded(std::move(NotifyLoaded)),
145         NotifyFinalized(std::move(NotifyFinalized)),
146         CreateMemoryManager(std::move(CreateMemoryManager)) {}
147
148   /// @brief Add a set of objects (or archives) that will be treated as a unit
149   ///        for the purposes of symbol lookup and memory management.
150   ///
151   /// @return A pair containing (1) A handle that can be used to free the memory
152   ///         allocated for the objects, and (2) a LoadedObjInfoList containing
153   ///         one LoadedObjInfo instance for each object at the corresponding
154   ///         index in the Objects list.
155   ///
156   ///   This version of this method allows the client to pass in an
157   /// RTDyldMemoryManager instance that will be used to allocate memory and look
158   /// up external symbol addresses for the given objects.
159   template <typename ObjSetT>
160   ObjSetHandleT addObjectSet(const ObjSetT &Objects,
161                              std::unique_ptr<RTDyldMemoryManager> MM) {
162
163     if (!MM) {
164       assert(CreateMemoryManager &&
165              "No memory manager or memory manager creator provided.");
166       MM = CreateMemoryManager();
167     }
168
169     ObjSetHandleT Handle = LinkedObjSetList.insert(
170         LinkedObjSetList.end(), LinkedObjectSet(std::move(MM)));
171     LinkedObjectSet &LOS = *Handle;
172     LoadedObjInfoList LoadedObjInfos;
173
174     for (auto &Obj : Objects)
175       LoadedObjInfos.push_back(LOS.addObject(*Obj));
176
177     NotifyLoaded(Handle, Objects, LoadedObjInfos);
178
179     return Handle;
180   }
181
182   /// @brief Remove the set of objects associated with handle H.
183   ///
184   ///   All memory allocated for the objects will be freed, and the sections and
185   /// symbols they provided will no longer be available. No attempt is made to
186   /// re-emit the missing symbols, and any use of these symbols (directly or
187   /// indirectly) will result in undefined behavior. If dependence tracking is
188   /// required to detect or resolve such issues it should be added at a higher
189   /// layer.
190   void removeObjectSet(ObjSetHandleT H) {
191     // How do we invalidate the symbols in H?
192     LinkedObjSetList.erase(H);
193   }
194
195   /// @brief Search for the given named symbol.
196   /// @param Name The name of the symbol to search for.
197   /// @param ExportedSymbolsOnly If true, search only for exported symbols.
198   /// @return A handle for the given named symbol, if it exists.
199   JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly) {
200     for (auto I = LinkedObjSetList.begin(), E = LinkedObjSetList.end(); I != E;
201          ++I)
202       if (auto Symbol = findSymbolIn(I, Name, ExportedSymbolsOnly))
203         return Symbol;
204
205     return nullptr;
206   }
207
208   /// @brief Search for the given named symbol in the context of the set of
209   ///        loaded objects represented by the handle H.
210   /// @param H The handle for the object set to search in.
211   /// @param Name The name of the symbol to search for.
212   /// @param ExportedSymbolsOnly If true, search only for exported symbols.
213   /// @return A handle for the given named symbol, if it is found in the
214   ///         given object set.
215   JITSymbol findSymbolIn(ObjSetHandleT H, StringRef Name,
216                          bool ExportedSymbolsOnly) {
217     if (auto Addr = H->getSymbolAddress(Name, ExportedSymbolsOnly)) {
218       if (!H->NeedsFinalization()) {
219         // If this instance has already been finalized then we can just return
220         // the address.
221         return JITSymbol(Addr);
222       } else {
223         // If this instance needs finalization return a functor that will do it.
224         // The functor still needs to double-check whether finalization is
225         // required, in case someone else finalizes this set before the functor
226         // is called.
227         return JITSymbol(
228           [this, Addr, H]() {
229             if (H->NeedsFinalization()) {
230               H->Finalize();
231               if (NotifyFinalized)
232                 NotifyFinalized(H);
233             }
234             return Addr;
235           });
236       }
237     }
238
239     return nullptr;
240   }
241
242   /// @brief Map section addresses for the objects associated with the handle H.
243   void mapSectionAddress(ObjSetHandleT H, const void *LocalAddress,
244                          TargetAddress TargetAddr) {
245     H->mapSectionAddress(LocalAddress, TargetAddr);
246   }
247
248   /// @brief Immediately emit and finalize the object set represented by the
249   ///        given handle.
250   /// @param H Handle for object set to emit/finalize.
251   void emitAndFinalize(ObjSetHandleT H) {
252     H->Finalize();
253     if (NotifyFinalized)
254       NotifyFinalized(H);
255   }
256
257 private:
258   LinkedObjectSetListT LinkedObjSetList;
259   NotifyLoadedFtor NotifyLoaded;
260   NotifyFinalizedFtor NotifyFinalized;
261   CreateRTDyldMMFtor CreateMemoryManager;
262 };
263
264 } // End namespace orc.
265 } // End namespace llvm
266
267 #endif // LLVM_EXECUTIONENGINE_ORC_OBJECTLINKINGLAYER_H