blob: a9f4794e1063d104d57b08e1b8baebd50dbcdff5 [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//===----------------------------------------------------------------------===//
Douglas Gregor677e15f2013-03-19 00:28:20 +000014#include "clang/Lex/ModuleMap.h"
Douglas Gregor98339b92011-08-25 20:47:51 +000015#include "clang/Serialization/ModuleManager.h"
Douglas Gregor188bdcd2013-01-25 23:32:03 +000016#include "clang/Serialization/GlobalModuleIndex.h"
Douglas Gregor98339b92011-08-25 20:47:51 +000017#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor677e15f2013-03-19 00:28:20 +000018#include "llvm/Support/PathV2.h"
Douglas Gregor98339b92011-08-25 20:47:51 +000019#include "llvm/Support/raw_ostream.h"
20#include "llvm/Support/system_error.h"
21
Douglas Gregor2492c892011-10-11 19:27:55 +000022#ifndef NDEBUG
23#include "llvm/Support/GraphWriter.h"
24#endif
25
Douglas Gregor98339b92011-08-25 20:47:51 +000026using namespace clang;
27using namespace serialization;
28
Douglas Gregor1a4761e2011-11-30 23:21:26 +000029ModuleFile *ModuleManager::lookup(StringRef Name) {
Douglas Gregorea14a872013-02-08 21:27:45 +000030 const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
31 /*cacheFailure=*/false);
Douglas Gregor98339b92011-08-25 20:47:51 +000032 return Modules[Entry];
33}
34
35llvm::MemoryBuffer *ModuleManager::lookupBuffer(StringRef Name) {
Douglas Gregorea14a872013-02-08 21:27:45 +000036 const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
37 /*cacheFailure=*/false);
Douglas Gregor98339b92011-08-25 20:47:51 +000038 return InMemoryBuffers[Entry];
39}
40
Douglas Gregor677e15f2013-03-19 00:28:20 +000041ModuleManager::AddModuleResult
Douglas Gregor87e2cfc2012-11-30 19:28:05 +000042ModuleManager::addModule(StringRef FileName, ModuleKind Type,
43 SourceLocation ImportLoc, ModuleFile *ImportedBy,
Douglas Gregor677e15f2013-03-19 00:28:20 +000044 unsigned Generation,
45 off_t ExpectedSize, time_t ExpectedModTime,
46 ModuleFile *&Module,
47 std::string &ErrorStr) {
48 Module = 0;
49
50 // Look for the file entry. This only fails if the expected size or
51 // modification time differ.
52 const FileEntry *Entry;
53 if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry))
54 return OutOfDate;
55
Douglas Gregor98339b92011-08-25 20:47:51 +000056 if (!Entry && FileName != "-") {
57 ErrorStr = "file not found";
Douglas Gregor677e15f2013-03-19 00:28:20 +000058 return Missing;
Douglas Gregor98339b92011-08-25 20:47:51 +000059 }
Douglas Gregor677e15f2013-03-19 00:28:20 +000060
61 // Check whether we already loaded this module, before
62 AddModuleResult Result = AlreadyLoaded;
Douglas Gregor1a4761e2011-11-30 23:21:26 +000063 ModuleFile *&ModuleEntry = Modules[Entry];
Douglas Gregor98339b92011-08-25 20:47:51 +000064 bool NewModule = false;
65 if (!ModuleEntry) {
66 // Allocate a new module.
Douglas Gregor057df202012-01-18 20:56:22 +000067 ModuleFile *New = new ModuleFile(Type, Generation);
Douglas Gregorcc71dbe2013-01-21 20:07:12 +000068 New->Index = Chain.size();
Douglas Gregor98339b92011-08-25 20:47:51 +000069 New->FileName = FileName.str();
Argyrios Kyrtzidisd64c26f2012-10-03 01:58:42 +000070 New->File = Entry;
Douglas Gregor87e2cfc2012-11-30 19:28:05 +000071 New->ImportLoc = ImportLoc;
Douglas Gregor98339b92011-08-25 20:47:51 +000072 Chain.push_back(New);
73 NewModule = true;
74 ModuleEntry = New;
Douglas Gregor87e2cfc2012-11-30 19:28:05 +000075
Douglas Gregor98339b92011-08-25 20:47:51 +000076 // Load the contents of the module
77 if (llvm::MemoryBuffer *Buffer = lookupBuffer(FileName)) {
78 // The buffer was already provided for us.
79 assert(Buffer && "Passed null buffer");
80 New->Buffer.reset(Buffer);
81 } else {
82 // Open the AST file.
83 llvm::error_code ec;
84 if (FileName == "-") {
85 ec = llvm::MemoryBuffer::getSTDIN(New->Buffer);
86 if (ec)
87 ErrorStr = ec.message();
88 } else
89 New->Buffer.reset(FileMgr.getBufferForFile(FileName, &ErrorStr));
90
91 if (!New->Buffer)
Douglas Gregor677e15f2013-03-19 00:28:20 +000092 return Missing;
Douglas Gregor98339b92011-08-25 20:47:51 +000093 }
94
95 // Initialize the stream
96 New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(),
Douglas Gregor677e15f2013-03-19 00:28:20 +000097 (const unsigned char *)New->Buffer->getBufferEnd());
98
99 Result = NewlyLoaded;
100 }
Douglas Gregor98339b92011-08-25 20:47:51 +0000101
102 if (ImportedBy) {
103 ModuleEntry->ImportedBy.insert(ImportedBy);
104 ImportedBy->Imports.insert(ModuleEntry);
105 } else {
Douglas Gregor87e2cfc2012-11-30 19:28:05 +0000106 if (!ModuleEntry->DirectlyImported)
107 ModuleEntry->ImportLoc = ImportLoc;
108
Douglas Gregor98339b92011-08-25 20:47:51 +0000109 ModuleEntry->DirectlyImported = true;
110 }
Douglas Gregor677e15f2013-03-19 00:28:20 +0000111
112 Module = ModuleEntry;
113 return NewModule? NewlyLoaded : AlreadyLoaded;
Douglas Gregor98339b92011-08-25 20:47:51 +0000114}
115
Douglas Gregor7cdd2812012-11-07 17:46:15 +0000116namespace {
117 /// \brief Predicate that checks whether a module file occurs within
118 /// the given set.
119 class IsInModuleFileSet : public std::unary_function<ModuleFile *, bool> {
120 llvm::SmallPtrSet<ModuleFile *, 4> &Removed;
121
122 public:
123 IsInModuleFileSet(llvm::SmallPtrSet<ModuleFile *, 4> &Removed)
124 : Removed(Removed) { }
125
126 bool operator()(ModuleFile *MF) const {
127 return Removed.count(MF);
128 }
129 };
130}
131
Douglas Gregor677e15f2013-03-19 00:28:20 +0000132void ModuleManager::removeModules(ModuleIterator first, ModuleIterator last,
133 ModuleMap *modMap) {
Douglas Gregor7cdd2812012-11-07 17:46:15 +0000134 if (first == last)
135 return;
136
137 // Collect the set of module file pointers that we'll be removing.
138 llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
139
140 // Remove any references to the now-destroyed modules.
141 IsInModuleFileSet checkInSet(victimSet);
142 for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
143 Chain[i]->ImportedBy.remove_if(checkInSet);
144 }
145
146 // Delete the modules and erase them from the various structures.
147 for (ModuleIterator victim = first; victim != last; ++victim) {
148 Modules.erase((*victim)->File);
Douglas Gregor677e15f2013-03-19 00:28:20 +0000149
150 FileMgr.invalidateCache((*victim)->File);
151 if (modMap) {
152 StringRef ModuleName = llvm::sys::path::stem((*victim)->FileName);
153 if (Module *mod = modMap->findModule(ModuleName)) {
154 mod->setASTFile(0);
155 }
156 }
Douglas Gregor7cdd2812012-11-07 17:46:15 +0000157 delete *victim;
158 }
159
160 // Remove the modules from the chain.
161 Chain.erase(first, last);
162}
163
Douglas Gregor98339b92011-08-25 20:47:51 +0000164void ModuleManager::addInMemoryBuffer(StringRef FileName,
165 llvm::MemoryBuffer *Buffer) {
166
167 const FileEntry *Entry = FileMgr.getVirtualFile(FileName,
168 Buffer->getBufferSize(), 0);
169 InMemoryBuffers[Entry] = Buffer;
170}
171
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000172void ModuleManager::updateModulesInCommonWithGlobalIndex() {
173 ModulesInCommonWithGlobalIndex.clear();
174
175 if (!GlobalIndex)
176 return;
177
178 // Collect the set of modules known to the global index.
Douglas Gregor677e15f2013-03-19 00:28:20 +0000179 GlobalIndex->noteAdditionalModulesLoaded();
180 GlobalIndex->getKnownModules(ModulesInCommonWithGlobalIndex);
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000181}
182
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000183ModuleManager::VisitState *ModuleManager::allocateVisitState() {
184 // Fast path: if we have a cached state, use it.
185 if (FirstVisitState) {
186 VisitState *Result = FirstVisitState;
187 FirstVisitState = FirstVisitState->NextState;
188 Result->NextState = 0;
189 return Result;
190 }
191
192 // Allocate and return a new state.
193 return new VisitState(size());
194}
195
196void ModuleManager::returnVisitState(VisitState *State) {
197 assert(State->NextState == 0 && "Visited state is in list?");
198 State->NextState = FirstVisitState;
199 FirstVisitState = State;
200}
201
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000202void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
203 GlobalIndex = Index;
Douglas Gregor677e15f2013-03-19 00:28:20 +0000204 if (GlobalIndex) {
205 GlobalIndex->setResolver(this);
206 }
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000207 updateModulesInCommonWithGlobalIndex();
208}
209
210ModuleManager::ModuleManager(FileManager &FileMgr)
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000211 : FileMgr(FileMgr), GlobalIndex(), FirstVisitState(0) { }
Douglas Gregor98339b92011-08-25 20:47:51 +0000212
213ModuleManager::~ModuleManager() {
214 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
215 delete Chain[e - i - 1];
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000216 delete FirstVisitState;
Douglas Gregor98339b92011-08-25 20:47:51 +0000217}
218
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000219void
220ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
221 void *UserData,
Douglas Gregor677e15f2013-03-19 00:28:20 +0000222 llvm::SmallPtrSet<ModuleFile *, 4> *ModuleFilesHit) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000223 // If the visitation order vector is the wrong size, recompute the order.
Douglas Gregord07865b2013-01-25 22:25:23 +0000224 if (VisitOrder.size() != Chain.size()) {
225 unsigned N = size();
226 VisitOrder.clear();
227 VisitOrder.reserve(N);
228
229 // Record the number of incoming edges for each module. When we
230 // encounter a module with no incoming edges, push it into the queue
231 // to seed the queue.
232 SmallVector<ModuleFile *, 4> Queue;
233 Queue.reserve(N);
234 llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
235 UnusedIncomingEdges.reserve(size());
236 for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
237 if (unsigned Size = (*M)->ImportedBy.size())
238 UnusedIncomingEdges.push_back(Size);
239 else {
240 UnusedIncomingEdges.push_back(0);
241 Queue.push_back(*M);
242 }
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000243 }
Douglas Gregord07865b2013-01-25 22:25:23 +0000244
245 // Traverse the graph, making sure to visit a module before visiting any
246 // of its dependencies.
247 unsigned QueueStart = 0;
248 while (QueueStart < Queue.size()) {
249 ModuleFile *CurrentModule = Queue[QueueStart++];
250 VisitOrder.push_back(CurrentModule);
251
252 // For any module that this module depends on, push it on the
253 // stack (if it hasn't already been marked as visited).
254 for (llvm::SetVector<ModuleFile *>::iterator
255 M = CurrentModule->Imports.begin(),
256 MEnd = CurrentModule->Imports.end();
257 M != MEnd; ++M) {
258 // Remove our current module as an impediment to visiting the
259 // module we depend on. If we were the last unvisited module
260 // that depends on this particular module, push it into the
261 // queue to be visited.
262 unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
263 if (NumUnusedEdges && (--NumUnusedEdges == 0))
264 Queue.push_back(*M);
265 }
266 }
267
268 assert(VisitOrder.size() == N && "Visitation order is wrong?");
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000269
270 // We may need to update the set of modules we have in common with the
271 // global module index, since modules could have been added to the module
272 // manager since we loaded the global module index.
273 updateModulesInCommonWithGlobalIndex();
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000274
275 delete FirstVisitState;
276 FirstVisitState = 0;
Douglas Gregor98339b92011-08-25 20:47:51 +0000277 }
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000278
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000279 VisitState *State = allocateVisitState();
280 unsigned VisitNumber = State->NextVisitNumber++;
Douglas Gregord07865b2013-01-25 22:25:23 +0000281
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000282 // If the caller has provided us with a hit-set that came from the global
283 // module index, mark every module file in common with the global module
284 // index that is *not* in that set as 'visited'.
285 if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
286 for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
287 {
288 ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
Douglas Gregor677e15f2013-03-19 00:28:20 +0000289 if (!ModuleFilesHit->count(M))
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000290 State->VisitNumber[M->Index] = VisitNumber;
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000291 }
292 }
293
Douglas Gregord07865b2013-01-25 22:25:23 +0000294 for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
295 ModuleFile *CurrentModule = VisitOrder[I];
296 // Should we skip this module file?
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000297 if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
Douglas Gregor98339b92011-08-25 20:47:51 +0000298 continue;
Douglas Gregord07865b2013-01-25 22:25:23 +0000299
300 // Visit the module.
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000301 assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
302 State->VisitNumber[CurrentModule->Index] = VisitNumber;
Douglas Gregord07865b2013-01-25 22:25:23 +0000303 if (!Visitor(*CurrentModule, UserData))
304 continue;
305
306 // The visitor has requested that cut off visitation of any
307 // module that the current module depends on. To indicate this
308 // behavior, we mark all of the reachable modules as having been visited.
309 ModuleFile *NextModule = CurrentModule;
Douglas Gregord07865b2013-01-25 22:25:23 +0000310 do {
311 // For any module that this module depends on, push it on the
312 // stack (if it hasn't already been marked as visited).
313 for (llvm::SetVector<ModuleFile *>::iterator
314 M = NextModule->Imports.begin(),
315 MEnd = NextModule->Imports.end();
316 M != MEnd; ++M) {
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000317 if (State->VisitNumber[(*M)->Index] != VisitNumber) {
318 State->Stack.push_back(*M);
319 State->VisitNumber[(*M)->Index] = VisitNumber;
Douglas Gregor98339b92011-08-25 20:47:51 +0000320 }
321 }
Douglas Gregord07865b2013-01-25 22:25:23 +0000322
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000323 if (State->Stack.empty())
Douglas Gregord07865b2013-01-25 22:25:23 +0000324 break;
325
326 // Pop the next module off the stack.
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000327 NextModule = State->Stack.back();
328 State->Stack.pop_back();
Douglas Gregord07865b2013-01-25 22:25:23 +0000329 } while (true);
Douglas Gregor98339b92011-08-25 20:47:51 +0000330 }
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000331
332 returnVisitState(State);
Douglas Gregor98339b92011-08-25 20:47:51 +0000333}
334
335/// \brief Perform a depth-first visit of the current module.
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000336static bool visitDepthFirst(ModuleFile &M,
337 bool (*Visitor)(ModuleFile &M, bool Preorder,
Douglas Gregor98339b92011-08-25 20:47:51 +0000338 void *UserData),
339 void *UserData,
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000340 SmallVectorImpl<bool> &Visited) {
Douglas Gregor98339b92011-08-25 20:47:51 +0000341 // Preorder visitation
342 if (Visitor(M, /*Preorder=*/true, UserData))
343 return true;
344
345 // Visit children
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000346 for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000347 IMEnd = M.Imports.end();
Douglas Gregor98339b92011-08-25 20:47:51 +0000348 IM != IMEnd; ++IM) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000349 if (Visited[(*IM)->Index])
Douglas Gregor98339b92011-08-25 20:47:51 +0000350 continue;
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000351 Visited[(*IM)->Index] = true;
352
Douglas Gregor98339b92011-08-25 20:47:51 +0000353 if (visitDepthFirst(**IM, Visitor, UserData, Visited))
354 return true;
355 }
356
357 // Postorder visitation
358 return Visitor(M, /*Preorder=*/false, UserData);
359}
360
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000361void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
Douglas Gregor98339b92011-08-25 20:47:51 +0000362 void *UserData),
363 void *UserData) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000364 SmallVector<bool, 16> Visited(size(), false);
Douglas Gregor98339b92011-08-25 20:47:51 +0000365 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000366 if (Visited[Chain[I]->Index])
Douglas Gregor98339b92011-08-25 20:47:51 +0000367 continue;
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000368 Visited[Chain[I]->Index] = true;
369
Douglas Gregor98339b92011-08-25 20:47:51 +0000370 if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
371 return;
372 }
373}
Douglas Gregor2492c892011-10-11 19:27:55 +0000374
Douglas Gregor677e15f2013-03-19 00:28:20 +0000375bool ModuleManager::lookupModuleFile(StringRef FileName,
376 off_t ExpectedSize,
377 time_t ExpectedModTime,
378 const FileEntry *&File) {
379 File = FileMgr.getFile(FileName, /*openFile=*/false, /*cacheFailure=*/false);
380
381 if (!File && FileName != "-") {
382 return false;
383 }
384
385 if ((ExpectedSize && ExpectedSize != File->getSize()) ||
386 (ExpectedModTime && ExpectedModTime != File->getModificationTime())) {
387 return true;
388 }
389
390 return false;
391}
392
393bool ModuleManager::resolveModuleFileName(StringRef FileName,
394 off_t ExpectedSize,
395 time_t ExpectedModTime,
396 ModuleFile *&File) {
397 File = 0;
398
399 // Look for the file entry corresponding to this name.
400 const FileEntry *F;
401 if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, F))
402 return true;
403
404 // If there is no file, we've succeeded (trivially).
405 if (!F)
406 return false;
407
408 // Determine whether we have a module file associated with this file entry.
409 llvm::DenseMap<const FileEntry *, ModuleFile *>::iterator Known
410 = Modules.find(F);
411 if (Known == Modules.end()) {
412 // We don't know about this module file; invalidate the cache.
413 FileMgr.invalidateCache(F);
414 return false;
415 }
416
417 File = Known->second;
418 return false;
419}
420
Douglas Gregor2492c892011-10-11 19:27:55 +0000421#ifndef NDEBUG
422namespace llvm {
423 template<>
424 struct GraphTraits<ModuleManager> {
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000425 typedef ModuleFile NodeType;
426 typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
Douglas Gregor2492c892011-10-11 19:27:55 +0000427 typedef ModuleManager::ModuleConstIterator nodes_iterator;
428
429 static ChildIteratorType child_begin(NodeType *Node) {
430 return Node->Imports.begin();
431 }
432
433 static ChildIteratorType child_end(NodeType *Node) {
434 return Node->Imports.end();
435 }
436
437 static nodes_iterator nodes_begin(const ModuleManager &Manager) {
438 return Manager.begin();
439 }
440
441 static nodes_iterator nodes_end(const ModuleManager &Manager) {
442 return Manager.end();
443 }
444 };
445
446 template<>
447 struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
448 explicit DOTGraphTraits(bool IsSimple = false)
449 : DefaultDOTGraphTraits(IsSimple) { }
450
451 static bool renderGraphFromBottomUp() {
452 return true;
453 }
454
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000455 std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
Douglas Gregor2492c892011-10-11 19:27:55 +0000456 return llvm::sys::path::stem(M->FileName);
457 }
458 };
459}
460
461void ModuleManager::viewGraph() {
462 llvm::ViewGraph(*this, "Modules");
463}
464#endif