1d44252ecSDouglas Gregor //===--- ModuleManager.cpp - Module Manager ---------------------*- C++ -*-===//
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 //===----------------------------------------------------------------------===//
149670f847SMehdi Amini #include "clang/Serialization/ModuleManager.h"
15*030d7d6dSDuncan P. N. Exon Smith #include "clang/Basic/MemoryBufferCache.h"
16bb165fb0SAdrian Prantl #include "clang/Frontend/PCHContainerOperations.h"
17beee15e7SBen Langmuir #include "clang/Lex/HeaderSearch.h"
187029ce1aSDouglas Gregor #include "clang/Lex/ModuleMap.h"
197211ac15SDouglas Gregor #include "clang/Serialization/GlobalModuleIndex.h"
20d44252ecSDouglas Gregor #include "llvm/Support/MemoryBuffer.h"
21552c169eSRafael Espindola #include "llvm/Support/Path.h"
228a8e554aSRafael Espindola #include <system_error>
23d44252ecSDouglas Gregor 
249d7c1a2aSDouglas Gregor #ifndef NDEBUG
259d7c1a2aSDouglas Gregor #include "llvm/Support/GraphWriter.h"
269d7c1a2aSDouglas Gregor #endif
279d7c1a2aSDouglas Gregor 
28d44252ecSDouglas Gregor using namespace clang;
29d44252ecSDouglas Gregor using namespace serialization;
30d44252ecSDouglas Gregor 
3137a93df3SRichard Smith ModuleFile *ModuleManager::lookup(StringRef Name) const {
32dadd85dcSDouglas Gregor   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
33dadd85dcSDouglas Gregor                                            /*cacheFailure=*/false);
34bf7fc9c5SDouglas Gregor   if (Entry)
35bf7fc9c5SDouglas Gregor     return lookup(Entry);
36bf7fc9c5SDouglas Gregor 
37a13603a2SCraig Topper   return nullptr;
38bf7fc9c5SDouglas Gregor }
39bf7fc9c5SDouglas Gregor 
4037a93df3SRichard Smith ModuleFile *ModuleManager::lookup(const FileEntry *File) const {
4137a93df3SRichard Smith   auto Known = Modules.find(File);
42bf7fc9c5SDouglas Gregor   if (Known == Modules.end())
43a13603a2SCraig Topper     return nullptr;
44bf7fc9c5SDouglas Gregor 
45bf7fc9c5SDouglas Gregor   return Known->second;
46d44252ecSDouglas Gregor }
47d44252ecSDouglas Gregor 
485cd06f26SRafael Espindola std::unique_ptr<llvm::MemoryBuffer>
495cd06f26SRafael Espindola ModuleManager::lookupBuffer(StringRef Name) {
50dadd85dcSDouglas Gregor   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
51dadd85dcSDouglas Gregor                                            /*cacheFailure=*/false);
525cd06f26SRafael Espindola   return std::move(InMemoryBuffers[Entry]);
53d44252ecSDouglas Gregor }
54d44252ecSDouglas Gregor 
5514afc8e7SDuncan P. N. Exon Smith static bool checkSignature(ASTFileSignature Signature,
5614afc8e7SDuncan P. N. Exon Smith                            ASTFileSignature ExpectedSignature,
5714afc8e7SDuncan P. N. Exon Smith                            std::string &ErrorStr) {
5814afc8e7SDuncan P. N. Exon Smith   if (!ExpectedSignature || Signature == ExpectedSignature)
5914afc8e7SDuncan P. N. Exon Smith     return false;
6014afc8e7SDuncan P. N. Exon Smith 
6114afc8e7SDuncan P. N. Exon Smith   ErrorStr =
6214afc8e7SDuncan P. N. Exon Smith       Signature ? "signature mismatch" : "could not read module signature";
6314afc8e7SDuncan P. N. Exon Smith   return true;
6414afc8e7SDuncan P. N. Exon Smith }
6514afc8e7SDuncan P. N. Exon Smith 
6626308a68SDuncan P. N. Exon Smith static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy,
6726308a68SDuncan P. N. Exon Smith                                 SourceLocation ImportLoc) {
6826308a68SDuncan P. N. Exon Smith   if (ImportedBy) {
6926308a68SDuncan P. N. Exon Smith     MF.ImportedBy.insert(ImportedBy);
7026308a68SDuncan P. N. Exon Smith     ImportedBy->Imports.insert(&MF);
7126308a68SDuncan P. N. Exon Smith   } else {
7226308a68SDuncan P. N. Exon Smith     if (!MF.DirectlyImported)
7326308a68SDuncan P. N. Exon Smith       MF.ImportLoc = ImportLoc;
7426308a68SDuncan P. N. Exon Smith 
7526308a68SDuncan P. N. Exon Smith     MF.DirectlyImported = true;
7626308a68SDuncan P. N. Exon Smith   }
7726308a68SDuncan P. N. Exon Smith }
7826308a68SDuncan P. N. Exon Smith 
797029ce1aSDouglas Gregor ModuleManager::AddModuleResult
80d44252ecSDouglas Gregor ModuleManager::addModule(StringRef FileName, ModuleKind Type,
816fb03aeaSDouglas Gregor                          SourceLocation ImportLoc, ModuleFile *ImportedBy,
827029ce1aSDouglas Gregor                          unsigned Generation,
837029ce1aSDouglas Gregor                          off_t ExpectedSize, time_t ExpectedModTime,
84487ea14aSBen Langmuir                          ASTFileSignature ExpectedSignature,
8570a1b816SBen Langmuir                          ASTFileSignatureReader ReadSignature,
867029ce1aSDouglas Gregor                          ModuleFile *&Module,
877029ce1aSDouglas Gregor                          std::string &ErrorStr) {
88a13603a2SCraig Topper   Module = nullptr;
897029ce1aSDouglas Gregor 
907029ce1aSDouglas Gregor   // Look for the file entry. This only fails if the expected size or
917029ce1aSDouglas Gregor   // modification time differ.
927029ce1aSDouglas Gregor   const FileEntry *Entry;
9311f2a477SManman Ren   if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {
945b390756SRichard Smith     // If we're not expecting to pull this file out of the module cache, it
955b390756SRichard Smith     // might have a different mtime due to being moved across filesystems in
965b390756SRichard Smith     // a distributed build. The size must still match, though. (As must the
975b390756SRichard Smith     // contents, but we can't check that.)
985b390756SRichard Smith     ExpectedModTime = 0;
995b390756SRichard Smith   }
100c27d0d5eSEli Friedman   if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
101c27d0d5eSEli Friedman     ErrorStr = "module file out of date";
1027029ce1aSDouglas Gregor     return OutOfDate;
103c27d0d5eSEli Friedman   }
1047029ce1aSDouglas Gregor 
105d44252ecSDouglas Gregor   if (!Entry && FileName != "-") {
106c27d0d5eSEli Friedman     ErrorStr = "module file not found";
1077029ce1aSDouglas Gregor     return Missing;
108d44252ecSDouglas Gregor   }
109d44252ecSDouglas Gregor 
110d44252ecSDouglas Gregor   // Check whether we already loaded this module, before
11126308a68SDuncan P. N. Exon Smith   if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) {
11226308a68SDuncan P. N. Exon Smith     // Check the stored signature.
11326308a68SDuncan P. N. Exon Smith     if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr))
11426308a68SDuncan P. N. Exon Smith       return OutOfDate;
11526308a68SDuncan P. N. Exon Smith 
11626308a68SDuncan P. N. Exon Smith     Module = ModuleEntry;
11726308a68SDuncan P. N. Exon Smith     updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc);
11826308a68SDuncan P. N. Exon Smith     return AlreadyLoaded;
11926308a68SDuncan P. N. Exon Smith   }
12026308a68SDuncan P. N. Exon Smith 
121d44252ecSDouglas Gregor   // Allocate a new module.
12226308a68SDuncan P. N. Exon Smith   auto NewModule = llvm::make_unique<ModuleFile>(Type, Generation);
123a897f7cdSDuncan P. N. Exon Smith   NewModule->Index = Chain.size();
124a897f7cdSDuncan P. N. Exon Smith   NewModule->FileName = FileName.str();
125a897f7cdSDuncan P. N. Exon Smith   NewModule->File = Entry;
126a897f7cdSDuncan P. N. Exon Smith   NewModule->ImportLoc = ImportLoc;
127a897f7cdSDuncan P. N. Exon Smith   NewModule->InputFilesValidationTimestamp = 0;
128d44252ecSDouglas Gregor 
129a897f7cdSDuncan P. N. Exon Smith   if (NewModule->Kind == MK_ImplicitModule) {
130a897f7cdSDuncan P. N. Exon Smith     std::string TimestampFilename = NewModule->getTimestampFilename();
131c8130a74SBen Langmuir     vfs::Status Status;
132f430da4dSDmitri Gribenko     // A cached stat value would be fine as well.
133f430da4dSDmitri Gribenko     if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
134a897f7cdSDuncan P. N. Exon Smith       NewModule->InputFilesValidationTimestamp =
135ac71c8e2SPavel Labath           llvm::sys::toTimeT(Status.getLastModificationTime());
136f430da4dSDmitri Gribenko   }
137f430da4dSDmitri Gribenko 
138d44252ecSDouglas Gregor   // Load the contents of the module
1395cd06f26SRafael Espindola   if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
140d44252ecSDouglas Gregor     // The buffer was already provided for us.
141*030d7d6dSDuncan P. N. Exon Smith     NewModule->Buffer = &PCMCache->addBuffer(FileName, std::move(Buffer));
142*030d7d6dSDuncan P. N. Exon Smith   } else if (llvm::MemoryBuffer *Buffer = PCMCache->lookupBuffer(FileName)) {
143*030d7d6dSDuncan P. N. Exon Smith     NewModule->Buffer = Buffer;
144d44252ecSDouglas Gregor   } else {
145d44252ecSDouglas Gregor     // Open the AST file.
14626308a68SDuncan P. N. Exon Smith     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf((std::error_code()));
147d44252ecSDouglas Gregor     if (FileName == "-") {
148a885796dSBenjamin Kramer       Buf = llvm::MemoryBuffer::getSTDIN();
1499801b253SBen Langmuir     } else {
1509801b253SBen Langmuir       // Leave the FileEntry open so if it gets read again by another
1519801b253SBen Langmuir       // ModuleManager it must be the same underlying file.
1529801b253SBen Langmuir       // FIXME: Because FileManager::getFile() doesn't guarantee that it will
1539801b253SBen Langmuir       // give us an open file, this may not be 100% reliable.
154a897f7cdSDuncan P. N. Exon Smith       Buf = FileMgr.getBufferForFile(NewModule->File,
155a885796dSBenjamin Kramer                                      /*IsVolatile=*/false,
156a885796dSBenjamin Kramer                                      /*ShouldClose=*/false);
1579801b253SBen Langmuir     }
158d44252ecSDouglas Gregor 
159a885796dSBenjamin Kramer     if (!Buf) {
160a885796dSBenjamin Kramer       ErrorStr = Buf.getError().message();
1617029ce1aSDouglas Gregor       return Missing;
162d44252ecSDouglas Gregor     }
163d44252ecSDouglas Gregor 
164*030d7d6dSDuncan P. N. Exon Smith     NewModule->Buffer = &PCMCache->addBuffer(FileName, std::move(*Buf));
165a885796dSBenjamin Kramer   }
166a885796dSBenjamin Kramer 
167bb165fb0SAdrian Prantl   // Initialize the stream.
168a897f7cdSDuncan P. N. Exon Smith   NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);
169487ea14aSBen Langmuir 
170688b69adSDuncan P. N. Exon Smith   // Read the signature eagerly now so that we can check it.  Avoid calling
171688b69adSDuncan P. N. Exon Smith   // ReadSignature unless there's something to check though.
172688b69adSDuncan P. N. Exon Smith   if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),
173*030d7d6dSDuncan P. N. Exon Smith                                           ExpectedSignature, ErrorStr)) {
174*030d7d6dSDuncan P. N. Exon Smith     // Try to remove the buffer.  If it can't be removed, then it was already
175*030d7d6dSDuncan P. N. Exon Smith     // validated by this process.
176*030d7d6dSDuncan P. N. Exon Smith     if (!PCMCache->tryToRemoveBuffer(NewModule->FileName))
177*030d7d6dSDuncan P. N. Exon Smith       FileMgr.invalidateCache(NewModule->File);
178ed982584SBen Langmuir     return OutOfDate;
179*030d7d6dSDuncan P. N. Exon Smith   }
180a897f7cdSDuncan P. N. Exon Smith 
18126308a68SDuncan P. N. Exon Smith   // We're keeping this module.  Store it everywhere.
18226308a68SDuncan P. N. Exon Smith   Module = Modules[Entry] = NewModule.get();
183d44252ecSDouglas Gregor 
18426308a68SDuncan P. N. Exon Smith   updateModuleImports(*NewModule, ImportedBy, ImportLoc);
1856fb03aeaSDouglas Gregor 
18626308a68SDuncan P. N. Exon Smith   if (!NewModule->isModule())
18726308a68SDuncan P. N. Exon Smith     PCHChain.push_back(NewModule.get());
18826308a68SDuncan P. N. Exon Smith   if (!ImportedBy)
18926308a68SDuncan P. N. Exon Smith     Roots.push_back(NewModule.get());
1903b99db55SRichard Smith 
191a897f7cdSDuncan P. N. Exon Smith   Chain.push_back(std::move(NewModule));
1923b99db55SRichard Smith   return NewlyLoaded;
193d44252ecSDouglas Gregor }
194d44252ecSDouglas Gregor 
1959801b253SBen Langmuir void ModuleManager::removeModules(
1968e6bc197SDuncan P. N. Exon Smith     ModuleIterator First,
1979801b253SBen Langmuir     llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
1987029ce1aSDouglas Gregor     ModuleMap *modMap) {
1998e6bc197SDuncan P. N. Exon Smith   auto Last = end();
2008e6bc197SDuncan P. N. Exon Smith   if (First == Last)
201188dbef2SDouglas Gregor     return;
202188dbef2SDouglas Gregor 
2038e6bc197SDuncan P. N. Exon Smith 
204a50dbb20SBen Langmuir   // Explicitly clear VisitOrder since we might not notice it is stale.
205a50dbb20SBen Langmuir   VisitOrder.clear();
206a50dbb20SBen Langmuir 
207188dbef2SDouglas Gregor   // Collect the set of module file pointers that we'll be removing.
20896a06e0eSDuncan P. N. Exon Smith   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(
2098e6bc197SDuncan P. N. Exon Smith       (llvm::pointer_iterator<ModuleIterator>(First)),
2108e6bc197SDuncan P. N. Exon Smith       (llvm::pointer_iterator<ModuleIterator>(Last)));
211188dbef2SDouglas Gregor 
2129eff8b14SManuel Klimek   auto IsVictim = [&](ModuleFile *MF) {
2139eff8b14SManuel Klimek     return victimSet.count(MF);
2149eff8b14SManuel Klimek   };
215188dbef2SDouglas Gregor   // Remove any references to the now-destroyed modules.
216073ec350SDuncan P. N. Exon Smith   for (auto I = begin(); I != First; ++I) {
217073ec350SDuncan P. N. Exon Smith     I->Imports.remove_if(IsVictim);
2188e6bc197SDuncan P. N. Exon Smith     I->ImportedBy.remove_if(IsVictim);
219073ec350SDuncan P. N. Exon Smith   }
2209eff8b14SManuel Klimek   Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),
2219eff8b14SManuel Klimek               Roots.end());
222188dbef2SDouglas Gregor 
22316fe4d17SRichard Smith   // Remove the modules from the PCH chain.
2248e6bc197SDuncan P. N. Exon Smith   for (auto I = First; I != Last; ++I) {
22596a06e0eSDuncan P. N. Exon Smith     if (!I->isModule()) {
22696a06e0eSDuncan P. N. Exon Smith       PCHChain.erase(std::find(PCHChain.begin(), PCHChain.end(), &*I),
22716fe4d17SRichard Smith                      PCHChain.end());
22816fe4d17SRichard Smith       break;
22916fe4d17SRichard Smith     }
23016fe4d17SRichard Smith   }
23116fe4d17SRichard Smith 
232188dbef2SDouglas Gregor   // Delete the modules and erase them from the various structures.
2338e6bc197SDuncan P. N. Exon Smith   for (ModuleIterator victim = First; victim != Last; ++victim) {
23496a06e0eSDuncan P. N. Exon Smith     Modules.erase(victim->File);
235ca39214fSBen Langmuir 
2367029ce1aSDouglas Gregor     if (modMap) {
23796a06e0eSDuncan P. N. Exon Smith       StringRef ModuleName = victim->ModuleName;
2387029ce1aSDouglas Gregor       if (Module *mod = modMap->findModule(ModuleName)) {
239a13603a2SCraig Topper         mod->setASTFile(nullptr);
2407029ce1aSDouglas Gregor       }
2417029ce1aSDouglas Gregor     }
2424f05478cSBen Langmuir 
2439801b253SBen Langmuir     // Files that didn't make it through ReadASTCore successfully will be
2449801b253SBen Langmuir     // rebuilt (or there was an error). Invalidate them so that we can load the
2459801b253SBen Langmuir     // new files that will be renamed over the old ones.
246*030d7d6dSDuncan P. N. Exon Smith     //
247*030d7d6dSDuncan P. N. Exon Smith     // The PCMCache tracks whether the module was succesfully loaded in another
248*030d7d6dSDuncan P. N. Exon Smith     // thread/context; in that case, it won't need to be rebuilt (and we can't
249*030d7d6dSDuncan P. N. Exon Smith     // safely invalidate it anyway).
250*030d7d6dSDuncan P. N. Exon Smith     if (LoadedSuccessfully.count(&*victim) == 0 &&
251*030d7d6dSDuncan P. N. Exon Smith         !PCMCache->tryToRemoveBuffer(victim->FileName))
25296a06e0eSDuncan P. N. Exon Smith       FileMgr.invalidateCache(victim->File);
253188dbef2SDouglas Gregor   }
254188dbef2SDouglas Gregor 
255a897f7cdSDuncan P. N. Exon Smith   // Delete the modules.
2568e6bc197SDuncan P. N. Exon Smith   Chain.erase(Chain.begin() + (First - begin()), Chain.end());
257188dbef2SDouglas Gregor }
258188dbef2SDouglas Gregor 
2595cd06f26SRafael Espindola void
2605cd06f26SRafael Espindola ModuleManager::addInMemoryBuffer(StringRef FileName,
2615cd06f26SRafael Espindola                                  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
262d44252ecSDouglas Gregor 
2635cd06f26SRafael Espindola   const FileEntry *Entry =
2645cd06f26SRafael Espindola       FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
2655cd06f26SRafael Espindola   InMemoryBuffers[Entry] = std::move(Buffer);
266d44252ecSDouglas Gregor }
267d44252ecSDouglas Gregor 
268e97cd90aSDouglas Gregor ModuleManager::VisitState *ModuleManager::allocateVisitState() {
269e97cd90aSDouglas Gregor   // Fast path: if we have a cached state, use it.
270e97cd90aSDouglas Gregor   if (FirstVisitState) {
271e97cd90aSDouglas Gregor     VisitState *Result = FirstVisitState;
272e97cd90aSDouglas Gregor     FirstVisitState = FirstVisitState->NextState;
273a13603a2SCraig Topper     Result->NextState = nullptr;
274e97cd90aSDouglas Gregor     return Result;
275e97cd90aSDouglas Gregor   }
276e97cd90aSDouglas Gregor 
277e97cd90aSDouglas Gregor   // Allocate and return a new state.
278e97cd90aSDouglas Gregor   return new VisitState(size());
279e97cd90aSDouglas Gregor }
280e97cd90aSDouglas Gregor 
281e97cd90aSDouglas Gregor void ModuleManager::returnVisitState(VisitState *State) {
282a13603a2SCraig Topper   assert(State->NextState == nullptr && "Visited state is in list?");
283e97cd90aSDouglas Gregor   State->NextState = FirstVisitState;
284e97cd90aSDouglas Gregor   FirstVisitState = State;
285e97cd90aSDouglas Gregor }
286e97cd90aSDouglas Gregor 
2877211ac15SDouglas Gregor void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
2887211ac15SDouglas Gregor   GlobalIndex = Index;
289603cd869SDouglas Gregor   if (!GlobalIndex) {
290603cd869SDouglas Gregor     ModulesInCommonWithGlobalIndex.clear();
291603cd869SDouglas Gregor     return;
2927029ce1aSDouglas Gregor   }
293603cd869SDouglas Gregor 
294603cd869SDouglas Gregor   // Notify the global module index about all of the modules we've already
295603cd869SDouglas Gregor   // loaded.
296a897f7cdSDuncan P. N. Exon Smith   for (ModuleFile &M : *this)
297a897f7cdSDuncan P. N. Exon Smith     if (!GlobalIndex->loadedModuleFile(&M))
298a897f7cdSDuncan P. N. Exon Smith       ModulesInCommonWithGlobalIndex.push_back(&M);
299603cd869SDouglas Gregor }
300603cd869SDouglas Gregor 
301603cd869SDouglas Gregor void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
302603cd869SDouglas Gregor   if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
303603cd869SDouglas Gregor     return;
304603cd869SDouglas Gregor 
305603cd869SDouglas Gregor   ModulesInCommonWithGlobalIndex.push_back(MF);
3067211ac15SDouglas Gregor }
3077211ac15SDouglas Gregor 
308*030d7d6dSDuncan P. N. Exon Smith ModuleManager::ModuleManager(FileManager &FileMgr, MemoryBufferCache &PCMCache,
309fb2398d0SAdrian Prantl                              const PCHContainerReader &PCHContainerRdr)
310*030d7d6dSDuncan P. N. Exon Smith     : FileMgr(FileMgr), PCMCache(&PCMCache), PCHContainerRdr(PCHContainerRdr),
311*030d7d6dSDuncan P. N. Exon Smith       GlobalIndex(), FirstVisitState(nullptr) {}
312d44252ecSDouglas Gregor 
313a897f7cdSDuncan P. N. Exon Smith ModuleManager::~ModuleManager() { delete FirstVisitState; }
314d44252ecSDouglas Gregor 
3159a9efbafSBenjamin Kramer void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
3164dd9b43cSCraig Topper                           llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
3177211ac15SDouglas Gregor   // If the visitation order vector is the wrong size, recompute the order.
318e41d7feaSDouglas Gregor   if (VisitOrder.size() != Chain.size()) {
319d44252ecSDouglas Gregor     unsigned N = size();
320e41d7feaSDouglas Gregor     VisitOrder.clear();
321e41d7feaSDouglas Gregor     VisitOrder.reserve(N);
322d44252ecSDouglas Gregor 
323d44252ecSDouglas Gregor     // Record the number of incoming edges for each module. When we
324d44252ecSDouglas Gregor     // encounter a module with no incoming edges, push it into the queue
325d44252ecSDouglas Gregor     // to seed the queue.
326de3ef502SDouglas Gregor     SmallVector<ModuleFile *, 4> Queue;
327d44252ecSDouglas Gregor     Queue.reserve(N);
328bdb259d2SDouglas Gregor     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
329a7c535b3SRichard Smith     UnusedIncomingEdges.resize(size());
33096a06e0eSDuncan P. N. Exon Smith     for (ModuleFile &M : llvm::reverse(*this)) {
33196a06e0eSDuncan P. N. Exon Smith       unsigned Size = M.ImportedBy.size();
33296a06e0eSDuncan P. N. Exon Smith       UnusedIncomingEdges[M.Index] = Size;
333a7c535b3SRichard Smith       if (!Size)
33496a06e0eSDuncan P. N. Exon Smith         Queue.push_back(&M);
335d44252ecSDouglas Gregor     }
336d44252ecSDouglas Gregor 
337e41d7feaSDouglas Gregor     // Traverse the graph, making sure to visit a module before visiting any
338e41d7feaSDouglas Gregor     // of its dependencies.
339a7c535b3SRichard Smith     while (!Queue.empty()) {
340a7c535b3SRichard Smith       ModuleFile *CurrentModule = Queue.pop_back_val();
341e41d7feaSDouglas Gregor       VisitOrder.push_back(CurrentModule);
342d44252ecSDouglas Gregor 
343d44252ecSDouglas Gregor       // For any module that this module depends on, push it on the
344d44252ecSDouglas Gregor       // stack (if it hasn't already been marked as visited).
345a7c535b3SRichard Smith       for (auto M = CurrentModule->Imports.rbegin(),
346a7c535b3SRichard Smith                 MEnd = CurrentModule->Imports.rend();
347d44252ecSDouglas Gregor            M != MEnd; ++M) {
348d44252ecSDouglas Gregor         // Remove our current module as an impediment to visiting the
349d44252ecSDouglas Gregor         // module we depend on. If we were the last unvisited module
350d44252ecSDouglas Gregor         // that depends on this particular module, push it into the
351d44252ecSDouglas Gregor         // queue to be visited.
352bdb259d2SDouglas Gregor         unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
353d44252ecSDouglas Gregor         if (NumUnusedEdges && (--NumUnusedEdges == 0))
354d44252ecSDouglas Gregor           Queue.push_back(*M);
355d44252ecSDouglas Gregor       }
356d44252ecSDouglas Gregor     }
357e41d7feaSDouglas Gregor 
358e41d7feaSDouglas Gregor     assert(VisitOrder.size() == N && "Visitation order is wrong?");
3597211ac15SDouglas Gregor 
360e97cd90aSDouglas Gregor     delete FirstVisitState;
361a13603a2SCraig Topper     FirstVisitState = nullptr;
362e41d7feaSDouglas Gregor   }
363e41d7feaSDouglas Gregor 
364e97cd90aSDouglas Gregor   VisitState *State = allocateVisitState();
365e97cd90aSDouglas Gregor   unsigned VisitNumber = State->NextVisitNumber++;
366e41d7feaSDouglas Gregor 
3677211ac15SDouglas Gregor   // If the caller has provided us with a hit-set that came from the global
3687211ac15SDouglas Gregor   // module index, mark every module file in common with the global module
3697211ac15SDouglas Gregor   // index that is *not* in that set as 'visited'.
3707211ac15SDouglas Gregor   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
3717211ac15SDouglas Gregor     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
3727211ac15SDouglas Gregor     {
3737211ac15SDouglas Gregor       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
3747029ce1aSDouglas Gregor       if (!ModuleFilesHit->count(M))
375e97cd90aSDouglas Gregor         State->VisitNumber[M->Index] = VisitNumber;
3767211ac15SDouglas Gregor     }
3777211ac15SDouglas Gregor   }
3787211ac15SDouglas Gregor 
379e41d7feaSDouglas Gregor   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
380e41d7feaSDouglas Gregor     ModuleFile *CurrentModule = VisitOrder[I];
381e41d7feaSDouglas Gregor     // Should we skip this module file?
382e97cd90aSDouglas Gregor     if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
383e41d7feaSDouglas Gregor       continue;
384e41d7feaSDouglas Gregor 
385e41d7feaSDouglas Gregor     // Visit the module.
386e97cd90aSDouglas Gregor     assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
387e97cd90aSDouglas Gregor     State->VisitNumber[CurrentModule->Index] = VisitNumber;
3889a9efbafSBenjamin Kramer     if (!Visitor(*CurrentModule))
389e41d7feaSDouglas Gregor       continue;
390e41d7feaSDouglas Gregor 
391e41d7feaSDouglas Gregor     // The visitor has requested that cut off visitation of any
392e41d7feaSDouglas Gregor     // module that the current module depends on. To indicate this
393e41d7feaSDouglas Gregor     // behavior, we mark all of the reachable modules as having been visited.
394e41d7feaSDouglas Gregor     ModuleFile *NextModule = CurrentModule;
395e41d7feaSDouglas Gregor     do {
396e41d7feaSDouglas Gregor       // For any module that this module depends on, push it on the
397e41d7feaSDouglas Gregor       // stack (if it hasn't already been marked as visited).
398e41d7feaSDouglas Gregor       for (llvm::SetVector<ModuleFile *>::iterator
399e41d7feaSDouglas Gregor              M = NextModule->Imports.begin(),
400e41d7feaSDouglas Gregor              MEnd = NextModule->Imports.end();
401e41d7feaSDouglas Gregor            M != MEnd; ++M) {
402e97cd90aSDouglas Gregor         if (State->VisitNumber[(*M)->Index] != VisitNumber) {
403e97cd90aSDouglas Gregor           State->Stack.push_back(*M);
404e97cd90aSDouglas Gregor           State->VisitNumber[(*M)->Index] = VisitNumber;
405e41d7feaSDouglas Gregor         }
406e41d7feaSDouglas Gregor       }
407e41d7feaSDouglas Gregor 
408e97cd90aSDouglas Gregor       if (State->Stack.empty())
409e41d7feaSDouglas Gregor         break;
410e41d7feaSDouglas Gregor 
411e41d7feaSDouglas Gregor       // Pop the next module off the stack.
41225284cc9SRobert Wilhelm       NextModule = State->Stack.pop_back_val();
413e41d7feaSDouglas Gregor     } while (true);
414e41d7feaSDouglas Gregor   }
415e97cd90aSDouglas Gregor 
416e97cd90aSDouglas Gregor   returnVisitState(State);
417d44252ecSDouglas Gregor }
418d44252ecSDouglas Gregor 
4197029ce1aSDouglas Gregor bool ModuleManager::lookupModuleFile(StringRef FileName,
4207029ce1aSDouglas Gregor                                      off_t ExpectedSize,
4217029ce1aSDouglas Gregor                                      time_t ExpectedModTime,
4227029ce1aSDouglas Gregor                                      const FileEntry *&File) {
4233bd6d7fbSRichard Smith   if (FileName == "-") {
4243bd6d7fbSRichard Smith     File = nullptr;
4253bd6d7fbSRichard Smith     return false;
4263bd6d7fbSRichard Smith   }
4273bd6d7fbSRichard Smith 
42805f82ba2SBen Langmuir   // Open the file immediately to ensure there is no race between stat'ing and
42905f82ba2SBen Langmuir   // opening the file.
43005f82ba2SBen Langmuir   File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
4313bd6d7fbSRichard Smith   if (!File)
4327029ce1aSDouglas Gregor     return false;
4337029ce1aSDouglas Gregor 
4347029ce1aSDouglas Gregor   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
435027731d7SBen Langmuir       (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
436027731d7SBen Langmuir     // Do not destroy File, as it may be referenced. If we need to rebuild it,
437027731d7SBen Langmuir     // it will be destroyed by removeModules.
4387029ce1aSDouglas Gregor     return true;
4397029ce1aSDouglas Gregor 
4407029ce1aSDouglas Gregor   return false;
4417029ce1aSDouglas Gregor }
4427029ce1aSDouglas Gregor 
4439d7c1a2aSDouglas Gregor #ifndef NDEBUG
4449d7c1a2aSDouglas Gregor namespace llvm {
4459d7c1a2aSDouglas Gregor   template<>
4469d7c1a2aSDouglas Gregor   struct GraphTraits<ModuleManager> {
4472931d171STim Shen     typedef ModuleFile *NodeRef;
448de3ef502SDouglas Gregor     typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
44996a06e0eSDuncan P. N. Exon Smith     typedef pointer_iterator<ModuleManager::ModuleConstIterator> nodes_iterator;
4509d7c1a2aSDouglas Gregor 
451f2187ed3STim Shen     static ChildIteratorType child_begin(NodeRef Node) {
4529d7c1a2aSDouglas Gregor       return Node->Imports.begin();
4539d7c1a2aSDouglas Gregor     }
4549d7c1a2aSDouglas Gregor 
455f2187ed3STim Shen     static ChildIteratorType child_end(NodeRef Node) {
4569d7c1a2aSDouglas Gregor       return Node->Imports.end();
4579d7c1a2aSDouglas Gregor     }
4589d7c1a2aSDouglas Gregor 
4599d7c1a2aSDouglas Gregor     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
46096a06e0eSDuncan P. N. Exon Smith       return nodes_iterator(Manager.begin());
4619d7c1a2aSDouglas Gregor     }
4629d7c1a2aSDouglas Gregor 
4639d7c1a2aSDouglas Gregor     static nodes_iterator nodes_end(const ModuleManager &Manager) {
46496a06e0eSDuncan P. N. Exon Smith       return nodes_iterator(Manager.end());
4659d7c1a2aSDouglas Gregor     }
4669d7c1a2aSDouglas Gregor   };
4679d7c1a2aSDouglas Gregor 
4689d7c1a2aSDouglas Gregor   template<>
4699d7c1a2aSDouglas Gregor   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
4709d7c1a2aSDouglas Gregor     explicit DOTGraphTraits(bool IsSimple = false)
4719d7c1a2aSDouglas Gregor       : DefaultDOTGraphTraits(IsSimple) { }
4729d7c1a2aSDouglas Gregor 
4739d7c1a2aSDouglas Gregor     static bool renderGraphFromBottomUp() {
4749d7c1a2aSDouglas Gregor       return true;
4759d7c1a2aSDouglas Gregor     }
4769d7c1a2aSDouglas Gregor 
477de3ef502SDouglas Gregor     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
478beee15e7SBen Langmuir       return M->ModuleName;
4799d7c1a2aSDouglas Gregor     }
4809d7c1a2aSDouglas Gregor   };
481ab9db510SAlexander Kornienko }
4829d7c1a2aSDouglas Gregor 
4839d7c1a2aSDouglas Gregor void ModuleManager::viewGraph() {
4849d7c1a2aSDouglas Gregor   llvm::ViewGraph(*this, "Modules");
4859d7c1a2aSDouglas Gregor }
4869d7c1a2aSDouglas Gregor #endif
487