]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Serialization/ModuleManager.h
Merge ^/head r284188 through r284643.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / Serialization / ModuleManager.h
1 //===--- ModuleManager.cpp - Module Manager ---------------------*- 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 //  This file defines the ModuleManager class, which manages a set of loaded
11 //  modules for the ASTReader.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CLANG_SERIALIZATION_MODULEMANAGER_H
16 #define LLVM_CLANG_SERIALIZATION_MODULEMANAGER_H
17
18 #include "clang/Basic/FileManager.h"
19 #include "clang/Serialization/Module.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22
23 namespace clang { 
24
25 class GlobalModuleIndex;
26 class ModuleMap;
27
28 namespace serialization {
29
30 /// \brief Manages the set of modules loaded by an AST reader.
31 class ModuleManager {
32   /// \brief The chain of AST files. The first entry is the one named by the
33   /// user, the last one is the one that doesn't depend on anything further.
34   SmallVector<ModuleFile *, 2> Chain;
35
36   // \brief The roots of the dependency DAG of AST files. This is used
37   // to implement short-circuiting logic when running DFS over the dependencies.
38   SmallVector<ModuleFile *, 2> Roots;
39   
40   /// \brief All loaded modules, indexed by name.
41   llvm::DenseMap<const FileEntry *, ModuleFile *> Modules;
42
43   typedef llvm::SetVector<const FileEntry *> AdditionalKnownModuleFileSet;
44
45   /// \brief Additional module files that are known but not loaded. Tracked
46   /// here so that we can re-export them if necessary.
47   AdditionalKnownModuleFileSet AdditionalKnownModuleFiles;
48
49   /// \brief FileManager that handles translating between filenames and
50   /// FileEntry *.
51   FileManager &FileMgr;
52   
53   /// \brief A lookup of in-memory (virtual file) buffers
54   llvm::DenseMap<const FileEntry *, std::unique_ptr<llvm::MemoryBuffer>>
55       InMemoryBuffers;
56
57   /// \brief The visitation order.
58   SmallVector<ModuleFile *, 4> VisitOrder;
59       
60   /// \brief The list of module files that both we and the global module index
61   /// know about.
62   ///
63   /// Either the global index or the module manager may have modules that the
64   /// other does not know about, because the global index can be out-of-date
65   /// (in which case the module manager could have modules it does not) and
66   /// this particular translation unit might not have loaded all of the modules
67   /// known to the global index.
68   SmallVector<ModuleFile *, 4> ModulesInCommonWithGlobalIndex;
69
70   /// \brief The global module index, if one is attached.
71   ///
72   /// The global module index will actually be owned by the ASTReader; this is
73   /// just an non-owning pointer.
74   GlobalModuleIndex *GlobalIndex;
75
76   /// \brief State used by the "visit" operation to avoid malloc traffic in
77   /// calls to visit().
78   struct VisitState {
79     explicit VisitState(unsigned N)
80       : VisitNumber(N, 0), NextVisitNumber(1), NextState(nullptr)
81     {
82       Stack.reserve(N);
83     }
84
85     ~VisitState() {
86       delete NextState;
87     }
88
89     /// \brief The stack used when marking the imports of a particular module
90     /// as not-to-be-visited.
91     SmallVector<ModuleFile *, 4> Stack;
92
93     /// \brief The visit number of each module file, which indicates when
94     /// this module file was last visited.
95     SmallVector<unsigned, 4> VisitNumber;
96
97     /// \brief The next visit number to use to mark visited module files.
98     unsigned NextVisitNumber;
99
100     /// \brief The next visit state.
101     VisitState *NextState;
102   };
103
104   /// \brief The first visit() state in the chain.
105   VisitState *FirstVisitState;
106
107   VisitState *allocateVisitState();
108   void returnVisitState(VisitState *State);
109
110 public:
111   typedef SmallVectorImpl<ModuleFile*>::iterator ModuleIterator;
112   typedef SmallVectorImpl<ModuleFile*>::const_iterator ModuleConstIterator;
113   typedef SmallVectorImpl<ModuleFile*>::reverse_iterator ModuleReverseIterator;
114   typedef std::pair<uint32_t, StringRef> ModuleOffset;
115   
116   explicit ModuleManager(FileManager &FileMgr);
117   ~ModuleManager();
118   
119   /// \brief Forward iterator to traverse all loaded modules.  This is reverse
120   /// source-order.
121   ModuleIterator begin() { return Chain.begin(); }
122   /// \brief Forward iterator end-point to traverse all loaded modules
123   ModuleIterator end() { return Chain.end(); }
124   
125   /// \brief Const forward iterator to traverse all loaded modules.  This is 
126   /// in reverse source-order.
127   ModuleConstIterator begin() const { return Chain.begin(); }
128   /// \brief Const forward iterator end-point to traverse all loaded modules
129   ModuleConstIterator end() const { return Chain.end(); }
130   
131   /// \brief Reverse iterator to traverse all loaded modules.  This is in 
132   /// source order.
133   ModuleReverseIterator rbegin() { return Chain.rbegin(); }
134   /// \brief Reverse iterator end-point to traverse all loaded modules.
135   ModuleReverseIterator rend() { return Chain.rend(); }
136   
137   /// \brief Returns the primary module associated with the manager, that is,
138   /// the first module loaded
139   ModuleFile &getPrimaryModule() { return *Chain[0]; }
140   
141   /// \brief Returns the primary module associated with the manager, that is,
142   /// the first module loaded.
143   ModuleFile &getPrimaryModule() const { return *Chain[0]; }
144   
145   /// \brief Returns the module associated with the given index
146   ModuleFile &operator[](unsigned Index) const { return *Chain[Index]; }
147   
148   /// \brief Returns the module associated with the given name
149   ModuleFile *lookup(StringRef Name);
150
151   /// \brief Returns the module associated with the given module file.
152   ModuleFile *lookup(const FileEntry *File);
153
154   /// \brief Returns the in-memory (virtual file) buffer with the given name
155   std::unique_ptr<llvm::MemoryBuffer> lookupBuffer(StringRef Name);
156   
157   /// \brief Number of modules loaded
158   unsigned size() const { return Chain.size(); }
159
160   /// \brief The result of attempting to add a new module.
161   enum AddModuleResult {
162     /// \brief The module file had already been loaded.
163     AlreadyLoaded,
164     /// \brief The module file was just loaded in response to this call.
165     NewlyLoaded,
166     /// \brief The module file is missing.
167     Missing,
168     /// \brief The module file is out-of-date.
169     OutOfDate
170   };
171
172   typedef ASTFileSignature(*ASTFileSignatureReader)(llvm::BitstreamReader &);
173
174   /// \brief Attempts to create a new module and add it to the list of known
175   /// modules.
176   ///
177   /// \param FileName The file name of the module to be loaded.
178   ///
179   /// \param Type The kind of module being loaded.
180   ///
181   /// \param ImportLoc The location at which the module is imported.
182   ///
183   /// \param ImportedBy The module that is importing this module, or NULL if
184   /// this module is imported directly by the user.
185   ///
186   /// \param Generation The generation in which this module was loaded.
187   ///
188   /// \param ExpectedSize The expected size of the module file, used for
189   /// validation. This will be zero if unknown.
190   ///
191   /// \param ExpectedModTime The expected modification time of the module
192   /// file, used for validation. This will be zero if unknown.
193   ///
194   /// \param ExpectedSignature The expected signature of the module file, used
195   /// for validation. This will be zero if unknown.
196   ///
197   /// \param ReadSignature Reads the signature from an AST file without actually
198   /// loading it.
199   ///
200   /// \param Module A pointer to the module file if the module was successfully
201   /// loaded.
202   ///
203   /// \param ErrorStr Will be set to a non-empty string if any errors occurred
204   /// while trying to load the module.
205   ///
206   /// \return A pointer to the module that corresponds to this file name,
207   /// and a value indicating whether the module was loaded.
208   AddModuleResult addModule(StringRef FileName, ModuleKind Type,
209                             SourceLocation ImportLoc,
210                             ModuleFile *ImportedBy, unsigned Generation,
211                             off_t ExpectedSize, time_t ExpectedModTime,
212                             ASTFileSignature ExpectedSignature,
213                             ASTFileSignatureReader ReadSignature,
214                             ModuleFile *&Module,
215                             std::string &ErrorStr);
216
217   /// \brief Remove the given set of modules.
218   void removeModules(ModuleIterator first, ModuleIterator last,
219                      llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
220                      ModuleMap *modMap);
221
222   /// \brief Add an in-memory buffer the list of known buffers
223   void addInMemoryBuffer(StringRef FileName,
224                          std::unique_ptr<llvm::MemoryBuffer> Buffer);
225
226   /// \brief Set the global module index.
227   void setGlobalIndex(GlobalModuleIndex *Index);
228
229   /// \brief Notification from the AST reader that the given module file
230   /// has been "accepted", and will not (can not) be unloaded.
231   void moduleFileAccepted(ModuleFile *MF);
232
233   /// \brief Notification from the frontend that the given module file is
234   /// part of this compilation (even if not imported) and, if this compilation
235   /// is exported, should be made available to importers of it.
236   bool addKnownModuleFile(StringRef FileName);
237
238   /// \brief Get a list of additional module files that are not currently
239   /// loaded but are considered to be part of the current compilation.
240   llvm::iterator_range<AdditionalKnownModuleFileSet::const_iterator>
241   getAdditionalKnownModuleFiles() {
242     return llvm::make_range(AdditionalKnownModuleFiles.begin(),
243                             AdditionalKnownModuleFiles.end());
244   }
245
246   /// \brief Visit each of the modules.
247   ///
248   /// This routine visits each of the modules, starting with the
249   /// "root" modules that no other loaded modules depend on, and
250   /// proceeding to the leaf modules, visiting each module only once
251   /// during the traversal.
252   ///
253   /// This traversal is intended to support various "lookup"
254   /// operations that can find data in any of the loaded modules.
255   ///
256   /// \param Visitor A visitor function that will be invoked with each
257   /// module and the given user data pointer. The return value must be
258   /// convertible to bool; when false, the visitation continues to
259   /// modules that the current module depends on. When true, the
260   /// visitation skips any modules that the current module depends on.
261   ///
262   /// \param UserData User data associated with the visitor object, which
263   /// will be passed along to the visitor.
264   ///
265   /// \param ModuleFilesHit If non-NULL, contains the set of module files
266   /// that we know we need to visit because the global module index told us to.
267   /// Any module that is known to both the global module index and the module
268   /// manager that is *not* in this set can be skipped.
269   void visit(bool (*Visitor)(ModuleFile &M, void *UserData), void *UserData,
270              llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit = nullptr);
271
272   /// \brief Control DFS behavior during preorder visitation.
273   enum DFSPreorderControl {
274     Continue,    /// Continue visiting all nodes.
275     Abort,       /// Stop the visitation immediately.
276     SkipImports, /// Do not visit imports of the current node.
277   };
278
279   /// \brief Visit each of the modules with a depth-first traversal.
280   ///
281   /// This routine visits each of the modules known to the module
282   /// manager using a depth-first search, starting with the first
283   /// loaded module. The traversal invokes one callback before
284   /// traversing the imports (preorder traversal) and one after
285   /// traversing the imports (postorder traversal).
286   ///
287   /// \param PreorderVisitor A visitor function that will be invoked with each
288   /// module before visiting its imports. The visitor can control how to
289   /// continue the visitation through its return value.
290   ///
291   /// \param PostorderVisitor A visitor function taht will be invoked with each
292   /// module after visiting its imports. The visitor may return true at any time
293   /// to abort the depth-first visitation.
294   ///
295   /// \param UserData User data ssociated with the visitor object,
296   /// which will be passed along to the user.
297   void visitDepthFirst(DFSPreorderControl (*PreorderVisitor)(ModuleFile &M,
298                                                              void *UserData),
299                        bool (*PostorderVisitor)(ModuleFile &M, void *UserData),
300                        void *UserData);
301
302   /// \brief Attempt to resolve the given module file name to a file entry.
303   ///
304   /// \param FileName The name of the module file.
305   ///
306   /// \param ExpectedSize The size that the module file is expected to have.
307   /// If the actual size differs, the resolver should return \c true.
308   ///
309   /// \param ExpectedModTime The modification time that the module file is
310   /// expected to have. If the actual modification time differs, the resolver
311   /// should return \c true.
312   ///
313   /// \param File Will be set to the file if there is one, or null
314   /// otherwise.
315   ///
316   /// \returns True if a file exists but does not meet the size/
317   /// modification time criteria, false if the file is either available and
318   /// suitable, or is missing.
319   bool lookupModuleFile(StringRef FileName,
320                         off_t ExpectedSize,
321                         time_t ExpectedModTime,
322                         const FileEntry *&File);
323
324   /// \brief View the graphviz representation of the module graph.
325   void viewGraph();
326 };
327
328 } } // end namespace clang::serialization
329
330 #endif