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 //===----------------------------------------------------------------------===//
14 #include "clang/Serialization/ModuleManager.h"
15 #include "clang/Frontend/PCHContainerOperations.h"
16 #include "clang/Lex/HeaderSearch.h"
17 #include "clang/Lex/ModuleMap.h"
18 #include "clang/Serialization/GlobalModuleIndex.h"
19 #include "llvm/Support/MemoryBuffer.h"
20 #include "llvm/Support/Path.h"
21 #include <system_error>
24 #include "llvm/Support/GraphWriter.h"
27 using namespace clang;
28 using namespace serialization;
30 ModuleFile *ModuleManager::lookup(StringRef Name) {
31 const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
32 /*cacheFailure=*/false);
39 ModuleFile *ModuleManager::lookup(const FileEntry *File) {
40 llvm::DenseMap<const FileEntry *, ModuleFile *>::iterator Known
42 if (Known == Modules.end())
48 std::unique_ptr<llvm::MemoryBuffer>
49 ModuleManager::lookupBuffer(StringRef Name) {
50 const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
51 /*cacheFailure=*/false);
52 return std::move(InMemoryBuffers[Entry]);
55 ModuleManager::AddModuleResult
56 ModuleManager::addModule(StringRef FileName, ModuleKind Type,
57 SourceLocation ImportLoc, ModuleFile *ImportedBy,
59 off_t ExpectedSize, time_t ExpectedModTime,
60 ASTFileSignature ExpectedSignature,
61 ASTFileSignatureReader ReadSignature,
63 std::string &ErrorStr) {
66 // Look for the file entry. This only fails if the expected size or
67 // modification time differ.
68 const FileEntry *Entry;
69 if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {
70 // If we're not expecting to pull this file out of the module cache, it
71 // might have a different mtime due to being moved across filesystems in
72 // a distributed build. The size must still match, though. (As must the
73 // contents, but we can't check that.)
76 if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
77 ErrorStr = "module file out of date";
81 if (!Entry && FileName != "-") {
82 ErrorStr = "module file not found";
86 // Check whether we already loaded this module, before
87 ModuleFile *ModuleEntry = Modules[Entry];
88 bool NewModule = false;
90 // Allocate a new module.
92 ModuleEntry = new ModuleFile(Type, Generation);
93 ModuleEntry->Index = Chain.size();
94 ModuleEntry->FileName = FileName.str();
95 ModuleEntry->File = Entry;
96 ModuleEntry->ImportLoc = ImportLoc;
97 ModuleEntry->InputFilesValidationTimestamp = 0;
99 if (ModuleEntry->Kind == MK_ImplicitModule) {
100 std::string TimestampFilename = ModuleEntry->getTimestampFilename();
102 // A cached stat value would be fine as well.
103 if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
104 ModuleEntry->InputFilesValidationTimestamp =
105 llvm::sys::toTimeT(Status.getLastModificationTime());
108 // Load the contents of the module
109 if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
110 // The buffer was already provided for us.
111 ModuleEntry->Buffer = std::move(Buffer);
113 // Open the AST file.
114 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf(
115 (std::error_code()));
116 if (FileName == "-") {
117 Buf = llvm::MemoryBuffer::getSTDIN();
119 // Leave the FileEntry open so if it gets read again by another
120 // ModuleManager it must be the same underlying file.
121 // FIXME: Because FileManager::getFile() doesn't guarantee that it will
122 // give us an open file, this may not be 100% reliable.
123 Buf = FileMgr.getBufferForFile(ModuleEntry->File,
124 /*IsVolatile=*/false,
125 /*ShouldClose=*/false);
129 ErrorStr = Buf.getError().message();
134 ModuleEntry->Buffer = std::move(*Buf);
137 // Initialize the stream.
138 ModuleEntry->Data = PCHContainerRdr.ExtractPCH(*ModuleEntry->Buffer);
141 if (ExpectedSignature) {
142 // If we've not read the control block yet, read the signature eagerly now
143 // so that we can check it.
144 if (!ModuleEntry->Signature)
145 ModuleEntry->Signature = ReadSignature(ModuleEntry->Data);
147 if (ModuleEntry->Signature != ExpectedSignature) {
148 ErrorStr = ModuleEntry->Signature ? "signature mismatch"
149 : "could not read module signature";
158 ModuleEntry->ImportedBy.insert(ImportedBy);
159 ImportedBy->Imports.insert(ModuleEntry);
161 if (!ModuleEntry->DirectlyImported)
162 ModuleEntry->ImportLoc = ImportLoc;
164 ModuleEntry->DirectlyImported = true;
167 Module = ModuleEntry;
170 return AlreadyLoaded;
172 assert(!Modules[Entry] && "module loaded twice");
173 Modules[Entry] = ModuleEntry;
175 Chain.push_back(ModuleEntry);
176 if (!ModuleEntry->isModule())
177 PCHChain.push_back(ModuleEntry);
179 Roots.push_back(ModuleEntry);
184 void ModuleManager::removeModules(
185 ModuleIterator first, ModuleIterator last,
186 llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
191 // Explicitly clear VisitOrder since we might not notice it is stale.
194 // Collect the set of module file pointers that we'll be removing.
195 llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
197 auto IsVictim = [&](ModuleFile *MF) {
198 return victimSet.count(MF);
200 // Remove any references to the now-destroyed modules.
201 for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
202 Chain[i]->ImportedBy.remove_if(IsVictim);
204 Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),
207 // Remove the modules from the PCH chain.
208 for (auto I = first; I != last; ++I) {
209 if (!(*I)->isModule()) {
210 PCHChain.erase(std::find(PCHChain.begin(), PCHChain.end(), *I),
216 // Delete the modules and erase them from the various structures.
217 for (ModuleIterator victim = first; victim != last; ++victim) {
218 Modules.erase((*victim)->File);
221 StringRef ModuleName = (*victim)->ModuleName;
222 if (Module *mod = modMap->findModule(ModuleName)) {
223 mod->setASTFile(nullptr);
227 // Files that didn't make it through ReadASTCore successfully will be
228 // rebuilt (or there was an error). Invalidate them so that we can load the
229 // new files that will be renamed over the old ones.
230 if (LoadedSuccessfully.count(*victim) == 0)
231 FileMgr.invalidateCache((*victim)->File);
236 // Remove the modules from the chain.
237 Chain.erase(first, last);
241 ModuleManager::addInMemoryBuffer(StringRef FileName,
242 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
244 const FileEntry *Entry =
245 FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
246 InMemoryBuffers[Entry] = std::move(Buffer);
249 ModuleManager::VisitState *ModuleManager::allocateVisitState() {
250 // Fast path: if we have a cached state, use it.
251 if (FirstVisitState) {
252 VisitState *Result = FirstVisitState;
253 FirstVisitState = FirstVisitState->NextState;
254 Result->NextState = nullptr;
258 // Allocate and return a new state.
259 return new VisitState(size());
262 void ModuleManager::returnVisitState(VisitState *State) {
263 assert(State->NextState == nullptr && "Visited state is in list?");
264 State->NextState = FirstVisitState;
265 FirstVisitState = State;
268 void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
271 ModulesInCommonWithGlobalIndex.clear();
275 // Notify the global module index about all of the modules we've already
277 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
278 if (!GlobalIndex->loadedModuleFile(Chain[I])) {
279 ModulesInCommonWithGlobalIndex.push_back(Chain[I]);
284 void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
285 if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
288 ModulesInCommonWithGlobalIndex.push_back(MF);
291 ModuleManager::ModuleManager(FileManager &FileMgr,
292 const PCHContainerReader &PCHContainerRdr)
293 : FileMgr(FileMgr), PCHContainerRdr(PCHContainerRdr), GlobalIndex(),
294 FirstVisitState(nullptr) {}
296 ModuleManager::~ModuleManager() {
297 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
298 delete Chain[e - i - 1];
299 delete FirstVisitState;
302 void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
303 llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
304 // If the visitation order vector is the wrong size, recompute the order.
305 if (VisitOrder.size() != Chain.size()) {
308 VisitOrder.reserve(N);
310 // Record the number of incoming edges for each module. When we
311 // encounter a module with no incoming edges, push it into the queue
312 // to seed the queue.
313 SmallVector<ModuleFile *, 4> Queue;
315 llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
316 UnusedIncomingEdges.resize(size());
317 for (ModuleFile *M : llvm::reverse(*this)) {
318 unsigned Size = M->ImportedBy.size();
319 UnusedIncomingEdges[M->Index] = Size;
324 // Traverse the graph, making sure to visit a module before visiting any
325 // of its dependencies.
326 while (!Queue.empty()) {
327 ModuleFile *CurrentModule = Queue.pop_back_val();
328 VisitOrder.push_back(CurrentModule);
330 // For any module that this module depends on, push it on the
331 // stack (if it hasn't already been marked as visited).
332 for (auto M = CurrentModule->Imports.rbegin(),
333 MEnd = CurrentModule->Imports.rend();
335 // Remove our current module as an impediment to visiting the
336 // module we depend on. If we were the last unvisited module
337 // that depends on this particular module, push it into the
338 // queue to be visited.
339 unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
340 if (NumUnusedEdges && (--NumUnusedEdges == 0))
345 assert(VisitOrder.size() == N && "Visitation order is wrong?");
347 delete FirstVisitState;
348 FirstVisitState = nullptr;
351 VisitState *State = allocateVisitState();
352 unsigned VisitNumber = State->NextVisitNumber++;
354 // If the caller has provided us with a hit-set that came from the global
355 // module index, mark every module file in common with the global module
356 // index that is *not* in that set as 'visited'.
357 if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
358 for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
360 ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
361 if (!ModuleFilesHit->count(M))
362 State->VisitNumber[M->Index] = VisitNumber;
366 for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
367 ModuleFile *CurrentModule = VisitOrder[I];
368 // Should we skip this module file?
369 if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
373 assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
374 State->VisitNumber[CurrentModule->Index] = VisitNumber;
375 if (!Visitor(*CurrentModule))
378 // The visitor has requested that cut off visitation of any
379 // module that the current module depends on. To indicate this
380 // behavior, we mark all of the reachable modules as having been visited.
381 ModuleFile *NextModule = CurrentModule;
383 // For any module that this module depends on, push it on the
384 // stack (if it hasn't already been marked as visited).
385 for (llvm::SetVector<ModuleFile *>::iterator
386 M = NextModule->Imports.begin(),
387 MEnd = NextModule->Imports.end();
389 if (State->VisitNumber[(*M)->Index] != VisitNumber) {
390 State->Stack.push_back(*M);
391 State->VisitNumber[(*M)->Index] = VisitNumber;
395 if (State->Stack.empty())
398 // Pop the next module off the stack.
399 NextModule = State->Stack.pop_back_val();
403 returnVisitState(State);
406 bool ModuleManager::lookupModuleFile(StringRef FileName,
408 time_t ExpectedModTime,
409 const FileEntry *&File) {
410 if (FileName == "-") {
415 // Open the file immediately to ensure there is no race between stat'ing and
417 File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
421 if ((ExpectedSize && ExpectedSize != File->getSize()) ||
422 (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
423 // Do not destroy File, as it may be referenced. If we need to rebuild it,
424 // it will be destroyed by removeModules.
433 struct GraphTraits<ModuleManager> {
434 typedef ModuleFile *NodeRef;
435 typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
436 typedef ModuleManager::ModuleConstIterator nodes_iterator;
438 static ChildIteratorType child_begin(NodeRef Node) {
439 return Node->Imports.begin();
442 static ChildIteratorType child_end(NodeRef Node) {
443 return Node->Imports.end();
446 static nodes_iterator nodes_begin(const ModuleManager &Manager) {
447 return Manager.begin();
450 static nodes_iterator nodes_end(const ModuleManager &Manager) {
451 return Manager.end();
456 struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
457 explicit DOTGraphTraits(bool IsSimple = false)
458 : DefaultDOTGraphTraits(IsSimple) { }
460 static bool renderGraphFromBottomUp() {
464 std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
465 return M->ModuleName;
470 void ModuleManager::viewGraph() {
471 llvm::ViewGraph(*this, "Modules");