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 //===----------------------------------------------------------------------===//
14*bb165fb0SAdrian Prantl #include "clang/Frontend/PCHContainerOperations.h"
15beee15e7SBen Langmuir #include "clang/Lex/HeaderSearch.h"
167029ce1aSDouglas Gregor #include "clang/Lex/ModuleMap.h"
177211ac15SDouglas Gregor #include "clang/Serialization/GlobalModuleIndex.h"
18af04f98cSBenjamin Kramer #include "clang/Serialization/ModuleManager.h"
19d44252ecSDouglas Gregor #include "llvm/Support/MemoryBuffer.h"
20552c169eSRafael Espindola #include "llvm/Support/Path.h"
21d44252ecSDouglas Gregor #include "llvm/Support/raw_ostream.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 
31de3ef502SDouglas Gregor ModuleFile *ModuleManager::lookup(StringRef Name) {
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 
40bf7fc9c5SDouglas Gregor ModuleFile *ModuleManager::lookup(const FileEntry *File) {
41bf7fc9c5SDouglas Gregor   llvm::DenseMap<const FileEntry *, ModuleFile *>::iterator Known
42bf7fc9c5SDouglas Gregor     = Modules.find(File);
43bf7fc9c5SDouglas Gregor   if (Known == Modules.end())
44a13603a2SCraig Topper     return nullptr;
45bf7fc9c5SDouglas Gregor 
46bf7fc9c5SDouglas Gregor   return Known->second;
47d44252ecSDouglas Gregor }
48d44252ecSDouglas Gregor 
495cd06f26SRafael Espindola std::unique_ptr<llvm::MemoryBuffer>
505cd06f26SRafael Espindola ModuleManager::lookupBuffer(StringRef Name) {
51dadd85dcSDouglas Gregor   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
52dadd85dcSDouglas Gregor                                            /*cacheFailure=*/false);
535cd06f26SRafael Espindola   return std::move(InMemoryBuffers[Entry]);
54d44252ecSDouglas Gregor }
55d44252ecSDouglas Gregor 
567029ce1aSDouglas Gregor ModuleManager::AddModuleResult
57d44252ecSDouglas Gregor ModuleManager::addModule(StringRef FileName, ModuleKind Type,
586fb03aeaSDouglas Gregor                          SourceLocation ImportLoc, ModuleFile *ImportedBy,
597029ce1aSDouglas Gregor                          unsigned Generation,
607029ce1aSDouglas Gregor                          off_t ExpectedSize, time_t ExpectedModTime,
61487ea14aSBen Langmuir                          ASTFileSignature ExpectedSignature,
6270a1b816SBen Langmuir                          ASTFileSignatureReader ReadSignature,
637029ce1aSDouglas Gregor                          ModuleFile *&Module,
647029ce1aSDouglas Gregor                          std::string &ErrorStr) {
65a13603a2SCraig Topper   Module = nullptr;
667029ce1aSDouglas Gregor 
677029ce1aSDouglas Gregor   // Look for the file entry. This only fails if the expected size or
687029ce1aSDouglas Gregor   // modification time differ.
697029ce1aSDouglas Gregor   const FileEntry *Entry;
705b390756SRichard Smith   if (Type == MK_ExplicitModule) {
715b390756SRichard Smith     // If we're not expecting to pull this file out of the module cache, it
725b390756SRichard Smith     // might have a different mtime due to being moved across filesystems in
735b390756SRichard Smith     // a distributed build. The size must still match, though. (As must the
745b390756SRichard Smith     // contents, but we can't check that.)
755b390756SRichard Smith     ExpectedModTime = 0;
765b390756SRichard Smith   }
77c27d0d5eSEli Friedman   if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
78c27d0d5eSEli Friedman     ErrorStr = "module file out of date";
797029ce1aSDouglas Gregor     return OutOfDate;
80c27d0d5eSEli Friedman   }
817029ce1aSDouglas Gregor 
82d44252ecSDouglas Gregor   if (!Entry && FileName != "-") {
83c27d0d5eSEli Friedman     ErrorStr = "module file not found";
847029ce1aSDouglas Gregor     return Missing;
85d44252ecSDouglas Gregor   }
86d44252ecSDouglas Gregor 
87d44252ecSDouglas Gregor   // Check whether we already loaded this module, before
88de3ef502SDouglas Gregor   ModuleFile *&ModuleEntry = Modules[Entry];
89d44252ecSDouglas Gregor   bool NewModule = false;
90d44252ecSDouglas Gregor   if (!ModuleEntry) {
91d44252ecSDouglas Gregor     // Allocate a new module.
924fc9f3e8SDouglas Gregor     ModuleFile *New = new ModuleFile(Type, Generation);
93bdb259d2SDouglas Gregor     New->Index = Chain.size();
94d44252ecSDouglas Gregor     New->FileName = FileName.str();
95aedf7144SArgyrios Kyrtzidis     New->File = Entry;
966fb03aeaSDouglas Gregor     New->ImportLoc = ImportLoc;
97d44252ecSDouglas Gregor     Chain.push_back(New);
989eff8b14SManuel Klimek     if (!ImportedBy)
999eff8b14SManuel Klimek       Roots.push_back(New);
100d44252ecSDouglas Gregor     NewModule = true;
101d44252ecSDouglas Gregor     ModuleEntry = New;
102d44252ecSDouglas Gregor 
103f430da4dSDmitri Gribenko     New->InputFilesValidationTimestamp = 0;
104e842a474SRichard Smith     if (New->Kind == MK_ImplicitModule) {
105f430da4dSDmitri Gribenko       std::string TimestampFilename = New->getTimestampFilename();
106c8130a74SBen Langmuir       vfs::Status Status;
107f430da4dSDmitri Gribenko       // A cached stat value would be fine as well.
108f430da4dSDmitri Gribenko       if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
109f430da4dSDmitri Gribenko         New->InputFilesValidationTimestamp =
110f430da4dSDmitri Gribenko             Status.getLastModificationTime().toEpochTime();
111f430da4dSDmitri Gribenko     }
112f430da4dSDmitri Gribenko 
113d44252ecSDouglas Gregor     // Load the contents of the module
1145cd06f26SRafael Espindola     if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
115d44252ecSDouglas Gregor       // The buffer was already provided for us.
1165cd06f26SRafael Espindola       New->Buffer = std::move(Buffer);
117d44252ecSDouglas Gregor     } else {
118d44252ecSDouglas Gregor       // Open the AST file.
119a885796dSBenjamin Kramer       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf(
120a885796dSBenjamin Kramer           (std::error_code()));
121d44252ecSDouglas Gregor       if (FileName == "-") {
122a885796dSBenjamin Kramer         Buf = llvm::MemoryBuffer::getSTDIN();
1239801b253SBen Langmuir       } else {
1249801b253SBen Langmuir         // Leave the FileEntry open so if it gets read again by another
1259801b253SBen Langmuir         // ModuleManager it must be the same underlying file.
1269801b253SBen Langmuir         // FIXME: Because FileManager::getFile() doesn't guarantee that it will
1279801b253SBen Langmuir         // give us an open file, this may not be 100% reliable.
128a885796dSBenjamin Kramer         Buf = FileMgr.getBufferForFile(New->File,
129a885796dSBenjamin Kramer                                        /*IsVolatile=*/false,
130a885796dSBenjamin Kramer                                        /*ShouldClose=*/false);
1319801b253SBen Langmuir       }
132d44252ecSDouglas Gregor 
133a885796dSBenjamin Kramer       if (!Buf) {
134a885796dSBenjamin Kramer         ErrorStr = Buf.getError().message();
1357029ce1aSDouglas Gregor         return Missing;
136d44252ecSDouglas Gregor       }
137d44252ecSDouglas Gregor 
138a885796dSBenjamin Kramer       New->Buffer = std::move(*Buf);
139a885796dSBenjamin Kramer     }
140a885796dSBenjamin Kramer 
141*bb165fb0SAdrian Prantl     // Initialize the stream.
142*bb165fb0SAdrian Prantl     PCHContainerOps.ExtractPCH(New->Buffer->getMemBufferRef(), New->StreamFile);
143ed982584SBen Langmuir   }
144487ea14aSBen Langmuir 
145487ea14aSBen Langmuir   if (ExpectedSignature) {
146ed982584SBen Langmuir     if (NewModule)
147ed982584SBen Langmuir       ModuleEntry->Signature = ReadSignature(ModuleEntry->StreamFile);
148ed982584SBen Langmuir     else
149ed982584SBen Langmuir       assert(ModuleEntry->Signature == ReadSignature(ModuleEntry->StreamFile));
150ed982584SBen Langmuir 
151ed982584SBen Langmuir     if (ModuleEntry->Signature != ExpectedSignature) {
152ed982584SBen Langmuir       ErrorStr = ModuleEntry->Signature ? "signature mismatch"
153487ea14aSBen Langmuir                                         : "could not read module signature";
154487ea14aSBen Langmuir 
155ed982584SBen Langmuir       if (NewModule) {
156487ea14aSBen Langmuir         // Remove the module file immediately, since removeModules might try to
157487ea14aSBen Langmuir         // invalidate the file cache for Entry, and that is not safe if this
158487ea14aSBen Langmuir         // module is *itself* up to date, but has an out-of-date importer.
159487ea14aSBen Langmuir         Modules.erase(Entry);
1609eff8b14SManuel Klimek         assert(Chain.back() == ModuleEntry);
161487ea14aSBen Langmuir         Chain.pop_back();
1629eff8b14SManuel Klimek         if (Roots.back() == ModuleEntry)
1639eff8b14SManuel Klimek           Roots.pop_back();
1649eff8b14SManuel Klimek         else
1659eff8b14SManuel Klimek           assert(ImportedBy);
166ed982584SBen Langmuir         delete ModuleEntry;
167487ea14aSBen Langmuir       }
168ed982584SBen Langmuir       return OutOfDate;
169487ea14aSBen Langmuir     }
1707029ce1aSDouglas Gregor   }
171d44252ecSDouglas Gregor 
172d44252ecSDouglas Gregor   if (ImportedBy) {
173d44252ecSDouglas Gregor     ModuleEntry->ImportedBy.insert(ImportedBy);
174d44252ecSDouglas Gregor     ImportedBy->Imports.insert(ModuleEntry);
175d44252ecSDouglas Gregor   } else {
1766fb03aeaSDouglas Gregor     if (!ModuleEntry->DirectlyImported)
1776fb03aeaSDouglas Gregor       ModuleEntry->ImportLoc = ImportLoc;
1786fb03aeaSDouglas Gregor 
179d44252ecSDouglas Gregor     ModuleEntry->DirectlyImported = true;
180d44252ecSDouglas Gregor   }
181d44252ecSDouglas Gregor 
1827029ce1aSDouglas Gregor   Module = ModuleEntry;
1837029ce1aSDouglas Gregor   return NewModule? NewlyLoaded : AlreadyLoaded;
184d44252ecSDouglas Gregor }
185d44252ecSDouglas Gregor 
1869801b253SBen Langmuir void ModuleManager::removeModules(
1879801b253SBen Langmuir     ModuleIterator first, ModuleIterator last,
1889801b253SBen Langmuir     llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
1897029ce1aSDouglas Gregor     ModuleMap *modMap) {
190188dbef2SDouglas Gregor   if (first == last)
191188dbef2SDouglas Gregor     return;
192188dbef2SDouglas Gregor 
193188dbef2SDouglas Gregor   // Collect the set of module file pointers that we'll be removing.
194188dbef2SDouglas Gregor   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
195188dbef2SDouglas Gregor 
1969eff8b14SManuel Klimek   auto IsVictim = [&](ModuleFile *MF) {
1979eff8b14SManuel Klimek     return victimSet.count(MF);
1989eff8b14SManuel Klimek   };
199188dbef2SDouglas Gregor   // Remove any references to the now-destroyed modules.
200188dbef2SDouglas Gregor   for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
2019eff8b14SManuel Klimek     Chain[i]->ImportedBy.remove_if(IsVictim);
202188dbef2SDouglas Gregor   }
2039eff8b14SManuel Klimek   Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),
2049eff8b14SManuel Klimek               Roots.end());
205188dbef2SDouglas Gregor 
206188dbef2SDouglas Gregor   // Delete the modules and erase them from the various structures.
207188dbef2SDouglas Gregor   for (ModuleIterator victim = first; victim != last; ++victim) {
208caea1318SBen Langmuir     Modules.erase((*victim)->File);
209ca39214fSBen Langmuir 
2107029ce1aSDouglas Gregor     if (modMap) {
211beee15e7SBen Langmuir       StringRef ModuleName = (*victim)->ModuleName;
2127029ce1aSDouglas Gregor       if (Module *mod = modMap->findModule(ModuleName)) {
213a13603a2SCraig Topper         mod->setASTFile(nullptr);
2147029ce1aSDouglas Gregor       }
2157029ce1aSDouglas Gregor     }
2164f05478cSBen Langmuir 
2179801b253SBen Langmuir     // Files that didn't make it through ReadASTCore successfully will be
2189801b253SBen Langmuir     // rebuilt (or there was an error). Invalidate them so that we can load the
2199801b253SBen Langmuir     // new files that will be renamed over the old ones.
2209801b253SBen Langmuir     if (LoadedSuccessfully.count(*victim) == 0)
2214f05478cSBen Langmuir       FileMgr.invalidateCache((*victim)->File);
2224f05478cSBen Langmuir 
223188dbef2SDouglas Gregor     delete *victim;
224188dbef2SDouglas Gregor   }
225188dbef2SDouglas Gregor 
226188dbef2SDouglas Gregor   // Remove the modules from the chain.
227188dbef2SDouglas Gregor   Chain.erase(first, last);
228188dbef2SDouglas Gregor }
229188dbef2SDouglas Gregor 
2305cd06f26SRafael Espindola void
2315cd06f26SRafael Espindola ModuleManager::addInMemoryBuffer(StringRef FileName,
2325cd06f26SRafael Espindola                                  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
233d44252ecSDouglas Gregor 
2345cd06f26SRafael Espindola   const FileEntry *Entry =
2355cd06f26SRafael Espindola       FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
2365cd06f26SRafael Espindola   InMemoryBuffers[Entry] = std::move(Buffer);
237d44252ecSDouglas Gregor }
238d44252ecSDouglas Gregor 
2397f330cdbSRichard Smith bool ModuleManager::addKnownModuleFile(StringRef FileName) {
2407f330cdbSRichard Smith   const FileEntry *File;
2417f330cdbSRichard Smith   if (lookupModuleFile(FileName, 0, 0, File))
2427f330cdbSRichard Smith     return true;
2437f330cdbSRichard Smith   if (!Modules.count(File))
2447f330cdbSRichard Smith     AdditionalKnownModuleFiles.insert(File);
2457f330cdbSRichard Smith   return false;
2467f330cdbSRichard Smith }
2477f330cdbSRichard Smith 
248e97cd90aSDouglas Gregor ModuleManager::VisitState *ModuleManager::allocateVisitState() {
249e97cd90aSDouglas Gregor   // Fast path: if we have a cached state, use it.
250e97cd90aSDouglas Gregor   if (FirstVisitState) {
251e97cd90aSDouglas Gregor     VisitState *Result = FirstVisitState;
252e97cd90aSDouglas Gregor     FirstVisitState = FirstVisitState->NextState;
253a13603a2SCraig Topper     Result->NextState = nullptr;
254e97cd90aSDouglas Gregor     return Result;
255e97cd90aSDouglas Gregor   }
256e97cd90aSDouglas Gregor 
257e97cd90aSDouglas Gregor   // Allocate and return a new state.
258e97cd90aSDouglas Gregor   return new VisitState(size());
259e97cd90aSDouglas Gregor }
260e97cd90aSDouglas Gregor 
261e97cd90aSDouglas Gregor void ModuleManager::returnVisitState(VisitState *State) {
262a13603a2SCraig Topper   assert(State->NextState == nullptr && "Visited state is in list?");
263e97cd90aSDouglas Gregor   State->NextState = FirstVisitState;
264e97cd90aSDouglas Gregor   FirstVisitState = State;
265e97cd90aSDouglas Gregor }
266e97cd90aSDouglas Gregor 
2677211ac15SDouglas Gregor void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
2687211ac15SDouglas Gregor   GlobalIndex = Index;
269603cd869SDouglas Gregor   if (!GlobalIndex) {
270603cd869SDouglas Gregor     ModulesInCommonWithGlobalIndex.clear();
271603cd869SDouglas Gregor     return;
2727029ce1aSDouglas Gregor   }
273603cd869SDouglas Gregor 
274603cd869SDouglas Gregor   // Notify the global module index about all of the modules we've already
275603cd869SDouglas Gregor   // loaded.
276603cd869SDouglas Gregor   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
277603cd869SDouglas Gregor     if (!GlobalIndex->loadedModuleFile(Chain[I])) {
278603cd869SDouglas Gregor       ModulesInCommonWithGlobalIndex.push_back(Chain[I]);
279603cd869SDouglas Gregor     }
280603cd869SDouglas Gregor   }
281603cd869SDouglas Gregor }
282603cd869SDouglas Gregor 
283603cd869SDouglas Gregor void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
2847f330cdbSRichard Smith   AdditionalKnownModuleFiles.remove(MF->File);
2857f330cdbSRichard Smith 
286603cd869SDouglas Gregor   if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
287603cd869SDouglas Gregor     return;
288603cd869SDouglas Gregor 
289603cd869SDouglas Gregor   ModulesInCommonWithGlobalIndex.push_back(MF);
2907211ac15SDouglas Gregor }
2917211ac15SDouglas Gregor 
292*bb165fb0SAdrian Prantl ModuleManager::ModuleManager(FileManager &FileMgr,
293*bb165fb0SAdrian Prantl                              const PCHContainerOperations &PCHContainerOps)
294*bb165fb0SAdrian Prantl     : FileMgr(FileMgr), PCHContainerOps(PCHContainerOps), GlobalIndex(),
295*bb165fb0SAdrian Prantl       FirstVisitState(nullptr) {}
296d44252ecSDouglas Gregor 
297d44252ecSDouglas Gregor ModuleManager::~ModuleManager() {
298d44252ecSDouglas Gregor   for (unsigned i = 0, e = Chain.size(); i != e; ++i)
299d44252ecSDouglas Gregor     delete Chain[e - i - 1];
300e97cd90aSDouglas Gregor   delete FirstVisitState;
301d44252ecSDouglas Gregor }
302d44252ecSDouglas Gregor 
3037211ac15SDouglas Gregor void
3047211ac15SDouglas Gregor ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
3057211ac15SDouglas Gregor                      void *UserData,
3064dd9b43cSCraig Topper                      llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
3077211ac15SDouglas Gregor   // If the visitation order vector is the wrong size, recompute the order.
308e41d7feaSDouglas Gregor   if (VisitOrder.size() != Chain.size()) {
309d44252ecSDouglas Gregor     unsigned N = size();
310e41d7feaSDouglas Gregor     VisitOrder.clear();
311e41d7feaSDouglas Gregor     VisitOrder.reserve(N);
312d44252ecSDouglas Gregor 
313d44252ecSDouglas Gregor     // Record the number of incoming edges for each module. When we
314d44252ecSDouglas Gregor     // encounter a module with no incoming edges, push it into the queue
315d44252ecSDouglas Gregor     // to seed the queue.
316de3ef502SDouglas Gregor     SmallVector<ModuleFile *, 4> Queue;
317d44252ecSDouglas Gregor     Queue.reserve(N);
318bdb259d2SDouglas Gregor     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
319bdb259d2SDouglas Gregor     UnusedIncomingEdges.reserve(size());
320d44252ecSDouglas Gregor     for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
321d44252ecSDouglas Gregor       if (unsigned Size = (*M)->ImportedBy.size())
322bdb259d2SDouglas Gregor         UnusedIncomingEdges.push_back(Size);
323bdb259d2SDouglas Gregor       else {
324bdb259d2SDouglas Gregor         UnusedIncomingEdges.push_back(0);
325d44252ecSDouglas Gregor         Queue.push_back(*M);
326d44252ecSDouglas Gregor       }
327bdb259d2SDouglas Gregor     }
328d44252ecSDouglas Gregor 
329e41d7feaSDouglas Gregor     // Traverse the graph, making sure to visit a module before visiting any
330e41d7feaSDouglas Gregor     // of its dependencies.
331d44252ecSDouglas Gregor     unsigned QueueStart = 0;
332d44252ecSDouglas Gregor     while (QueueStart < Queue.size()) {
333de3ef502SDouglas Gregor       ModuleFile *CurrentModule = Queue[QueueStart++];
334e41d7feaSDouglas Gregor       VisitOrder.push_back(CurrentModule);
335d44252ecSDouglas Gregor 
336d44252ecSDouglas Gregor       // For any module that this module depends on, push it on the
337d44252ecSDouglas Gregor       // stack (if it hasn't already been marked as visited).
338bdb259d2SDouglas Gregor       for (llvm::SetVector<ModuleFile *>::iterator
339bdb259d2SDouglas Gregor              M = CurrentModule->Imports.begin(),
340d44252ecSDouglas Gregor              MEnd = CurrentModule->Imports.end();
341d44252ecSDouglas Gregor            M != MEnd; ++M) {
342d44252ecSDouglas Gregor         // Remove our current module as an impediment to visiting the
343d44252ecSDouglas Gregor         // module we depend on. If we were the last unvisited module
344d44252ecSDouglas Gregor         // that depends on this particular module, push it into the
345d44252ecSDouglas Gregor         // queue to be visited.
346bdb259d2SDouglas Gregor         unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
347d44252ecSDouglas Gregor         if (NumUnusedEdges && (--NumUnusedEdges == 0))
348d44252ecSDouglas Gregor           Queue.push_back(*M);
349d44252ecSDouglas Gregor       }
350d44252ecSDouglas Gregor     }
351e41d7feaSDouglas Gregor 
352e41d7feaSDouglas Gregor     assert(VisitOrder.size() == N && "Visitation order is wrong?");
3537211ac15SDouglas Gregor 
354e97cd90aSDouglas Gregor     delete FirstVisitState;
355a13603a2SCraig Topper     FirstVisitState = nullptr;
356e41d7feaSDouglas Gregor   }
357e41d7feaSDouglas Gregor 
358e97cd90aSDouglas Gregor   VisitState *State = allocateVisitState();
359e97cd90aSDouglas Gregor   unsigned VisitNumber = State->NextVisitNumber++;
360e41d7feaSDouglas Gregor 
3617211ac15SDouglas Gregor   // If the caller has provided us with a hit-set that came from the global
3627211ac15SDouglas Gregor   // module index, mark every module file in common with the global module
3637211ac15SDouglas Gregor   // index that is *not* in that set as 'visited'.
3647211ac15SDouglas Gregor   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
3657211ac15SDouglas Gregor     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
3667211ac15SDouglas Gregor     {
3677211ac15SDouglas Gregor       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
3687029ce1aSDouglas Gregor       if (!ModuleFilesHit->count(M))
369e97cd90aSDouglas Gregor         State->VisitNumber[M->Index] = VisitNumber;
3707211ac15SDouglas Gregor     }
3717211ac15SDouglas Gregor   }
3727211ac15SDouglas Gregor 
373e41d7feaSDouglas Gregor   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
374e41d7feaSDouglas Gregor     ModuleFile *CurrentModule = VisitOrder[I];
375e41d7feaSDouglas Gregor     // Should we skip this module file?
376e97cd90aSDouglas Gregor     if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
377e41d7feaSDouglas Gregor       continue;
378e41d7feaSDouglas Gregor 
379e41d7feaSDouglas Gregor     // Visit the module.
380e97cd90aSDouglas Gregor     assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
381e97cd90aSDouglas Gregor     State->VisitNumber[CurrentModule->Index] = VisitNumber;
382e41d7feaSDouglas Gregor     if (!Visitor(*CurrentModule, UserData))
383e41d7feaSDouglas Gregor       continue;
384e41d7feaSDouglas Gregor 
385e41d7feaSDouglas Gregor     // The visitor has requested that cut off visitation of any
386e41d7feaSDouglas Gregor     // module that the current module depends on. To indicate this
387e41d7feaSDouglas Gregor     // behavior, we mark all of the reachable modules as having been visited.
388e41d7feaSDouglas Gregor     ModuleFile *NextModule = CurrentModule;
389e41d7feaSDouglas Gregor     do {
390e41d7feaSDouglas Gregor       // For any module that this module depends on, push it on the
391e41d7feaSDouglas Gregor       // stack (if it hasn't already been marked as visited).
392e41d7feaSDouglas Gregor       for (llvm::SetVector<ModuleFile *>::iterator
393e41d7feaSDouglas Gregor              M = NextModule->Imports.begin(),
394e41d7feaSDouglas Gregor              MEnd = NextModule->Imports.end();
395e41d7feaSDouglas Gregor            M != MEnd; ++M) {
396e97cd90aSDouglas Gregor         if (State->VisitNumber[(*M)->Index] != VisitNumber) {
397e97cd90aSDouglas Gregor           State->Stack.push_back(*M);
398e97cd90aSDouglas Gregor           State->VisitNumber[(*M)->Index] = VisitNumber;
399e41d7feaSDouglas Gregor         }
400e41d7feaSDouglas Gregor       }
401e41d7feaSDouglas Gregor 
402e97cd90aSDouglas Gregor       if (State->Stack.empty())
403e41d7feaSDouglas Gregor         break;
404e41d7feaSDouglas Gregor 
405e41d7feaSDouglas Gregor       // Pop the next module off the stack.
40625284cc9SRobert Wilhelm       NextModule = State->Stack.pop_back_val();
407e41d7feaSDouglas Gregor     } while (true);
408e41d7feaSDouglas Gregor   }
409e97cd90aSDouglas Gregor 
410e97cd90aSDouglas Gregor   returnVisitState(State);
411d44252ecSDouglas Gregor }
412d44252ecSDouglas Gregor 
4139eff8b14SManuel Klimek static void markVisitedDepthFirst(ModuleFile &M,
414bdb259d2SDouglas Gregor                                   SmallVectorImpl<bool> &Visited) {
4159eff8b14SManuel Klimek   for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
4169eff8b14SManuel Klimek                                                IMEnd = M.Imports.end();
4179eff8b14SManuel Klimek        IM != IMEnd; ++IM) {
4189eff8b14SManuel Klimek     if (Visited[(*IM)->Index])
4199eff8b14SManuel Klimek       continue;
4209eff8b14SManuel Klimek     Visited[(*IM)->Index] = true;
4219eff8b14SManuel Klimek     if (!M.DirectlyImported)
4229eff8b14SManuel Klimek       markVisitedDepthFirst(**IM, Visited);
4239eff8b14SManuel Klimek   }
4249eff8b14SManuel Klimek }
4259eff8b14SManuel Klimek 
4269eff8b14SManuel Klimek /// \brief Perform a depth-first visit of the current module.
4279eff8b14SManuel Klimek static bool visitDepthFirst(
4289eff8b14SManuel Klimek     ModuleFile &M,
4299eff8b14SManuel Klimek     ModuleManager::DFSPreorderControl (*PreorderVisitor)(ModuleFile &M,
4309eff8b14SManuel Klimek                                                          void *UserData),
4319eff8b14SManuel Klimek     bool (*PostorderVisitor)(ModuleFile &M, void *UserData), void *UserData,
4329eff8b14SManuel Klimek     SmallVectorImpl<bool> &Visited) {
4339eff8b14SManuel Klimek   if (PreorderVisitor) {
4349eff8b14SManuel Klimek     switch (PreorderVisitor(M, UserData)) {
4359eff8b14SManuel Klimek     case ModuleManager::Abort:
436d44252ecSDouglas Gregor       return true;
4379eff8b14SManuel Klimek     case ModuleManager::SkipImports:
4389eff8b14SManuel Klimek       markVisitedDepthFirst(M, Visited);
4399eff8b14SManuel Klimek       return false;
4409eff8b14SManuel Klimek     case ModuleManager::Continue:
4419eff8b14SManuel Klimek       break;
4429eff8b14SManuel Klimek     }
4439eff8b14SManuel Klimek   }
444d44252ecSDouglas Gregor 
445d44252ecSDouglas Gregor   // Visit children
446de3ef502SDouglas Gregor   for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
447d44252ecSDouglas Gregor                                             IMEnd = M.Imports.end();
448d44252ecSDouglas Gregor        IM != IMEnd; ++IM) {
449bdb259d2SDouglas Gregor     if (Visited[(*IM)->Index])
450d44252ecSDouglas Gregor       continue;
451bdb259d2SDouglas Gregor     Visited[(*IM)->Index] = true;
452d44252ecSDouglas Gregor 
4539eff8b14SManuel Klimek     if (visitDepthFirst(**IM, PreorderVisitor, PostorderVisitor, UserData, Visited))
454d44252ecSDouglas Gregor       return true;
455d44252ecSDouglas Gregor   }
456d44252ecSDouglas Gregor 
4579eff8b14SManuel Klimek   if (PostorderVisitor)
4589eff8b14SManuel Klimek     return PostorderVisitor(M, UserData);
4599eff8b14SManuel Klimek 
4609eff8b14SManuel Klimek   return false;
461d44252ecSDouglas Gregor }
462d44252ecSDouglas Gregor 
4639eff8b14SManuel Klimek void ModuleManager::visitDepthFirst(
4649eff8b14SManuel Klimek     ModuleManager::DFSPreorderControl (*PreorderVisitor)(ModuleFile &M,
465d44252ecSDouglas Gregor                                                          void *UserData),
4669eff8b14SManuel Klimek     bool (*PostorderVisitor)(ModuleFile &M, void *UserData), void *UserData) {
467bdb259d2SDouglas Gregor   SmallVector<bool, 16> Visited(size(), false);
4689eff8b14SManuel Klimek   for (unsigned I = 0, N = Roots.size(); I != N; ++I) {
4699eff8b14SManuel Klimek     if (Visited[Roots[I]->Index])
470d44252ecSDouglas Gregor       continue;
4719eff8b14SManuel Klimek     Visited[Roots[I]->Index] = true;
472d44252ecSDouglas Gregor 
4739eff8b14SManuel Klimek     if (::visitDepthFirst(*Roots[I], PreorderVisitor, PostorderVisitor, UserData, Visited))
474d44252ecSDouglas Gregor       return;
475d44252ecSDouglas Gregor   }
476d44252ecSDouglas Gregor }
4779d7c1a2aSDouglas Gregor 
4787029ce1aSDouglas Gregor bool ModuleManager::lookupModuleFile(StringRef FileName,
4797029ce1aSDouglas Gregor                                      off_t ExpectedSize,
4807029ce1aSDouglas Gregor                                      time_t ExpectedModTime,
4817029ce1aSDouglas Gregor                                      const FileEntry *&File) {
48205f82ba2SBen Langmuir   // Open the file immediately to ensure there is no race between stat'ing and
48305f82ba2SBen Langmuir   // opening the file.
48405f82ba2SBen Langmuir   File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
4857029ce1aSDouglas Gregor 
4867029ce1aSDouglas Gregor   if (!File && FileName != "-") {
4877029ce1aSDouglas Gregor     return false;
4887029ce1aSDouglas Gregor   }
4897029ce1aSDouglas Gregor 
4907029ce1aSDouglas Gregor   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
491027731d7SBen Langmuir       (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
492027731d7SBen Langmuir     // Do not destroy File, as it may be referenced. If we need to rebuild it,
493027731d7SBen Langmuir     // it will be destroyed by removeModules.
4947029ce1aSDouglas Gregor     return true;
4957029ce1aSDouglas Gregor 
4967029ce1aSDouglas Gregor   return false;
4977029ce1aSDouglas Gregor }
4987029ce1aSDouglas Gregor 
4999d7c1a2aSDouglas Gregor #ifndef NDEBUG
5009d7c1a2aSDouglas Gregor namespace llvm {
5019d7c1a2aSDouglas Gregor   template<>
5029d7c1a2aSDouglas Gregor   struct GraphTraits<ModuleManager> {
503de3ef502SDouglas Gregor     typedef ModuleFile NodeType;
504de3ef502SDouglas Gregor     typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
5059d7c1a2aSDouglas Gregor     typedef ModuleManager::ModuleConstIterator nodes_iterator;
5069d7c1a2aSDouglas Gregor 
5079d7c1a2aSDouglas Gregor     static ChildIteratorType child_begin(NodeType *Node) {
5089d7c1a2aSDouglas Gregor       return Node->Imports.begin();
5099d7c1a2aSDouglas Gregor     }
5109d7c1a2aSDouglas Gregor 
5119d7c1a2aSDouglas Gregor     static ChildIteratorType child_end(NodeType *Node) {
5129d7c1a2aSDouglas Gregor       return Node->Imports.end();
5139d7c1a2aSDouglas Gregor     }
5149d7c1a2aSDouglas Gregor 
5159d7c1a2aSDouglas Gregor     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
5169d7c1a2aSDouglas Gregor       return Manager.begin();
5179d7c1a2aSDouglas Gregor     }
5189d7c1a2aSDouglas Gregor 
5199d7c1a2aSDouglas Gregor     static nodes_iterator nodes_end(const ModuleManager &Manager) {
5209d7c1a2aSDouglas Gregor       return Manager.end();
5219d7c1a2aSDouglas Gregor     }
5229d7c1a2aSDouglas Gregor   };
5239d7c1a2aSDouglas Gregor 
5249d7c1a2aSDouglas Gregor   template<>
5259d7c1a2aSDouglas Gregor   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
5269d7c1a2aSDouglas Gregor     explicit DOTGraphTraits(bool IsSimple = false)
5279d7c1a2aSDouglas Gregor       : DefaultDOTGraphTraits(IsSimple) { }
5289d7c1a2aSDouglas Gregor 
5299d7c1a2aSDouglas Gregor     static bool renderGraphFromBottomUp() {
5309d7c1a2aSDouglas Gregor       return true;
5319d7c1a2aSDouglas Gregor     }
5329d7c1a2aSDouglas Gregor 
533de3ef502SDouglas Gregor     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
534beee15e7SBen Langmuir       return M->ModuleName;
5359d7c1a2aSDouglas Gregor     }
5369d7c1a2aSDouglas Gregor   };
5379d7c1a2aSDouglas Gregor }
5389d7c1a2aSDouglas Gregor 
5399d7c1a2aSDouglas Gregor void ModuleManager::viewGraph() {
5409d7c1a2aSDouglas Gregor   llvm::ViewGraph(*this, "Modules");
5419d7c1a2aSDouglas Gregor }
5429d7c1a2aSDouglas Gregor #endif
543