1 //===- ModuleManager.cpp - Module Manager ---------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines the ModuleManager class, which manages a set of loaded
10 // modules for the ASTReader.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Serialization/ModuleManager.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/LLVM.h"
17 #include "clang/Lex/HeaderSearch.h"
18 #include "clang/Lex/ModuleMap.h"
19 #include "clang/Serialization/GlobalModuleIndex.h"
20 #include "clang/Serialization/InMemoryModuleCache.h"
21 #include "clang/Serialization/Module.h"
22 #include "clang/Serialization/PCHContainerOperations.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/iterator.h"
29 #include "llvm/Support/Chrono.h"
30 #include "llvm/Support/DOTGraphTraits.h"
31 #include "llvm/Support/ErrorOr.h"
32 #include "llvm/Support/GraphWriter.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/VirtualFileSystem.h"
39 #include <system_error>
41 using namespace clang;
42 using namespace serialization;
44 ModuleFile *ModuleManager::lookupByFileName(StringRef Name) const {
45 auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
46 /*CacheFailure=*/false);
48 return lookup(*Entry);
53 ModuleFile *ModuleManager::lookupByModuleName(StringRef Name) const {
54 if (const Module *Mod = HeaderSearchInfo.getModuleMap().findModule(Name))
55 if (const FileEntry *File = Mod->getASTFile())
61 ModuleFile *ModuleManager::lookup(const FileEntry *File) const {
62 auto Known = Modules.find(File);
63 if (Known == Modules.end())
69 std::unique_ptr<llvm::MemoryBuffer>
70 ModuleManager::lookupBuffer(StringRef Name) {
71 auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
72 /*CacheFailure=*/false);
75 return std::move(InMemoryBuffers[*Entry]);
78 static bool checkSignature(ASTFileSignature Signature,
79 ASTFileSignature ExpectedSignature,
80 std::string &ErrorStr) {
81 if (!ExpectedSignature || Signature == ExpectedSignature)
85 Signature ? "signature mismatch" : "could not read module signature";
89 static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy,
90 SourceLocation ImportLoc) {
92 MF.ImportedBy.insert(ImportedBy);
93 ImportedBy->Imports.insert(&MF);
95 if (!MF.DirectlyImported)
96 MF.ImportLoc = ImportLoc;
98 MF.DirectlyImported = true;
102 ModuleManager::AddModuleResult
103 ModuleManager::addModule(StringRef FileName, ModuleKind Type,
104 SourceLocation ImportLoc, ModuleFile *ImportedBy,
106 off_t ExpectedSize, time_t ExpectedModTime,
107 ASTFileSignature ExpectedSignature,
108 ASTFileSignatureReader ReadSignature,
110 std::string &ErrorStr) {
113 // Look for the file entry. This only fails if the expected size or
114 // modification time differ.
115 const FileEntry *Entry;
116 if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {
117 // If we're not expecting to pull this file out of the module cache, it
118 // might have a different mtime due to being moved across filesystems in
119 // a distributed build. The size must still match, though. (As must the
120 // contents, but we can't check that.)
123 // Note: ExpectedSize and ExpectedModTime will be 0 for MK_ImplicitModule
124 // when using an ASTFileSignature.
125 if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
126 ErrorStr = "module file out of date";
130 if (!Entry && FileName != "-") {
131 ErrorStr = "module file not found";
135 // Check whether we already loaded this module, before
136 if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) {
137 // Check the stored signature.
138 if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr))
141 Module = ModuleEntry;
142 updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc);
143 return AlreadyLoaded;
146 // Allocate a new module.
147 auto NewModule = std::make_unique<ModuleFile>(Type, Generation);
148 NewModule->Index = Chain.size();
149 NewModule->FileName = FileName.str();
150 NewModule->File = Entry;
151 NewModule->ImportLoc = ImportLoc;
152 NewModule->InputFilesValidationTimestamp = 0;
154 if (NewModule->Kind == MK_ImplicitModule) {
155 std::string TimestampFilename = NewModule->getTimestampFilename();
156 llvm::vfs::Status Status;
157 // A cached stat value would be fine as well.
158 if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
159 NewModule->InputFilesValidationTimestamp =
160 llvm::sys::toTimeT(Status.getLastModificationTime());
163 // Load the contents of the module
164 if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
165 // The buffer was already provided for us.
166 NewModule->Buffer = &ModuleCache->addBuiltPCM(FileName, std::move(Buffer));
167 // Since the cached buffer is reused, it is safe to close the file
168 // descriptor that was opened while stat()ing the PCM in
169 // lookupModuleFile() above, it won't be needed any longer.
171 } else if (llvm::MemoryBuffer *Buffer =
172 getModuleCache().lookupPCM(FileName)) {
173 NewModule->Buffer = Buffer;
174 // As above, the file descriptor is no longer needed.
176 } else if (getModuleCache().shouldBuildPCM(FileName)) {
177 // Report that the module is out of date, since we tried (and failed) to
178 // import it earlier.
182 // Open the AST file.
183 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf((std::error_code()));
184 if (FileName == "-") {
185 Buf = llvm::MemoryBuffer::getSTDIN();
187 // Get a buffer of the file and close the file descriptor when done.
188 Buf = FileMgr.getBufferForFile(NewModule->File, /*isVolatile=*/false);
192 ErrorStr = Buf.getError().message();
196 NewModule->Buffer = &getModuleCache().addPCM(FileName, std::move(*Buf));
199 // Initialize the stream.
200 NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);
202 // Read the signature eagerly now so that we can check it. Avoid calling
203 // ReadSignature unless there's something to check though.
204 if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),
205 ExpectedSignature, ErrorStr))
208 // We're keeping this module. Store it everywhere.
209 Module = Modules[Entry] = NewModule.get();
211 updateModuleImports(*NewModule, ImportedBy, ImportLoc);
213 if (!NewModule->isModule())
214 PCHChain.push_back(NewModule.get());
216 Roots.push_back(NewModule.get());
218 Chain.push_back(std::move(NewModule));
222 void ModuleManager::removeModules(
223 ModuleIterator First,
224 llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
230 // Explicitly clear VisitOrder since we might not notice it is stale.
233 // Collect the set of module file pointers that we'll be removing.
234 llvm::SmallPtrSet<ModuleFile *, 4> victimSet(
235 (llvm::pointer_iterator<ModuleIterator>(First)),
236 (llvm::pointer_iterator<ModuleIterator>(Last)));
238 auto IsVictim = [&](ModuleFile *MF) {
239 return victimSet.count(MF);
241 // Remove any references to the now-destroyed modules.
242 for (auto I = begin(); I != First; ++I) {
243 I->Imports.remove_if(IsVictim);
244 I->ImportedBy.remove_if(IsVictim);
246 Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),
249 // Remove the modules from the PCH chain.
250 for (auto I = First; I != Last; ++I) {
251 if (!I->isModule()) {
252 PCHChain.erase(llvm::find(PCHChain, &*I), PCHChain.end());
257 // Delete the modules and erase them from the various structures.
258 for (ModuleIterator victim = First; victim != Last; ++victim) {
259 Modules.erase(victim->File);
262 StringRef ModuleName = victim->ModuleName;
263 if (Module *mod = modMap->findModule(ModuleName)) {
264 mod->setASTFile(nullptr);
269 // Delete the modules.
270 Chain.erase(Chain.begin() + (First - begin()), Chain.end());
274 ModuleManager::addInMemoryBuffer(StringRef FileName,
275 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
276 const FileEntry *Entry =
277 FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
278 InMemoryBuffers[Entry] = std::move(Buffer);
281 ModuleManager::VisitState *ModuleManager::allocateVisitState() {
282 // Fast path: if we have a cached state, use it.
283 if (FirstVisitState) {
284 VisitState *Result = FirstVisitState;
285 FirstVisitState = FirstVisitState->NextState;
286 Result->NextState = nullptr;
290 // Allocate and return a new state.
291 return new VisitState(size());
294 void ModuleManager::returnVisitState(VisitState *State) {
295 assert(State->NextState == nullptr && "Visited state is in list?");
296 State->NextState = FirstVisitState;
297 FirstVisitState = State;
300 void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
303 ModulesInCommonWithGlobalIndex.clear();
307 // Notify the global module index about all of the modules we've already
309 for (ModuleFile &M : *this)
310 if (!GlobalIndex->loadedModuleFile(&M))
311 ModulesInCommonWithGlobalIndex.push_back(&M);
314 void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
315 if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
318 ModulesInCommonWithGlobalIndex.push_back(MF);
321 ModuleManager::ModuleManager(FileManager &FileMgr,
322 InMemoryModuleCache &ModuleCache,
323 const PCHContainerReader &PCHContainerRdr,
324 const HeaderSearch &HeaderSearchInfo)
325 : FileMgr(FileMgr), ModuleCache(&ModuleCache),
326 PCHContainerRdr(PCHContainerRdr), HeaderSearchInfo(HeaderSearchInfo) {}
328 ModuleManager::~ModuleManager() { delete FirstVisitState; }
330 void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
331 llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
332 // If the visitation order vector is the wrong size, recompute the order.
333 if (VisitOrder.size() != Chain.size()) {
336 VisitOrder.reserve(N);
338 // Record the number of incoming edges for each module. When we
339 // encounter a module with no incoming edges, push it into the queue
340 // to seed the queue.
341 SmallVector<ModuleFile *, 4> Queue;
343 llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
344 UnusedIncomingEdges.resize(size());
345 for (ModuleFile &M : llvm::reverse(*this)) {
346 unsigned Size = M.ImportedBy.size();
347 UnusedIncomingEdges[M.Index] = Size;
352 // Traverse the graph, making sure to visit a module before visiting any
353 // of its dependencies.
354 while (!Queue.empty()) {
355 ModuleFile *CurrentModule = Queue.pop_back_val();
356 VisitOrder.push_back(CurrentModule);
358 // For any module that this module depends on, push it on the
359 // stack (if it hasn't already been marked as visited).
360 for (auto M = CurrentModule->Imports.rbegin(),
361 MEnd = CurrentModule->Imports.rend();
363 // Remove our current module as an impediment to visiting the
364 // module we depend on. If we were the last unvisited module
365 // that depends on this particular module, push it into the
366 // queue to be visited.
367 unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
368 if (NumUnusedEdges && (--NumUnusedEdges == 0))
373 assert(VisitOrder.size() == N && "Visitation order is wrong?");
375 delete FirstVisitState;
376 FirstVisitState = nullptr;
379 VisitState *State = allocateVisitState();
380 unsigned VisitNumber = State->NextVisitNumber++;
382 // If the caller has provided us with a hit-set that came from the global
383 // module index, mark every module file in common with the global module
384 // index that is *not* in that set as 'visited'.
385 if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
386 for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
388 ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
389 if (!ModuleFilesHit->count(M))
390 State->VisitNumber[M->Index] = VisitNumber;
394 for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
395 ModuleFile *CurrentModule = VisitOrder[I];
396 // Should we skip this module file?
397 if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
401 assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
402 State->VisitNumber[CurrentModule->Index] = VisitNumber;
403 if (!Visitor(*CurrentModule))
406 // The visitor has requested that cut off visitation of any
407 // module that the current module depends on. To indicate this
408 // behavior, we mark all of the reachable modules as having been visited.
409 ModuleFile *NextModule = CurrentModule;
411 // For any module that this module depends on, push it on the
412 // stack (if it hasn't already been marked as visited).
413 for (llvm::SetVector<ModuleFile *>::iterator
414 M = NextModule->Imports.begin(),
415 MEnd = NextModule->Imports.end();
417 if (State->VisitNumber[(*M)->Index] != VisitNumber) {
418 State->Stack.push_back(*M);
419 State->VisitNumber[(*M)->Index] = VisitNumber;
423 if (State->Stack.empty())
426 // Pop the next module off the stack.
427 NextModule = State->Stack.pop_back_val();
431 returnVisitState(State);
434 bool ModuleManager::lookupModuleFile(StringRef FileName,
436 time_t ExpectedModTime,
437 const FileEntry *&File) {
438 if (FileName == "-") {
443 // Open the file immediately to ensure there is no race between stat'ing and
445 auto FileOrErr = FileMgr.getFile(FileName, /*OpenFile=*/true,
446 /*CacheFailure=*/false);
453 if ((ExpectedSize && ExpectedSize != File->getSize()) ||
454 (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
455 // Do not destroy File, as it may be referenced. If we need to rebuild it,
456 // it will be destroyed by removeModules.
466 struct GraphTraits<ModuleManager> {
467 using NodeRef = ModuleFile *;
468 using ChildIteratorType = llvm::SetVector<ModuleFile *>::const_iterator;
469 using nodes_iterator = pointer_iterator<ModuleManager::ModuleConstIterator>;
471 static ChildIteratorType child_begin(NodeRef Node) {
472 return Node->Imports.begin();
475 static ChildIteratorType child_end(NodeRef Node) {
476 return Node->Imports.end();
479 static nodes_iterator nodes_begin(const ModuleManager &Manager) {
480 return nodes_iterator(Manager.begin());
483 static nodes_iterator nodes_end(const ModuleManager &Manager) {
484 return nodes_iterator(Manager.end());
489 struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
490 explicit DOTGraphTraits(bool IsSimple = false)
491 : DefaultDOTGraphTraits(IsSimple) {}
493 static bool renderGraphFromBottomUp() { return true; }
495 std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
496 return M->ModuleName;
502 void ModuleManager::viewGraph() {
503 llvm::ViewGraph(*this, "Modules");