blob: bc9917b5822757cc0eccd8dcf6a2b599d1297cfb [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
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000165ModuleManager::VisitState *ModuleManager::allocateVisitState() {
166 // Fast path: if we have a cached state, use it.
167 if (FirstVisitState) {
168 VisitState *Result = FirstVisitState;
169 FirstVisitState = FirstVisitState->NextState;
170 Result->NextState = 0;
171 return Result;
172 }
173
174 // Allocate and return a new state.
175 return new VisitState(size());
176}
177
178void ModuleManager::returnVisitState(VisitState *State) {
179 assert(State->NextState == 0 && "Visited state is in list?");
180 State->NextState = FirstVisitState;
181 FirstVisitState = State;
182}
183
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000184void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
185 GlobalIndex = Index;
186 updateModulesInCommonWithGlobalIndex();
187}
188
189ModuleManager::ModuleManager(FileManager &FileMgr)
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000190 : FileMgr(FileMgr), GlobalIndex(), FirstVisitState(0) { }
Douglas Gregor98339b92011-08-25 20:47:51 +0000191
192ModuleManager::~ModuleManager() {
193 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
194 delete Chain[e - i - 1];
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000195 delete FirstVisitState;
Douglas Gregor98339b92011-08-25 20:47:51 +0000196}
197
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000198void
199ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
200 void *UserData,
201 llvm::SmallPtrSet<const FileEntry *, 4> *ModuleFilesHit) {
202 // If the visitation order vector is the wrong size, recompute the order.
Douglas Gregord07865b2013-01-25 22:25:23 +0000203 if (VisitOrder.size() != Chain.size()) {
204 unsigned N = size();
205 VisitOrder.clear();
206 VisitOrder.reserve(N);
207
208 // Record the number of incoming edges for each module. When we
209 // encounter a module with no incoming edges, push it into the queue
210 // to seed the queue.
211 SmallVector<ModuleFile *, 4> Queue;
212 Queue.reserve(N);
213 llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
214 UnusedIncomingEdges.reserve(size());
215 for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
216 if (unsigned Size = (*M)->ImportedBy.size())
217 UnusedIncomingEdges.push_back(Size);
218 else {
219 UnusedIncomingEdges.push_back(0);
220 Queue.push_back(*M);
221 }
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000222 }
Douglas Gregord07865b2013-01-25 22:25:23 +0000223
224 // Traverse the graph, making sure to visit a module before visiting any
225 // of its dependencies.
226 unsigned QueueStart = 0;
227 while (QueueStart < Queue.size()) {
228 ModuleFile *CurrentModule = Queue[QueueStart++];
229 VisitOrder.push_back(CurrentModule);
230
231 // For any module that this module depends on, push it on the
232 // stack (if it hasn't already been marked as visited).
233 for (llvm::SetVector<ModuleFile *>::iterator
234 M = CurrentModule->Imports.begin(),
235 MEnd = CurrentModule->Imports.end();
236 M != MEnd; ++M) {
237 // Remove our current module as an impediment to visiting the
238 // module we depend on. If we were the last unvisited module
239 // that depends on this particular module, push it into the
240 // queue to be visited.
241 unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
242 if (NumUnusedEdges && (--NumUnusedEdges == 0))
243 Queue.push_back(*M);
244 }
245 }
246
247 assert(VisitOrder.size() == N && "Visitation order is wrong?");
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000248
249 // We may need to update the set of modules we have in common with the
250 // global module index, since modules could have been added to the module
251 // manager since we loaded the global module index.
252 updateModulesInCommonWithGlobalIndex();
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000253
254 delete FirstVisitState;
255 FirstVisitState = 0;
Douglas Gregor98339b92011-08-25 20:47:51 +0000256 }
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000257
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000258 VisitState *State = allocateVisitState();
259 unsigned VisitNumber = State->NextVisitNumber++;
Douglas Gregord07865b2013-01-25 22:25:23 +0000260
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000261 // If the caller has provided us with a hit-set that came from the global
262 // module index, mark every module file in common with the global module
263 // index that is *not* in that set as 'visited'.
264 if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
265 for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
266 {
267 ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
268 if (!ModuleFilesHit->count(M->File))
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000269 State->VisitNumber[M->Index] = VisitNumber;
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000270 }
271 }
272
Douglas Gregord07865b2013-01-25 22:25:23 +0000273 for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
274 ModuleFile *CurrentModule = VisitOrder[I];
275 // Should we skip this module file?
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000276 if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
Douglas Gregor98339b92011-08-25 20:47:51 +0000277 continue;
Douglas Gregord07865b2013-01-25 22:25:23 +0000278
279 // Visit the module.
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000280 assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
281 State->VisitNumber[CurrentModule->Index] = VisitNumber;
Douglas Gregord07865b2013-01-25 22:25:23 +0000282 if (!Visitor(*CurrentModule, UserData))
283 continue;
284
285 // The visitor has requested that cut off visitation of any
286 // module that the current module depends on. To indicate this
287 // behavior, we mark all of the reachable modules as having been visited.
288 ModuleFile *NextModule = CurrentModule;
Douglas Gregord07865b2013-01-25 22:25:23 +0000289 do {
290 // For any module that this module depends on, push it on the
291 // stack (if it hasn't already been marked as visited).
292 for (llvm::SetVector<ModuleFile *>::iterator
293 M = NextModule->Imports.begin(),
294 MEnd = NextModule->Imports.end();
295 M != MEnd; ++M) {
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000296 if (State->VisitNumber[(*M)->Index] != VisitNumber) {
297 State->Stack.push_back(*M);
298 State->VisitNumber[(*M)->Index] = VisitNumber;
Douglas Gregor98339b92011-08-25 20:47:51 +0000299 }
300 }
Douglas Gregord07865b2013-01-25 22:25:23 +0000301
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000302 if (State->Stack.empty())
Douglas Gregord07865b2013-01-25 22:25:23 +0000303 break;
304
305 // Pop the next module off the stack.
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000306 NextModule = State->Stack.back();
307 State->Stack.pop_back();
Douglas Gregord07865b2013-01-25 22:25:23 +0000308 } while (true);
Douglas Gregor98339b92011-08-25 20:47:51 +0000309 }
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000310
311 returnVisitState(State);
Douglas Gregor98339b92011-08-25 20:47:51 +0000312}
313
314/// \brief Perform a depth-first visit of the current module.
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000315static bool visitDepthFirst(ModuleFile &M,
316 bool (*Visitor)(ModuleFile &M, bool Preorder,
Douglas Gregor98339b92011-08-25 20:47:51 +0000317 void *UserData),
318 void *UserData,
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000319 SmallVectorImpl<bool> &Visited) {
Douglas Gregor98339b92011-08-25 20:47:51 +0000320 // Preorder visitation
321 if (Visitor(M, /*Preorder=*/true, UserData))
322 return true;
323
324 // Visit children
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000325 for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000326 IMEnd = M.Imports.end();
Douglas Gregor98339b92011-08-25 20:47:51 +0000327 IM != IMEnd; ++IM) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000328 if (Visited[(*IM)->Index])
Douglas Gregor98339b92011-08-25 20:47:51 +0000329 continue;
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000330 Visited[(*IM)->Index] = true;
331
Douglas Gregor98339b92011-08-25 20:47:51 +0000332 if (visitDepthFirst(**IM, Visitor, UserData, Visited))
333 return true;
334 }
335
336 // Postorder visitation
337 return Visitor(M, /*Preorder=*/false, UserData);
338}
339
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000340void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
Douglas Gregor98339b92011-08-25 20:47:51 +0000341 void *UserData),
342 void *UserData) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000343 SmallVector<bool, 16> Visited(size(), false);
Douglas Gregor98339b92011-08-25 20:47:51 +0000344 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000345 if (Visited[Chain[I]->Index])
Douglas Gregor98339b92011-08-25 20:47:51 +0000346 continue;
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000347 Visited[Chain[I]->Index] = true;
348
Douglas Gregor98339b92011-08-25 20:47:51 +0000349 if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
350 return;
351 }
352}
Douglas Gregor2492c892011-10-11 19:27:55 +0000353
354#ifndef NDEBUG
355namespace llvm {
356 template<>
357 struct GraphTraits<ModuleManager> {
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000358 typedef ModuleFile NodeType;
359 typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
Douglas Gregor2492c892011-10-11 19:27:55 +0000360 typedef ModuleManager::ModuleConstIterator nodes_iterator;
361
362 static ChildIteratorType child_begin(NodeType *Node) {
363 return Node->Imports.begin();
364 }
365
366 static ChildIteratorType child_end(NodeType *Node) {
367 return Node->Imports.end();
368 }
369
370 static nodes_iterator nodes_begin(const ModuleManager &Manager) {
371 return Manager.begin();
372 }
373
374 static nodes_iterator nodes_end(const ModuleManager &Manager) {
375 return Manager.end();
376 }
377 };
378
379 template<>
380 struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
381 explicit DOTGraphTraits(bool IsSimple = false)
382 : DefaultDOTGraphTraits(IsSimple) { }
383
384 static bool renderGraphFromBottomUp() {
385 return true;
386 }
387
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000388 std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
Douglas Gregor2492c892011-10-11 19:27:55 +0000389 return llvm::sys::path::stem(M->FileName);
390 }
391 };
392}
393
394void ModuleManager::viewGraph() {
395 llvm::ViewGraph(*this, "Modules");
396}
397#endif