1 //===--- ModuleManager.cpp - Module Manager ---------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ModuleManager class, which manages a set of loaded
11 // modules for the ASTReader.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_SERIALIZATION_MODULEMANAGER_H
16 #define LLVM_CLANG_SERIALIZATION_MODULEMANAGER_H
18 #include "clang/Basic/FileManager.h"
19 #include "clang/Serialization/Module.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallPtrSet.h"
25 class GlobalModuleIndex;
28 namespace serialization {
30 /// \brief Manages the set of modules loaded by an AST reader.
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;
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;
40 /// \brief All loaded modules, indexed by name.
41 llvm::DenseMap<const FileEntry *, ModuleFile *> Modules;
43 typedef llvm::SetVector<const FileEntry *> AdditionalKnownModuleFileSet;
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;
49 /// \brief FileManager that handles translating between filenames and
53 /// \brief A lookup of in-memory (virtual file) buffers
54 llvm::DenseMap<const FileEntry *, std::unique_ptr<llvm::MemoryBuffer>>
57 /// \brief The visitation order.
58 SmallVector<ModuleFile *, 4> VisitOrder;
60 /// \brief The list of module files that both we and the global module index
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;
70 /// \brief The global module index, if one is attached.
72 /// The global module index will actually be owned by the ASTReader; this is
73 /// just an non-owning pointer.
74 GlobalModuleIndex *GlobalIndex;
76 /// \brief State used by the "visit" operation to avoid malloc traffic in
79 explicit VisitState(unsigned N)
80 : VisitNumber(N, 0), NextVisitNumber(1), NextState(nullptr)
89 /// \brief The stack used when marking the imports of a particular module
90 /// as not-to-be-visited.
91 SmallVector<ModuleFile *, 4> Stack;
93 /// \brief The visit number of each module file, which indicates when
94 /// this module file was last visited.
95 SmallVector<unsigned, 4> VisitNumber;
97 /// \brief The next visit number to use to mark visited module files.
98 unsigned NextVisitNumber;
100 /// \brief The next visit state.
101 VisitState *NextState;
104 /// \brief The first visit() state in the chain.
105 VisitState *FirstVisitState;
107 VisitState *allocateVisitState();
108 void returnVisitState(VisitState *State);
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;
116 explicit ModuleManager(FileManager &FileMgr);
119 /// \brief Forward iterator to traverse all loaded modules. This is reverse
121 ModuleIterator begin() { return Chain.begin(); }
122 /// \brief Forward iterator end-point to traverse all loaded modules
123 ModuleIterator end() { return Chain.end(); }
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(); }
131 /// \brief Reverse iterator to traverse all loaded modules. This is in
133 ModuleReverseIterator rbegin() { return Chain.rbegin(); }
134 /// \brief Reverse iterator end-point to traverse all loaded modules.
135 ModuleReverseIterator rend() { return Chain.rend(); }
137 /// \brief Returns the primary module associated with the manager, that is,
138 /// the first module loaded
139 ModuleFile &getPrimaryModule() { return *Chain[0]; }
141 /// \brief Returns the primary module associated with the manager, that is,
142 /// the first module loaded.
143 ModuleFile &getPrimaryModule() const { return *Chain[0]; }
145 /// \brief Returns the module associated with the given index
146 ModuleFile &operator[](unsigned Index) const { return *Chain[Index]; }
148 /// \brief Returns the module associated with the given name
149 ModuleFile *lookup(StringRef Name);
151 /// \brief Returns the module associated with the given module file.
152 ModuleFile *lookup(const FileEntry *File);
154 /// \brief Returns the in-memory (virtual file) buffer with the given name
155 std::unique_ptr<llvm::MemoryBuffer> lookupBuffer(StringRef Name);
157 /// \brief Number of modules loaded
158 unsigned size() const { return Chain.size(); }
160 /// \brief The result of attempting to add a new module.
161 enum AddModuleResult {
162 /// \brief The module file had already been loaded.
164 /// \brief The module file was just loaded in response to this call.
166 /// \brief The module file is missing.
168 /// \brief The module file is out-of-date.
172 typedef ASTFileSignature(*ASTFileSignatureReader)(llvm::BitstreamReader &);
174 /// \brief Attempts to create a new module and add it to the list of known
177 /// \param FileName The file name of the module to be loaded.
179 /// \param Type The kind of module being loaded.
181 /// \param ImportLoc The location at which the module is imported.
183 /// \param ImportedBy The module that is importing this module, or NULL if
184 /// this module is imported directly by the user.
186 /// \param Generation The generation in which this module was loaded.
188 /// \param ExpectedSize The expected size of the module file, used for
189 /// validation. This will be zero if unknown.
191 /// \param ExpectedModTime The expected modification time of the module
192 /// file, used for validation. This will be zero if unknown.
194 /// \param ExpectedSignature The expected signature of the module file, used
195 /// for validation. This will be zero if unknown.
197 /// \param ReadSignature Reads the signature from an AST file without actually
200 /// \param Module A pointer to the module file if the module was successfully
203 /// \param ErrorStr Will be set to a non-empty string if any errors occurred
204 /// while trying to load the module.
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,
215 std::string &ErrorStr);
217 /// \brief Remove the given set of modules.
218 void removeModules(ModuleIterator first, ModuleIterator last,
219 llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
222 /// \brief Add an in-memory buffer the list of known buffers
223 void addInMemoryBuffer(StringRef FileName,
224 std::unique_ptr<llvm::MemoryBuffer> Buffer);
226 /// \brief Set the global module index.
227 void setGlobalIndex(GlobalModuleIndex *Index);
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);
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);
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());
246 /// \brief Visit each of the modules.
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.
253 /// This traversal is intended to support various "lookup"
254 /// operations that can find data in any of the loaded modules.
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.
262 /// \param UserData User data associated with the visitor object, which
263 /// will be passed along to the visitor.
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);
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.
279 /// \brief Visit each of the modules with a depth-first traversal.
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).
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.
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.
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,
299 bool (*PostorderVisitor)(ModuleFile &M, void *UserData),
302 /// \brief Attempt to resolve the given module file name to a file entry.
304 /// \param FileName The name of the module file.
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.
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.
313 /// \param File Will be set to the file if there is one, or null
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,
321 time_t ExpectedModTime,
322 const FileEntry *&File);
324 /// \brief View the graphviz representation of the module graph.
328 } } // end namespace clang::serialization