blob: 3513eba86024ceebd2310259c052b182f42d1276 [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"
Douglas Gregor98339b92011-08-25 20:47:51 +000017#include "llvm/Support/MemoryBuffer.h"
Rafael Espindola8229d222013-06-11 22:15:02 +000018#include "llvm/Support/Path.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 Gregorc544ba02013-03-27 16:47:18 +000032 if (Entry)
33 return lookup(Entry);
34
35 return 0;
36}
37
38ModuleFile *ModuleManager::lookup(const FileEntry *File) {
39 llvm::DenseMap<const FileEntry *, ModuleFile *>::iterator Known
40 = Modules.find(File);
41 if (Known == Modules.end())
42 return 0;
43
44 return Known->second;
Douglas Gregor98339b92011-08-25 20:47:51 +000045}
46
47llvm::MemoryBuffer *ModuleManager::lookupBuffer(StringRef Name) {
Douglas Gregorea14a872013-02-08 21:27:45 +000048 const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false,
49 /*cacheFailure=*/false);
Douglas Gregor98339b92011-08-25 20:47:51 +000050 return InMemoryBuffers[Entry];
51}
52
Douglas Gregor677e15f2013-03-19 00:28:20 +000053ModuleManager::AddModuleResult
Douglas Gregor87e2cfc2012-11-30 19:28:05 +000054ModuleManager::addModule(StringRef FileName, ModuleKind Type,
55 SourceLocation ImportLoc, ModuleFile *ImportedBy,
Douglas Gregor677e15f2013-03-19 00:28:20 +000056 unsigned Generation,
57 off_t ExpectedSize, time_t ExpectedModTime,
58 ModuleFile *&Module,
59 std::string &ErrorStr) {
60 Module = 0;
61
62 // Look for the file entry. This only fails if the expected size or
63 // modification time differ.
64 const FileEntry *Entry;
Eli Friedmanedadb9a2013-09-05 23:50:58 +000065 if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
66 ErrorStr = "module file out of date";
Douglas Gregor677e15f2013-03-19 00:28:20 +000067 return OutOfDate;
Eli Friedmanedadb9a2013-09-05 23:50:58 +000068 }
Douglas Gregor677e15f2013-03-19 00:28:20 +000069
Douglas Gregor98339b92011-08-25 20:47:51 +000070 if (!Entry && FileName != "-") {
Eli Friedmanedadb9a2013-09-05 23:50:58 +000071 ErrorStr = "module file not found";
Douglas Gregor677e15f2013-03-19 00:28:20 +000072 return Missing;
Douglas Gregor98339b92011-08-25 20:47:51 +000073 }
Douglas Gregor677e15f2013-03-19 00:28:20 +000074
75 // Check whether we already loaded this module, before
Douglas Gregor1a4761e2011-11-30 23:21:26 +000076 ModuleFile *&ModuleEntry = Modules[Entry];
Douglas Gregor98339b92011-08-25 20:47:51 +000077 bool NewModule = false;
78 if (!ModuleEntry) {
79 // Allocate a new module.
Douglas Gregor057df202012-01-18 20:56:22 +000080 ModuleFile *New = new ModuleFile(Type, Generation);
Douglas Gregorcc71dbe2013-01-21 20:07:12 +000081 New->Index = Chain.size();
Douglas Gregor98339b92011-08-25 20:47:51 +000082 New->FileName = FileName.str();
Argyrios Kyrtzidisd64c26f2012-10-03 01:58:42 +000083 New->File = Entry;
Douglas Gregor87e2cfc2012-11-30 19:28:05 +000084 New->ImportLoc = ImportLoc;
Douglas Gregor98339b92011-08-25 20:47:51 +000085 Chain.push_back(New);
86 NewModule = true;
87 ModuleEntry = New;
Douglas Gregor87e2cfc2012-11-30 19:28:05 +000088
Stephen Hines651f13c2014-04-23 16:59:28 -070089 New->InputFilesValidationTimestamp = 0;
90 if (New->Kind == MK_Module) {
91 std::string TimestampFilename = New->getTimestampFilename();
92 vfs::Status Status;
93 // A cached stat value would be fine as well.
94 if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
95 New->InputFilesValidationTimestamp =
96 Status.getLastModificationTime().toEpochTime();
97 }
98
Douglas Gregor98339b92011-08-25 20:47:51 +000099 // Load the contents of the module
100 if (llvm::MemoryBuffer *Buffer = lookupBuffer(FileName)) {
101 // The buffer was already provided for us.
102 assert(Buffer && "Passed null buffer");
103 New->Buffer.reset(Buffer);
104 } else {
105 // Open the AST file.
106 llvm::error_code ec;
107 if (FileName == "-") {
108 ec = llvm::MemoryBuffer::getSTDIN(New->Buffer);
109 if (ec)
110 ErrorStr = ec.message();
111 } else
112 New->Buffer.reset(FileMgr.getBufferForFile(FileName, &ErrorStr));
113
114 if (!New->Buffer)
Douglas Gregor677e15f2013-03-19 00:28:20 +0000115 return Missing;
Douglas Gregor98339b92011-08-25 20:47:51 +0000116 }
117
118 // Initialize the stream
119 New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(),
Douglas Gregor677e15f2013-03-19 00:28:20 +0000120 (const unsigned char *)New->Buffer->getBufferEnd());
Douglas Gregor677e15f2013-03-19 00:28:20 +0000121 }
Douglas Gregor98339b92011-08-25 20:47:51 +0000122
123 if (ImportedBy) {
124 ModuleEntry->ImportedBy.insert(ImportedBy);
125 ImportedBy->Imports.insert(ModuleEntry);
126 } else {
Douglas Gregor87e2cfc2012-11-30 19:28:05 +0000127 if (!ModuleEntry->DirectlyImported)
128 ModuleEntry->ImportLoc = ImportLoc;
129
Douglas Gregor98339b92011-08-25 20:47:51 +0000130 ModuleEntry->DirectlyImported = true;
131 }
Douglas Gregor677e15f2013-03-19 00:28:20 +0000132
133 Module = ModuleEntry;
134 return NewModule? NewlyLoaded : AlreadyLoaded;
Douglas Gregor98339b92011-08-25 20:47:51 +0000135}
136
Douglas Gregor677e15f2013-03-19 00:28:20 +0000137void ModuleManager::removeModules(ModuleIterator first, ModuleIterator last,
138 ModuleMap *modMap) {
Douglas Gregor7cdd2812012-11-07 17:46:15 +0000139 if (first == last)
140 return;
141
142 // Collect the set of module file pointers that we'll be removing.
143 llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last);
144
145 // Remove any references to the now-destroyed modules.
Douglas Gregor7cdd2812012-11-07 17:46:15 +0000146 for (unsigned i = 0, n = Chain.size(); i != n; ++i) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700147 Chain[i]->ImportedBy.remove_if([&](ModuleFile *MF) {
148 return victimSet.count(MF);
149 });
Douglas Gregor7cdd2812012-11-07 17:46:15 +0000150 }
151
152 // Delete the modules and erase them from the various structures.
153 for (ModuleIterator victim = first; victim != last; ++victim) {
154 Modules.erase((*victim)->File);
Douglas Gregor677e15f2013-03-19 00:28:20 +0000155
156 FileMgr.invalidateCache((*victim)->File);
157 if (modMap) {
158 StringRef ModuleName = llvm::sys::path::stem((*victim)->FileName);
159 if (Module *mod = modMap->findModule(ModuleName)) {
160 mod->setASTFile(0);
161 }
162 }
Douglas Gregor7cdd2812012-11-07 17:46:15 +0000163 delete *victim;
164 }
165
166 // Remove the modules from the chain.
167 Chain.erase(first, last);
168}
169
Douglas Gregor98339b92011-08-25 20:47:51 +0000170void ModuleManager::addInMemoryBuffer(StringRef FileName,
171 llvm::MemoryBuffer *Buffer) {
172
173 const FileEntry *Entry = FileMgr.getVirtualFile(FileName,
174 Buffer->getBufferSize(), 0);
175 InMemoryBuffers[Entry] = Buffer;
176}
177
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000178ModuleManager::VisitState *ModuleManager::allocateVisitState() {
179 // Fast path: if we have a cached state, use it.
180 if (FirstVisitState) {
181 VisitState *Result = FirstVisitState;
182 FirstVisitState = FirstVisitState->NextState;
183 Result->NextState = 0;
184 return Result;
185 }
186
187 // Allocate and return a new state.
188 return new VisitState(size());
189}
190
191void ModuleManager::returnVisitState(VisitState *State) {
192 assert(State->NextState == 0 && "Visited state is in list?");
193 State->NextState = FirstVisitState;
194 FirstVisitState = State;
195}
196
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000197void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
198 GlobalIndex = Index;
Douglas Gregorfa69fc12013-03-22 18:50:14 +0000199 if (!GlobalIndex) {
200 ModulesInCommonWithGlobalIndex.clear();
201 return;
Douglas Gregor677e15f2013-03-19 00:28:20 +0000202 }
Douglas Gregorfa69fc12013-03-22 18:50:14 +0000203
204 // Notify the global module index about all of the modules we've already
205 // loaded.
206 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
207 if (!GlobalIndex->loadedModuleFile(Chain[I])) {
208 ModulesInCommonWithGlobalIndex.push_back(Chain[I]);
209 }
210 }
211}
212
213void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
214 if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
215 return;
216
217 ModulesInCommonWithGlobalIndex.push_back(MF);
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000218}
219
220ModuleManager::ModuleManager(FileManager &FileMgr)
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000221 : FileMgr(FileMgr), GlobalIndex(), FirstVisitState(0) { }
Douglas Gregor98339b92011-08-25 20:47:51 +0000222
223ModuleManager::~ModuleManager() {
224 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
225 delete Chain[e - i - 1];
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000226 delete FirstVisitState;
Douglas Gregor98339b92011-08-25 20:47:51 +0000227}
228
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000229void
230ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),
231 void *UserData,
Douglas Gregor677e15f2013-03-19 00:28:20 +0000232 llvm::SmallPtrSet<ModuleFile *, 4> *ModuleFilesHit) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000233 // If the visitation order vector is the wrong size, recompute the order.
Douglas Gregord07865b2013-01-25 22:25:23 +0000234 if (VisitOrder.size() != Chain.size()) {
235 unsigned N = size();
236 VisitOrder.clear();
237 VisitOrder.reserve(N);
238
239 // Record the number of incoming edges for each module. When we
240 // encounter a module with no incoming edges, push it into the queue
241 // to seed the queue.
242 SmallVector<ModuleFile *, 4> Queue;
243 Queue.reserve(N);
244 llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
245 UnusedIncomingEdges.reserve(size());
246 for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
247 if (unsigned Size = (*M)->ImportedBy.size())
248 UnusedIncomingEdges.push_back(Size);
249 else {
250 UnusedIncomingEdges.push_back(0);
251 Queue.push_back(*M);
252 }
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000253 }
Douglas Gregord07865b2013-01-25 22:25:23 +0000254
255 // Traverse the graph, making sure to visit a module before visiting any
256 // of its dependencies.
257 unsigned QueueStart = 0;
258 while (QueueStart < Queue.size()) {
259 ModuleFile *CurrentModule = Queue[QueueStart++];
260 VisitOrder.push_back(CurrentModule);
261
262 // For any module that this module depends on, push it on the
263 // stack (if it hasn't already been marked as visited).
264 for (llvm::SetVector<ModuleFile *>::iterator
265 M = CurrentModule->Imports.begin(),
266 MEnd = CurrentModule->Imports.end();
267 M != MEnd; ++M) {
268 // Remove our current module as an impediment to visiting the
269 // module we depend on. If we were the last unvisited module
270 // that depends on this particular module, push it into the
271 // queue to be visited.
272 unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
273 if (NumUnusedEdges && (--NumUnusedEdges == 0))
274 Queue.push_back(*M);
275 }
276 }
277
278 assert(VisitOrder.size() == N && "Visitation order is wrong?");
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000279
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000280 delete FirstVisitState;
281 FirstVisitState = 0;
Douglas Gregor98339b92011-08-25 20:47:51 +0000282 }
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000283
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000284 VisitState *State = allocateVisitState();
285 unsigned VisitNumber = State->NextVisitNumber++;
Douglas Gregord07865b2013-01-25 22:25:23 +0000286
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000287 // If the caller has provided us with a hit-set that came from the global
288 // module index, mark every module file in common with the global module
289 // index that is *not* in that set as 'visited'.
290 if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
291 for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
292 {
293 ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
Douglas Gregor677e15f2013-03-19 00:28:20 +0000294 if (!ModuleFilesHit->count(M))
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000295 State->VisitNumber[M->Index] = VisitNumber;
Douglas Gregor188bdcd2013-01-25 23:32:03 +0000296 }
297 }
298
Douglas Gregord07865b2013-01-25 22:25:23 +0000299 for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
300 ModuleFile *CurrentModule = VisitOrder[I];
301 // Should we skip this module file?
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000302 if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
Douglas Gregor98339b92011-08-25 20:47:51 +0000303 continue;
Douglas Gregord07865b2013-01-25 22:25:23 +0000304
305 // Visit the module.
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000306 assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
307 State->VisitNumber[CurrentModule->Index] = VisitNumber;
Douglas Gregord07865b2013-01-25 22:25:23 +0000308 if (!Visitor(*CurrentModule, UserData))
309 continue;
310
311 // The visitor has requested that cut off visitation of any
312 // module that the current module depends on. To indicate this
313 // behavior, we mark all of the reachable modules as having been visited.
314 ModuleFile *NextModule = CurrentModule;
Douglas Gregord07865b2013-01-25 22:25:23 +0000315 do {
316 // For any module that this module depends on, push it on the
317 // stack (if it hasn't already been marked as visited).
318 for (llvm::SetVector<ModuleFile *>::iterator
319 M = NextModule->Imports.begin(),
320 MEnd = NextModule->Imports.end();
321 M != MEnd; ++M) {
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000322 if (State->VisitNumber[(*M)->Index] != VisitNumber) {
323 State->Stack.push_back(*M);
324 State->VisitNumber[(*M)->Index] = VisitNumber;
Douglas Gregor98339b92011-08-25 20:47:51 +0000325 }
326 }
Douglas Gregord07865b2013-01-25 22:25:23 +0000327
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000328 if (State->Stack.empty())
Douglas Gregord07865b2013-01-25 22:25:23 +0000329 break;
330
331 // Pop the next module off the stack.
Robert Wilhelm344472e2013-08-23 16:11:15 +0000332 NextModule = State->Stack.pop_back_val();
Douglas Gregord07865b2013-01-25 22:25:23 +0000333 } while (true);
Douglas Gregor98339b92011-08-25 20:47:51 +0000334 }
Douglas Gregord3cf5fb2013-01-28 16:46:33 +0000335
336 returnVisitState(State);
Douglas Gregor98339b92011-08-25 20:47:51 +0000337}
338
339/// \brief Perform a depth-first visit of the current module.
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000340static bool visitDepthFirst(ModuleFile &M,
341 bool (*Visitor)(ModuleFile &M, bool Preorder,
Douglas Gregor98339b92011-08-25 20:47:51 +0000342 void *UserData),
343 void *UserData,
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000344 SmallVectorImpl<bool> &Visited) {
Douglas Gregor98339b92011-08-25 20:47:51 +0000345 // Preorder visitation
346 if (Visitor(M, /*Preorder=*/true, UserData))
347 return true;
348
349 // Visit children
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000350 for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(),
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000351 IMEnd = M.Imports.end();
Douglas Gregor98339b92011-08-25 20:47:51 +0000352 IM != IMEnd; ++IM) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000353 if (Visited[(*IM)->Index])
Douglas Gregor98339b92011-08-25 20:47:51 +0000354 continue;
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000355 Visited[(*IM)->Index] = true;
356
Douglas Gregor98339b92011-08-25 20:47:51 +0000357 if (visitDepthFirst(**IM, Visitor, UserData, Visited))
358 return true;
359 }
360
361 // Postorder visitation
362 return Visitor(M, /*Preorder=*/false, UserData);
363}
364
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000365void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,
Douglas Gregor98339b92011-08-25 20:47:51 +0000366 void *UserData),
367 void *UserData) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000368 SmallVector<bool, 16> Visited(size(), false);
Douglas Gregor98339b92011-08-25 20:47:51 +0000369 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000370 if (Visited[Chain[I]->Index])
Douglas Gregor98339b92011-08-25 20:47:51 +0000371 continue;
Douglas Gregorcc71dbe2013-01-21 20:07:12 +0000372 Visited[Chain[I]->Index] = true;
373
Douglas Gregor98339b92011-08-25 20:47:51 +0000374 if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
375 return;
376 }
377}
Douglas Gregor2492c892011-10-11 19:27:55 +0000378
Douglas Gregor677e15f2013-03-19 00:28:20 +0000379bool ModuleManager::lookupModuleFile(StringRef FileName,
380 off_t ExpectedSize,
381 time_t ExpectedModTime,
382 const FileEntry *&File) {
383 File = FileMgr.getFile(FileName, /*openFile=*/false, /*cacheFailure=*/false);
384
385 if (!File && FileName != "-") {
386 return false;
387 }
388
389 if ((ExpectedSize && ExpectedSize != File->getSize()) ||
390 (ExpectedModTime && ExpectedModTime != File->getModificationTime())) {
391 return true;
392 }
393
394 return false;
395}
396
Douglas Gregor2492c892011-10-11 19:27:55 +0000397#ifndef NDEBUG
398namespace llvm {
399 template<>
400 struct GraphTraits<ModuleManager> {
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000401 typedef ModuleFile NodeType;
402 typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType;
Douglas Gregor2492c892011-10-11 19:27:55 +0000403 typedef ModuleManager::ModuleConstIterator nodes_iterator;
404
405 static ChildIteratorType child_begin(NodeType *Node) {
406 return Node->Imports.begin();
407 }
408
409 static ChildIteratorType child_end(NodeType *Node) {
410 return Node->Imports.end();
411 }
412
413 static nodes_iterator nodes_begin(const ModuleManager &Manager) {
414 return Manager.begin();
415 }
416
417 static nodes_iterator nodes_end(const ModuleManager &Manager) {
418 return Manager.end();
419 }
420 };
421
422 template<>
423 struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
424 explicit DOTGraphTraits(bool IsSimple = false)
425 : DefaultDOTGraphTraits(IsSimple) { }
426
427 static bool renderGraphFromBottomUp() {
428 return true;
429 }
430
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000431 std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
Douglas Gregor2492c892011-10-11 19:27:55 +0000432 return llvm::sys::path::stem(M->FileName);
433 }
434 };
435}
436
437void ModuleManager::viewGraph() {
438 llvm::ViewGraph(*this, "Modules");
439}
440#endif