xref: /llvm-project/clang/lib/Serialization/ModuleManager.cpp (revision 466f8843f526b03c8944a46af5ebb374133b5389)
1 //===- ModuleManager.cpp - Module Manager ---------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines the ModuleManager class, which manages a set of loaded
10 //  modules for the ASTReader.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Serialization/ModuleManager.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/LLVM.h"
17 #include "clang/Lex/HeaderSearch.h"
18 #include "clang/Lex/ModuleMap.h"
19 #include "clang/Serialization/GlobalModuleIndex.h"
20 #include "clang/Serialization/InMemoryModuleCache.h"
21 #include "clang/Serialization/ModuleFile.h"
22 #include "clang/Serialization/PCHContainerOperations.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/iterator.h"
29 #include "llvm/Support/Chrono.h"
30 #include "llvm/Support/DOTGraphTraits.h"
31 #include "llvm/Support/ErrorOr.h"
32 #include "llvm/Support/GraphWriter.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/VirtualFileSystem.h"
35 #include <algorithm>
36 #include <cassert>
37 #include <memory>
38 #include <string>
39 #include <system_error>
40 
41 using namespace clang;
42 using namespace serialization;
43 
44 ModuleFile *ModuleManager::lookupByFileName(StringRef Name) const {
45   auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
46                                /*CacheFailure=*/false);
47   if (Entry)
48     return lookup(*Entry);
49 
50   return nullptr;
51 }
52 
53 ModuleFile *ModuleManager::lookupByModuleName(StringRef Name) const {
54   if (const Module *Mod = HeaderSearchInfo.getModuleMap().findModule(Name))
55     if (const FileEntry *File = Mod->getASTFile())
56       return lookup(File);
57 
58   return nullptr;
59 }
60 
61 ModuleFile *ModuleManager::lookup(const FileEntry *File) const {
62   auto Known = Modules.find(File);
63   if (Known == Modules.end())
64     return nullptr;
65 
66   return Known->second;
67 }
68 
69 std::unique_ptr<llvm::MemoryBuffer>
70 ModuleManager::lookupBuffer(StringRef Name) {
71   auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
72                                /*CacheFailure=*/false);
73   if (!Entry)
74     return nullptr;
75   return std::move(InMemoryBuffers[*Entry]);
76 }
77 
78 static bool checkSignature(ASTFileSignature Signature,
79                            ASTFileSignature ExpectedSignature,
80                            std::string &ErrorStr) {
81   if (!ExpectedSignature || Signature == ExpectedSignature)
82     return false;
83 
84   ErrorStr =
85       Signature ? "signature mismatch" : "could not read module signature";
86   return true;
87 }
88 
89 static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy,
90                                 SourceLocation ImportLoc) {
91   if (ImportedBy) {
92     MF.ImportedBy.insert(ImportedBy);
93     ImportedBy->Imports.insert(&MF);
94   } else {
95     if (!MF.DirectlyImported)
96       MF.ImportLoc = ImportLoc;
97 
98     MF.DirectlyImported = true;
99   }
100 }
101 
102 ModuleManager::AddModuleResult
103 ModuleManager::addModule(StringRef FileName, ModuleKind Type,
104                          SourceLocation ImportLoc, ModuleFile *ImportedBy,
105                          unsigned Generation,
106                          off_t ExpectedSize, time_t ExpectedModTime,
107                          ASTFileSignature ExpectedSignature,
108                          ASTFileSignatureReader ReadSignature,
109                          ModuleFile *&Module,
110                          std::string &ErrorStr) {
111   Module = nullptr;
112 
113   // Look for the file entry. This only fails if the expected size or
114   // modification time differ.
115   const FileEntry *Entry;
116   if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {
117     // If we're not expecting to pull this file out of the module cache, it
118     // might have a different mtime due to being moved across filesystems in
119     // a distributed build. The size must still match, though. (As must the
120     // contents, but we can't check that.)
121     ExpectedModTime = 0;
122   }
123   // Note: ExpectedSize and ExpectedModTime will be 0 for MK_ImplicitModule
124   // when using an ASTFileSignature.
125   if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
126     ErrorStr = "module file out of date";
127     return OutOfDate;
128   }
129 
130   if (!Entry && FileName != "-") {
131     ErrorStr = "module file not found";
132     return Missing;
133   }
134 
135   // Check whether we already loaded this module, before
136   if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) {
137     // Check the stored signature.
138     if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr))
139       return OutOfDate;
140 
141     Module = ModuleEntry;
142     updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc);
143     return AlreadyLoaded;
144   }
145 
146   // Allocate a new module.
147   auto NewModule = std::make_unique<ModuleFile>(Type, Generation);
148   NewModule->Index = Chain.size();
149   NewModule->FileName = FileName.str();
150   NewModule->File = Entry;
151   NewModule->ImportLoc = ImportLoc;
152   NewModule->InputFilesValidationTimestamp = 0;
153 
154   if (NewModule->Kind == MK_ImplicitModule) {
155     std::string TimestampFilename = NewModule->getTimestampFilename();
156     llvm::vfs::Status Status;
157     // A cached stat value would be fine as well.
158     if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status))
159       NewModule->InputFilesValidationTimestamp =
160           llvm::sys::toTimeT(Status.getLastModificationTime());
161   }
162 
163   // Load the contents of the module
164   if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) {
165     // The buffer was already provided for us.
166     NewModule->Buffer = &ModuleCache->addFinalPCM(FileName, std::move(Buffer));
167     // Since the cached buffer is reused, it is safe to close the file
168     // descriptor that was opened while stat()ing the PCM in
169     // lookupModuleFile() above, it won't be needed any longer.
170     Entry->closeFile();
171   } else if (llvm::MemoryBuffer *Buffer =
172                  getModuleCache().lookupPCM(FileName)) {
173     NewModule->Buffer = Buffer;
174     // As above, the file descriptor is no longer needed.
175     Entry->closeFile();
176   } else {
177     // Open the AST file.
178     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf((std::error_code()));
179     if (FileName == "-") {
180       Buf = llvm::MemoryBuffer::getSTDIN();
181     } else {
182       // Get a buffer of the file and close the file descriptor when done.
183       // The file is volatile because in a parallel build we expect multiple
184       // compiler processes to use the same module file rebuilding it if needed.
185       Buf = FileMgr.getBufferForFile(NewModule->File, /*isVolatile=*/true);
186     }
187 
188     if (!Buf) {
189       ErrorStr = Buf.getError().message();
190       return Missing;
191     }
192 
193     NewModule->Buffer = &getModuleCache().addPCM(FileName, std::move(*Buf));
194   }
195 
196   // Initialize the stream.
197   NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);
198 
199   // Read the signature eagerly now so that we can check it.  Avoid calling
200   // ReadSignature unless there's something to check though.
201   if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),
202                                           ExpectedSignature, ErrorStr))
203     return OutOfDate;
204 
205   // We're keeping this module.  Store it everywhere.
206   Module = Modules[Entry] = NewModule.get();
207 
208   updateModuleImports(*NewModule, ImportedBy, ImportLoc);
209 
210   if (!NewModule->isModule())
211     PCHChain.push_back(NewModule.get());
212   if (!ImportedBy)
213     Roots.push_back(NewModule.get());
214 
215   Chain.push_back(std::move(NewModule));
216   return NewlyLoaded;
217 }
218 
219 void ModuleManager::removeModules(ModuleIterator First, ModuleMap *modMap) {
220   auto Last = end();
221   if (First == Last)
222     return;
223 
224   // Explicitly clear VisitOrder since we might not notice it is stale.
225   VisitOrder.clear();
226 
227   // Collect the set of module file pointers that we'll be removing.
228   llvm::SmallPtrSet<ModuleFile *, 4> victimSet(
229       (llvm::pointer_iterator<ModuleIterator>(First)),
230       (llvm::pointer_iterator<ModuleIterator>(Last)));
231 
232   auto IsVictim = [&](ModuleFile *MF) {
233     return victimSet.count(MF);
234   };
235   // Remove any references to the now-destroyed modules.
236   for (auto I = begin(); I != First; ++I) {
237     I->Imports.remove_if(IsVictim);
238     I->ImportedBy.remove_if(IsVictim);
239   }
240   Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim),
241               Roots.end());
242 
243   // Remove the modules from the PCH chain.
244   for (auto I = First; I != Last; ++I) {
245     if (!I->isModule()) {
246       PCHChain.erase(llvm::find(PCHChain, &*I), PCHChain.end());
247       break;
248     }
249   }
250 
251   // Delete the modules and erase them from the various structures.
252   for (ModuleIterator victim = First; victim != Last; ++victim) {
253     Modules.erase(victim->File);
254 
255     if (modMap) {
256       StringRef ModuleName = victim->ModuleName;
257       if (Module *mod = modMap->findModule(ModuleName)) {
258         mod->setASTFile(nullptr);
259       }
260     }
261   }
262 
263   // Delete the modules.
264   Chain.erase(Chain.begin() + (First - begin()), Chain.end());
265 }
266 
267 void
268 ModuleManager::addInMemoryBuffer(StringRef FileName,
269                                  std::unique_ptr<llvm::MemoryBuffer> Buffer) {
270   const FileEntry *Entry =
271       FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0);
272   InMemoryBuffers[Entry] = std::move(Buffer);
273 }
274 
275 ModuleManager::VisitState *ModuleManager::allocateVisitState() {
276   // Fast path: if we have a cached state, use it.
277   if (FirstVisitState) {
278     VisitState *Result = FirstVisitState;
279     FirstVisitState = FirstVisitState->NextState;
280     Result->NextState = nullptr;
281     return Result;
282   }
283 
284   // Allocate and return a new state.
285   return new VisitState(size());
286 }
287 
288 void ModuleManager::returnVisitState(VisitState *State) {
289   assert(State->NextState == nullptr && "Visited state is in list?");
290   State->NextState = FirstVisitState;
291   FirstVisitState = State;
292 }
293 
294 void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) {
295   GlobalIndex = Index;
296   if (!GlobalIndex) {
297     ModulesInCommonWithGlobalIndex.clear();
298     return;
299   }
300 
301   // Notify the global module index about all of the modules we've already
302   // loaded.
303   for (ModuleFile &M : *this)
304     if (!GlobalIndex->loadedModuleFile(&M))
305       ModulesInCommonWithGlobalIndex.push_back(&M);
306 }
307 
308 void ModuleManager::moduleFileAccepted(ModuleFile *MF) {
309   if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
310     return;
311 
312   ModulesInCommonWithGlobalIndex.push_back(MF);
313 }
314 
315 ModuleManager::ModuleManager(FileManager &FileMgr,
316                              InMemoryModuleCache &ModuleCache,
317                              const PCHContainerReader &PCHContainerRdr,
318                              const HeaderSearch &HeaderSearchInfo)
319     : FileMgr(FileMgr), ModuleCache(&ModuleCache),
320       PCHContainerRdr(PCHContainerRdr), HeaderSearchInfo(HeaderSearchInfo) {}
321 
322 ModuleManager::~ModuleManager() { delete FirstVisitState; }
323 
324 void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor,
325                           llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
326   // If the visitation order vector is the wrong size, recompute the order.
327   if (VisitOrder.size() != Chain.size()) {
328     unsigned N = size();
329     VisitOrder.clear();
330     VisitOrder.reserve(N);
331 
332     // Record the number of incoming edges for each module. When we
333     // encounter a module with no incoming edges, push it into the queue
334     // to seed the queue.
335     SmallVector<ModuleFile *, 4> Queue;
336     Queue.reserve(N);
337     llvm::SmallVector<unsigned, 4> UnusedIncomingEdges;
338     UnusedIncomingEdges.resize(size());
339     for (ModuleFile &M : llvm::reverse(*this)) {
340       unsigned Size = M.ImportedBy.size();
341       UnusedIncomingEdges[M.Index] = Size;
342       if (!Size)
343         Queue.push_back(&M);
344     }
345 
346     // Traverse the graph, making sure to visit a module before visiting any
347     // of its dependencies.
348     while (!Queue.empty()) {
349       ModuleFile *CurrentModule = Queue.pop_back_val();
350       VisitOrder.push_back(CurrentModule);
351 
352       // For any module that this module depends on, push it on the
353       // stack (if it hasn't already been marked as visited).
354       for (auto M = CurrentModule->Imports.rbegin(),
355                 MEnd = CurrentModule->Imports.rend();
356            M != MEnd; ++M) {
357         // Remove our current module as an impediment to visiting the
358         // module we depend on. If we were the last unvisited module
359         // that depends on this particular module, push it into the
360         // queue to be visited.
361         unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index];
362         if (NumUnusedEdges && (--NumUnusedEdges == 0))
363           Queue.push_back(*M);
364       }
365     }
366 
367     assert(VisitOrder.size() == N && "Visitation order is wrong?");
368 
369     delete FirstVisitState;
370     FirstVisitState = nullptr;
371   }
372 
373   VisitState *State = allocateVisitState();
374   unsigned VisitNumber = State->NextVisitNumber++;
375 
376   // If the caller has provided us with a hit-set that came from the global
377   // module index, mark every module file in common with the global module
378   // index that is *not* in that set as 'visited'.
379   if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
380     for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
381     {
382       ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
383       if (!ModuleFilesHit->count(M))
384         State->VisitNumber[M->Index] = VisitNumber;
385     }
386   }
387 
388   for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
389     ModuleFile *CurrentModule = VisitOrder[I];
390     // Should we skip this module file?
391     if (State->VisitNumber[CurrentModule->Index] == VisitNumber)
392       continue;
393 
394     // Visit the module.
395     assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1);
396     State->VisitNumber[CurrentModule->Index] = VisitNumber;
397     if (!Visitor(*CurrentModule))
398       continue;
399 
400     // The visitor has requested that cut off visitation of any
401     // module that the current module depends on. To indicate this
402     // behavior, we mark all of the reachable modules as having been visited.
403     ModuleFile *NextModule = CurrentModule;
404     do {
405       // For any module that this module depends on, push it on the
406       // stack (if it hasn't already been marked as visited).
407       for (llvm::SetVector<ModuleFile *>::iterator
408              M = NextModule->Imports.begin(),
409              MEnd = NextModule->Imports.end();
410            M != MEnd; ++M) {
411         if (State->VisitNumber[(*M)->Index] != VisitNumber) {
412           State->Stack.push_back(*M);
413           State->VisitNumber[(*M)->Index] = VisitNumber;
414         }
415       }
416 
417       if (State->Stack.empty())
418         break;
419 
420       // Pop the next module off the stack.
421       NextModule = State->Stack.pop_back_val();
422     } while (true);
423   }
424 
425   returnVisitState(State);
426 }
427 
428 bool ModuleManager::lookupModuleFile(StringRef FileName,
429                                      off_t ExpectedSize,
430                                      time_t ExpectedModTime,
431                                      const FileEntry *&File) {
432   if (FileName == "-") {
433     File = nullptr;
434     return false;
435   }
436 
437   // Open the file immediately to ensure there is no race between stat'ing and
438   // opening the file.
439   auto FileOrErr = FileMgr.getFile(FileName, /*OpenFile=*/true,
440                                    /*CacheFailure=*/false);
441   if (!FileOrErr) {
442     File = nullptr;
443     return false;
444   }
445   File = *FileOrErr;
446 
447   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
448       (ExpectedModTime && ExpectedModTime != File->getModificationTime()))
449     // Do not destroy File, as it may be referenced. If we need to rebuild it,
450     // it will be destroyed by removeModules.
451     return true;
452 
453   return false;
454 }
455 
456 #ifndef NDEBUG
457 namespace llvm {
458 
459   template<>
460   struct GraphTraits<ModuleManager> {
461     using NodeRef = ModuleFile *;
462     using ChildIteratorType = llvm::SetVector<ModuleFile *>::const_iterator;
463     using nodes_iterator = pointer_iterator<ModuleManager::ModuleConstIterator>;
464 
465     static ChildIteratorType child_begin(NodeRef Node) {
466       return Node->Imports.begin();
467     }
468 
469     static ChildIteratorType child_end(NodeRef Node) {
470       return Node->Imports.end();
471     }
472 
473     static nodes_iterator nodes_begin(const ModuleManager &Manager) {
474       return nodes_iterator(Manager.begin());
475     }
476 
477     static nodes_iterator nodes_end(const ModuleManager &Manager) {
478       return nodes_iterator(Manager.end());
479     }
480   };
481 
482   template<>
483   struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits {
484     explicit DOTGraphTraits(bool IsSimple = false)
485         : DefaultDOTGraphTraits(IsSimple) {}
486 
487     static bool renderGraphFromBottomUp() { return true; }
488 
489     std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
490       return M->ModuleName;
491     }
492   };
493 
494 } // namespace llvm
495 
496 void ModuleManager::viewGraph() {
497   llvm::ViewGraph(*this, "Modules");
498 }
499 #endif
500