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