1 //===--- 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 //===----------------------------------------------------------------------===// 14 #include "clang/Lex/HeaderSearch.h" 15 #include "clang/Lex/ModuleMap.h" 16 #include "clang/Serialization/GlobalModuleIndex.h" 17 #include "clang/Serialization/ModuleManager.h" 18 #include "llvm/Support/MemoryBuffer.h" 19 #include "llvm/Support/Path.h" 20 #include "llvm/Support/raw_ostream.h" 21 #include <system_error> 22 23 #ifndef NDEBUG 24 #include "llvm/Support/GraphWriter.h" 25 #endif 26 27 using namespace clang; 28 using namespace serialization; 29 30 ModuleFile *ModuleManager::lookup(StringRef Name) { 31 const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false, 32 /*cacheFailure=*/false); 33 if (Entry) 34 return lookup(Entry); 35 36 return nullptr; 37 } 38 39 ModuleFile *ModuleManager::lookup(const FileEntry *File) { 40 llvm::DenseMap<const FileEntry *, ModuleFile *>::iterator Known 41 = Modules.find(File); 42 if (Known == Modules.end()) 43 return nullptr; 44 45 return Known->second; 46 } 47 48 std::unique_ptr<llvm::MemoryBuffer> 49 ModuleManager::lookupBuffer(StringRef Name) { 50 const FileEntry *Entry = FileMgr.getFile(Name, /*openFile=*/false, 51 /*cacheFailure=*/false); 52 return std::move(InMemoryBuffers[Entry]); 53 } 54 55 ModuleManager::AddModuleResult 56 ModuleManager::addModule(StringRef FileName, ModuleKind Type, 57 SourceLocation ImportLoc, ModuleFile *ImportedBy, 58 unsigned Generation, 59 off_t ExpectedSize, time_t ExpectedModTime, 60 ASTFileSignature ExpectedSignature, 61 std::function<ASTFileSignature(llvm::BitstreamReader &)> 62 ReadSignature, 63 ModuleFile *&Module, 64 std::string &ErrorStr) { 65 Module = nullptr; 66 67 // Look for the file entry. This only fails if the expected size or 68 // modification time differ. 69 const FileEntry *Entry; 70 if (Type == MK_ExplicitModule) { 71 // If we're not expecting to pull this file out of the module cache, it 72 // might have a different mtime due to being moved across filesystems in 73 // a distributed build. The size must still match, though. (As must the 74 // contents, but we can't check that.) 75 ExpectedModTime = 0; 76 } 77 if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) { 78 ErrorStr = "module file out of date"; 79 return OutOfDate; 80 } 81 82 if (!Entry && FileName != "-") { 83 ErrorStr = "module file not found"; 84 return Missing; 85 } 86 87 // Check whether we already loaded this module, before 88 ModuleFile *&ModuleEntry = Modules[Entry]; 89 bool NewModule = false; 90 if (!ModuleEntry) { 91 // Allocate a new module. 92 ModuleFile *New = new ModuleFile(Type, Generation); 93 New->Index = Chain.size(); 94 New->FileName = FileName.str(); 95 New->File = Entry; 96 New->ImportLoc = ImportLoc; 97 Chain.push_back(New); 98 NewModule = true; 99 ModuleEntry = New; 100 101 New->InputFilesValidationTimestamp = 0; 102 if (New->Kind == MK_ImplicitModule) { 103 std::string TimestampFilename = New->getTimestampFilename(); 104 vfs::Status Status; 105 // A cached stat value would be fine as well. 106 if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status)) 107 New->InputFilesValidationTimestamp = 108 Status.getLastModificationTime().toEpochTime(); 109 } 110 111 // Load the contents of the module 112 if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) { 113 // The buffer was already provided for us. 114 New->Buffer = std::move(Buffer); 115 } else { 116 // Open the AST file. 117 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf( 118 (std::error_code())); 119 if (FileName == "-") { 120 Buf = llvm::MemoryBuffer::getSTDIN(); 121 } else { 122 // Leave the FileEntry open so if it gets read again by another 123 // ModuleManager it must be the same underlying file. 124 // FIXME: Because FileManager::getFile() doesn't guarantee that it will 125 // give us an open file, this may not be 100% reliable. 126 Buf = FileMgr.getBufferForFile(New->File, 127 /*IsVolatile=*/false, 128 /*ShouldClose=*/false); 129 } 130 131 if (!Buf) { 132 ErrorStr = Buf.getError().message(); 133 return Missing; 134 } 135 136 New->Buffer = std::move(*Buf); 137 } 138 139 // Initialize the stream 140 New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(), 141 (const unsigned char *)New->Buffer->getBufferEnd()); 142 } 143 144 if (ExpectedSignature) { 145 if (NewModule) 146 ModuleEntry->Signature = ReadSignature(ModuleEntry->StreamFile); 147 else 148 assert(ModuleEntry->Signature == ReadSignature(ModuleEntry->StreamFile)); 149 150 if (ModuleEntry->Signature != ExpectedSignature) { 151 ErrorStr = ModuleEntry->Signature ? "signature mismatch" 152 : "could not read module signature"; 153 154 if (NewModule) { 155 // Remove the module file immediately, since removeModules might try to 156 // invalidate the file cache for Entry, and that is not safe if this 157 // module is *itself* up to date, but has an out-of-date importer. 158 Modules.erase(Entry); 159 Chain.pop_back(); 160 delete ModuleEntry; 161 } 162 return OutOfDate; 163 } 164 } 165 166 if (ImportedBy) { 167 ModuleEntry->ImportedBy.insert(ImportedBy); 168 ImportedBy->Imports.insert(ModuleEntry); 169 } else { 170 if (!ModuleEntry->DirectlyImported) 171 ModuleEntry->ImportLoc = ImportLoc; 172 173 ModuleEntry->DirectlyImported = true; 174 } 175 176 Module = ModuleEntry; 177 return NewModule? NewlyLoaded : AlreadyLoaded; 178 } 179 180 void ModuleManager::removeModules( 181 ModuleIterator first, ModuleIterator last, 182 llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully, 183 ModuleMap *modMap) { 184 if (first == last) 185 return; 186 187 // Collect the set of module file pointers that we'll be removing. 188 llvm::SmallPtrSet<ModuleFile *, 4> victimSet(first, last); 189 190 // Remove any references to the now-destroyed modules. 191 for (unsigned i = 0, n = Chain.size(); i != n; ++i) { 192 Chain[i]->ImportedBy.remove_if([&](ModuleFile *MF) { 193 return victimSet.count(MF); 194 }); 195 } 196 197 // Delete the modules and erase them from the various structures. 198 for (ModuleIterator victim = first; victim != last; ++victim) { 199 Modules.erase((*victim)->File); 200 201 if (modMap) { 202 StringRef ModuleName = (*victim)->ModuleName; 203 if (Module *mod = modMap->findModule(ModuleName)) { 204 mod->setASTFile(nullptr); 205 } 206 } 207 208 // Files that didn't make it through ReadASTCore successfully will be 209 // rebuilt (or there was an error). Invalidate them so that we can load the 210 // new files that will be renamed over the old ones. 211 if (LoadedSuccessfully.count(*victim) == 0) 212 FileMgr.invalidateCache((*victim)->File); 213 214 delete *victim; 215 } 216 217 // Remove the modules from the chain. 218 Chain.erase(first, last); 219 } 220 221 void 222 ModuleManager::addInMemoryBuffer(StringRef FileName, 223 std::unique_ptr<llvm::MemoryBuffer> Buffer) { 224 225 const FileEntry *Entry = 226 FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0); 227 InMemoryBuffers[Entry] = std::move(Buffer); 228 } 229 230 bool ModuleManager::addKnownModuleFile(StringRef FileName) { 231 const FileEntry *File; 232 if (lookupModuleFile(FileName, 0, 0, File)) 233 return true; 234 if (!Modules.count(File)) 235 AdditionalKnownModuleFiles.insert(File); 236 return false; 237 } 238 239 ModuleManager::VisitState *ModuleManager::allocateVisitState() { 240 // Fast path: if we have a cached state, use it. 241 if (FirstVisitState) { 242 VisitState *Result = FirstVisitState; 243 FirstVisitState = FirstVisitState->NextState; 244 Result->NextState = nullptr; 245 return Result; 246 } 247 248 // Allocate and return a new state. 249 return new VisitState(size()); 250 } 251 252 void ModuleManager::returnVisitState(VisitState *State) { 253 assert(State->NextState == nullptr && "Visited state is in list?"); 254 State->NextState = FirstVisitState; 255 FirstVisitState = State; 256 } 257 258 void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) { 259 GlobalIndex = Index; 260 if (!GlobalIndex) { 261 ModulesInCommonWithGlobalIndex.clear(); 262 return; 263 } 264 265 // Notify the global module index about all of the modules we've already 266 // loaded. 267 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 268 if (!GlobalIndex->loadedModuleFile(Chain[I])) { 269 ModulesInCommonWithGlobalIndex.push_back(Chain[I]); 270 } 271 } 272 } 273 274 void ModuleManager::moduleFileAccepted(ModuleFile *MF) { 275 AdditionalKnownModuleFiles.remove(MF->File); 276 277 if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF)) 278 return; 279 280 ModulesInCommonWithGlobalIndex.push_back(MF); 281 } 282 283 ModuleManager::ModuleManager(FileManager &FileMgr) 284 : FileMgr(FileMgr), GlobalIndex(), FirstVisitState(nullptr) {} 285 286 ModuleManager::~ModuleManager() { 287 for (unsigned i = 0, e = Chain.size(); i != e; ++i) 288 delete Chain[e - i - 1]; 289 delete FirstVisitState; 290 } 291 292 void 293 ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData), 294 void *UserData, 295 llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) { 296 // If the visitation order vector is the wrong size, recompute the order. 297 if (VisitOrder.size() != Chain.size()) { 298 unsigned N = size(); 299 VisitOrder.clear(); 300 VisitOrder.reserve(N); 301 302 // Record the number of incoming edges for each module. When we 303 // encounter a module with no incoming edges, push it into the queue 304 // to seed the queue. 305 SmallVector<ModuleFile *, 4> Queue; 306 Queue.reserve(N); 307 llvm::SmallVector<unsigned, 4> UnusedIncomingEdges; 308 UnusedIncomingEdges.reserve(size()); 309 for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) { 310 if (unsigned Size = (*M)->ImportedBy.size()) 311 UnusedIncomingEdges.push_back(Size); 312 else { 313 UnusedIncomingEdges.push_back(0); 314 Queue.push_back(*M); 315 } 316 } 317 318 // Traverse the graph, making sure to visit a module before visiting any 319 // of its dependencies. 320 unsigned QueueStart = 0; 321 while (QueueStart < Queue.size()) { 322 ModuleFile *CurrentModule = Queue[QueueStart++]; 323 VisitOrder.push_back(CurrentModule); 324 325 // For any module that this module depends on, push it on the 326 // stack (if it hasn't already been marked as visited). 327 for (llvm::SetVector<ModuleFile *>::iterator 328 M = CurrentModule->Imports.begin(), 329 MEnd = CurrentModule->Imports.end(); 330 M != MEnd; ++M) { 331 // Remove our current module as an impediment to visiting the 332 // module we depend on. If we were the last unvisited module 333 // that depends on this particular module, push it into the 334 // queue to be visited. 335 unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index]; 336 if (NumUnusedEdges && (--NumUnusedEdges == 0)) 337 Queue.push_back(*M); 338 } 339 } 340 341 assert(VisitOrder.size() == N && "Visitation order is wrong?"); 342 343 delete FirstVisitState; 344 FirstVisitState = nullptr; 345 } 346 347 VisitState *State = allocateVisitState(); 348 unsigned VisitNumber = State->NextVisitNumber++; 349 350 // If the caller has provided us with a hit-set that came from the global 351 // module index, mark every module file in common with the global module 352 // index that is *not* in that set as 'visited'. 353 if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) { 354 for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I) 355 { 356 ModuleFile *M = ModulesInCommonWithGlobalIndex[I]; 357 if (!ModuleFilesHit->count(M)) 358 State->VisitNumber[M->Index] = VisitNumber; 359 } 360 } 361 362 for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) { 363 ModuleFile *CurrentModule = VisitOrder[I]; 364 // Should we skip this module file? 365 if (State->VisitNumber[CurrentModule->Index] == VisitNumber) 366 continue; 367 368 // Visit the module. 369 assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1); 370 State->VisitNumber[CurrentModule->Index] = VisitNumber; 371 if (!Visitor(*CurrentModule, UserData)) 372 continue; 373 374 // The visitor has requested that cut off visitation of any 375 // module that the current module depends on. To indicate this 376 // behavior, we mark all of the reachable modules as having been visited. 377 ModuleFile *NextModule = CurrentModule; 378 do { 379 // For any module that this module depends on, push it on the 380 // stack (if it hasn't already been marked as visited). 381 for (llvm::SetVector<ModuleFile *>::iterator 382 M = NextModule->Imports.begin(), 383 MEnd = NextModule->Imports.end(); 384 M != MEnd; ++M) { 385 if (State->VisitNumber[(*M)->Index] != VisitNumber) { 386 State->Stack.push_back(*M); 387 State->VisitNumber[(*M)->Index] = VisitNumber; 388 } 389 } 390 391 if (State->Stack.empty()) 392 break; 393 394 // Pop the next module off the stack. 395 NextModule = State->Stack.pop_back_val(); 396 } while (true); 397 } 398 399 returnVisitState(State); 400 } 401 402 /// \brief Perform a depth-first visit of the current module. 403 static bool visitDepthFirst(ModuleFile &M, 404 bool (*Visitor)(ModuleFile &M, bool Preorder, 405 void *UserData), 406 void *UserData, 407 SmallVectorImpl<bool> &Visited) { 408 // Preorder visitation 409 if (Visitor(M, /*Preorder=*/true, UserData)) 410 return true; 411 412 // Visit children 413 for (llvm::SetVector<ModuleFile *>::iterator IM = M.Imports.begin(), 414 IMEnd = M.Imports.end(); 415 IM != IMEnd; ++IM) { 416 if (Visited[(*IM)->Index]) 417 continue; 418 Visited[(*IM)->Index] = true; 419 420 if (visitDepthFirst(**IM, Visitor, UserData, Visited)) 421 return true; 422 } 423 424 // Postorder visitation 425 return Visitor(M, /*Preorder=*/false, UserData); 426 } 427 428 void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder, 429 void *UserData), 430 void *UserData) { 431 SmallVector<bool, 16> Visited(size(), false); 432 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 433 if (Visited[Chain[I]->Index]) 434 continue; 435 Visited[Chain[I]->Index] = true; 436 437 if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited)) 438 return; 439 } 440 } 441 442 bool ModuleManager::lookupModuleFile(StringRef FileName, 443 off_t ExpectedSize, 444 time_t ExpectedModTime, 445 const FileEntry *&File) { 446 // Open the file immediately to ensure there is no race between stat'ing and 447 // opening the file. 448 File = FileMgr.getFile(FileName, /*openFile=*/true, /*cacheFailure=*/false); 449 450 if (!File && FileName != "-") { 451 return false; 452 } 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 template<> 466 struct GraphTraits<ModuleManager> { 467 typedef ModuleFile NodeType; 468 typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorType; 469 typedef ModuleManager::ModuleConstIterator nodes_iterator; 470 471 static ChildIteratorType child_begin(NodeType *Node) { 472 return Node->Imports.begin(); 473 } 474 475 static ChildIteratorType child_end(NodeType *Node) { 476 return Node->Imports.end(); 477 } 478 479 static nodes_iterator nodes_begin(const ModuleManager &Manager) { 480 return Manager.begin(); 481 } 482 483 static nodes_iterator nodes_end(const ModuleManager &Manager) { 484 return Manager.end(); 485 } 486 }; 487 488 template<> 489 struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits { 490 explicit DOTGraphTraits(bool IsSimple = false) 491 : DefaultDOTGraphTraits(IsSimple) { } 492 493 static bool renderGraphFromBottomUp() { 494 return true; 495 } 496 497 std::string getNodeLabel(ModuleFile *M, const ModuleManager&) { 498 return M->ModuleName; 499 } 500 }; 501 } 502 503 void ModuleManager::viewGraph() { 504 llvm::ViewGraph(*this, "Modules"); 505 } 506 #endif 507