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