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