blob: 193a38b97384e7f1aa91899774f141bb61c7f717 [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
Douglas Gregor1a4761e2011-11-30 23:21:26 +000062 ModuleFile *&ModuleEntry = Modules[Entry];
Douglas Gregor98339b92011-08-25 20:47:51 +000063 bool NewModule = false;
64 if (!ModuleEntry) {
65 // Allocate a new module.
Douglas Gregor057df202012-01-18 20:56:22 +000066 ModuleFile *New = new ModuleFile(Type, Generation);
Douglas Gregorcc71dbe2013-01-21 20:07:12 +000067 New->Index = Chain.size();
Douglas Gregor98339b92011-08-25 20:47:51 +000068 New->FileName = FileName.str();
Argyrios Kyrtzidisd64c26f2012-10-03 01:58:42 +000069 New->File = Entry;
Douglas Gregor87e2cfc2012-11-30 19:28:05 +000070 New->ImportLoc = ImportLoc;
Douglas Gregor98339b92011-08-25 20:47:51 +000071 Chain.push_back(New);
72 NewModule = true;
73 ModuleEntry = New;
Douglas Gregor87e2cfc2012-11-30 19:28:05 +000074
Douglas Gregor98339b92011-08-25 20:47:51 +000075 // Load the contents of the module
76 if (llvm::MemoryBuffer *Buffer = lookupBuffer(FileName)) {
77 // The buffer was already provided for us.
78 assert(Buffer && "Passed null buffer");
79 New->Buffer.reset(Buffer);
80 } else {
81 // Open the AST file.
82 llvm::error_code ec;
83 if (FileName == "-") {
84 ec = llvm::MemoryBuffer::getSTDIN(New->Buffer);
85 if (ec)
86 ErrorStr = ec.message();
87 } else
88 New->Buffer.reset(FileMgr.getBufferForFile(FileName, &ErrorStr));
89
90 if (!New->Buffer)
Douglas Gregor677e15f2013-03-19 00:28:20 +000091 return Missing;
Douglas Gregor98339b92011-08-25 20:47:51 +000092 }
93
94 // Initialize the stream
95 New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(),
Douglas Gregor677e15f2013-03-19 00:28:20 +000096 (const unsigned char *)New->Buffer->getBufferEnd());
Douglas Gregor677e15f2013-03-19 00:28:20 +000097 }
Douglas Gregor98339b92011-08-25 20:47:51 +000098
99 if (ImportedBy) {
100 ModuleEntry->ImportedBy.insert(ImportedBy);
101 ImportedBy->Imports.insert(ModuleEntry);
102 } else {
Douglas Gregor87e2cfc2012-11-30 19:28:05 +0000103 if (!ModuleEntry->DirectlyImported)
104 ModuleEntry->ImportLoc = ImportLoc;
105
Douglas Gregor98339b92011-08-25 20:47:51 +0000106 ModuleEntry->DirectlyImported = true;
107 }
Douglas Gregor677e15f2013-03-19 00:28:20 +0000108
109 Module = ModuleEntry;
110 return NewModule? NewlyLoaded : AlreadyLoaded;
Douglas Gregor98339b92011-08-25 20:47:51 +0000111}
112
Douglas Gregor7cdd2812012-11-07 17:46:15 +0000113namespace {
114 /// \brief Predicate that checks whether a module file occurs within
115 /// the given set.
116 class IsInModuleFileSet : public std::unary_function<ModuleFile *, bool> {
117 llvm::SmallPtrSet<ModuleFile *, 4> &Removed;
118
119 public:
120 IsInModuleFileSet(llvm::SmallPtrSet<ModuleFile *, 4> &Removed)
121 : Removed(Removed) { }
122
123 bool operator()(ModuleFile *MF) const {
124 return Removed.count(MF);
125 }
126 };
127}
128
Douglas Gregor677e15f2013-03-19 00:28:20 +0000129void ModuleManager::removeModules(ModuleIterator first, ModuleIterator last,
130 ModuleMap *modMap) {
Douglas Gregor7cdd2812012-11-07 17:46:15 +0000131 if (first == last)
132 return;
133
134 // Collect the set of module file pointers that we'll be removing.
135 llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
136
137 // Remove any references to the now-destroyed modules.
138 IsInModuleFileSet checkInSet(victimSet);
139 for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
140 Chain[i]->ImportedBy.remove_if(checkInSet);
141 }
142
143 // Delete the modules and erase them from the various structures.
144 for (ModuleIterator victim = first; victim != last; ++victim) {
145 Modules.erase((*victim)->File);
Douglas Gregor677e15f2013-03-19 00:28:20 +0000146
147 FileMgr.invalidateCache((*victim)->File);
148 if (modMap) {
149 StringRef ModuleName = llvm::sys::path::stem((*victim)->FileName);
150 if (Module *mod = modMap->findModule(ModuleName)) {
151 mod->setASTFile(0);
152 }
153 }
Douglas Gregor7cdd2812012-11-07 17:46:15 +0000154 delete *victim;
155 }
156
157 // Remove the modules from the chain.
158 Chain.erase(first, last);
159}
160
Douglas Gregor98339b92011-08-25 20:47:51 +0000161void ModuleManager::addInMemoryBuffer(StringRef FileName,
162 llvm::MemoryBuffer *Buffer) {
163
164 const FileEntry *Entry = FileMgr.getVirtualFile(FileName,
165 Buffer->getBufferSize(), 0);
166 InMemoryBuffers[Entry] = Buffer;
167}
168
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000169ModuleManager::VisitState *ModuleManager::allocateVisitState() {
170 // Fast path: if we have a cached state, use it.
171 if (FirstVisitState) {
172 VisitState *Result = FirstVisitState;
173 FirstVisitState = FirstVisitState->NextState;
174 Result->NextState = 0;
175 return Result;
176 }
177
178 // Allocate and return a new state.
179 return new VisitState(size());
180}
181
182void ModuleManager::returnVisitState(VisitState *State) {
183 assert(State->NextState == 0 && "Visited state is in list?");
184 State->NextState = FirstVisitState;
185 FirstVisitState = State;
186}
187
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000188void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
189 GlobalIndex = Index;
Douglas Gregorfa69fc12013-03-22 18:50:14 +0000190 if (!GlobalIndex) {
191 ModulesInCommonWithGlobalIndex.clear();
192 return;
Douglas Gregor677e15f2013-03-19 00:28:20 +0000193 }
Douglas Gregorfa69fc12013-03-22 18:50:14 +0000194
195 // Notify the global module index about all of the modules we've already
196 // loaded.
197 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
198 if (!GlobalIndex->loadedModuleFile(Chain[I])) {
199 ModulesInCommonWithGlobalIndex.push_back(Chain[I]);
200 }
201 }
202}
203
204void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
205 if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
206 return;
207
208 ModulesInCommonWithGlobalIndex.push_back(MF);
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000209}
210
211ModuleManager::ModuleManager(FileManager &FileMgr)
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000212 : FileMgr(FileMgr), GlobalIndex(), FirstVisitState(0) { }
Douglas Gregor98339b92011-08-25 20:47:51 +0000213
214ModuleManager::~ModuleManager() {
215 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
216 delete Chain[e - i - 1];
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000217 delete FirstVisitState;
Douglas Gregor98339b92011-08-25 20:47:51 +0000218}
219
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000220void
221ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
222 void *UserData,
Douglas Gregor677e15f2013-03-19 00:28:20 +0000223 llvm::SmallPtrSet<ModuleFile *, 4> *ModuleFilesHit) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000224 // If the visitation order vector is the wrong size, recompute the order.
Douglas Gregord07865b2013-01-25 22:25:23 +0000225 if (VisitOrder.size() != Chain.size()) {
226 unsigned N = size();
227 VisitOrder.clear();
228 VisitOrder.reserve(N);
229
230 // Record the number of incoming edges for each module. When we
231 // encounter a module with no incoming edges, push it into the queue
232 // to seed the queue.
233 SmallVector<ModuleFile *, 4> Queue;
234 Queue.reserve(N);
235 llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
236 UnusedIncomingEdges.reserve(size());
237 for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
238 if (unsigned Size = (*M)->ImportedBy.size())
239 UnusedIncomingEdges.push_back(Size);
240 else {
241 UnusedIncomingEdges.push_back(0);
242 Queue.push_back(*M);
243 }
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000244 }
Douglas Gregord07865b2013-01-25 22:25:23 +0000245
246 // Traverse the graph, making sure to visit a module before visiting any
247 // of its dependencies.
248 unsigned QueueStart = 0;
249 while (QueueStart < Queue.size()) {
250 ModuleFile *CurrentModule = Queue[QueueStart++];
251 VisitOrder.push_back(CurrentModule);
252
253 // For any module that this module depends on, push it on the
254 // stack (if it hasn't already been marked as visited).
255 for (llvm::SetVector<ModuleFile *>::iterator
256 M = CurrentModule->Imports.begin(),
257 MEnd = CurrentModule->Imports.end();
258 M != MEnd; ++M) {
259 // Remove our current module as an impediment to visiting the
260 // module we depend on. If we were the last unvisited module
261 // that depends on this particular module, push it into the
262 // queue to be visited.
263 unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
264 if (NumUnusedEdges && (--NumUnusedEdges == 0))
265 Queue.push_back(*M);
266 }
267 }
268
269 assert(VisitOrder.size() == N && "Visitation order is wrong?");
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000270
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000271 delete FirstVisitState;
272 FirstVisitState = 0;
Douglas Gregor98339b92011-08-25 20:47:51 +0000273 }
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000274
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000275 VisitState *State = allocateVisitState();
276 unsigned VisitNumber = State->NextVisitNumber++;
Douglas Gregord07865b2013-01-25 22:25:23 +0000277
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000278 // If the caller has provided us with a hit-set that came from the global
279 // module index, mark every module file in common with the global module
280 // index that is *not* in that set as 'visited'.
281 if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
282 for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
283 {
284 ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
Douglas Gregor677e15f2013-03-19 00:28:20 +0000285 if (!ModuleFilesHit->count(M))
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000286 State->VisitNumber[M->Index] = VisitNumber;
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000287 }
288 }
289
Douglas Gregord07865b2013-01-25 22:25:23 +0000290 for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
291 ModuleFile *CurrentModule = VisitOrder[I];
292 // Should we skip this module file?
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000293 if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
Douglas Gregor98339b92011-08-25 20:47:51 +0000294 continue;
Douglas Gregord07865b2013-01-25 22:25:23 +0000295
296 // Visit the module.
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000297 assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
298 State->VisitNumber[CurrentModule->Index] = VisitNumber;
Douglas Gregord07865b2013-01-25 22:25:23 +0000299 if (!Visitor(*CurrentModule, UserData))
300 continue;
301
302 // The visitor has requested that cut off visitation of any
303 // module that the current module depends on. To indicate this
304 // behavior, we mark all of the reachable modules as having been visited.
305 ModuleFile *NextModule = CurrentModule;
Douglas Gregord07865b2013-01-25 22:25:23 +0000306 do {
307 // For any module that this module depends on, push it on the
308 // stack (if it hasn't already been marked as visited).
309 for (llvm::SetVector<ModuleFile *>::iterator
310 M = NextModule->Imports.begin(),
311 MEnd = NextModule->Imports.end();
312 M != MEnd; ++M) {
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000313 if (State->VisitNumber[(*M)->Index] != VisitNumber) {
314 State->Stack.push_back(*M);
315 State->VisitNumber[(*M)->Index] = VisitNumber;
Douglas Gregor98339b92011-08-25 20:47:51 +0000316 }
317 }
Douglas Gregord07865b2013-01-25 22:25:23 +0000318
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000319 if (State->Stack.empty())
Douglas Gregord07865b2013-01-25 22:25:23 +0000320 break;
321
322 // Pop the next module off the stack.
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000323 NextModule = State->Stack.back();
324 State->Stack.pop_back();
Douglas Gregord07865b2013-01-25 22:25:23 +0000325 } while (true);
Douglas Gregor98339b92011-08-25 20:47:51 +0000326 }
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000327
328 returnVisitState(State);
Douglas Gregor98339b92011-08-25 20:47:51 +0000329}
330
331/// \brief Perform a depth-first visit of the current module.
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000332static bool visitDepthFirst(ModuleFile &M,
333 bool (*Visitor)(ModuleFile &M, bool Preorder,
Douglas Gregor98339b92011-08-25 20:47:51 +0000334 void *UserData),
335 void *UserData,
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000336 SmallVectorImpl<bool> &Visited) {
Douglas Gregor98339b92011-08-25 20:47:51 +0000337 // Preorder visitation
338 if (Visitor(M, /*Preorder=*/true, UserData))
339 return true;
340
341 // Visit children
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000342 for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000343 IMEnd = M.Imports.end();
Douglas Gregor98339b92011-08-25 20:47:51 +0000344 IM != IMEnd; ++IM) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000345 if (Visited[(*IM)->Index])
Douglas Gregor98339b92011-08-25 20:47:51 +0000346 continue;
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000347 Visited[(*IM)->Index] = true;
348
Douglas Gregor98339b92011-08-25 20:47:51 +0000349 if (visitDepthFirst(**IM, Visitor, UserData, Visited))
350 return true;
351 }
352
353 // Postorder visitation
354 return Visitor(M, /*Preorder=*/false, UserData);
355}
356
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000357void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
Douglas Gregor98339b92011-08-25 20:47:51 +0000358 void *UserData),
359 void *UserData) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000360 SmallVector<bool, 16> Visited(size(), false);
Douglas Gregor98339b92011-08-25 20:47:51 +0000361 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000362 if (Visited[Chain[I]->Index])
Douglas Gregor98339b92011-08-25 20:47:51 +0000363 continue;
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000364 Visited[Chain[I]->Index] = true;
365
Douglas Gregor98339b92011-08-25 20:47:51 +0000366 if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
367 return;
368 }
369}
Douglas Gregor2492c892011-10-11 19:27:55 +0000370
Douglas Gregor677e15f2013-03-19 00:28:20 +0000371bool ModuleManager::lookupModuleFile(StringRef FileName,
372 off_t ExpectedSize,
373 time_t ExpectedModTime,
374 const FileEntry *&File) {
375 File = FileMgr.getFile(FileName, /*openFile=*/false, /*cacheFailure=*/false);
376
377 if (!File && FileName != "-") {
378 return false;
379 }
380
381 if ((ExpectedSize && ExpectedSize != File->getSize()) ||
382 (ExpectedModTime && ExpectedModTime != File->getModificationTime())) {
383 return true;
384 }
385
386 return false;
387}
388
Douglas Gregor2492c892011-10-11 19:27:55 +0000389#ifndef NDEBUG
390namespace llvm {
391 template<>
392 struct GraphTraits<ModuleManager> {
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000393 typedef ModuleFile NodeType;
394 typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
Douglas Gregor2492c892011-10-11 19:27:55 +0000395 typedef ModuleManager::ModuleConstIterator nodes_iterator;
396
397 static ChildIteratorType child_begin(NodeType *Node) {
398 return Node->Imports.begin();
399 }
400
401 static ChildIteratorType child_end(NodeType *Node) {
402 return Node->Imports.end();
403 }
404
405 static nodes_iterator nodes_begin(const ModuleManager &Manager) {
406 return Manager.begin();
407 }
408
409 static nodes_iterator nodes_end(const ModuleManager &Manager) {
410 return Manager.end();
411 }
412 };
413
414 template<>
415 struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
416 explicit DOTGraphTraits(bool IsSimple = false)
417 : DefaultDOTGraphTraits(IsSimple) { }
418
419 static bool renderGraphFromBottomUp() {
420 return true;
421 }
422
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000423 std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
Douglas Gregor2492c892011-10-11 19:27:55 +0000424 return llvm::sys::path::stem(M->FileName);
425 }
426 };
427}
428
429void ModuleManager::viewGraph() {
430 llvm::ViewGraph(*this, "Modules");
431}
432#endif