1*b7d89107SEugene Zelenko //===- ModuleManager.cpp - Module Manager ---------------------------------===//
2d44252ecSDouglas Gregor //
3d44252ecSDouglas Gregor //                     The LLVM Compiler Infrastructure
4d44252ecSDouglas Gregor //
5d44252ecSDouglas Gregor // This file is distributed under the University of Illinois Open Source
6d44252ecSDouglas Gregor // License. See LICENSE.TXT for details.
7d44252ecSDouglas Gregor //
8d44252ecSDouglas Gregor //===----------------------------------------------------------------------===//
9d44252ecSDouglas Gregor //
10d44252ecSDouglas Gregor //  This file defines the ModuleManager class, which manages a set of loaded
11d44252ecSDouglas Gregor //  modules for the ASTReader.
12d44252ecSDouglas Gregor //
13d44252ecSDouglas Gregor //===----------------------------------------------------------------------===//
14*b7d89107SEugene Zelenko 
159670f847SMehdi Amini #include "clang/Serialization/ModuleManager.h"
16*b7d89107SEugene Zelenko #include "clang/Basic/FileManager.h"
17*b7d89107SEugene Zelenko #include "clang/Basic/LLVM.h"
18030d7d6dSDuncan P. N. Exon Smith #include "clang/Basic/MemoryBufferCache.h"
19*b7d89107SEugene Zelenko #include "clang/Basic/VirtualFileSystem.h"
20bb165fb0SAdrian Prantl #include "clang/Frontend/PCHContainerOperations.h"
21beee15e7SBen Langmuir #include "clang/Lex/HeaderSearch.h"
227029ce1aSDouglas Gregor #include "clang/Lex/ModuleMap.h"
237211ac15SDouglas Gregor #include "clang/Serialization/GlobalModuleIndex.h"
24*b7d89107SEugene Zelenko #include "clang/Serialization/Module.h"
25*b7d89107SEugene Zelenko #include "llvm/ADT/STLExtras.h"
26*b7d89107SEugene Zelenko #include "llvm/ADT/SetVector.h"
27*b7d89107SEugene Zelenko #include "llvm/ADT/SmallPtrSet.h"
28*b7d89107SEugene Zelenko #include "llvm/ADT/SmallVector.h"
29*b7d89107SEugene Zelenko #include "llvm/ADT/StringRef.h"
30*b7d89107SEugene Zelenko #include "llvm/ADT/iterator.h"
31*b7d89107SEugene Zelenko #include "llvm/Support/Chrono.h"
32*b7d89107SEugene Zelenko #include "llvm/Support/DOTGraphTraits.h"
33*b7d89107SEugene Zelenko #include "llvm/Support/ErrorOr.h"
349d7c1a2aSDouglas Gregor #include "llvm/Support/GraphWriter.h"
35*b7d89107SEugene Zelenko #include "llvm/Support/MemoryBuffer.h"
36*b7d89107SEugene Zelenko #include <algorithm>
37*b7d89107SEugene Zelenko #include <cassert>
38*b7d89107SEugene Zelenko #include <memory>
39*b7d89107SEugene Zelenko #include <string>
40*b7d89107SEugene Zelenko #include <system_error>
419d7c1a2aSDouglas Gregor 
42d44252ecSDouglas Gregor using namespace clang;
43d44252ecSDouglas Gregor using namespace serialization;
44d44252ecSDouglas Gregor 
45d30446fdSBoris Kolpackov ModuleFile *ModuleManager::lookupByFileName(StringRef Name) const {
46dadd85dcSDouglas Gregor   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
47dadd85dcSDouglas Gregor                                            /*cacheFailure=*/false);
48bf7fc9c5SDouglas Gregor   if (Entry)
49bf7fc9c5SDouglas Gregor     return lookup(Entry);
50bf7fc9c5SDouglas Gregor 
51a13603a2SCraig Topper   return nullptr;
52bf7fc9c5SDouglas Gregor }
53bf7fc9c5SDouglas Gregor 
54d30446fdSBoris Kolpackov ModuleFile *ModuleManager::lookupByModuleName(StringRef Name) const {
55d30446fdSBoris Kolpackov   if (const Module *Mod = HeaderSearchInfo.getModuleMap().findModule(Name))
56d30446fdSBoris Kolpackov     if (const FileEntry *File = Mod->getASTFile())
57d30446fdSBoris Kolpackov       return lookup(File);
58d30446fdSBoris Kolpackov 
59d30446fdSBoris Kolpackov   return nullptr;
60d30446fdSBoris Kolpackov }
61d30446fdSBoris Kolpackov 
6237a93df3SRichard Smith ModuleFile *ModuleManager::lookup(const FileEntry *File) const {
6337a93df3SRichard Smith   auto Known = Modules.find(File);
64bf7fc9c5SDouglas Gregor   if (Known == Modules.end())
65a13603a2SCraig Topper     return nullptr;
66bf7fc9c5SDouglas Gregor 
67bf7fc9c5SDouglas Gregor   return Known->second;
68d44252ecSDouglas Gregor }
69d44252ecSDouglas Gregor 
705cd06f26SRafael Espindola std::unique_ptr<llvm::MemoryBuffer>
715cd06f26SRafael Espindola ModuleManager::lookupBuffer(StringRef Name) {
72dadd85dcSDouglas Gregor   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
73dadd85dcSDouglas Gregor                                            /*cacheFailure=*/false);
745cd06f26SRafael Espindola   return std::move(InMemoryBuffers[Entry]);
75d44252ecSDouglas Gregor }
76d44252ecSDouglas Gregor 
7714afc8e7SDuncan P. N. Exon Smith static bool checkSignature(ASTFileSignature Signature,
7814afc8e7SDuncan P. N. Exon Smith                            ASTFileSignature ExpectedSignature,
7914afc8e7SDuncan P. N. Exon Smith                            std::string &ErrorStr) {
8014afc8e7SDuncan P. N. Exon Smith   if (!ExpectedSignature || Signature == ExpectedSignature)
8114afc8e7SDuncan P. N. Exon Smith     return false;
8214afc8e7SDuncan P. N. Exon Smith 
8314afc8e7SDuncan P. N. Exon Smith   ErrorStr =
8414afc8e7SDuncan P. N. Exon Smith       Signature ? "signature mismatch" : "could not read module signature";
8514afc8e7SDuncan P. N. Exon Smith   return true;
8614afc8e7SDuncan P. N. Exon Smith }
8714afc8e7SDuncan P. N. Exon Smith 
8826308a68SDuncan P. N. Exon Smith static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy,
8926308a68SDuncan P. N. Exon Smith                                 SourceLocation ImportLoc) {
9026308a68SDuncan P. N. Exon Smith   if (ImportedBy) {
9126308a68SDuncan P. N. Exon Smith     MF.ImportedBy.insert(ImportedBy);
9226308a68SDuncan P. N. Exon Smith     ImportedBy->Imports.insert(&MF);
9326308a68SDuncan P. N. Exon Smith   } else {
9426308a68SDuncan P. N. Exon Smith     if (!MF.DirectlyImported)
9526308a68SDuncan P. N. Exon Smith       MF.ImportLoc = ImportLoc;
9626308a68SDuncan P. N. Exon Smith 
9726308a68SDuncan P. N. Exon Smith     MF.DirectlyImported = true;
9826308a68SDuncan P. N. Exon Smith   }
9926308a68SDuncan P. N. Exon Smith }
10026308a68SDuncan P. N. Exon Smith 
1017029ce1aSDouglas Gregor ModuleManager::AddModuleResult
102d44252ecSDouglas Gregor ModuleManager::addModule(StringRef FileName, ModuleKind Type,
1036fb03aeaSDouglas Gregor                          SourceLocation ImportLoc, ModuleFile *ImportedBy,
1047029ce1aSDouglas Gregor                          unsigned Generation,
1057029ce1aSDouglas Gregor                          off_t ExpectedSize, time_t ExpectedModTime,
106487ea14aSBen Langmuir                          ASTFileSignature ExpectedSignature,
10770a1b816SBen Langmuir                          ASTFileSignatureReader ReadSignature,
1087029ce1aSDouglas Gregor                          ModuleFile *&Module,
1097029ce1aSDouglas Gregor                          std::string &ErrorStr) {
110a13603a2SCraig Topper   Module = nullptr;
1117029ce1aSDouglas Gregor 
1127029ce1aSDouglas Gregor   // Look for the file entry. This only fails if the expected size or
1137029ce1aSDouglas Gregor   // modification time differ.
1147029ce1aSDouglas Gregor   const FileEntry *Entry;
11511f2a477SManman Ren   if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {
1165b390756SRichard Smith     // If we're not expecting to pull this file out of the module cache, it
1175b390756SRichard Smith     // might have a different mtime due to being moved across filesystems in
1185b390756SRichard Smith     // a distributed build. The size must still match, though. (As must the
1195b390756SRichard Smith     // contents, but we can't check that.)
1205b390756SRichard Smith     ExpectedModTime = 0;
1215b390756SRichard Smith   }
122c27d0d5eSEli Friedman   if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
123c27d0d5eSEli Friedman     ErrorStr = "module file out of date";
1247029ce1aSDouglas Gregor     return OutOfDate;
125c27d0d5eSEli Friedman   }
1267029ce1aSDouglas Gregor 
127d44252ecSDouglas Gregor   if (!Entry && FileName != "-") {
128c27d0d5eSEli Friedman     ErrorStr = "module file not found";
1297029ce1aSDouglas Gregor     return Missing;
130d44252ecSDouglas Gregor   }
131d44252ecSDouglas Gregor 
132d44252ecSDouglas Gregor   // Check whether we already loaded this module, before
13326308a68SDuncan P. N. Exon Smith   if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) {
13426308a68SDuncan P. N. Exon Smith     // Check the stored signature.
13526308a68SDuncan P. N. Exon Smith     if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr))
13626308a68SDuncan P. N. Exon Smith       return OutOfDate;
13726308a68SDuncan P. N. Exon Smith 
13826308a68SDuncan P. N. Exon Smith     Module = ModuleEntry;
13926308a68SDuncan P. N. Exon Smith     updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc);
14026308a68SDuncan P. N. Exon Smith     return AlreadyLoaded;
14126308a68SDuncan P. N. Exon Smith   }
14226308a68SDuncan P. N. Exon Smith 
143d44252ecSDouglas Gregor   // Allocate a new module.
14426308a68SDuncan P. N. Exon Smith   auto NewModule = llvm::make_unique<ModuleFile>(Type, Generation);
145a897f7cdSDuncan P. N. Exon Smith   NewModule->Index = Chain.size();
146a897f7cdSDuncan P. N. Exon Smith   NewModule->FileName = FileName.str();
147a897f7cdSDuncan P. N. Exon Smith   NewModule->File = Entry;
148a897f7cdSDuncan P. N. Exon Smith   NewModule->ImportLoc = ImportLoc;
149a897f7cdSDuncan P. N. Exon Smith   NewModule->InputFilesValidationTimestamp = 0;
150d44252ecSDouglas Gregor 
151a897f7cdSDuncan P. N. Exon Smith   if (NewModule->Kind == MK_ImplicitModule) {
152a897f7cdSDuncan P. N. Exon Smith     std::string TimestampFilename = NewModule->getTimestampFilename();
153c8130a74SBen Langmuir     vfs::Status Status;
154f430da4dSDmitri Gribenko     // A cached stat value would be fine as well.
155f430da4dSDmitri Gribenko     if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
156a897f7cdSDuncan P. N. Exon Smith       NewModule->InputFilesValidationTimestamp =
157ac71c8e2SPavel Labath           llvm::sys::toTimeT(Status.getLastModificationTime());
158f430da4dSDmitri Gribenko   }
159f430da4dSDmitri Gribenko 
160d44252ecSDouglas Gregor   // Load the contents of the module
1615cd06f26SRafael Espindola   if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
162d44252ecSDouglas Gregor     // The buffer was already provided for us.
163030d7d6dSDuncan P. N. Exon Smith     NewModule->Buffer = &PCMCache->addBuffer(FileName, std::move(Buffer));
164030d7d6dSDuncan P. N. Exon Smith   } else if (llvm::MemoryBuffer *Buffer = PCMCache->lookupBuffer(FileName)) {
165030d7d6dSDuncan P. N. Exon Smith     NewModule->Buffer = Buffer;
166d44252ecSDouglas Gregor   } else {
167d44252ecSDouglas Gregor     // Open the AST file.
16826308a68SDuncan P. N. Exon Smith     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf((std::error_code()));
169d44252ecSDouglas Gregor     if (FileName == "-") {
170a885796dSBenjamin Kramer       Buf = llvm::MemoryBuffer::getSTDIN();
1719801b253SBen Langmuir     } else {
1729801b253SBen Langmuir       // Leave the FileEntry open so if it gets read again by another
1739801b253SBen Langmuir       // ModuleManager it must be the same underlying file.
1749801b253SBen Langmuir       // FIXME: Because FileManager::getFile() doesn't guarantee that it will
1759801b253SBen Langmuir       // give us an open file, this may not be 100% reliable.
176a897f7cdSDuncan P. N. Exon Smith       Buf = FileMgr.getBufferForFile(NewModule->File,
177a885796dSBenjamin Kramer                                      /*IsVolatile=*/false,
178a885796dSBenjamin Kramer                                      /*ShouldClose=*/false);
1799801b253SBen Langmuir     }
180d44252ecSDouglas Gregor 
181a885796dSBenjamin Kramer     if (!Buf) {
182a885796dSBenjamin Kramer       ErrorStr = Buf.getError().message();
1837029ce1aSDouglas Gregor       return Missing;
184d44252ecSDouglas Gregor     }
185d44252ecSDouglas Gregor 
186030d7d6dSDuncan P. N. Exon Smith     NewModule->Buffer = &PCMCache->addBuffer(FileName, std::move(*Buf));
187a885796dSBenjamin Kramer   }
188a885796dSBenjamin Kramer 
189bb165fb0SAdrian Prantl   // Initialize the stream.
190a897f7cdSDuncan P. N. Exon Smith   NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);
191487ea14aSBen Langmuir 
192688b69adSDuncan P. N. Exon Smith   // Read the signature eagerly now so that we can check it.  Avoid calling
193688b69adSDuncan P. N. Exon Smith   // ReadSignature unless there's something to check though.
194688b69adSDuncan P. N. Exon Smith   if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),
195030d7d6dSDuncan P. N. Exon Smith                                           ExpectedSignature, ErrorStr)) {
196030d7d6dSDuncan P. N. Exon Smith     // Try to remove the buffer.  If it can't be removed, then it was already
197030d7d6dSDuncan P. N. Exon Smith     // validated by this process.
198030d7d6dSDuncan P. N. Exon Smith     if (!PCMCache->tryToRemoveBuffer(NewModule->FileName))
199030d7d6dSDuncan P. N. Exon Smith       FileMgr.invalidateCache(NewModule->File);
200ed982584SBen Langmuir     return OutOfDate;
201030d7d6dSDuncan P. N. Exon Smith   }
202a897f7cdSDuncan P. N. Exon Smith 
20326308a68SDuncan P. N. Exon Smith   // We're keeping this module.  Store it everywhere.
20426308a68SDuncan P. N. Exon Smith   Module = Modules[Entry] = NewModule.get();
205d44252ecSDouglas Gregor 
20626308a68SDuncan P. N. Exon Smith   updateModuleImports(*NewModule, ImportedBy, ImportLoc);
2076fb03aeaSDouglas Gregor 
20826308a68SDuncan P. N. Exon Smith   if (!NewModule->isModule())
20926308a68SDuncan P. N. Exon Smith     PCHChain.push_back(NewModule.get());
21026308a68SDuncan P. N. Exon Smith   if (!ImportedBy)
21126308a68SDuncan P. N. Exon Smith     Roots.push_back(NewModule.get());
2123b99db55SRichard Smith 
213a897f7cdSDuncan P. N. Exon Smith   Chain.push_back(std::move(NewModule));
2143b99db55SRichard Smith   return NewlyLoaded;
215d44252ecSDouglas Gregor }
216d44252ecSDouglas Gregor 
2179801b253SBen Langmuir void ModuleManager::removeModules(
2188e6bc197SDuncan P. N. Exon Smith     ModuleIterator First,
2199801b253SBen Langmuir     llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
2207029ce1aSDouglas Gregor     ModuleMap *modMap) {
2218e6bc197SDuncan P. N. Exon Smith   auto Last = end();
2228e6bc197SDuncan P. N. Exon Smith   if (First == Last)
223188dbef2SDouglas Gregor     return;
224188dbef2SDouglas Gregor 
225a50dbb20SBen Langmuir   // Explicitly clear VisitOrder since we might not notice it is stale.
226a50dbb20SBen Langmuir   VisitOrder.clear();
227a50dbb20SBen Langmuir 
228188dbef2SDouglas Gregor   // Collect the set of module file pointers that we'll be removing.
22996a06e0eSDuncan P. N. Exon Smith   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(
2308e6bc197SDuncan P. N. Exon Smith       (llvm::pointer_iterator<ModuleIterator>(First)),
2318e6bc197SDuncan P. N. Exon Smith       (llvm::pointer_iterator<ModuleIterator>(Last)));
232188dbef2SDouglas Gregor 
2339eff8b14SManuel Klimek   auto IsVictim = [&](ModuleFile *MF) {
2349eff8b14SManuel Klimek     return victimSet.count(MF);
2359eff8b14SManuel Klimek   };
236188dbef2SDouglas Gregor   // Remove any references to the now-destroyed modules.
237073ec350SDuncan P. N. Exon Smith   for (auto I = begin(); I != First; ++I) {
238073ec350SDuncan P. N. Exon Smith     I->Imports.remove_if(IsVictim);
2398e6bc197SDuncan P. N. Exon Smith     I->ImportedBy.remove_if(IsVictim);
240073ec350SDuncan P. N. Exon Smith   }
2419eff8b14SManuel Klimek   Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),
2429eff8b14SManuel Klimek               Roots.end());
243188dbef2SDouglas Gregor 
24416fe4d17SRichard Smith   // Remove the modules from the PCH chain.
2458e6bc197SDuncan P. N. Exon Smith   for (auto I = First; I != Last; ++I) {
24696a06e0eSDuncan P. N. Exon Smith     if (!I->isModule()) {
24796a06e0eSDuncan P. N. Exon Smith       PCHChain.erase(std::find(PCHChain.begin(), PCHChain.end(), &*I),
24816fe4d17SRichard Smith                      PCHChain.end());
24916fe4d17SRichard Smith       break;
25016fe4d17SRichard Smith     }
25116fe4d17SRichard Smith   }
25216fe4d17SRichard Smith 
253188dbef2SDouglas Gregor   // Delete the modules and erase them from the various structures.
2548e6bc197SDuncan P. N. Exon Smith   for (ModuleIterator victim = First; victim != Last; ++victim) {
25596a06e0eSDuncan P. N. Exon Smith     Modules.erase(victim->File);
256ca39214fSBen Langmuir 
2577029ce1aSDouglas Gregor     if (modMap) {
25896a06e0eSDuncan P. N. Exon Smith       StringRef ModuleName = victim->ModuleName;
2597029ce1aSDouglas Gregor       if (Module *mod = modMap->findModule(ModuleName)) {
260a13603a2SCraig Topper         mod->setASTFile(nullptr);
2617029ce1aSDouglas Gregor       }
2627029ce1aSDouglas Gregor     }
2634f05478cSBen Langmuir 
2649801b253SBen Langmuir     // Files that didn't make it through ReadASTCore successfully will be
2659801b253SBen Langmuir     // rebuilt (or there was an error). Invalidate them so that we can load the
2669801b253SBen Langmuir     // new files that will be renamed over the old ones.
267030d7d6dSDuncan P. N. Exon Smith     //
2682c51880aSSimon Pilgrim     // The PCMCache tracks whether the module was successfully loaded in another
269030d7d6dSDuncan P. N. Exon Smith     // thread/context; in that case, it won't need to be rebuilt (and we can't
270030d7d6dSDuncan P. N. Exon Smith     // safely invalidate it anyway).
271030d7d6dSDuncan P. N. Exon Smith     if (LoadedSuccessfully.count(&*victim) == 0 &&
272030d7d6dSDuncan P. N. Exon Smith         !PCMCache->tryToRemoveBuffer(victim->FileName))
27396a06e0eSDuncan P. N. Exon Smith       FileMgr.invalidateCache(victim->File);
274188dbef2SDouglas Gregor   }
275188dbef2SDouglas Gregor 
276a897f7cdSDuncan P. N. Exon Smith   // Delete the modules.
2778e6bc197SDuncan P. N. Exon Smith   Chain.erase(Chain.begin() + (First - begin()), Chain.end());
278188dbef2SDouglas Gregor }
279188dbef2SDouglas Gregor 
2805cd06f26SRafael Espindola void
2815cd06f26SRafael Espindola ModuleManager::addInMemoryBuffer(StringRef FileName,
2825cd06f26SRafael Espindola                                  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
2835cd06f26SRafael Espindola   const FileEntry *Entry =
2845cd06f26SRafael Espindola       FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
2855cd06f26SRafael Espindola   InMemoryBuffers[Entry] = std::move(Buffer);
286d44252ecSDouglas Gregor }
287d44252ecSDouglas Gregor 
288e97cd90aSDouglas Gregor ModuleManager::VisitState *ModuleManager::allocateVisitState() {
289e97cd90aSDouglas Gregor   // Fast path: if we have a cached state, use it.
290e97cd90aSDouglas Gregor   if (FirstVisitState) {
291e97cd90aSDouglas Gregor     VisitState *Result = FirstVisitState;
292e97cd90aSDouglas Gregor     FirstVisitState = FirstVisitState->NextState;
293a13603a2SCraig Topper     Result->NextState = nullptr;
294e97cd90aSDouglas Gregor     return Result;
295e97cd90aSDouglas Gregor   }
296e97cd90aSDouglas Gregor 
297e97cd90aSDouglas Gregor   // Allocate and return a new state.
298e97cd90aSDouglas Gregor   return new VisitState(size());
299e97cd90aSDouglas Gregor }
300e97cd90aSDouglas Gregor 
301e97cd90aSDouglas Gregor void ModuleManager::returnVisitState(VisitState *State) {
302a13603a2SCraig Topper   assert(State->NextState == nullptr && "Visited state is in list?");
303e97cd90aSDouglas Gregor   State->NextState = FirstVisitState;
304e97cd90aSDouglas Gregor   FirstVisitState = State;
305e97cd90aSDouglas Gregor }
306e97cd90aSDouglas Gregor 
3077211ac15SDouglas Gregor void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
3087211ac15SDouglas Gregor   GlobalIndex = Index;
309603cd869SDouglas Gregor   if (!GlobalIndex) {
310603cd869SDouglas Gregor     ModulesInCommonWithGlobalIndex.clear();
311603cd869SDouglas Gregor     return;
3127029ce1aSDouglas Gregor   }
313603cd869SDouglas Gregor 
314603cd869SDouglas Gregor   // Notify the global module index about all of the modules we've already
315603cd869SDouglas Gregor   // loaded.
316a897f7cdSDuncan P. N. Exon Smith   for (ModuleFile &M : *this)
317a897f7cdSDuncan P. N. Exon Smith     if (!GlobalIndex->loadedModuleFile(&M))
318a897f7cdSDuncan P. N. Exon Smith       ModulesInCommonWithGlobalIndex.push_back(&M);
319603cd869SDouglas Gregor }
320603cd869SDouglas Gregor 
321603cd869SDouglas Gregor void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
322603cd869SDouglas Gregor   if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
323603cd869SDouglas Gregor     return;
324603cd869SDouglas Gregor 
325603cd869SDouglas Gregor   ModulesInCommonWithGlobalIndex.push_back(MF);
3267211ac15SDouglas Gregor }
3277211ac15SDouglas Gregor 
328030d7d6dSDuncan P. N. Exon Smith ModuleManager::ModuleManager(FileManager &FileMgr, MemoryBufferCache &PCMCache,
329d30446fdSBoris Kolpackov                              const PCHContainerReader &PCHContainerRdr,
330d30446fdSBoris Kolpackov                              const HeaderSearch& HeaderSearchInfo)
331030d7d6dSDuncan P. N. Exon Smith     : FileMgr(FileMgr), PCMCache(&PCMCache), PCHContainerRdr(PCHContainerRdr),
332*b7d89107SEugene Zelenko       HeaderSearchInfo(HeaderSearchInfo) {}
333d44252ecSDouglas Gregor 
334a897f7cdSDuncan P. N. Exon Smith ModuleManager::~ModuleManager() { delete FirstVisitState; }
335d44252ecSDouglas Gregor 
3369a9efbafSBenjamin Kramer void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
3374dd9b43cSCraig Topper                           llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
3387211ac15SDouglas Gregor   // If the visitation order vector is the wrong size, recompute the order.
339e41d7feaSDouglas Gregor   if (VisitOrder.size() != Chain.size()) {
340d44252ecSDouglas Gregor     unsigned N = size();
341e41d7feaSDouglas Gregor     VisitOrder.clear();
342e41d7feaSDouglas Gregor     VisitOrder.reserve(N);
343d44252ecSDouglas Gregor 
344d44252ecSDouglas Gregor     // Record the number of incoming edges for each module. When we
345d44252ecSDouglas Gregor     // encounter a module with no incoming edges, push it into the queue
346d44252ecSDouglas Gregor     // to seed the queue.
347de3ef502SDouglas Gregor     SmallVector<ModuleFile *, 4> Queue;
348d44252ecSDouglas Gregor     Queue.reserve(N);
349bdb259d2SDouglas Gregor     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
350a7c535b3SRichard Smith     UnusedIncomingEdges.resize(size());
35196a06e0eSDuncan P. N. Exon Smith     for (ModuleFile &M : llvm::reverse(*this)) {
35296a06e0eSDuncan P. N. Exon Smith       unsigned Size = M.ImportedBy.size();
35396a06e0eSDuncan P. N. Exon Smith       UnusedIncomingEdges[M.Index] = Size;
354a7c535b3SRichard Smith       if (!Size)
35596a06e0eSDuncan P. N. Exon Smith         Queue.push_back(&M);
356d44252ecSDouglas Gregor     }
357d44252ecSDouglas Gregor 
358e41d7feaSDouglas Gregor     // Traverse the graph, making sure to visit a module before visiting any
359e41d7feaSDouglas Gregor     // of its dependencies.
360a7c535b3SRichard Smith     while (!Queue.empty()) {
361a7c535b3SRichard Smith       ModuleFile *CurrentModule = Queue.pop_back_val();
362e41d7feaSDouglas Gregor       VisitOrder.push_back(CurrentModule);
363d44252ecSDouglas Gregor 
364d44252ecSDouglas Gregor       // For any module that this module depends on, push it on the
365d44252ecSDouglas Gregor       // stack (if it hasn't already been marked as visited).
366a7c535b3SRichard Smith       for (auto M = CurrentModule->Imports.rbegin(),
367a7c535b3SRichard Smith                 MEnd = CurrentModule->Imports.rend();
368d44252ecSDouglas Gregor            M != MEnd; ++M) {
369d44252ecSDouglas Gregor         // Remove our current module as an impediment to visiting the
370d44252ecSDouglas Gregor         // module we depend on. If we were the last unvisited module
371d44252ecSDouglas Gregor         // that depends on this particular module, push it into the
372d44252ecSDouglas Gregor         // queue to be visited.
373bdb259d2SDouglas Gregor         unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
374d44252ecSDouglas Gregor         if (NumUnusedEdges && (--NumUnusedEdges == 0))
375d44252ecSDouglas Gregor           Queue.push_back(*M);
376d44252ecSDouglas Gregor       }
377d44252ecSDouglas Gregor     }
378e41d7feaSDouglas Gregor 
379e41d7feaSDouglas Gregor     assert(VisitOrder.size() == N && "Visitation order is wrong?");
3807211ac15SDouglas Gregor 
381e97cd90aSDouglas Gregor     delete FirstVisitState;
382a13603a2SCraig Topper     FirstVisitState = nullptr;
383e41d7feaSDouglas Gregor   }
384e41d7feaSDouglas Gregor 
385e97cd90aSDouglas Gregor   VisitState *State = allocateVisitState();
386e97cd90aSDouglas Gregor   unsigned VisitNumber = State->NextVisitNumber++;
387e41d7feaSDouglas Gregor 
3887211ac15SDouglas Gregor   // If the caller has provided us with a hit-set that came from the global
3897211ac15SDouglas Gregor   // module index, mark every module file in common with the global module
3907211ac15SDouglas Gregor   // index that is *not* in that set as 'visited'.
3917211ac15SDouglas Gregor   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
3927211ac15SDouglas Gregor     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
3937211ac15SDouglas Gregor     {
3947211ac15SDouglas Gregor       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
3957029ce1aSDouglas Gregor       if (!ModuleFilesHit->count(M))
396e97cd90aSDouglas Gregor         State->VisitNumber[M->Index] = VisitNumber;
3977211ac15SDouglas Gregor     }
3987211ac15SDouglas Gregor   }
3997211ac15SDouglas Gregor 
400e41d7feaSDouglas Gregor   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
401e41d7feaSDouglas Gregor     ModuleFile *CurrentModule = VisitOrder[I];
402e41d7feaSDouglas Gregor     // Should we skip this module file?
403e97cd90aSDouglas Gregor     if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
404e41d7feaSDouglas Gregor       continue;
405e41d7feaSDouglas Gregor 
406e41d7feaSDouglas Gregor     // Visit the module.
407e97cd90aSDouglas Gregor     assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
408e97cd90aSDouglas Gregor     State->VisitNumber[CurrentModule->Index] = VisitNumber;
4099a9efbafSBenjamin Kramer     if (!Visitor(*CurrentModule))
410e41d7feaSDouglas Gregor       continue;
411e41d7feaSDouglas Gregor 
412e41d7feaSDouglas Gregor     // The visitor has requested that cut off visitation of any
413e41d7feaSDouglas Gregor     // module that the current module depends on. To indicate this
414e41d7feaSDouglas Gregor     // behavior, we mark all of the reachable modules as having been visited.
415e41d7feaSDouglas Gregor     ModuleFile *NextModule = CurrentModule;
416e41d7feaSDouglas Gregor     do {
417e41d7feaSDouglas Gregor       // For any module that this module depends on, push it on the
418e41d7feaSDouglas Gregor       // stack (if it hasn't already been marked as visited).
419e41d7feaSDouglas Gregor       for (llvm::SetVector<ModuleFile *>::iterator
420e41d7feaSDouglas Gregor              M = NextModule->Imports.begin(),
421e41d7feaSDouglas Gregor              MEnd = NextModule->Imports.end();
422e41d7feaSDouglas Gregor            M != MEnd; ++M) {
423e97cd90aSDouglas Gregor         if (State->VisitNumber[(*M)->Index] != VisitNumber) {
424e97cd90aSDouglas Gregor           State->Stack.push_back(*M);
425e97cd90aSDouglas Gregor           State->VisitNumber[(*M)->Index] = VisitNumber;
426e41d7feaSDouglas Gregor         }
427e41d7feaSDouglas Gregor       }
428e41d7feaSDouglas Gregor 
429e97cd90aSDouglas Gregor       if (State->Stack.empty())
430e41d7feaSDouglas Gregor         break;
431e41d7feaSDouglas Gregor 
432e41d7feaSDouglas Gregor       // Pop the next module off the stack.
43325284cc9SRobert Wilhelm       NextModule = State->Stack.pop_back_val();
434e41d7feaSDouglas Gregor     } while (true);
435e41d7feaSDouglas Gregor   }
436e97cd90aSDouglas Gregor 
437e97cd90aSDouglas Gregor   returnVisitState(State);
438d44252ecSDouglas Gregor }
439d44252ecSDouglas Gregor 
4407029ce1aSDouglas Gregor bool ModuleManager::lookupModuleFile(StringRef FileName,
4417029ce1aSDouglas Gregor                                      off_t ExpectedSize,
4427029ce1aSDouglas Gregor                                      time_t ExpectedModTime,
4437029ce1aSDouglas Gregor                                      const FileEntry *&File) {
4443bd6d7fbSRichard Smith   if (FileName == "-") {
4453bd6d7fbSRichard Smith     File = nullptr;
4463bd6d7fbSRichard Smith     return false;
4473bd6d7fbSRichard Smith   }
4483bd6d7fbSRichard Smith 
44905f82ba2SBen Langmuir   // Open the file immediately to ensure there is no race between stat'ing and
45005f82ba2SBen Langmuir   // opening the file.
45105f82ba2SBen Langmuir   File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
4523bd6d7fbSRichard Smith   if (!File)
4537029ce1aSDouglas Gregor     return false;
4547029ce1aSDouglas Gregor 
4557029ce1aSDouglas Gregor   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
456027731d7SBen Langmuir       (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
457027731d7SBen Langmuir     // Do not destroy File, as it may be referenced. If we need to rebuild it,
458027731d7SBen Langmuir     // it will be destroyed by removeModules.
4597029ce1aSDouglas Gregor     return true;
4607029ce1aSDouglas Gregor 
4617029ce1aSDouglas Gregor   return false;
4627029ce1aSDouglas Gregor }
4637029ce1aSDouglas Gregor 
4649d7c1a2aSDouglas Gregor #ifndef NDEBUG
4659d7c1a2aSDouglas Gregor namespace llvm {
466*b7d89107SEugene Zelenko 
4679d7c1a2aSDouglas Gregor   template<>
4689d7c1a2aSDouglas Gregor   struct GraphTraits<ModuleManager> {
469*b7d89107SEugene Zelenko     using NodeRef = ModuleFile *;
470*b7d89107SEugene Zelenko     using ChildIteratorType = llvm::SetVector<ModuleFile *>::const_iterator;
471*b7d89107SEugene Zelenko     using nodes_iterator = pointer_iterator<ModuleManager::ModuleConstIterator>;
4729d7c1a2aSDouglas Gregor 
473f2187ed3STim Shen     static ChildIteratorType child_begin(NodeRef Node) {
4749d7c1a2aSDouglas Gregor       return Node->Imports.begin();
4759d7c1a2aSDouglas Gregor     }
4769d7c1a2aSDouglas Gregor 
477f2187ed3STim Shen     static ChildIteratorType child_end(NodeRef Node) {
4789d7c1a2aSDouglas Gregor       return Node->Imports.end();
4799d7c1a2aSDouglas Gregor     }
4809d7c1a2aSDouglas Gregor 
4819d7c1a2aSDouglas Gregor     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
48296a06e0eSDuncan P. N. Exon Smith       return nodes_iterator(Manager.begin());
4839d7c1a2aSDouglas Gregor     }
4849d7c1a2aSDouglas Gregor 
4859d7c1a2aSDouglas Gregor     static nodes_iterator nodes_end(const ModuleManager &Manager) {
48696a06e0eSDuncan P. N. Exon Smith       return nodes_iterator(Manager.end());
4879d7c1a2aSDouglas Gregor     }
4889d7c1a2aSDouglas Gregor   };
4899d7c1a2aSDouglas Gregor 
4909d7c1a2aSDouglas Gregor   template<>
4919d7c1a2aSDouglas Gregor   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
4929d7c1a2aSDouglas Gregor     explicit DOTGraphTraits(bool IsSimple = false)
4939d7c1a2aSDouglas Gregor         : DefaultDOTGraphTraits(IsSimple) {}
4949d7c1a2aSDouglas Gregor 
495*b7d89107SEugene Zelenko     static bool renderGraphFromBottomUp() { return true; }
4969d7c1a2aSDouglas Gregor 
497de3ef502SDouglas Gregor     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
498beee15e7SBen Langmuir       return M->ModuleName;
4999d7c1a2aSDouglas Gregor     }
5009d7c1a2aSDouglas Gregor   };
501*b7d89107SEugene Zelenko 
502*b7d89107SEugene Zelenko } // namespace llvm
5039d7c1a2aSDouglas Gregor 
5049d7c1a2aSDouglas Gregor void ModuleManager::viewGraph() {
5059d7c1a2aSDouglas Gregor   llvm::ViewGraph(*this, "Modules");
5069d7c1a2aSDouglas Gregor }
5079d7c1a2aSDouglas Gregor #endif
508