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 
48*5cd06f26SRafael Espindola std::unique_ptr<llvm::MemoryBuffer>
49*5cd06f26SRafael Espindola ModuleManager::lookupBuffer(StringRef Name) {
50dadd85dcSDouglas Gregor   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
51dadd85dcSDouglas Gregor                                            /*cacheFailure=*/false);
52*5cd06f26SRafael 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,
607029ce1aSDouglas Gregor                          ModuleFile *&Module,
617029ce1aSDouglas Gregor                          std::string &ErrorStr) {
62a13603a2SCraig Topper   Module = nullptr;
637029ce1aSDouglas Gregor 
647029ce1aSDouglas Gregor   // Look for the file entry. This only fails if the expected size or
657029ce1aSDouglas Gregor   // modification time differ.
667029ce1aSDouglas Gregor   const FileEntry *Entry;
67c27d0d5eSEli Friedman   if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
68c27d0d5eSEli Friedman     ErrorStr = "module file out of date";
697029ce1aSDouglas Gregor     return OutOfDate;
70c27d0d5eSEli Friedman   }
717029ce1aSDouglas Gregor 
72d44252ecSDouglas Gregor   if (!Entry && FileName != "-") {
73c27d0d5eSEli Friedman     ErrorStr = "module file not found";
747029ce1aSDouglas Gregor     return Missing;
75d44252ecSDouglas Gregor   }
76d44252ecSDouglas Gregor 
77d44252ecSDouglas Gregor   // Check whether we already loaded this module, before
78de3ef502SDouglas Gregor   ModuleFile *&ModuleEntry = Modules[Entry];
79d44252ecSDouglas Gregor   bool NewModule = false;
80d44252ecSDouglas Gregor   if (!ModuleEntry) {
81d44252ecSDouglas Gregor     // Allocate a new module.
824fc9f3e8SDouglas Gregor     ModuleFile *New = new ModuleFile(Type, Generation);
83bdb259d2SDouglas Gregor     New->Index = Chain.size();
84d44252ecSDouglas Gregor     New->FileName = FileName.str();
85aedf7144SArgyrios Kyrtzidis     New->File = Entry;
866fb03aeaSDouglas Gregor     New->ImportLoc = ImportLoc;
87d44252ecSDouglas Gregor     Chain.push_back(New);
88d44252ecSDouglas Gregor     NewModule = true;
89d44252ecSDouglas Gregor     ModuleEntry = New;
90d44252ecSDouglas Gregor 
91f430da4dSDmitri Gribenko     New->InputFilesValidationTimestamp = 0;
92f430da4dSDmitri Gribenko     if (New->Kind == MK_Module) {
93f430da4dSDmitri Gribenko       std::string TimestampFilename = New->getTimestampFilename();
94c8130a74SBen Langmuir       vfs::Status Status;
95f430da4dSDmitri Gribenko       // A cached stat value would be fine as well.
96f430da4dSDmitri Gribenko       if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
97f430da4dSDmitri Gribenko         New->InputFilesValidationTimestamp =
98f430da4dSDmitri Gribenko             Status.getLastModificationTime().toEpochTime();
99f430da4dSDmitri Gribenko     }
100f430da4dSDmitri Gribenko 
101d44252ecSDouglas Gregor     // Load the contents of the module
102*5cd06f26SRafael Espindola     if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
103d44252ecSDouglas Gregor       // The buffer was already provided for us.
104*5cd06f26SRafael Espindola       New->Buffer = std::move(Buffer);
105d44252ecSDouglas Gregor     } else {
106d44252ecSDouglas Gregor       // Open the AST file.
107c080917eSRafael Espindola       std::error_code ec;
108d44252ecSDouglas Gregor       if (FileName == "-") {
1092d2b420aSRafael Espindola         llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf =
1102d2b420aSRafael Espindola             llvm::MemoryBuffer::getSTDIN();
1112d2b420aSRafael Espindola         ec = Buf.getError();
112d44252ecSDouglas Gregor         if (ec)
113d44252ecSDouglas Gregor           ErrorStr = ec.message();
1142d2b420aSRafael Espindola         else
1152d2b420aSRafael Espindola           New->Buffer = std::move(Buf.get());
1169801b253SBen Langmuir       } else {
1179801b253SBen Langmuir         // Leave the FileEntry open so if it gets read again by another
1189801b253SBen Langmuir         // ModuleManager it must be the same underlying file.
1199801b253SBen Langmuir         // FIXME: Because FileManager::getFile() doesn't guarantee that it will
1209801b253SBen Langmuir         // give us an open file, this may not be 100% reliable.
1219801b253SBen Langmuir         New->Buffer.reset(FileMgr.getBufferForFile(New->File, &ErrorStr,
1229801b253SBen Langmuir                                                    /*IsVolatile*/false,
1239801b253SBen Langmuir                                                    /*ShouldClose*/false));
1249801b253SBen Langmuir       }
125d44252ecSDouglas Gregor 
126d44252ecSDouglas Gregor       if (!New->Buffer)
1277029ce1aSDouglas Gregor         return Missing;
128d44252ecSDouglas Gregor     }
129d44252ecSDouglas Gregor 
130d44252ecSDouglas Gregor     // Initialize the stream
131d44252ecSDouglas Gregor     New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(),
1327029ce1aSDouglas Gregor                          (const unsigned char *)New->Buffer->getBufferEnd());
1337029ce1aSDouglas Gregor   }
134d44252ecSDouglas Gregor 
135d44252ecSDouglas Gregor   if (ImportedBy) {
136d44252ecSDouglas Gregor     ModuleEntry->ImportedBy.insert(ImportedBy);
137d44252ecSDouglas Gregor     ImportedBy->Imports.insert(ModuleEntry);
138d44252ecSDouglas Gregor   } else {
1396fb03aeaSDouglas Gregor     if (!ModuleEntry->DirectlyImported)
1406fb03aeaSDouglas Gregor       ModuleEntry->ImportLoc = ImportLoc;
1416fb03aeaSDouglas Gregor 
142d44252ecSDouglas Gregor     ModuleEntry->DirectlyImported = true;
143d44252ecSDouglas Gregor   }
144d44252ecSDouglas Gregor 
1457029ce1aSDouglas Gregor   Module = ModuleEntry;
1467029ce1aSDouglas Gregor   return NewModule? NewlyLoaded : AlreadyLoaded;
147d44252ecSDouglas Gregor }
148d44252ecSDouglas Gregor 
1499801b253SBen Langmuir void ModuleManager::removeModules(
1509801b253SBen Langmuir     ModuleIterator first, ModuleIterator last,
1519801b253SBen Langmuir     llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
1527029ce1aSDouglas Gregor     ModuleMap *modMap) {
153188dbef2SDouglas Gregor   if (first == last)
154188dbef2SDouglas Gregor     return;
155188dbef2SDouglas Gregor 
156188dbef2SDouglas Gregor   // Collect the set of module file pointers that we'll be removing.
157188dbef2SDouglas Gregor   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
158188dbef2SDouglas Gregor 
159188dbef2SDouglas Gregor   // Remove any references to the now-destroyed modules.
160188dbef2SDouglas Gregor   for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
161b55d0226SChandler Carruth     Chain[i]->ImportedBy.remove_if([&](ModuleFile *MF) {
162b55d0226SChandler Carruth       return victimSet.count(MF);
163b55d0226SChandler Carruth     });
164188dbef2SDouglas Gregor   }
165188dbef2SDouglas Gregor 
166188dbef2SDouglas Gregor   // Delete the modules and erase them from the various structures.
167188dbef2SDouglas Gregor   for (ModuleIterator victim = first; victim != last; ++victim) {
168caea1318SBen Langmuir     Modules.erase((*victim)->File);
169ca39214fSBen Langmuir 
1707029ce1aSDouglas Gregor     if (modMap) {
171beee15e7SBen Langmuir       StringRef ModuleName = (*victim)->ModuleName;
1727029ce1aSDouglas Gregor       if (Module *mod = modMap->findModule(ModuleName)) {
173a13603a2SCraig Topper         mod->setASTFile(nullptr);
1747029ce1aSDouglas Gregor       }
1757029ce1aSDouglas Gregor     }
1764f05478cSBen Langmuir 
1779801b253SBen Langmuir     // Files that didn't make it through ReadASTCore successfully will be
1789801b253SBen Langmuir     // rebuilt (or there was an error). Invalidate them so that we can load the
1799801b253SBen Langmuir     // new files that will be renamed over the old ones.
1809801b253SBen Langmuir     if (LoadedSuccessfully.count(*victim) == 0)
1814f05478cSBen Langmuir       FileMgr.invalidateCache((*victim)->File);
1824f05478cSBen Langmuir 
183188dbef2SDouglas Gregor     delete *victim;
184188dbef2SDouglas Gregor   }
185188dbef2SDouglas Gregor 
186188dbef2SDouglas Gregor   // Remove the modules from the chain.
187188dbef2SDouglas Gregor   Chain.erase(first, last);
188188dbef2SDouglas Gregor }
189188dbef2SDouglas Gregor 
190*5cd06f26SRafael Espindola void
191*5cd06f26SRafael Espindola ModuleManager::addInMemoryBuffer(StringRef FileName,
192*5cd06f26SRafael Espindola                                  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
193d44252ecSDouglas Gregor 
194*5cd06f26SRafael Espindola   const FileEntry *Entry =
195*5cd06f26SRafael Espindola       FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
196*5cd06f26SRafael Espindola   InMemoryBuffers[Entry] = std::move(Buffer);
197d44252ecSDouglas Gregor }
198d44252ecSDouglas Gregor 
199e97cd90aSDouglas Gregor ModuleManager::VisitState *ModuleManager::allocateVisitState() {
200e97cd90aSDouglas Gregor   // Fast path: if we have a cached state, use it.
201e97cd90aSDouglas Gregor   if (FirstVisitState) {
202e97cd90aSDouglas Gregor     VisitState *Result = FirstVisitState;
203e97cd90aSDouglas Gregor     FirstVisitState = FirstVisitState->NextState;
204a13603a2SCraig Topper     Result->NextState = nullptr;
205e97cd90aSDouglas Gregor     return Result;
206e97cd90aSDouglas Gregor   }
207e97cd90aSDouglas Gregor 
208e97cd90aSDouglas Gregor   // Allocate and return a new state.
209e97cd90aSDouglas Gregor   return new VisitState(size());
210e97cd90aSDouglas Gregor }
211e97cd90aSDouglas Gregor 
212e97cd90aSDouglas Gregor void ModuleManager::returnVisitState(VisitState *State) {
213a13603a2SCraig Topper   assert(State->NextState == nullptr && "Visited state is in list?");
214e97cd90aSDouglas Gregor   State->NextState = FirstVisitState;
215e97cd90aSDouglas Gregor   FirstVisitState = State;
216e97cd90aSDouglas Gregor }
217e97cd90aSDouglas Gregor 
2187211ac15SDouglas Gregor void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
2197211ac15SDouglas Gregor   GlobalIndex = Index;
220603cd869SDouglas Gregor   if (!GlobalIndex) {
221603cd869SDouglas Gregor     ModulesInCommonWithGlobalIndex.clear();
222603cd869SDouglas Gregor     return;
2237029ce1aSDouglas Gregor   }
224603cd869SDouglas Gregor 
225603cd869SDouglas Gregor   // Notify the global module index about all of the modules we've already
226603cd869SDouglas Gregor   // loaded.
227603cd869SDouglas Gregor   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
228603cd869SDouglas Gregor     if (!GlobalIndex->loadedModuleFile(Chain[I])) {
229603cd869SDouglas Gregor       ModulesInCommonWithGlobalIndex.push_back(Chain[I]);
230603cd869SDouglas Gregor     }
231603cd869SDouglas Gregor   }
232603cd869SDouglas Gregor }
233603cd869SDouglas Gregor 
234603cd869SDouglas Gregor void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
235603cd869SDouglas Gregor   if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
236603cd869SDouglas Gregor     return;
237603cd869SDouglas Gregor 
238603cd869SDouglas Gregor   ModulesInCommonWithGlobalIndex.push_back(MF);
2397211ac15SDouglas Gregor }
2407211ac15SDouglas Gregor 
2417211ac15SDouglas Gregor ModuleManager::ModuleManager(FileManager &FileMgr)
242a13603a2SCraig Topper   : FileMgr(FileMgr), GlobalIndex(), FirstVisitState(nullptr) {}
243d44252ecSDouglas Gregor 
244d44252ecSDouglas Gregor ModuleManager::~ModuleManager() {
245d44252ecSDouglas Gregor   for (unsigned i = 0, e = Chain.size(); i != e; ++i)
246d44252ecSDouglas Gregor     delete Chain[e - i - 1];
247e97cd90aSDouglas Gregor   delete FirstVisitState;
248d44252ecSDouglas Gregor }
249d44252ecSDouglas Gregor 
2507211ac15SDouglas Gregor void
2517211ac15SDouglas Gregor ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
2527211ac15SDouglas Gregor                      void *UserData,
2534dd9b43cSCraig Topper                      llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
2547211ac15SDouglas Gregor   // If the visitation order vector is the wrong size, recompute the order.
255e41d7feaSDouglas Gregor   if (VisitOrder.size() != Chain.size()) {
256d44252ecSDouglas Gregor     unsigned N = size();
257e41d7feaSDouglas Gregor     VisitOrder.clear();
258e41d7feaSDouglas Gregor     VisitOrder.reserve(N);
259d44252ecSDouglas Gregor 
260d44252ecSDouglas Gregor     // Record the number of incoming edges for each module. When we
261d44252ecSDouglas Gregor     // encounter a module with no incoming edges, push it into the queue
262d44252ecSDouglas Gregor     // to seed the queue.
263de3ef502SDouglas Gregor     SmallVector<ModuleFile *, 4> Queue;
264d44252ecSDouglas Gregor     Queue.reserve(N);
265bdb259d2SDouglas Gregor     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
266bdb259d2SDouglas Gregor     UnusedIncomingEdges.reserve(size());
267d44252ecSDouglas Gregor     for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
268d44252ecSDouglas Gregor       if (unsigned Size = (*M)->ImportedBy.size())
269bdb259d2SDouglas Gregor         UnusedIncomingEdges.push_back(Size);
270bdb259d2SDouglas Gregor       else {
271bdb259d2SDouglas Gregor         UnusedIncomingEdges.push_back(0);
272d44252ecSDouglas Gregor         Queue.push_back(*M);
273d44252ecSDouglas Gregor       }
274bdb259d2SDouglas Gregor     }
275d44252ecSDouglas Gregor 
276e41d7feaSDouglas Gregor     // Traverse the graph, making sure to visit a module before visiting any
277e41d7feaSDouglas Gregor     // of its dependencies.
278d44252ecSDouglas Gregor     unsigned QueueStart = 0;
279d44252ecSDouglas Gregor     while (QueueStart < Queue.size()) {
280de3ef502SDouglas Gregor       ModuleFile *CurrentModule = Queue[QueueStart++];
281e41d7feaSDouglas Gregor       VisitOrder.push_back(CurrentModule);
282d44252ecSDouglas Gregor 
283d44252ecSDouglas Gregor       // For any module that this module depends on, push it on the
284d44252ecSDouglas Gregor       // stack (if it hasn't already been marked as visited).
285bdb259d2SDouglas Gregor       for (llvm::SetVector<ModuleFile *>::iterator
286bdb259d2SDouglas Gregor              M = CurrentModule->Imports.begin(),
287d44252ecSDouglas Gregor              MEnd = CurrentModule->Imports.end();
288d44252ecSDouglas Gregor            M != MEnd; ++M) {
289d44252ecSDouglas Gregor         // Remove our current module as an impediment to visiting the
290d44252ecSDouglas Gregor         // module we depend on. If we were the last unvisited module
291d44252ecSDouglas Gregor         // that depends on this particular module, push it into the
292d44252ecSDouglas Gregor         // queue to be visited.
293bdb259d2SDouglas Gregor         unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
294d44252ecSDouglas Gregor         if (NumUnusedEdges && (--NumUnusedEdges == 0))
295d44252ecSDouglas Gregor           Queue.push_back(*M);
296d44252ecSDouglas Gregor       }
297d44252ecSDouglas Gregor     }
298e41d7feaSDouglas Gregor 
299e41d7feaSDouglas Gregor     assert(VisitOrder.size() == N && "Visitation order is wrong?");
3007211ac15SDouglas Gregor 
301e97cd90aSDouglas Gregor     delete FirstVisitState;
302a13603a2SCraig Topper     FirstVisitState = nullptr;
303e41d7feaSDouglas Gregor   }
304e41d7feaSDouglas Gregor 
305e97cd90aSDouglas Gregor   VisitState *State = allocateVisitState();
306e97cd90aSDouglas Gregor   unsigned VisitNumber = State->NextVisitNumber++;
307e41d7feaSDouglas Gregor 
3087211ac15SDouglas Gregor   // If the caller has provided us with a hit-set that came from the global
3097211ac15SDouglas Gregor   // module index, mark every module file in common with the global module
3107211ac15SDouglas Gregor   // index that is *not* in that set as 'visited'.
3117211ac15SDouglas Gregor   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
3127211ac15SDouglas Gregor     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
3137211ac15SDouglas Gregor     {
3147211ac15SDouglas Gregor       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
3157029ce1aSDouglas Gregor       if (!ModuleFilesHit->count(M))
316e97cd90aSDouglas Gregor         State->VisitNumber[M->Index] = VisitNumber;
3177211ac15SDouglas Gregor     }
3187211ac15SDouglas Gregor   }
3197211ac15SDouglas Gregor 
320e41d7feaSDouglas Gregor   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
321e41d7feaSDouglas Gregor     ModuleFile *CurrentModule = VisitOrder[I];
322e41d7feaSDouglas Gregor     // Should we skip this module file?
323e97cd90aSDouglas Gregor     if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
324e41d7feaSDouglas Gregor       continue;
325e41d7feaSDouglas Gregor 
326e41d7feaSDouglas Gregor     // Visit the module.
327e97cd90aSDouglas Gregor     assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
328e97cd90aSDouglas Gregor     State->VisitNumber[CurrentModule->Index] = VisitNumber;
329e41d7feaSDouglas Gregor     if (!Visitor(*CurrentModule, UserData))
330e41d7feaSDouglas Gregor       continue;
331e41d7feaSDouglas Gregor 
332e41d7feaSDouglas Gregor     // The visitor has requested that cut off visitation of any
333e41d7feaSDouglas Gregor     // module that the current module depends on. To indicate this
334e41d7feaSDouglas Gregor     // behavior, we mark all of the reachable modules as having been visited.
335e41d7feaSDouglas Gregor     ModuleFile *NextModule = CurrentModule;
336e41d7feaSDouglas Gregor     do {
337e41d7feaSDouglas Gregor       // For any module that this module depends on, push it on the
338e41d7feaSDouglas Gregor       // stack (if it hasn't already been marked as visited).
339e41d7feaSDouglas Gregor       for (llvm::SetVector<ModuleFile *>::iterator
340e41d7feaSDouglas Gregor              M = NextModule->Imports.begin(),
341e41d7feaSDouglas Gregor              MEnd = NextModule->Imports.end();
342e41d7feaSDouglas Gregor            M != MEnd; ++M) {
343e97cd90aSDouglas Gregor         if (State->VisitNumber[(*M)->Index] != VisitNumber) {
344e97cd90aSDouglas Gregor           State->Stack.push_back(*M);
345e97cd90aSDouglas Gregor           State->VisitNumber[(*M)->Index] = VisitNumber;
346e41d7feaSDouglas Gregor         }
347e41d7feaSDouglas Gregor       }
348e41d7feaSDouglas Gregor 
349e97cd90aSDouglas Gregor       if (State->Stack.empty())
350e41d7feaSDouglas Gregor         break;
351e41d7feaSDouglas Gregor 
352e41d7feaSDouglas Gregor       // Pop the next module off the stack.
35325284cc9SRobert Wilhelm       NextModule = State->Stack.pop_back_val();
354e41d7feaSDouglas Gregor     } while (true);
355e41d7feaSDouglas Gregor   }
356e97cd90aSDouglas Gregor 
357e97cd90aSDouglas Gregor   returnVisitState(State);
358d44252ecSDouglas Gregor }
359d44252ecSDouglas Gregor 
360d44252ecSDouglas Gregor /// \brief Perform a depth-first visit of the current module.
361de3ef502SDouglas Gregor static bool visitDepthFirst(ModuleFile &M,
362de3ef502SDouglas Gregor                             bool (*Visitor)(ModuleFile &M, bool Preorder,
363d44252ecSDouglas Gregor                                             void *UserData),
364d44252ecSDouglas Gregor                             void *UserData,
365bdb259d2SDouglas Gregor                             SmallVectorImpl<bool> &Visited) {
366d44252ecSDouglas Gregor   // Preorder visitation
367d44252ecSDouglas Gregor   if (Visitor(M, /*Preorder=*/true, UserData))
368d44252ecSDouglas Gregor     return true;
369d44252ecSDouglas Gregor 
370d44252ecSDouglas Gregor   // Visit children
371de3ef502SDouglas Gregor   for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
372d44252ecSDouglas Gregor                                             IMEnd = M.Imports.end();
373d44252ecSDouglas Gregor        IM != IMEnd; ++IM) {
374bdb259d2SDouglas Gregor     if (Visited[(*IM)->Index])
375d44252ecSDouglas Gregor       continue;
376bdb259d2SDouglas Gregor     Visited[(*IM)->Index] = true;
377d44252ecSDouglas Gregor 
378d44252ecSDouglas Gregor     if (visitDepthFirst(**IM, Visitor, UserData, Visited))
379d44252ecSDouglas Gregor       return true;
380d44252ecSDouglas Gregor   }
381d44252ecSDouglas Gregor 
382d44252ecSDouglas Gregor   // Postorder visitation
383d44252ecSDouglas Gregor   return Visitor(M, /*Preorder=*/false, UserData);
384d44252ecSDouglas Gregor }
385d44252ecSDouglas Gregor 
386de3ef502SDouglas Gregor void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
387d44252ecSDouglas Gregor                                                     void *UserData),
388d44252ecSDouglas Gregor                                     void *UserData) {
389bdb259d2SDouglas Gregor   SmallVector<bool, 16> Visited(size(), false);
390d44252ecSDouglas Gregor   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
391bdb259d2SDouglas Gregor     if (Visited[Chain[I]->Index])
392d44252ecSDouglas Gregor       continue;
393bdb259d2SDouglas Gregor     Visited[Chain[I]->Index] = true;
394d44252ecSDouglas Gregor 
395d44252ecSDouglas Gregor     if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
396d44252ecSDouglas Gregor       return;
397d44252ecSDouglas Gregor   }
398d44252ecSDouglas Gregor }
3999d7c1a2aSDouglas Gregor 
4007029ce1aSDouglas Gregor bool ModuleManager::lookupModuleFile(StringRef FileName,
4017029ce1aSDouglas Gregor                                      off_t ExpectedSize,
4027029ce1aSDouglas Gregor                                      time_t ExpectedModTime,
4037029ce1aSDouglas Gregor                                      const FileEntry *&File) {
40405f82ba2SBen Langmuir   // Open the file immediately to ensure there is no race between stat'ing and
40505f82ba2SBen Langmuir   // opening the file.
40605f82ba2SBen Langmuir   File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
4077029ce1aSDouglas Gregor 
4087029ce1aSDouglas Gregor   if (!File && FileName != "-") {
4097029ce1aSDouglas Gregor     return false;
4107029ce1aSDouglas Gregor   }
4117029ce1aSDouglas Gregor 
4127029ce1aSDouglas Gregor   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
413027731d7SBen Langmuir       (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
414027731d7SBen Langmuir     // Do not destroy File, as it may be referenced. If we need to rebuild it,
415027731d7SBen Langmuir     // it will be destroyed by removeModules.
4167029ce1aSDouglas Gregor     return true;
4177029ce1aSDouglas Gregor 
4187029ce1aSDouglas Gregor   return false;
4197029ce1aSDouglas Gregor }
4207029ce1aSDouglas Gregor 
4219d7c1a2aSDouglas Gregor #ifndef NDEBUG
4229d7c1a2aSDouglas Gregor namespace llvm {
4239d7c1a2aSDouglas Gregor   template<>
4249d7c1a2aSDouglas Gregor   struct GraphTraits<ModuleManager> {
425de3ef502SDouglas Gregor     typedef ModuleFile NodeType;
426de3ef502SDouglas Gregor     typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
4279d7c1a2aSDouglas Gregor     typedef ModuleManager::ModuleConstIterator nodes_iterator;
4289d7c1a2aSDouglas Gregor 
4299d7c1a2aSDouglas Gregor     static ChildIteratorType child_begin(NodeType *Node) {
4309d7c1a2aSDouglas Gregor       return Node->Imports.begin();
4319d7c1a2aSDouglas Gregor     }
4329d7c1a2aSDouglas Gregor 
4339d7c1a2aSDouglas Gregor     static ChildIteratorType child_end(NodeType *Node) {
4349d7c1a2aSDouglas Gregor       return Node->Imports.end();
4359d7c1a2aSDouglas Gregor     }
4369d7c1a2aSDouglas Gregor 
4379d7c1a2aSDouglas Gregor     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
4389d7c1a2aSDouglas Gregor       return Manager.begin();
4399d7c1a2aSDouglas Gregor     }
4409d7c1a2aSDouglas Gregor 
4419d7c1a2aSDouglas Gregor     static nodes_iterator nodes_end(const ModuleManager &Manager) {
4429d7c1a2aSDouglas Gregor       return Manager.end();
4439d7c1a2aSDouglas Gregor     }
4449d7c1a2aSDouglas Gregor   };
4459d7c1a2aSDouglas Gregor 
4469d7c1a2aSDouglas Gregor   template<>
4479d7c1a2aSDouglas Gregor   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
4489d7c1a2aSDouglas Gregor     explicit DOTGraphTraits(bool IsSimple = false)
4499d7c1a2aSDouglas Gregor       : DefaultDOTGraphTraits(IsSimple) { }
4509d7c1a2aSDouglas Gregor 
4519d7c1a2aSDouglas Gregor     static bool renderGraphFromBottomUp() {
4529d7c1a2aSDouglas Gregor       return true;
4539d7c1a2aSDouglas Gregor     }
4549d7c1a2aSDouglas Gregor 
455de3ef502SDouglas Gregor     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
456beee15e7SBen Langmuir       return M->ModuleName;
4579d7c1a2aSDouglas Gregor     }
4589d7c1a2aSDouglas Gregor   };
4599d7c1a2aSDouglas Gregor }
4609d7c1a2aSDouglas Gregor 
4619d7c1a2aSDouglas Gregor void ModuleManager::viewGraph() {
4629d7c1a2aSDouglas Gregor   llvm::ViewGraph(*this, "Modules");
4639d7c1a2aSDouglas Gregor }
4649d7c1a2aSDouglas Gregor #endif
465