blob: 97c86a7bb8a412684c84cefb91ecc8682cb7bd71 [file] [log] [blame]
Douglas Gregor98339b92011-08-25 20:47:51 +00001//===--- 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"
Douglas Gregor188bdcd2013-01-25 23:32:03 +000015#include "clang/Serialization/GlobalModuleIndex.h"
Douglas Gregor98339b92011-08-25 20:47:51 +000016#include "llvm/Support/MemoryBuffer.h"
17#include "llvm/Support/raw_ostream.h"
18#include "llvm/Support/system_error.h"
19
Douglas Gregor2492c892011-10-11 19:27:55 +000020#ifndef NDEBUG
21#include "llvm/Support/GraphWriter.h"
22#endif
23
Douglas Gregor98339b92011-08-25 20:47:51 +000024using namespace clang;
25using namespace serialization;
26
Douglas Gregor1a4761e2011-11-30 23:21:26 +000027ModuleFile *ModuleManager::lookup(StringRef Name) {
Douglas Gregor98339b92011-08-25 20:47:51 +000028 const FileEntry *Entry = FileMgr.getFile(Name);
29 return Modules[Entry];
30}
31
32llvm::MemoryBuffer *ModuleManager::lookupBuffer(StringRef Name) {
33 const FileEntry *Entry = FileMgr.getFile(Name);
34 return InMemoryBuffers[Entry];
35}
36
Douglas Gregor1a4761e2011-11-30 23:21:26 +000037std::pair<ModuleFile *, bool>
Douglas Gregor87e2cfc2012-11-30 19:28:05 +000038ModuleManager::addModule(StringRef FileName, ModuleKind Type,
39 SourceLocation ImportLoc, ModuleFile *ImportedBy,
40 unsigned Generation, std::string &ErrorStr) {
Douglas Gregor98339b92011-08-25 20:47:51 +000041 const FileEntry *Entry = FileMgr.getFile(FileName);
42 if (!Entry && FileName != "-") {
43 ErrorStr = "file not found";
Douglas Gregor1a4761e2011-11-30 23:21:26 +000044 return std::make_pair(static_cast<ModuleFile*>(0), false);
Douglas Gregor98339b92011-08-25 20:47:51 +000045 }
46
47 // Check whether we already loaded this module, before
Douglas Gregor1a4761e2011-11-30 23:21:26 +000048 ModuleFile *&ModuleEntry = Modules[Entry];
Douglas Gregor98339b92011-08-25 20:47:51 +000049 bool NewModule = false;
50 if (!ModuleEntry) {
51 // Allocate a new module.
Douglas Gregor057df202012-01-18 20:56:22 +000052 ModuleFile *New = new ModuleFile(Type, Generation);
Douglas Gregorcc71dbe2013-01-21 20:07:12 +000053 New->Index = Chain.size();
Douglas Gregor98339b92011-08-25 20:47:51 +000054 New->FileName = FileName.str();
Argyrios Kyrtzidisd64c26f2012-10-03 01:58:42 +000055 New->File = Entry;
Douglas Gregor87e2cfc2012-11-30 19:28:05 +000056 New->ImportLoc = ImportLoc;
Douglas Gregor98339b92011-08-25 20:47:51 +000057 Chain.push_back(New);
58 NewModule = true;
59 ModuleEntry = New;
Douglas Gregor87e2cfc2012-11-30 19:28:05 +000060
Douglas Gregor98339b92011-08-25 20:47:51 +000061 // 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)
Douglas Gregor1a4761e2011-11-30 23:21:26 +000077 return std::make_pair(static_cast<ModuleFile*>(0), false);
Douglas Gregor98339b92011-08-25 20:47:51 +000078 }
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 {
Douglas Gregor87e2cfc2012-11-30 19:28:05 +000088 if (!ModuleEntry->DirectlyImported)
89 ModuleEntry->ImportLoc = ImportLoc;
90
Douglas Gregor98339b92011-08-25 20:47:51 +000091 ModuleEntry->DirectlyImported = true;
92 }
93
94 return std::make_pair(ModuleEntry, NewModule);
95}
96
Douglas Gregor7cdd2812012-11-07 17:46:15 +000097namespace {
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
113void 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
Douglas Gregor98339b92011-08-25 20:47:51 +0000136void 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
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000144void 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
165void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
166 GlobalIndex = Index;
167 updateModulesInCommonWithGlobalIndex();
168}
169
170ModuleManager::ModuleManager(FileManager &FileMgr)
171 : FileMgr(FileMgr), GlobalIndex() { }
Douglas Gregor98339b92011-08-25 20:47:51 +0000172
173ModuleManager::~ModuleManager() {
174 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
175 delete Chain[e - i - 1];
176}
177
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000178void
179ModuleManager::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.
Douglas Gregord07865b2013-01-25 22:25:23 +0000183 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 }
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000202 }
Douglas Gregord07865b2013-01-25 22:25:23 +0000203
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?");
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000228
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();
Douglas Gregor98339b92011-08-25 20:47:51 +0000233 }
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000234
Douglas Gregord07865b2013-01-25 22:25:23 +0000235 SmallVector<ModuleFile *, 4> Stack;
236 SmallVector<bool, 4> Visited(size(), false);
237
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000238 // 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
Douglas Gregord07865b2013-01-25 22:25:23 +0000250 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])
Douglas Gregor98339b92011-08-25 20:47:51 +0000254 continue;
Douglas Gregord07865b2013-01-25 22:25:23 +0000255
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;
Douglas Gregor98339b92011-08-25 20:47:51 +0000276 }
277 }
Douglas Gregord07865b2013-01-25 22:25:23 +0000278
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);
Douglas Gregor98339b92011-08-25 20:47:51 +0000286 }
287}
288
289/// \brief Perform a depth-first visit of the current module.
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000290static bool visitDepthFirst(ModuleFile &M,
291 bool (*Visitor)(ModuleFile &M, bool Preorder,
Douglas Gregor98339b92011-08-25 20:47:51 +0000292 void *UserData),
293 void *UserData,
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000294 SmallVectorImpl<bool> &Visited) {
Douglas Gregor98339b92011-08-25 20:47:51 +0000295 // Preorder visitation
296 if (Visitor(M, /*Preorder=*/true, UserData))
297 return true;
298
299 // Visit children
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000300 for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000301 IMEnd = M.Imports.end();
Douglas Gregor98339b92011-08-25 20:47:51 +0000302 IM != IMEnd; ++IM) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000303 if (Visited[(*IM)->Index])
Douglas Gregor98339b92011-08-25 20:47:51 +0000304 continue;
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000305 Visited[(*IM)->Index] = true;
306
Douglas Gregor98339b92011-08-25 20:47:51 +0000307 if (visitDepthFirst(**IM, Visitor, UserData, Visited))
308 return true;
309 }
310
311 // Postorder visitation
312 return Visitor(M, /*Preorder=*/false, UserData);
313}
314
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000315void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
Douglas Gregor98339b92011-08-25 20:47:51 +0000316 void *UserData),
317 void *UserData) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000318 SmallVector<bool, 16> Visited(size(), false);
Douglas Gregor98339b92011-08-25 20:47:51 +0000319 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000320 if (Visited[Chain[I]->Index])
Douglas Gregor98339b92011-08-25 20:47:51 +0000321 continue;
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000322 Visited[Chain[I]->Index] = true;
323
Douglas Gregor98339b92011-08-25 20:47:51 +0000324 if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
325 return;
326 }
327}
Douglas Gregor2492c892011-10-11 19:27:55 +0000328
329#ifndef NDEBUG
330namespace llvm {
331 template<>
332 struct GraphTraits<ModuleManager> {
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000333 typedef ModuleFile NodeType;
334 typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
Douglas Gregor2492c892011-10-11 19:27:55 +0000335 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
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000363 std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
Douglas Gregor2492c892011-10-11 19:27:55 +0000364 return llvm::sys::path::stem(M->FileName);
365 }
366 };
367}
368
369void ModuleManager::viewGraph() {
370 llvm::ViewGraph(*this, "Modules");
371}
372#endif