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 //===----------------------------------------------------------------------===//
14beee15e7SBen Langmuir #include "clang/Lex/HeaderSearch.h"
157029ce1aSDouglas Gregor #include "clang/Lex/ModuleMap.h"
167211ac15SDouglas Gregor #include "clang/Serialization/GlobalModuleIndex.h"
17af04f98cSBenjamin Kramer #include "clang/Serialization/ModuleManager.h"
18d44252ecSDouglas Gregor #include "llvm/Support/MemoryBuffer.h"
19552c169eSRafael Espindola #include "llvm/Support/Path.h"
20d44252ecSDouglas Gregor #include "llvm/Support/raw_ostream.h"
218a8e554aSRafael Espindola #include <system_error>
22d44252ecSDouglas Gregor 
239d7c1a2aSDouglas Gregor #ifndef NDEBUG
249d7c1a2aSDouglas Gregor #include "llvm/Support/GraphWriter.h"
259d7c1a2aSDouglas Gregor #endif
269d7c1a2aSDouglas Gregor 
27d44252ecSDouglas Gregor using namespace clang;
28d44252ecSDouglas Gregor using namespace serialization;
29d44252ecSDouglas Gregor 
30de3ef502SDouglas Gregor ModuleFile *ModuleManager::lookup(StringRef Name) {
31dadd85dcSDouglas Gregor   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
32dadd85dcSDouglas Gregor                                            /*cacheFailure=*/false);
33bf7fc9c5SDouglas Gregor   if (Entry)
34bf7fc9c5SDouglas Gregor     return lookup(Entry);
35bf7fc9c5SDouglas Gregor 
36a13603a2SCraig Topper   return nullptr;
37bf7fc9c5SDouglas Gregor }
38bf7fc9c5SDouglas Gregor 
39bf7fc9c5SDouglas Gregor ModuleFile *ModuleManager::lookup(const FileEntry *File) {
40bf7fc9c5SDouglas Gregor   llvm::DenseMap<const FileEntry *, ModuleFile *>::iterator Known
41bf7fc9c5SDouglas Gregor     = 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 
557029ce1aSDouglas Gregor ModuleManager::AddModuleResult
56d44252ecSDouglas Gregor ModuleManager::addModule(StringRef FileName, ModuleKind Type,
576fb03aeaSDouglas Gregor                          SourceLocation ImportLoc, ModuleFile *ImportedBy,
587029ce1aSDouglas Gregor                          unsigned Generation,
597029ce1aSDouglas Gregor                          off_t ExpectedSize, time_t ExpectedModTime,
60487ea14aSBen Langmuir                          ASTFileSignature ExpectedSignature,
61487ea14aSBen Langmuir                          std::function<ASTFileSignature(llvm::BitstreamReader &)>
62487ea14aSBen Langmuir                              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);
98d44252ecSDouglas Gregor     NewModule = true;
99d44252ecSDouglas Gregor     ModuleEntry = New;
100d44252ecSDouglas Gregor 
101f430da4dSDmitri Gribenko     New->InputFilesValidationTimestamp = 0;
102e842a474SRichard Smith     if (New->Kind == MK_ImplicitModule) {
103f430da4dSDmitri Gribenko       std::string TimestampFilename = New->getTimestampFilename();
104c8130a74SBen Langmuir       vfs::Status Status;
105f430da4dSDmitri Gribenko       // A cached stat value would be fine as well.
106f430da4dSDmitri Gribenko       if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
107f430da4dSDmitri Gribenko         New->InputFilesValidationTimestamp =
108f430da4dSDmitri Gribenko             Status.getLastModificationTime().toEpochTime();
109f430da4dSDmitri Gribenko     }
110f430da4dSDmitri Gribenko 
111d44252ecSDouglas Gregor     // Load the contents of the module
1125cd06f26SRafael Espindola     if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
113d44252ecSDouglas Gregor       // The buffer was already provided for us.
1145cd06f26SRafael Espindola       New->Buffer = std::move(Buffer);
115d44252ecSDouglas Gregor     } else {
116d44252ecSDouglas Gregor       // Open the AST file.
117a885796dSBenjamin Kramer       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf(
118a885796dSBenjamin Kramer           (std::error_code()));
119d44252ecSDouglas Gregor       if (FileName == "-") {
120a885796dSBenjamin Kramer         Buf = llvm::MemoryBuffer::getSTDIN();
1219801b253SBen Langmuir       } else {
1229801b253SBen Langmuir         // Leave the FileEntry open so if it gets read again by another
1239801b253SBen Langmuir         // ModuleManager it must be the same underlying file.
1249801b253SBen Langmuir         // FIXME: Because FileManager::getFile() doesn't guarantee that it will
1259801b253SBen Langmuir         // give us an open file, this may not be 100% reliable.
126a885796dSBenjamin Kramer         Buf = FileMgr.getBufferForFile(New->File,
127a885796dSBenjamin Kramer                                        /*IsVolatile=*/false,
128a885796dSBenjamin Kramer                                        /*ShouldClose=*/false);
1299801b253SBen Langmuir       }
130d44252ecSDouglas Gregor 
131a885796dSBenjamin Kramer       if (!Buf) {
132a885796dSBenjamin Kramer         ErrorStr = Buf.getError().message();
1337029ce1aSDouglas Gregor         return Missing;
134d44252ecSDouglas Gregor       }
135d44252ecSDouglas Gregor 
136a885796dSBenjamin Kramer       New->Buffer = std::move(*Buf);
137a885796dSBenjamin Kramer     }
138a885796dSBenjamin Kramer 
139cbc368c5SAdrian Prantl     // Initialize the stream
140cbc368c5SAdrian Prantl     New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(),
141cbc368c5SAdrian Prantl                          (const unsigned char *)New->Buffer->getBufferEnd());
142ed982584SBen Langmuir   }
143487ea14aSBen Langmuir 
144487ea14aSBen Langmuir   if (ExpectedSignature) {
145ed982584SBen Langmuir     if (NewModule)
146ed982584SBen Langmuir       ModuleEntry->Signature = ReadSignature(ModuleEntry->StreamFile);
147ed982584SBen Langmuir     else
148ed982584SBen Langmuir       assert(ModuleEntry->Signature == ReadSignature(ModuleEntry->StreamFile));
149ed982584SBen Langmuir 
150ed982584SBen Langmuir     if (ModuleEntry->Signature != ExpectedSignature) {
151ed982584SBen Langmuir       ErrorStr = ModuleEntry->Signature ? "signature mismatch"
152487ea14aSBen Langmuir                                         : "could not read module signature";
153487ea14aSBen Langmuir 
154ed982584SBen Langmuir       if (NewModule) {
155487ea14aSBen Langmuir         // Remove the module file immediately, since removeModules might try to
156487ea14aSBen Langmuir         // invalidate the file cache for Entry, and that is not safe if this
157487ea14aSBen Langmuir         // module is *itself* up to date, but has an out-of-date importer.
158487ea14aSBen Langmuir         Modules.erase(Entry);
159487ea14aSBen Langmuir         Chain.pop_back();
160ed982584SBen Langmuir         delete ModuleEntry;
161487ea14aSBen Langmuir       }
162ed982584SBen Langmuir       return OutOfDate;
163487ea14aSBen Langmuir     }
1647029ce1aSDouglas Gregor   }
165d44252ecSDouglas Gregor 
166d44252ecSDouglas Gregor   if (ImportedBy) {
167d44252ecSDouglas Gregor     ModuleEntry->ImportedBy.insert(ImportedBy);
168d44252ecSDouglas Gregor     ImportedBy->Imports.insert(ModuleEntry);
169d44252ecSDouglas Gregor   } else {
1706fb03aeaSDouglas Gregor     if (!ModuleEntry->DirectlyImported)
1716fb03aeaSDouglas Gregor       ModuleEntry->ImportLoc = ImportLoc;
1726fb03aeaSDouglas Gregor 
173d44252ecSDouglas Gregor     ModuleEntry->DirectlyImported = true;
174d44252ecSDouglas Gregor   }
175d44252ecSDouglas Gregor 
1767029ce1aSDouglas Gregor   Module = ModuleEntry;
1777029ce1aSDouglas Gregor   return NewModule? NewlyLoaded : AlreadyLoaded;
178d44252ecSDouglas Gregor }
179d44252ecSDouglas Gregor 
1809801b253SBen Langmuir void ModuleManager::removeModules(
1819801b253SBen Langmuir     ModuleIterator first, ModuleIterator last,
1829801b253SBen Langmuir     llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
1837029ce1aSDouglas Gregor     ModuleMap *modMap) {
184188dbef2SDouglas Gregor   if (first == last)
185188dbef2SDouglas Gregor     return;
186188dbef2SDouglas Gregor 
187188dbef2SDouglas Gregor   // Collect the set of module file pointers that we'll be removing.
188188dbef2SDouglas Gregor   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
189188dbef2SDouglas Gregor 
190188dbef2SDouglas Gregor   // Remove any references to the now-destroyed modules.
191188dbef2SDouglas Gregor   for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
192b55d0226SChandler Carruth     Chain[i]->ImportedBy.remove_if([&](ModuleFile *MF) {
193b55d0226SChandler Carruth       return victimSet.count(MF);
194b55d0226SChandler Carruth     });
195188dbef2SDouglas Gregor   }
196188dbef2SDouglas Gregor 
197188dbef2SDouglas Gregor   // Delete the modules and erase them from the various structures.
198188dbef2SDouglas Gregor   for (ModuleIterator victim = first; victim != last; ++victim) {
199caea1318SBen Langmuir     Modules.erase((*victim)->File);
200ca39214fSBen Langmuir 
2017029ce1aSDouglas Gregor     if (modMap) {
202beee15e7SBen Langmuir       StringRef ModuleName = (*victim)->ModuleName;
2037029ce1aSDouglas Gregor       if (Module *mod = modMap->findModule(ModuleName)) {
204a13603a2SCraig Topper         mod->setASTFile(nullptr);
2057029ce1aSDouglas Gregor       }
2067029ce1aSDouglas Gregor     }
2074f05478cSBen Langmuir 
2089801b253SBen Langmuir     // Files that didn't make it through ReadASTCore successfully will be
2099801b253SBen Langmuir     // rebuilt (or there was an error). Invalidate them so that we can load the
2109801b253SBen Langmuir     // new files that will be renamed over the old ones.
2119801b253SBen Langmuir     if (LoadedSuccessfully.count(*victim) == 0)
2124f05478cSBen Langmuir       FileMgr.invalidateCache((*victim)->File);
2134f05478cSBen Langmuir 
214188dbef2SDouglas Gregor     delete *victim;
215188dbef2SDouglas Gregor   }
216188dbef2SDouglas Gregor 
217188dbef2SDouglas Gregor   // Remove the modules from the chain.
218188dbef2SDouglas Gregor   Chain.erase(first, last);
219188dbef2SDouglas Gregor }
220188dbef2SDouglas Gregor 
2215cd06f26SRafael Espindola void
2225cd06f26SRafael Espindola ModuleManager::addInMemoryBuffer(StringRef FileName,
2235cd06f26SRafael Espindola                                  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
224d44252ecSDouglas Gregor 
2255cd06f26SRafael Espindola   const FileEntry *Entry =
2265cd06f26SRafael Espindola       FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
2275cd06f26SRafael Espindola   InMemoryBuffers[Entry] = std::move(Buffer);
228d44252ecSDouglas Gregor }
229d44252ecSDouglas Gregor 
230*7f330cdbSRichard Smith bool ModuleManager::addKnownModuleFile(StringRef FileName) {
231*7f330cdbSRichard Smith   const FileEntry *File;
232*7f330cdbSRichard Smith   if (lookupModuleFile(FileName, 0, 0, File))
233*7f330cdbSRichard Smith     return true;
234*7f330cdbSRichard Smith   if (!Modules.count(File))
235*7f330cdbSRichard Smith     AdditionalKnownModuleFiles.insert(File);
236*7f330cdbSRichard Smith   return false;
237*7f330cdbSRichard Smith }
238*7f330cdbSRichard Smith 
239e97cd90aSDouglas Gregor ModuleManager::VisitState *ModuleManager::allocateVisitState() {
240e97cd90aSDouglas Gregor   // Fast path: if we have a cached state, use it.
241e97cd90aSDouglas Gregor   if (FirstVisitState) {
242e97cd90aSDouglas Gregor     VisitState *Result = FirstVisitState;
243e97cd90aSDouglas Gregor     FirstVisitState = FirstVisitState->NextState;
244a13603a2SCraig Topper     Result->NextState = nullptr;
245e97cd90aSDouglas Gregor     return Result;
246e97cd90aSDouglas Gregor   }
247e97cd90aSDouglas Gregor 
248e97cd90aSDouglas Gregor   // Allocate and return a new state.
249e97cd90aSDouglas Gregor   return new VisitState(size());
250e97cd90aSDouglas Gregor }
251e97cd90aSDouglas Gregor 
252e97cd90aSDouglas Gregor void ModuleManager::returnVisitState(VisitState *State) {
253a13603a2SCraig Topper   assert(State->NextState == nullptr && "Visited state is in list?");
254e97cd90aSDouglas Gregor   State->NextState = FirstVisitState;
255e97cd90aSDouglas Gregor   FirstVisitState = State;
256e97cd90aSDouglas Gregor }
257e97cd90aSDouglas Gregor 
2587211ac15SDouglas Gregor void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
2597211ac15SDouglas Gregor   GlobalIndex = Index;
260603cd869SDouglas Gregor   if (!GlobalIndex) {
261603cd869SDouglas Gregor     ModulesInCommonWithGlobalIndex.clear();
262603cd869SDouglas Gregor     return;
2637029ce1aSDouglas Gregor   }
264603cd869SDouglas Gregor 
265603cd869SDouglas Gregor   // Notify the global module index about all of the modules we've already
266603cd869SDouglas Gregor   // loaded.
267603cd869SDouglas Gregor   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
268603cd869SDouglas Gregor     if (!GlobalIndex->loadedModuleFile(Chain[I])) {
269603cd869SDouglas Gregor       ModulesInCommonWithGlobalIndex.push_back(Chain[I]);
270603cd869SDouglas Gregor     }
271603cd869SDouglas Gregor   }
272603cd869SDouglas Gregor }
273603cd869SDouglas Gregor 
274603cd869SDouglas Gregor void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
275*7f330cdbSRichard Smith   AdditionalKnownModuleFiles.remove(MF->File);
276*7f330cdbSRichard Smith 
277603cd869SDouglas Gregor   if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
278603cd869SDouglas Gregor     return;
279603cd869SDouglas Gregor 
280603cd869SDouglas Gregor   ModulesInCommonWithGlobalIndex.push_back(MF);
2817211ac15SDouglas Gregor }
2827211ac15SDouglas Gregor 
2837211ac15SDouglas Gregor ModuleManager::ModuleManager(FileManager &FileMgr)
284a13603a2SCraig Topper   : FileMgr(FileMgr), GlobalIndex(), FirstVisitState(nullptr) {}
285d44252ecSDouglas Gregor 
286d44252ecSDouglas Gregor ModuleManager::~ModuleManager() {
287d44252ecSDouglas Gregor   for (unsigned i = 0, e = Chain.size(); i != e; ++i)
288d44252ecSDouglas Gregor     delete Chain[e - i - 1];
289e97cd90aSDouglas Gregor   delete FirstVisitState;
290d44252ecSDouglas Gregor }
291d44252ecSDouglas Gregor 
2927211ac15SDouglas Gregor void
2937211ac15SDouglas Gregor ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
2947211ac15SDouglas Gregor                      void *UserData,
2954dd9b43cSCraig Topper                      llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
2967211ac15SDouglas Gregor   // If the visitation order vector is the wrong size, recompute the order.
297e41d7feaSDouglas Gregor   if (VisitOrder.size() != Chain.size()) {
298d44252ecSDouglas Gregor     unsigned N = size();
299e41d7feaSDouglas Gregor     VisitOrder.clear();
300e41d7feaSDouglas Gregor     VisitOrder.reserve(N);
301d44252ecSDouglas Gregor 
302d44252ecSDouglas Gregor     // Record the number of incoming edges for each module. When we
303d44252ecSDouglas Gregor     // encounter a module with no incoming edges, push it into the queue
304d44252ecSDouglas Gregor     // to seed the queue.
305de3ef502SDouglas Gregor     SmallVector<ModuleFile *, 4> Queue;
306d44252ecSDouglas Gregor     Queue.reserve(N);
307bdb259d2SDouglas Gregor     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
308bdb259d2SDouglas Gregor     UnusedIncomingEdges.reserve(size());
309d44252ecSDouglas Gregor     for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
310d44252ecSDouglas Gregor       if (unsigned Size = (*M)->ImportedBy.size())
311bdb259d2SDouglas Gregor         UnusedIncomingEdges.push_back(Size);
312bdb259d2SDouglas Gregor       else {
313bdb259d2SDouglas Gregor         UnusedIncomingEdges.push_back(0);
314d44252ecSDouglas Gregor         Queue.push_back(*M);
315d44252ecSDouglas Gregor       }
316bdb259d2SDouglas Gregor     }
317d44252ecSDouglas Gregor 
318e41d7feaSDouglas Gregor     // Traverse the graph, making sure to visit a module before visiting any
319e41d7feaSDouglas Gregor     // of its dependencies.
320d44252ecSDouglas Gregor     unsigned QueueStart = 0;
321d44252ecSDouglas Gregor     while (QueueStart < Queue.size()) {
322de3ef502SDouglas Gregor       ModuleFile *CurrentModule = Queue[QueueStart++];
323e41d7feaSDouglas Gregor       VisitOrder.push_back(CurrentModule);
324d44252ecSDouglas Gregor 
325d44252ecSDouglas Gregor       // For any module that this module depends on, push it on the
326d44252ecSDouglas Gregor       // stack (if it hasn't already been marked as visited).
327bdb259d2SDouglas Gregor       for (llvm::SetVector<ModuleFile *>::iterator
328bdb259d2SDouglas Gregor              M = CurrentModule->Imports.begin(),
329d44252ecSDouglas Gregor              MEnd = CurrentModule->Imports.end();
330d44252ecSDouglas Gregor            M != MEnd; ++M) {
331d44252ecSDouglas Gregor         // Remove our current module as an impediment to visiting the
332d44252ecSDouglas Gregor         // module we depend on. If we were the last unvisited module
333d44252ecSDouglas Gregor         // that depends on this particular module, push it into the
334d44252ecSDouglas Gregor         // queue to be visited.
335bdb259d2SDouglas Gregor         unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
336d44252ecSDouglas Gregor         if (NumUnusedEdges && (--NumUnusedEdges == 0))
337d44252ecSDouglas Gregor           Queue.push_back(*M);
338d44252ecSDouglas Gregor       }
339d44252ecSDouglas Gregor     }
340e41d7feaSDouglas Gregor 
341e41d7feaSDouglas Gregor     assert(VisitOrder.size() == N && "Visitation order is wrong?");
3427211ac15SDouglas Gregor 
343e97cd90aSDouglas Gregor     delete FirstVisitState;
344a13603a2SCraig Topper     FirstVisitState = nullptr;
345e41d7feaSDouglas Gregor   }
346e41d7feaSDouglas Gregor 
347e97cd90aSDouglas Gregor   VisitState *State = allocateVisitState();
348e97cd90aSDouglas Gregor   unsigned VisitNumber = State->NextVisitNumber++;
349e41d7feaSDouglas Gregor 
3507211ac15SDouglas Gregor   // If the caller has provided us with a hit-set that came from the global
3517211ac15SDouglas Gregor   // module index, mark every module file in common with the global module
3527211ac15SDouglas Gregor   // index that is *not* in that set as 'visited'.
3537211ac15SDouglas Gregor   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
3547211ac15SDouglas Gregor     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
3557211ac15SDouglas Gregor     {
3567211ac15SDouglas Gregor       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
3577029ce1aSDouglas Gregor       if (!ModuleFilesHit->count(M))
358e97cd90aSDouglas Gregor         State->VisitNumber[M->Index] = VisitNumber;
3597211ac15SDouglas Gregor     }
3607211ac15SDouglas Gregor   }
3617211ac15SDouglas Gregor 
362e41d7feaSDouglas Gregor   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
363e41d7feaSDouglas Gregor     ModuleFile *CurrentModule = VisitOrder[I];
364e41d7feaSDouglas Gregor     // Should we skip this module file?
365e97cd90aSDouglas Gregor     if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
366e41d7feaSDouglas Gregor       continue;
367e41d7feaSDouglas Gregor 
368e41d7feaSDouglas Gregor     // Visit the module.
369e97cd90aSDouglas Gregor     assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
370e97cd90aSDouglas Gregor     State->VisitNumber[CurrentModule->Index] = VisitNumber;
371e41d7feaSDouglas Gregor     if (!Visitor(*CurrentModule, UserData))
372e41d7feaSDouglas Gregor       continue;
373e41d7feaSDouglas Gregor 
374e41d7feaSDouglas Gregor     // The visitor has requested that cut off visitation of any
375e41d7feaSDouglas Gregor     // module that the current module depends on. To indicate this
376e41d7feaSDouglas Gregor     // behavior, we mark all of the reachable modules as having been visited.
377e41d7feaSDouglas Gregor     ModuleFile *NextModule = CurrentModule;
378e41d7feaSDouglas Gregor     do {
379e41d7feaSDouglas Gregor       // For any module that this module depends on, push it on the
380e41d7feaSDouglas Gregor       // stack (if it hasn't already been marked as visited).
381e41d7feaSDouglas Gregor       for (llvm::SetVector<ModuleFile *>::iterator
382e41d7feaSDouglas Gregor              M = NextModule->Imports.begin(),
383e41d7feaSDouglas Gregor              MEnd = NextModule->Imports.end();
384e41d7feaSDouglas Gregor            M != MEnd; ++M) {
385e97cd90aSDouglas Gregor         if (State->VisitNumber[(*M)->Index] != VisitNumber) {
386e97cd90aSDouglas Gregor           State->Stack.push_back(*M);
387e97cd90aSDouglas Gregor           State->VisitNumber[(*M)->Index] = VisitNumber;
388e41d7feaSDouglas Gregor         }
389e41d7feaSDouglas Gregor       }
390e41d7feaSDouglas Gregor 
391e97cd90aSDouglas Gregor       if (State->Stack.empty())
392e41d7feaSDouglas Gregor         break;
393e41d7feaSDouglas Gregor 
394e41d7feaSDouglas Gregor       // Pop the next module off the stack.
39525284cc9SRobert Wilhelm       NextModule = State->Stack.pop_back_val();
396e41d7feaSDouglas Gregor     } while (true);
397e41d7feaSDouglas Gregor   }
398e97cd90aSDouglas Gregor 
399e97cd90aSDouglas Gregor   returnVisitState(State);
400d44252ecSDouglas Gregor }
401d44252ecSDouglas Gregor 
402d44252ecSDouglas Gregor /// \brief Perform a depth-first visit of the current module.
403de3ef502SDouglas Gregor static bool visitDepthFirst(ModuleFile &M,
404de3ef502SDouglas Gregor                             bool (*Visitor)(ModuleFile &M, bool Preorder,
405d44252ecSDouglas Gregor                                             void *UserData),
406d44252ecSDouglas Gregor                             void *UserData,
407bdb259d2SDouglas Gregor                             SmallVectorImpl<bool> &Visited) {
408d44252ecSDouglas Gregor   // Preorder visitation
409d44252ecSDouglas Gregor   if (Visitor(M, /*Preorder=*/true, UserData))
410d44252ecSDouglas Gregor     return true;
411d44252ecSDouglas Gregor 
412d44252ecSDouglas Gregor   // Visit children
413de3ef502SDouglas Gregor   for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
414d44252ecSDouglas Gregor                                             IMEnd = M.Imports.end();
415d44252ecSDouglas Gregor        IM != IMEnd; ++IM) {
416bdb259d2SDouglas Gregor     if (Visited[(*IM)->Index])
417d44252ecSDouglas Gregor       continue;
418bdb259d2SDouglas Gregor     Visited[(*IM)->Index] = true;
419d44252ecSDouglas Gregor 
420d44252ecSDouglas Gregor     if (visitDepthFirst(**IM, Visitor, UserData, Visited))
421d44252ecSDouglas Gregor       return true;
422d44252ecSDouglas Gregor   }
423d44252ecSDouglas Gregor 
424d44252ecSDouglas Gregor   // Postorder visitation
425d44252ecSDouglas Gregor   return Visitor(M, /*Preorder=*/false, UserData);
426d44252ecSDouglas Gregor }
427d44252ecSDouglas Gregor 
428de3ef502SDouglas Gregor void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
429d44252ecSDouglas Gregor                                                     void *UserData),
430d44252ecSDouglas Gregor                                     void *UserData) {
431bdb259d2SDouglas Gregor   SmallVector<bool, 16> Visited(size(), false);
432d44252ecSDouglas Gregor   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
433bdb259d2SDouglas Gregor     if (Visited[Chain[I]->Index])
434d44252ecSDouglas Gregor       continue;
435bdb259d2SDouglas Gregor     Visited[Chain[I]->Index] = true;
436d44252ecSDouglas Gregor 
437d44252ecSDouglas Gregor     if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
438d44252ecSDouglas Gregor       return;
439d44252ecSDouglas Gregor   }
440d44252ecSDouglas Gregor }
4419d7c1a2aSDouglas Gregor 
4427029ce1aSDouglas Gregor bool ModuleManager::lookupModuleFile(StringRef FileName,
4437029ce1aSDouglas Gregor                                      off_t ExpectedSize,
4447029ce1aSDouglas Gregor                                      time_t ExpectedModTime,
4457029ce1aSDouglas Gregor                                      const FileEntry *&File) {
44605f82ba2SBen Langmuir   // Open the file immediately to ensure there is no race between stat'ing and
44705f82ba2SBen Langmuir   // opening the file.
44805f82ba2SBen Langmuir   File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
4497029ce1aSDouglas Gregor 
4507029ce1aSDouglas Gregor   if (!File && FileName != "-") {
4517029ce1aSDouglas Gregor     return false;
4527029ce1aSDouglas Gregor   }
4537029ce1aSDouglas Gregor 
4547029ce1aSDouglas Gregor   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
455027731d7SBen Langmuir       (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
456027731d7SBen Langmuir     // Do not destroy File, as it may be referenced. If we need to rebuild it,
457027731d7SBen Langmuir     // it will be destroyed by removeModules.
4587029ce1aSDouglas Gregor     return true;
4597029ce1aSDouglas Gregor 
4607029ce1aSDouglas Gregor   return false;
4617029ce1aSDouglas Gregor }
4627029ce1aSDouglas Gregor 
4639d7c1a2aSDouglas Gregor #ifndef NDEBUG
4649d7c1a2aSDouglas Gregor namespace llvm {
4659d7c1a2aSDouglas Gregor   template<>
4669d7c1a2aSDouglas Gregor   struct GraphTraits<ModuleManager> {
467de3ef502SDouglas Gregor     typedef ModuleFile NodeType;
468de3ef502SDouglas Gregor     typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
4699d7c1a2aSDouglas Gregor     typedef ModuleManager::ModuleConstIterator nodes_iterator;
4709d7c1a2aSDouglas Gregor 
4719d7c1a2aSDouglas Gregor     static ChildIteratorType child_begin(NodeType *Node) {
4729d7c1a2aSDouglas Gregor       return Node->Imports.begin();
4739d7c1a2aSDouglas Gregor     }
4749d7c1a2aSDouglas Gregor 
4759d7c1a2aSDouglas Gregor     static ChildIteratorType child_end(NodeType *Node) {
4769d7c1a2aSDouglas Gregor       return Node->Imports.end();
4779d7c1a2aSDouglas Gregor     }
4789d7c1a2aSDouglas Gregor 
4799d7c1a2aSDouglas Gregor     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
4809d7c1a2aSDouglas Gregor       return Manager.begin();
4819d7c1a2aSDouglas Gregor     }
4829d7c1a2aSDouglas Gregor 
4839d7c1a2aSDouglas Gregor     static nodes_iterator nodes_end(const ModuleManager &Manager) {
4849d7c1a2aSDouglas Gregor       return Manager.end();
4859d7c1a2aSDouglas Gregor     }
4869d7c1a2aSDouglas Gregor   };
4879d7c1a2aSDouglas Gregor 
4889d7c1a2aSDouglas Gregor   template<>
4899d7c1a2aSDouglas Gregor   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
4909d7c1a2aSDouglas Gregor     explicit DOTGraphTraits(bool IsSimple = false)
4919d7c1a2aSDouglas Gregor       : DefaultDOTGraphTraits(IsSimple) { }
4929d7c1a2aSDouglas Gregor 
4939d7c1a2aSDouglas Gregor     static bool renderGraphFromBottomUp() {
4949d7c1a2aSDouglas Gregor       return true;
4959d7c1a2aSDouglas Gregor     }
4969d7c1a2aSDouglas Gregor 
497de3ef502SDouglas Gregor     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
498beee15e7SBen Langmuir       return M->ModuleName;
4999d7c1a2aSDouglas Gregor     }
5009d7c1a2aSDouglas Gregor   };
5019d7c1a2aSDouglas Gregor }
5029d7c1a2aSDouglas Gregor 
5039d7c1a2aSDouglas Gregor void ModuleManager::viewGraph() {
5049d7c1a2aSDouglas Gregor   llvm::ViewGraph(*this, "Modules");
5059d7c1a2aSDouglas Gregor }
5069d7c1a2aSDouglas Gregor #endif
507