blob: a5e81e89545e9e509dd7e0332ceace8aecc1e3d5 [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 Gregor188bdcd2013-01-25 23:32:03 +000015#include "clang/Serialization/GlobalModuleIndex.h"
Benjamin Kramerae0cdff2013-08-24 13:16:22 +000016#include "clang/Serialization/ModuleManager.h"
17#include "llvm/ADT/STLExtras.h"
Douglas Gregor98339b92011-08-25 20:47:51 +000018#include "llvm/Support/MemoryBuffer.h"
Rafael Espindola8229d222013-06-11 22:15:02 +000019#include "llvm/Support/Path.h"
Douglas Gregor98339b92011-08-25 20:47:51 +000020#include "llvm/Support/raw_ostream.h"
21#include "llvm/Support/system_error.h"
22
Douglas Gregor2492c892011-10-11 19:27:55 +000023#ifndef NDEBUG
24#include "llvm/Support/GraphWriter.h"
25#endif
26
Douglas Gregor98339b92011-08-25 20:47:51 +000027using namespace clang;
28using namespace serialization;
29
Douglas Gregor1a4761e2011-11-30 23:21:26 +000030ModuleFile *ModuleManager::lookup(StringRef Name) {
Douglas Gregorea14a872013-02-08 21:27:45 +000031 const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
32 /*cacheFailure=*/false);
Douglas Gregorc544ba02013-03-27 16:47:18 +000033 if (Entry)
34 return lookup(Entry);
35
36 return 0;
37}
38
39ModuleFile *ModuleManager::lookup(const FileEntry *File) {
40 llvm::DenseMap<const FileEntry *, ModuleFile *>::iterator Known
41 = Modules.find(File);
42 if (Known == Modules.end())
43 return 0;
44
45 return Known->second;
Douglas Gregor98339b92011-08-25 20:47:51 +000046}
47
48llvm::MemoryBuffer *ModuleManager::lookupBuffer(StringRef Name) {
Douglas Gregorea14a872013-02-08 21:27:45 +000049 const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
50 /*cacheFailure=*/false);
Douglas Gregor98339b92011-08-25 20:47:51 +000051 return InMemoryBuffers[Entry];
52}
53
Douglas Gregor677e15f2013-03-19 00:28:20 +000054ModuleManager::AddModuleResult
Douglas Gregor87e2cfc2012-11-30 19:28:05 +000055ModuleManager::addModule(StringRef FileName, ModuleKind Type,
56 SourceLocation ImportLoc, ModuleFile *ImportedBy,
Douglas Gregor677e15f2013-03-19 00:28:20 +000057 unsigned Generation,
58 off_t ExpectedSize, time_t ExpectedModTime,
59 ModuleFile *&Module,
60 std::string &ErrorStr) {
61 Module = 0;
62
63 // Look for the file entry. This only fails if the expected size or
64 // modification time differ.
65 const FileEntry *Entry;
66 if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry))
67 return OutOfDate;
68
Douglas Gregor98339b92011-08-25 20:47:51 +000069 if (!Entry && FileName != "-") {
70 ErrorStr = "file not found";
Douglas Gregor677e15f2013-03-19 00:28:20 +000071 return Missing;
Douglas Gregor98339b92011-08-25 20:47:51 +000072 }
Douglas Gregor677e15f2013-03-19 00:28:20 +000073
74 // Check whether we already loaded this module, before
Douglas Gregor1a4761e2011-11-30 23:21:26 +000075 ModuleFile *&ModuleEntry = Modules[Entry];
Douglas Gregor98339b92011-08-25 20:47:51 +000076 bool NewModule = false;
77 if (!ModuleEntry) {
78 // Allocate a new module.
Douglas Gregor057df202012-01-18 20:56:22 +000079 ModuleFile *New = new ModuleFile(Type, Generation);
Douglas Gregorcc71dbe2013-01-21 20:07:12 +000080 New->Index = Chain.size();
Douglas Gregor98339b92011-08-25 20:47:51 +000081 New->FileName = FileName.str();
Argyrios Kyrtzidisd64c26f2012-10-03 01:58:42 +000082 New->File = Entry;
Douglas Gregor87e2cfc2012-11-30 19:28:05 +000083 New->ImportLoc = ImportLoc;
Douglas Gregor98339b92011-08-25 20:47:51 +000084 Chain.push_back(New);
85 NewModule = true;
86 ModuleEntry = New;
Douglas Gregor87e2cfc2012-11-30 19:28:05 +000087
Douglas Gregor98339b92011-08-25 20:47:51 +000088 // Load the contents of the module
89 if (llvm::MemoryBuffer *Buffer = lookupBuffer(FileName)) {
90 // The buffer was already provided for us.
91 assert(Buffer && "Passed null buffer");
92 New->Buffer.reset(Buffer);
93 } else {
94 // Open the AST file.
95 llvm::error_code ec;
96 if (FileName == "-") {
97 ec = llvm::MemoryBuffer::getSTDIN(New->Buffer);
98 if (ec)
99 ErrorStr = ec.message();
100 } else
101 New->Buffer.reset(FileMgr.getBufferForFile(FileName, &ErrorStr));
102
103 if (!New->Buffer)
Douglas Gregor677e15f2013-03-19 00:28:20 +0000104 return Missing;
Douglas Gregor98339b92011-08-25 20:47:51 +0000105 }
106
107 // Initialize the stream
108 New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(),
Douglas Gregor677e15f2013-03-19 00:28:20 +0000109 (const unsigned char *)New->Buffer->getBufferEnd());
Douglas Gregor677e15f2013-03-19 00:28:20 +0000110 }
Douglas Gregor98339b92011-08-25 20:47:51 +0000111
112 if (ImportedBy) {
113 ModuleEntry->ImportedBy.insert(ImportedBy);
114 ImportedBy->Imports.insert(ModuleEntry);
115 } else {
Douglas Gregor87e2cfc2012-11-30 19:28:05 +0000116 if (!ModuleEntry->DirectlyImported)
117 ModuleEntry->ImportLoc = ImportLoc;
118
Douglas Gregor98339b92011-08-25 20:47:51 +0000119 ModuleEntry->DirectlyImported = true;
120 }
Douglas Gregor677e15f2013-03-19 00:28:20 +0000121
122 Module = ModuleEntry;
123 return NewModule? NewlyLoaded : AlreadyLoaded;
Douglas Gregor98339b92011-08-25 20:47:51 +0000124}
125
Douglas Gregor7cdd2812012-11-07 17:46:15 +0000126namespace {
127 /// \brief Predicate that checks whether a module file occurs within
128 /// the given set.
129 class IsInModuleFileSet : public std::unary_function<ModuleFile *, bool> {
130 llvm::SmallPtrSet<ModuleFile *, 4> &Removed;
131
132 public:
133 IsInModuleFileSet(llvm::SmallPtrSet<ModuleFile *, 4> &Removed)
134 : Removed(Removed) { }
135
136 bool operator()(ModuleFile *MF) const {
137 return Removed.count(MF);
138 }
139 };
140}
141
Douglas Gregor677e15f2013-03-19 00:28:20 +0000142void ModuleManager::removeModules(ModuleIterator first, ModuleIterator last,
143 ModuleMap *modMap) {
Douglas Gregor7cdd2812012-11-07 17:46:15 +0000144 if (first == last)
145 return;
146
147 // Collect the set of module file pointers that we'll be removing.
148 llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
149
150 // Remove any references to the now-destroyed modules.
151 IsInModuleFileSet checkInSet(victimSet);
152 for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
153 Chain[i]->ImportedBy.remove_if(checkInSet);
154 }
155
156 // Delete the modules and erase them from the various structures.
157 for (ModuleIterator victim = first; victim != last; ++victim) {
158 Modules.erase((*victim)->File);
Douglas Gregor677e15f2013-03-19 00:28:20 +0000159
160 FileMgr.invalidateCache((*victim)->File);
161 if (modMap) {
162 StringRef ModuleName = llvm::sys::path::stem((*victim)->FileName);
163 if (Module *mod = modMap->findModule(ModuleName)) {
164 mod->setASTFile(0);
165 }
166 }
Douglas Gregor7cdd2812012-11-07 17:46:15 +0000167 delete *victim;
168 }
169
170 // Remove the modules from the chain.
171 Chain.erase(first, last);
172}
173
Douglas Gregor98339b92011-08-25 20:47:51 +0000174void ModuleManager::addInMemoryBuffer(StringRef FileName,
175 llvm::MemoryBuffer *Buffer) {
176
177 const FileEntry *Entry = FileMgr.getVirtualFile(FileName,
178 Buffer->getBufferSize(), 0);
179 InMemoryBuffers[Entry] = Buffer;
180}
181
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000182ModuleManager::VisitState *ModuleManager::allocateVisitState() {
183 // Fast path: if we have a cached state, use it.
184 if (FirstVisitState) {
185 VisitState *Result = FirstVisitState;
186 FirstVisitState = FirstVisitState->NextState;
187 Result->NextState = 0;
188 return Result;
189 }
190
191 // Allocate and return a new state.
192 return new VisitState(size());
193}
194
195void ModuleManager::returnVisitState(VisitState *State) {
196 assert(State->NextState == 0 && "Visited state is in list?");
197 State->NextState = FirstVisitState;
198 FirstVisitState = State;
199}
200
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000201void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
202 GlobalIndex = Index;
Douglas Gregorfa69fc12013-03-22 18:50:14 +0000203 if (!GlobalIndex) {
204 ModulesInCommonWithGlobalIndex.clear();
205 return;
Douglas Gregor677e15f2013-03-19 00:28:20 +0000206 }
Douglas Gregorfa69fc12013-03-22 18:50:14 +0000207
208 // Notify the global module index about all of the modules we've already
209 // loaded.
210 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
211 if (!GlobalIndex->loadedModuleFile(Chain[I])) {
212 ModulesInCommonWithGlobalIndex.push_back(Chain[I]);
213 }
214 }
215}
216
217void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
218 if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
219 return;
220
221 ModulesInCommonWithGlobalIndex.push_back(MF);
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000222}
223
224ModuleManager::ModuleManager(FileManager &FileMgr)
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000225 : FileMgr(FileMgr), GlobalIndex(), FirstVisitState(0) { }
Douglas Gregor98339b92011-08-25 20:47:51 +0000226
227ModuleManager::~ModuleManager() {
228 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
229 delete Chain[e - i - 1];
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000230 delete FirstVisitState;
Douglas Gregor98339b92011-08-25 20:47:51 +0000231}
232
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000233void
234ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
235 void *UserData,
Douglas Gregor677e15f2013-03-19 00:28:20 +0000236 llvm::SmallPtrSet<ModuleFile *, 4> *ModuleFilesHit) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000237 // If the visitation order vector is the wrong size, recompute the order.
Douglas Gregord07865b2013-01-25 22:25:23 +0000238 if (VisitOrder.size() != Chain.size()) {
239 unsigned N = size();
240 VisitOrder.clear();
241 VisitOrder.reserve(N);
242
243 // Record the number of incoming edges for each module. When we
244 // encounter a module with no incoming edges, push it into the queue
245 // to seed the queue.
246 SmallVector<ModuleFile *, 4> Queue;
247 Queue.reserve(N);
248 llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
249 UnusedIncomingEdges.reserve(size());
250 for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
251 if (unsigned Size = (*M)->ImportedBy.size())
252 UnusedIncomingEdges.push_back(Size);
253 else {
254 UnusedIncomingEdges.push_back(0);
255 Queue.push_back(*M);
256 }
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000257 }
Douglas Gregord07865b2013-01-25 22:25:23 +0000258
259 // Traverse the graph, making sure to visit a module before visiting any
260 // of its dependencies.
261 unsigned QueueStart = 0;
262 while (QueueStart < Queue.size()) {
263 ModuleFile *CurrentModule = Queue[QueueStart++];
264 VisitOrder.push_back(CurrentModule);
265
266 // For any module that this module depends on, push it on the
267 // stack (if it hasn't already been marked as visited).
268 for (llvm::SetVector<ModuleFile *>::iterator
269 M = CurrentModule->Imports.begin(),
270 MEnd = CurrentModule->Imports.end();
271 M != MEnd; ++M) {
272 // Remove our current module as an impediment to visiting the
273 // module we depend on. If we were the last unvisited module
274 // that depends on this particular module, push it into the
275 // queue to be visited.
276 unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
277 if (NumUnusedEdges && (--NumUnusedEdges == 0))
278 Queue.push_back(*M);
279 }
280 }
281
282 assert(VisitOrder.size() == N && "Visitation order is wrong?");
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000283
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000284 delete FirstVisitState;
285 FirstVisitState = 0;
Douglas Gregor98339b92011-08-25 20:47:51 +0000286 }
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000287
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000288 VisitState *State = allocateVisitState();
289 unsigned VisitNumber = State->NextVisitNumber++;
Douglas Gregord07865b2013-01-25 22:25:23 +0000290
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000291 // If the caller has provided us with a hit-set that came from the global
292 // module index, mark every module file in common with the global module
293 // index that is *not* in that set as 'visited'.
294 if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
295 for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
296 {
297 ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
Douglas Gregor677e15f2013-03-19 00:28:20 +0000298 if (!ModuleFilesHit->count(M))
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000299 State->VisitNumber[M->Index] = VisitNumber;
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000300 }
301 }
302
Douglas Gregord07865b2013-01-25 22:25:23 +0000303 for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
304 ModuleFile *CurrentModule = VisitOrder[I];
305 // Should we skip this module file?
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000306 if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
Douglas Gregor98339b92011-08-25 20:47:51 +0000307 continue;
Douglas Gregord07865b2013-01-25 22:25:23 +0000308
309 // Visit the module.
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000310 assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
311 State->VisitNumber[CurrentModule->Index] = VisitNumber;
Douglas Gregord07865b2013-01-25 22:25:23 +0000312 if (!Visitor(*CurrentModule, UserData))
313 continue;
314
315 // The visitor has requested that cut off visitation of any
316 // module that the current module depends on. To indicate this
317 // behavior, we mark all of the reachable modules as having been visited.
318 ModuleFile *NextModule = CurrentModule;
Douglas Gregord07865b2013-01-25 22:25:23 +0000319 do {
320 // For any module that this module depends on, push it on the
321 // stack (if it hasn't already been marked as visited).
322 for (llvm::SetVector<ModuleFile *>::iterator
323 M = NextModule->Imports.begin(),
324 MEnd = NextModule->Imports.end();
325 M != MEnd; ++M) {
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000326 if (State->VisitNumber[(*M)->Index] != VisitNumber) {
327 State->Stack.push_back(*M);
328 State->VisitNumber[(*M)->Index] = VisitNumber;
Douglas Gregor98339b92011-08-25 20:47:51 +0000329 }
330 }
Douglas Gregord07865b2013-01-25 22:25:23 +0000331
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000332 if (State->Stack.empty())
Douglas Gregord07865b2013-01-25 22:25:23 +0000333 break;
334
335 // Pop the next module off the stack.
Robert Wilhelm344472e2013-08-23 16:11:15 +0000336 NextModule = State->Stack.pop_back_val();
Douglas Gregord07865b2013-01-25 22:25:23 +0000337 } while (true);
Douglas Gregor98339b92011-08-25 20:47:51 +0000338 }
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000339
340 returnVisitState(State);
Douglas Gregor98339b92011-08-25 20:47:51 +0000341}
342
343/// \brief Perform a depth-first visit of the current module.
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000344static bool visitDepthFirst(ModuleFile &M,
345 bool (*Visitor)(ModuleFile &M, bool Preorder,
Douglas Gregor98339b92011-08-25 20:47:51 +0000346 void *UserData),
347 void *UserData,
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000348 SmallVectorImpl<bool> &Visited) {
Douglas Gregor98339b92011-08-25 20:47:51 +0000349 // Preorder visitation
350 if (Visitor(M, /*Preorder=*/true, UserData))
351 return true;
352
353 // Visit children
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000354 for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000355 IMEnd = M.Imports.end();
Douglas Gregor98339b92011-08-25 20:47:51 +0000356 IM != IMEnd; ++IM) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000357 if (Visited[(*IM)->Index])
Douglas Gregor98339b92011-08-25 20:47:51 +0000358 continue;
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000359 Visited[(*IM)->Index] = true;
360
Douglas Gregor98339b92011-08-25 20:47:51 +0000361 if (visitDepthFirst(**IM, Visitor, UserData, Visited))
362 return true;
363 }
364
365 // Postorder visitation
366 return Visitor(M, /*Preorder=*/false, UserData);
367}
368
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000369void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
Douglas Gregor98339b92011-08-25 20:47:51 +0000370 void *UserData),
371 void *UserData) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000372 SmallVector<bool, 16> Visited(size(), false);
Douglas Gregor98339b92011-08-25 20:47:51 +0000373 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000374 if (Visited[Chain[I]->Index])
Douglas Gregor98339b92011-08-25 20:47:51 +0000375 continue;
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000376 Visited[Chain[I]->Index] = true;
377
Douglas Gregor98339b92011-08-25 20:47:51 +0000378 if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
379 return;
380 }
381}
Douglas Gregor2492c892011-10-11 19:27:55 +0000382
Douglas Gregor677e15f2013-03-19 00:28:20 +0000383bool ModuleManager::lookupModuleFile(StringRef FileName,
384 off_t ExpectedSize,
385 time_t ExpectedModTime,
386 const FileEntry *&File) {
387 File = FileMgr.getFile(FileName, /*openFile=*/false, /*cacheFailure=*/false);
388
389 if (!File && FileName != "-") {
390 return false;
391 }
392
393 if ((ExpectedSize && ExpectedSize != File->getSize()) ||
394 (ExpectedModTime && ExpectedModTime != File->getModificationTime())) {
395 return true;
396 }
397
398 return false;
399}
400
Douglas Gregor2492c892011-10-11 19:27:55 +0000401#ifndef NDEBUG
402namespace llvm {
403 template<>
404 struct GraphTraits<ModuleManager> {
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000405 typedef ModuleFile NodeType;
406 typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
Douglas Gregor2492c892011-10-11 19:27:55 +0000407 typedef ModuleManager::ModuleConstIterator nodes_iterator;
408
409 static ChildIteratorType child_begin(NodeType *Node) {
410 return Node->Imports.begin();
411 }
412
413 static ChildIteratorType child_end(NodeType *Node) {
414 return Node->Imports.end();
415 }
416
417 static nodes_iterator nodes_begin(const ModuleManager &Manager) {
418 return Manager.begin();
419 }
420
421 static nodes_iterator nodes_end(const ModuleManager &Manager) {
422 return Manager.end();
423 }
424 };
425
426 template<>
427 struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
428 explicit DOTGraphTraits(bool IsSimple = false)
429 : DefaultDOTGraphTraits(IsSimple) { }
430
431 static bool renderGraphFromBottomUp() {
432 return true;
433 }
434
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000435 std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
Douglas Gregor2492c892011-10-11 19:27:55 +0000436 return llvm::sys::path::stem(M->FileName);
437 }
438 };
439}
440
441void ModuleManager::viewGraph() {
442 llvm::ViewGraph(*this, "Modules");
443}
444#endif