xref: /llvm-project/clang/lib/Serialization/ModuleManager.cpp (revision 7211ac15bbd97fd9ea8016a6632cb039a1071f1d)
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/Serialization/ModuleManager.h"
15 #include "clang/Serialization/GlobalModuleIndex.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "llvm/Support/raw_ostream.h"
18 #include "llvm/Support/system_error.h"
19 
20 #ifndef NDEBUG
21 #include "llvm/Support/GraphWriter.h"
22 #endif
23 
24 using namespace clang;
25 using namespace serialization;
26 
27 ModuleFile *ModuleManager::lookup(StringRef Name) {
28   const FileEntry *Entry = FileMgr.getFile(Name);
29   return Modules[Entry];
30 }
31 
32 llvm::MemoryBuffer *ModuleManager::lookupBuffer(StringRef Name) {
33   const FileEntry *Entry = FileMgr.getFile(Name);
34   return InMemoryBuffers[Entry];
35 }
36 
37 std::pair<ModuleFile *, bool>
38 ModuleManager::addModule(StringRef FileName, ModuleKind Type,
39                          SourceLocation ImportLoc, ModuleFile *ImportedBy,
40                          unsigned Generation, std::string &ErrorStr) {
41   const FileEntry *Entry = FileMgr.getFile(FileName);
42   if (!Entry && FileName != "-") {
43     ErrorStr = "file not found";
44     return std::make_pair(static_cast<ModuleFile*>(0), false);
45   }
46 
47   // Check whether we already loaded this module, before
48   ModuleFile *&ModuleEntry = Modules[Entry];
49   bool NewModule = false;
50   if (!ModuleEntry) {
51     // Allocate a new module.
52     ModuleFile *New = new ModuleFile(Type, Generation);
53     New->Index = Chain.size();
54     New->FileName = FileName.str();
55     New->File = Entry;
56     New->ImportLoc = ImportLoc;
57     Chain.push_back(New);
58     NewModule = true;
59     ModuleEntry = New;
60 
61     // Load the contents of the module
62     if (llvm::MemoryBuffer *Buffer = lookupBuffer(FileName)) {
63       // The buffer was already provided for us.
64       assert(Buffer && "Passed null buffer");
65       New->Buffer.reset(Buffer);
66     } else {
67       // Open the AST file.
68       llvm::error_code ec;
69       if (FileName == "-") {
70         ec = llvm::MemoryBuffer::getSTDIN(New->Buffer);
71         if (ec)
72           ErrorStr = ec.message();
73       } else
74         New->Buffer.reset(FileMgr.getBufferForFile(FileName, &ErrorStr));
75 
76       if (!New->Buffer)
77         return std::make_pair(static_cast<ModuleFile*>(0), false);
78     }
79 
80     // Initialize the stream
81     New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(),
82                          (const unsigned char *)New->Buffer->getBufferEnd());     }
83 
84   if (ImportedBy) {
85     ModuleEntry->ImportedBy.insert(ImportedBy);
86     ImportedBy->Imports.insert(ModuleEntry);
87   } else {
88     if (!ModuleEntry->DirectlyImported)
89       ModuleEntry->ImportLoc = ImportLoc;
90 
91     ModuleEntry->DirectlyImported = true;
92   }
93 
94   return std::make_pair(ModuleEntry, NewModule);
95 }
96 
97 namespace {
98   /// \brief Predicate that checks whether a module file occurs within
99   /// the given set.
100   class IsInModuleFileSet : public std::unary_function<ModuleFile *, bool> {
101     llvm::SmallPtrSet<ModuleFile *, 4> &Removed;
102 
103   public:
104     IsInModuleFileSet(llvm::SmallPtrSet<ModuleFile *, 4> &Removed)
105     : Removed(Removed) { }
106 
107     bool operator()(ModuleFile *MF) const {
108       return Removed.count(MF);
109     }
110   };
111 }
112 
113 void ModuleManager::removeModules(ModuleIterator first, ModuleIterator last) {
114   if (first == last)
115     return;
116 
117   // Collect the set of module file pointers that we'll be removing.
118   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
119 
120   // Remove any references to the now-destroyed modules.
121   IsInModuleFileSet checkInSet(victimSet);
122   for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
123     Chain[i]->ImportedBy.remove_if(checkInSet);
124   }
125 
126   // Delete the modules and erase them from the various structures.
127   for (ModuleIterator victim = first; victim != last; ++victim) {
128     Modules.erase((*victim)->File);
129     delete *victim;
130   }
131 
132   // Remove the modules from the chain.
133   Chain.erase(first, last);
134 }
135 
136 void ModuleManager::addInMemoryBuffer(StringRef FileName,
137                                       llvm::MemoryBuffer *Buffer) {
138 
139   const FileEntry *Entry = FileMgr.getVirtualFile(FileName,
140                                                   Buffer->getBufferSize(), 0);
141   InMemoryBuffers[Entry] = Buffer;
142 }
143 
144 void ModuleManager::updateModulesInCommonWithGlobalIndex() {
145   ModulesInCommonWithGlobalIndex.clear();
146 
147   if (!GlobalIndex)
148     return;
149 
150   // Collect the set of modules known to the global index.
151   SmallVector<const FileEntry *, 16> KnownModules;
152   GlobalIndex->getKnownModules(KnownModules);
153 
154   // Map those modules to AST files known to the module manager.
155   for (unsigned I = 0, N = KnownModules.size(); I != N; ++I) {
156     llvm::DenseMap<const FileEntry *, ModuleFile *>::iterator Known
157       = Modules.find(KnownModules[I]);
158     if (Known == Modules.end())
159       continue;
160 
161     ModulesInCommonWithGlobalIndex.push_back(Known->second);
162   }
163 }
164 
165 void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
166   GlobalIndex = Index;
167   updateModulesInCommonWithGlobalIndex();
168 }
169 
170 ModuleManager::ModuleManager(FileManager &FileMgr)
171   : FileMgr(FileMgr), GlobalIndex() { }
172 
173 ModuleManager::~ModuleManager() {
174   for (unsigned i = 0, e = Chain.size(); i != e; ++i)
175     delete Chain[e - i - 1];
176 }
177 
178 void
179 ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
180                      void *UserData,
181                      llvm::SmallPtrSet<const FileEntry *, 4> *ModuleFilesHit) {
182   // If the visitation order vector is the wrong size, recompute the order.
183   if (VisitOrder.size() != Chain.size()) {
184     unsigned N = size();
185     VisitOrder.clear();
186     VisitOrder.reserve(N);
187 
188     // Record the number of incoming edges for each module. When we
189     // encounter a module with no incoming edges, push it into the queue
190     // to seed the queue.
191     SmallVector<ModuleFile *, 4> Queue;
192     Queue.reserve(N);
193     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
194     UnusedIncomingEdges.reserve(size());
195     for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
196       if (unsigned Size = (*M)->ImportedBy.size())
197         UnusedIncomingEdges.push_back(Size);
198       else {
199         UnusedIncomingEdges.push_back(0);
200         Queue.push_back(*M);
201       }
202     }
203 
204     // Traverse the graph, making sure to visit a module before visiting any
205     // of its dependencies.
206     unsigned QueueStart = 0;
207     while (QueueStart < Queue.size()) {
208       ModuleFile *CurrentModule = Queue[QueueStart++];
209       VisitOrder.push_back(CurrentModule);
210 
211       // For any module that this module depends on, push it on the
212       // stack (if it hasn't already been marked as visited).
213       for (llvm::SetVector<ModuleFile *>::iterator
214              M = CurrentModule->Imports.begin(),
215              MEnd = CurrentModule->Imports.end();
216            M != MEnd; ++M) {
217         // Remove our current module as an impediment to visiting the
218         // module we depend on. If we were the last unvisited module
219         // that depends on this particular module, push it into the
220         // queue to be visited.
221         unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
222         if (NumUnusedEdges && (--NumUnusedEdges == 0))
223           Queue.push_back(*M);
224       }
225     }
226 
227     assert(VisitOrder.size() == N && "Visitation order is wrong?");
228 
229     // We may need to update the set of modules we have in common with the
230     // global module index, since modules could have been added to the module
231     // manager since we loaded the global module index.
232     updateModulesInCommonWithGlobalIndex();
233   }
234 
235   SmallVector<ModuleFile *, 4> Stack;
236   SmallVector<bool, 4> Visited(size(), false);
237 
238   // If the caller has provided us with a hit-set that came from the global
239   // module index, mark every module file in common with the global module
240   // index that is *not* in that set as 'visited'.
241   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
242     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
243     {
244       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
245       if (!ModuleFilesHit->count(M->File))
246         Visited[M->Index] = true;
247     }
248   }
249 
250   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
251     ModuleFile *CurrentModule = VisitOrder[I];
252     // Should we skip this module file?
253     if (Visited[CurrentModule->Index])
254       continue;
255 
256     // Visit the module.
257     Visited[CurrentModule->Index] = true;
258     if (!Visitor(*CurrentModule, UserData))
259       continue;
260 
261     // The visitor has requested that cut off visitation of any
262     // module that the current module depends on. To indicate this
263     // behavior, we mark all of the reachable modules as having been visited.
264     ModuleFile *NextModule = CurrentModule;
265     Stack.reserve(size());
266     do {
267       // For any module that this module depends on, push it on the
268       // stack (if it hasn't already been marked as visited).
269       for (llvm::SetVector<ModuleFile *>::iterator
270              M = NextModule->Imports.begin(),
271              MEnd = NextModule->Imports.end();
272            M != MEnd; ++M) {
273         if (!Visited[(*M)->Index]) {
274           Stack.push_back(*M);
275           Visited[(*M)->Index] = true;
276         }
277       }
278 
279       if (Stack.empty())
280         break;
281 
282       // Pop the next module off the stack.
283       NextModule = Stack.back();
284       Stack.pop_back();
285     } while (true);
286   }
287 }
288 
289 /// \brief Perform a depth-first visit of the current module.
290 static bool visitDepthFirst(ModuleFile &M,
291                             bool (*Visitor)(ModuleFile &M, bool Preorder,
292                                             void *UserData),
293                             void *UserData,
294                             SmallVectorImpl<bool> &Visited) {
295   // Preorder visitation
296   if (Visitor(M, /*Preorder=*/true, UserData))
297     return true;
298 
299   // Visit children
300   for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
301                                             IMEnd = M.Imports.end();
302        IM != IMEnd; ++IM) {
303     if (Visited[(*IM)->Index])
304       continue;
305     Visited[(*IM)->Index] = true;
306 
307     if (visitDepthFirst(**IM, Visitor, UserData, Visited))
308       return true;
309   }
310 
311   // Postorder visitation
312   return Visitor(M, /*Preorder=*/false, UserData);
313 }
314 
315 void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
316                                                     void *UserData),
317                                     void *UserData) {
318   SmallVector<bool, 16> Visited(size(), false);
319   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
320     if (Visited[Chain[I]->Index])
321       continue;
322     Visited[Chain[I]->Index] = true;
323 
324     if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
325       return;
326   }
327 }
328 
329 #ifndef NDEBUG
330 namespace llvm {
331   template<>
332   struct GraphTraits<ModuleManager> {
333     typedef ModuleFile NodeType;
334     typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
335     typedef ModuleManager::ModuleConstIterator nodes_iterator;
336 
337     static ChildIteratorType child_begin(NodeType *Node) {
338       return Node->Imports.begin();
339     }
340 
341     static ChildIteratorType child_end(NodeType *Node) {
342       return Node->Imports.end();
343     }
344 
345     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
346       return Manager.begin();
347     }
348 
349     static nodes_iterator nodes_end(const ModuleManager &Manager) {
350       return Manager.end();
351     }
352   };
353 
354   template<>
355   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
356     explicit DOTGraphTraits(bool IsSimple = false)
357       : DefaultDOTGraphTraits(IsSimple) { }
358 
359     static bool renderGraphFromBottomUp() {
360       return true;
361     }
362 
363     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
364       return llvm::sys::path::stem(M->FileName);
365     }
366   };
367 }
368 
369 void ModuleManager::viewGraph() {
370   llvm::ViewGraph(*this, "Modules");
371 }
372 #endif
373