1 //===--- ModuleManager.cpp - Module Manager ---------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the ModuleManager class, which manages a set of loaded
11 //  modules for the ASTReader.
12 //
13 //===----------------------------------------------------------------------===//
14 #include "clang/Lex/HeaderSearch.h"
15 #include "clang/Lex/ModuleMap.h"
16 #include "clang/Serialization/GlobalModuleIndex.h"
17 #include "clang/Serialization/ModuleManager.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 #include "llvm/Support/Path.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <system_error>
22 
23 #ifndef NDEBUG
24 #include "llvm/Support/GraphWriter.h"
25 #endif
26 
27 using namespace clang;
28 using namespace serialization;
29 
30 ModuleFile *ModuleManager::lookup(StringRef Name) {
31   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
32                                            /*cacheFailure=*/false);
33   if (Entry)
34     return lookup(Entry);
35 
36   return nullptr;
37 }
38 
39 ModuleFile *ModuleManager::lookup(const FileEntry *File) {
40   llvm::DenseMap<const FileEntry *, ModuleFile *>::iterator Known
41     = Modules.find(File);
42   if (Known == Modules.end())
43     return nullptr;
44 
45   return Known->second;
46 }
47 
48 std::unique_ptr<llvm::MemoryBuffer>
49 ModuleManager::lookupBuffer(StringRef Name) {
50   const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
51                                            /*cacheFailure=*/false);
52   return std::move(InMemoryBuffers[Entry]);
53 }
54 
55 ModuleManager::AddModuleResult
56 ModuleManager::addModule(StringRef FileName, ModuleKind Type,
57                          SourceLocation ImportLoc, ModuleFile *ImportedBy,
58                          unsigned Generation,
59                          off_t ExpectedSize, time_t ExpectedModTime,
60                          ASTFileSignature ExpectedSignature,
61                          std::function<ASTFileSignature(llvm::BitstreamReader &)>
62                              ReadSignature,
63                          ModuleFile *&Module,
64                          std::string &ErrorStr) {
65   Module = nullptr;
66 
67   // Look for the file entry. This only fails if the expected size or
68   // modification time differ.
69   const FileEntry *Entry;
70   if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
71     ErrorStr = "module file out of date";
72     return OutOfDate;
73   }
74 
75   if (!Entry && FileName != "-") {
76     ErrorStr = "module file not found";
77     return Missing;
78   }
79 
80   // Check whether we already loaded this module, before
81   ModuleFile *&ModuleEntry = Modules[Entry];
82   bool NewModule = false;
83   if (!ModuleEntry) {
84     // Allocate a new module.
85     ModuleFile *New = new ModuleFile(Type, Generation);
86     New->Index = Chain.size();
87     New->FileName = FileName.str();
88     New->File = Entry;
89     New->ImportLoc = ImportLoc;
90     Chain.push_back(New);
91     NewModule = true;
92     ModuleEntry = New;
93 
94     New->InputFilesValidationTimestamp = 0;
95     if (New->Kind == MK_ImplicitModule) {
96       std::string TimestampFilename = New->getTimestampFilename();
97       vfs::Status Status;
98       // A cached stat value would be fine as well.
99       if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
100         New->InputFilesValidationTimestamp =
101             Status.getLastModificationTime().toEpochTime();
102     }
103 
104     // Load the contents of the module
105     if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
106       // The buffer was already provided for us.
107       New->Buffer = std::move(Buffer);
108     } else {
109       // Open the AST file.
110       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf(
111           (std::error_code()));
112       if (FileName == "-") {
113         Buf = llvm::MemoryBuffer::getSTDIN();
114       } else {
115         // Leave the FileEntry open so if it gets read again by another
116         // ModuleManager it must be the same underlying file.
117         // FIXME: Because FileManager::getFile() doesn't guarantee that it will
118         // give us an open file, this may not be 100% reliable.
119         Buf = FileMgr.getBufferForFile(New->File,
120                                        /*IsVolatile=*/false,
121                                        /*ShouldClose=*/false);
122       }
123 
124       if (!Buf) {
125         ErrorStr = Buf.getError().message();
126         return Missing;
127       }
128 
129       New->Buffer = std::move(*Buf);
130     }
131 
132     // Initialize the stream
133     New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(),
134                          (const unsigned char *)New->Buffer->getBufferEnd());
135 
136     if (ExpectedSignature) {
137       New->Signature = ReadSignature(New->StreamFile);
138       if (New->Signature != ExpectedSignature) {
139         ErrorStr = New->Signature ? "signature mismatch"
140                                   : "could not read module signature";
141 
142         // Remove the module file immediately, since removeModules might try to
143         // invalidate the file cache for Entry, and that is not safe if this
144         // module is *itself* up to date, but has an out-of-date importer.
145         Modules.erase(Entry);
146         Chain.pop_back();
147         delete New;
148         return OutOfDate;
149       }
150     }
151   }
152 
153   if (ImportedBy) {
154     ModuleEntry->ImportedBy.insert(ImportedBy);
155     ImportedBy->Imports.insert(ModuleEntry);
156   } else {
157     if (!ModuleEntry->DirectlyImported)
158       ModuleEntry->ImportLoc = ImportLoc;
159 
160     ModuleEntry->DirectlyImported = true;
161   }
162 
163   Module = ModuleEntry;
164   return NewModule? NewlyLoaded : AlreadyLoaded;
165 }
166 
167 void ModuleManager::removeModules(
168     ModuleIterator first, ModuleIterator last,
169     llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully,
170     ModuleMap *modMap) {
171   if (first == last)
172     return;
173 
174   // Collect the set of module file pointers that we'll be removing.
175   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
176 
177   // Remove any references to the now-destroyed modules.
178   for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
179     Chain[i]->ImportedBy.remove_if([&](ModuleFile *MF) {
180       return victimSet.count(MF);
181     });
182   }
183 
184   // Delete the modules and erase them from the various structures.
185   for (ModuleIterator victim = first; victim != last; ++victim) {
186     Modules.erase((*victim)->File);
187 
188     if (modMap) {
189       StringRef ModuleName = (*victim)->ModuleName;
190       if (Module *mod = modMap->findModule(ModuleName)) {
191         mod->setASTFile(nullptr);
192       }
193     }
194 
195     // Files that didn't make it through ReadASTCore successfully will be
196     // rebuilt (or there was an error). Invalidate them so that we can load the
197     // new files that will be renamed over the old ones.
198     if (LoadedSuccessfully.count(*victim) == 0)
199       FileMgr.invalidateCache((*victim)->File);
200 
201     delete *victim;
202   }
203 
204   // Remove the modules from the chain.
205   Chain.erase(first, last);
206 }
207 
208 void
209 ModuleManager::addInMemoryBuffer(StringRef FileName,
210                                  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
211 
212   const FileEntry *Entry =
213       FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
214   InMemoryBuffers[Entry] = std::move(Buffer);
215 }
216 
217 ModuleManager::VisitState *ModuleManager::allocateVisitState() {
218   // Fast path: if we have a cached state, use it.
219   if (FirstVisitState) {
220     VisitState *Result = FirstVisitState;
221     FirstVisitState = FirstVisitState->NextState;
222     Result->NextState = nullptr;
223     return Result;
224   }
225 
226   // Allocate and return a new state.
227   return new VisitState(size());
228 }
229 
230 void ModuleManager::returnVisitState(VisitState *State) {
231   assert(State->NextState == nullptr && "Visited state is in list?");
232   State->NextState = FirstVisitState;
233   FirstVisitState = State;
234 }
235 
236 void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
237   GlobalIndex = Index;
238   if (!GlobalIndex) {
239     ModulesInCommonWithGlobalIndex.clear();
240     return;
241   }
242 
243   // Notify the global module index about all of the modules we've already
244   // loaded.
245   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
246     if (!GlobalIndex->loadedModuleFile(Chain[I])) {
247       ModulesInCommonWithGlobalIndex.push_back(Chain[I]);
248     }
249   }
250 }
251 
252 void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
253   if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
254     return;
255 
256   ModulesInCommonWithGlobalIndex.push_back(MF);
257 }
258 
259 ModuleManager::ModuleManager(FileManager &FileMgr)
260   : FileMgr(FileMgr), GlobalIndex(), FirstVisitState(nullptr) {}
261 
262 ModuleManager::~ModuleManager() {
263   for (unsigned i = 0, e = Chain.size(); i != e; ++i)
264     delete Chain[e - i - 1];
265   delete FirstVisitState;
266 }
267 
268 void
269 ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
270                      void *UserData,
271                      llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
272   // If the visitation order vector is the wrong size, recompute the order.
273   if (VisitOrder.size() != Chain.size()) {
274     unsigned N = size();
275     VisitOrder.clear();
276     VisitOrder.reserve(N);
277 
278     // Record the number of incoming edges for each module. When we
279     // encounter a module with no incoming edges, push it into the queue
280     // to seed the queue.
281     SmallVector<ModuleFile *, 4> Queue;
282     Queue.reserve(N);
283     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
284     UnusedIncomingEdges.reserve(size());
285     for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
286       if (unsigned Size = (*M)->ImportedBy.size())
287         UnusedIncomingEdges.push_back(Size);
288       else {
289         UnusedIncomingEdges.push_back(0);
290         Queue.push_back(*M);
291       }
292     }
293 
294     // Traverse the graph, making sure to visit a module before visiting any
295     // of its dependencies.
296     unsigned QueueStart = 0;
297     while (QueueStart < Queue.size()) {
298       ModuleFile *CurrentModule = Queue[QueueStart++];
299       VisitOrder.push_back(CurrentModule);
300 
301       // For any module that this module depends on, push it on the
302       // stack (if it hasn't already been marked as visited).
303       for (llvm::SetVector<ModuleFile *>::iterator
304              M = CurrentModule->Imports.begin(),
305              MEnd = CurrentModule->Imports.end();
306            M != MEnd; ++M) {
307         // Remove our current module as an impediment to visiting the
308         // module we depend on. If we were the last unvisited module
309         // that depends on this particular module, push it into the
310         // queue to be visited.
311         unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
312         if (NumUnusedEdges && (--NumUnusedEdges == 0))
313           Queue.push_back(*M);
314       }
315     }
316 
317     assert(VisitOrder.size() == N && "Visitation order is wrong?");
318 
319     delete FirstVisitState;
320     FirstVisitState = nullptr;
321   }
322 
323   VisitState *State = allocateVisitState();
324   unsigned VisitNumber = State->NextVisitNumber++;
325 
326   // If the caller has provided us with a hit-set that came from the global
327   // module index, mark every module file in common with the global module
328   // index that is *not* in that set as 'visited'.
329   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
330     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
331     {
332       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
333       if (!ModuleFilesHit->count(M))
334         State->VisitNumber[M->Index] = VisitNumber;
335     }
336   }
337 
338   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
339     ModuleFile *CurrentModule = VisitOrder[I];
340     // Should we skip this module file?
341     if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
342       continue;
343 
344     // Visit the module.
345     assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
346     State->VisitNumber[CurrentModule->Index] = VisitNumber;
347     if (!Visitor(*CurrentModule, UserData))
348       continue;
349 
350     // The visitor has requested that cut off visitation of any
351     // module that the current module depends on. To indicate this
352     // behavior, we mark all of the reachable modules as having been visited.
353     ModuleFile *NextModule = CurrentModule;
354     do {
355       // For any module that this module depends on, push it on the
356       // stack (if it hasn't already been marked as visited).
357       for (llvm::SetVector<ModuleFile *>::iterator
358              M = NextModule->Imports.begin(),
359              MEnd = NextModule->Imports.end();
360            M != MEnd; ++M) {
361         if (State->VisitNumber[(*M)->Index] != VisitNumber) {
362           State->Stack.push_back(*M);
363           State->VisitNumber[(*M)->Index] = VisitNumber;
364         }
365       }
366 
367       if (State->Stack.empty())
368         break;
369 
370       // Pop the next module off the stack.
371       NextModule = State->Stack.pop_back_val();
372     } while (true);
373   }
374 
375   returnVisitState(State);
376 }
377 
378 /// \brief Perform a depth-first visit of the current module.
379 static bool visitDepthFirst(ModuleFile &M,
380                             bool (*Visitor)(ModuleFile &M, bool Preorder,
381                                             void *UserData),
382                             void *UserData,
383                             SmallVectorImpl<bool> &Visited) {
384   // Preorder visitation
385   if (Visitor(M, /*Preorder=*/true, UserData))
386     return true;
387 
388   // Visit children
389   for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
390                                             IMEnd = M.Imports.end();
391        IM != IMEnd; ++IM) {
392     if (Visited[(*IM)->Index])
393       continue;
394     Visited[(*IM)->Index] = true;
395 
396     if (visitDepthFirst(**IM, Visitor, UserData, Visited))
397       return true;
398   }
399 
400   // Postorder visitation
401   return Visitor(M, /*Preorder=*/false, UserData);
402 }
403 
404 void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
405                                                     void *UserData),
406                                     void *UserData) {
407   SmallVector<bool, 16> Visited(size(), false);
408   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
409     if (Visited[Chain[I]->Index])
410       continue;
411     Visited[Chain[I]->Index] = true;
412 
413     if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
414       return;
415   }
416 }
417 
418 bool ModuleManager::lookupModuleFile(StringRef FileName,
419                                      off_t ExpectedSize,
420                                      time_t ExpectedModTime,
421                                      const FileEntry *&File) {
422   // Open the file immediately to ensure there is no race between stat'ing and
423   // opening the file.
424   File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false);
425 
426   if (!File && FileName != "-") {
427     return false;
428   }
429 
430   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
431       (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
432     // Do not destroy File, as it may be referenced. If we need to rebuild it,
433     // it will be destroyed by removeModules.
434     return true;
435 
436   return false;
437 }
438 
439 #ifndef NDEBUG
440 namespace llvm {
441   template<>
442   struct GraphTraits<ModuleManager> {
443     typedef ModuleFile NodeType;
444     typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
445     typedef ModuleManager::ModuleConstIterator nodes_iterator;
446 
447     static ChildIteratorType child_begin(NodeType *Node) {
448       return Node->Imports.begin();
449     }
450 
451     static ChildIteratorType child_end(NodeType *Node) {
452       return Node->Imports.end();
453     }
454 
455     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
456       return Manager.begin();
457     }
458 
459     static nodes_iterator nodes_end(const ModuleManager &Manager) {
460       return Manager.end();
461     }
462   };
463 
464   template<>
465   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
466     explicit DOTGraphTraits(bool IsSimple = false)
467       : DefaultDOTGraphTraits(IsSimple) { }
468 
469     static bool renderGraphFromBottomUp() {
470       return true;
471     }
472 
473     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
474       return M->ModuleName;
475     }
476   };
477 }
478 
479 void ModuleManager::viewGraph() {
480   llvm::ViewGraph(*this, "Modules");
481 }
482 #endif
483