1b7d89107SEugene Zelenko //===- ModuleManager.cpp - Module Manager ---------------------------------===// 2d44252ecSDouglas Gregor // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6d44252ecSDouglas Gregor // 7d44252ecSDouglas Gregor //===----------------------------------------------------------------------===// 8d44252ecSDouglas Gregor // 9d44252ecSDouglas Gregor // This file defines the ModuleManager class, which manages a set of loaded 10d44252ecSDouglas Gregor // modules for the ASTReader. 11d44252ecSDouglas Gregor // 12d44252ecSDouglas Gregor //===----------------------------------------------------------------------===// 13b7d89107SEugene Zelenko 149670f847SMehdi Amini #include "clang/Serialization/ModuleManager.h" 15b7d89107SEugene Zelenko #include "clang/Basic/FileManager.h" 16b7d89107SEugene Zelenko #include "clang/Basic/LLVM.h" 17beee15e7SBen Langmuir #include "clang/Lex/HeaderSearch.h" 187029ce1aSDouglas Gregor #include "clang/Lex/ModuleMap.h" 197211ac15SDouglas Gregor #include "clang/Serialization/GlobalModuleIndex.h" 208bef5cd4SDuncan P. N. Exon Smith #include "clang/Serialization/InMemoryModuleCache.h" 21b7d89107SEugene Zelenko #include "clang/Serialization/Module.h" 22f3b0046bSRichard Trieu #include "clang/Serialization/PCHContainerOperations.h" 23b7d89107SEugene Zelenko #include "llvm/ADT/STLExtras.h" 24b7d89107SEugene Zelenko #include "llvm/ADT/SetVector.h" 25b7d89107SEugene Zelenko #include "llvm/ADT/SmallPtrSet.h" 26b7d89107SEugene Zelenko #include "llvm/ADT/SmallVector.h" 27b7d89107SEugene Zelenko #include "llvm/ADT/StringRef.h" 28b7d89107SEugene Zelenko #include "llvm/ADT/iterator.h" 29b7d89107SEugene Zelenko #include "llvm/Support/Chrono.h" 30b7d89107SEugene Zelenko #include "llvm/Support/DOTGraphTraits.h" 31b7d89107SEugene Zelenko #include "llvm/Support/ErrorOr.h" 329d7c1a2aSDouglas Gregor #include "llvm/Support/GraphWriter.h" 33b7d89107SEugene Zelenko #include "llvm/Support/MemoryBuffer.h" 34fc51490bSJonas Devlieghere #include "llvm/Support/VirtualFileSystem.h" 35b7d89107SEugene Zelenko #include <algorithm> 36b7d89107SEugene Zelenko #include <cassert> 37b7d89107SEugene Zelenko #include <memory> 38b7d89107SEugene Zelenko #include <string> 39b7d89107SEugene Zelenko #include <system_error> 409d7c1a2aSDouglas Gregor 41d44252ecSDouglas Gregor using namespace clang; 42d44252ecSDouglas Gregor using namespace serialization; 43d44252ecSDouglas Gregor 44d30446fdSBoris Kolpackov ModuleFile *ModuleManager::lookupByFileName(StringRef Name) const { 458d323d15SHarlan Haskins auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false, 4649a3ad21SRui Ueyama /*CacheFailure=*/false); 47bf7fc9c5SDouglas Gregor if (Entry) 488d323d15SHarlan Haskins return lookup(*Entry); 49bf7fc9c5SDouglas Gregor 50a13603a2SCraig Topper return nullptr; 51bf7fc9c5SDouglas Gregor } 52bf7fc9c5SDouglas Gregor 53d30446fdSBoris Kolpackov ModuleFile *ModuleManager::lookupByModuleName(StringRef Name) const { 54d30446fdSBoris Kolpackov if (const Module *Mod = HeaderSearchInfo.getModuleMap().findModule(Name)) 55d30446fdSBoris Kolpackov if (const FileEntry *File = Mod->getASTFile()) 56d30446fdSBoris Kolpackov return lookup(File); 57d30446fdSBoris Kolpackov 58d30446fdSBoris Kolpackov return nullptr; 59d30446fdSBoris Kolpackov } 60d30446fdSBoris Kolpackov 6137a93df3SRichard Smith ModuleFile *ModuleManager::lookup(const FileEntry *File) const { 6237a93df3SRichard Smith auto Known = Modules.find(File); 63bf7fc9c5SDouglas Gregor if (Known == Modules.end()) 64a13603a2SCraig Topper return nullptr; 65bf7fc9c5SDouglas Gregor 66bf7fc9c5SDouglas Gregor return Known->second; 67d44252ecSDouglas Gregor } 68d44252ecSDouglas Gregor 695cd06f26SRafael Espindola std::unique_ptr<llvm::MemoryBuffer> 705cd06f26SRafael Espindola ModuleManager::lookupBuffer(StringRef Name) { 718d323d15SHarlan Haskins auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false, 7249a3ad21SRui Ueyama /*CacheFailure=*/false); 738d323d15SHarlan Haskins if (!Entry) 748d323d15SHarlan Haskins return nullptr; 758d323d15SHarlan Haskins return std::move(InMemoryBuffers[*Entry]); 76d44252ecSDouglas Gregor } 77d44252ecSDouglas Gregor 7814afc8e7SDuncan P. N. Exon Smith static bool checkSignature(ASTFileSignature Signature, 7914afc8e7SDuncan P. N. Exon Smith ASTFileSignature ExpectedSignature, 8014afc8e7SDuncan P. N. Exon Smith std::string &ErrorStr) { 8114afc8e7SDuncan P. N. Exon Smith if (!ExpectedSignature || Signature == ExpectedSignature) 8214afc8e7SDuncan P. N. Exon Smith return false; 8314afc8e7SDuncan P. N. Exon Smith 8414afc8e7SDuncan P. N. Exon Smith ErrorStr = 8514afc8e7SDuncan P. N. Exon Smith Signature ? "signature mismatch" : "could not read module signature"; 8614afc8e7SDuncan P. N. Exon Smith return true; 8714afc8e7SDuncan P. N. Exon Smith } 8814afc8e7SDuncan P. N. Exon Smith 8926308a68SDuncan P. N. Exon Smith static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy, 9026308a68SDuncan P. N. Exon Smith SourceLocation ImportLoc) { 9126308a68SDuncan P. N. Exon Smith if (ImportedBy) { 9226308a68SDuncan P. N. Exon Smith MF.ImportedBy.insert(ImportedBy); 9326308a68SDuncan P. N. Exon Smith ImportedBy->Imports.insert(&MF); 9426308a68SDuncan P. N. Exon Smith } else { 9526308a68SDuncan P. N. Exon Smith if (!MF.DirectlyImported) 9626308a68SDuncan P. N. Exon Smith MF.ImportLoc = ImportLoc; 9726308a68SDuncan P. N. Exon Smith 9826308a68SDuncan P. N. Exon Smith MF.DirectlyImported = true; 9926308a68SDuncan P. N. Exon Smith } 10026308a68SDuncan P. N. Exon Smith } 10126308a68SDuncan P. N. Exon Smith 1027029ce1aSDouglas Gregor ModuleManager::AddModuleResult 103d44252ecSDouglas Gregor ModuleManager::addModule(StringRef FileName, ModuleKind Type, 1046fb03aeaSDouglas Gregor SourceLocation ImportLoc, ModuleFile *ImportedBy, 1057029ce1aSDouglas Gregor unsigned Generation, 1067029ce1aSDouglas Gregor off_t ExpectedSize, time_t ExpectedModTime, 107487ea14aSBen Langmuir ASTFileSignature ExpectedSignature, 10870a1b816SBen Langmuir ASTFileSignatureReader ReadSignature, 1097029ce1aSDouglas Gregor ModuleFile *&Module, 1107029ce1aSDouglas Gregor std::string &ErrorStr) { 111a13603a2SCraig Topper Module = nullptr; 1127029ce1aSDouglas Gregor 1137029ce1aSDouglas Gregor // Look for the file entry. This only fails if the expected size or 1147029ce1aSDouglas Gregor // modification time differ. 1157029ce1aSDouglas Gregor const FileEntry *Entry; 11611f2a477SManman Ren if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) { 1175b390756SRichard Smith // If we're not expecting to pull this file out of the module cache, it 1185b390756SRichard Smith // might have a different mtime due to being moved across filesystems in 1195b390756SRichard Smith // a distributed build. The size must still match, though. (As must the 1205b390756SRichard Smith // contents, but we can't check that.) 1215b390756SRichard Smith ExpectedModTime = 0; 1225b390756SRichard Smith } 1230a2be46cSDuncan P. N. Exon Smith // Note: ExpectedSize and ExpectedModTime will be 0 for MK_ImplicitModule 1240a2be46cSDuncan P. N. Exon Smith // when using an ASTFileSignature. 125c27d0d5eSEli Friedman if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) { 126c27d0d5eSEli Friedman ErrorStr = "module file out of date"; 1277029ce1aSDouglas Gregor return OutOfDate; 128c27d0d5eSEli Friedman } 1297029ce1aSDouglas Gregor 130d44252ecSDouglas Gregor if (!Entry && FileName != "-") { 131c27d0d5eSEli Friedman ErrorStr = "module file not found"; 1327029ce1aSDouglas Gregor return Missing; 133d44252ecSDouglas Gregor } 134d44252ecSDouglas Gregor 135d44252ecSDouglas Gregor // Check whether we already loaded this module, before 13626308a68SDuncan P. N. Exon Smith if (ModuleFile *ModuleEntry = Modules.lookup(Entry)) { 13726308a68SDuncan P. N. Exon Smith // Check the stored signature. 13826308a68SDuncan P. N. Exon Smith if (checkSignature(ModuleEntry->Signature, ExpectedSignature, ErrorStr)) 13926308a68SDuncan P. N. Exon Smith return OutOfDate; 14026308a68SDuncan P. N. Exon Smith 14126308a68SDuncan P. N. Exon Smith Module = ModuleEntry; 14226308a68SDuncan P. N. Exon Smith updateModuleImports(*ModuleEntry, ImportedBy, ImportLoc); 14326308a68SDuncan P. N. Exon Smith return AlreadyLoaded; 14426308a68SDuncan P. N. Exon Smith } 14526308a68SDuncan P. N. Exon Smith 146d44252ecSDouglas Gregor // Allocate a new module. 1472b3d49b6SJonas Devlieghere auto NewModule = std::make_unique<ModuleFile>(Type, Generation); 148a897f7cdSDuncan P. N. Exon Smith NewModule->Index = Chain.size(); 149a897f7cdSDuncan P. N. Exon Smith NewModule->FileName = FileName.str(); 150a897f7cdSDuncan P. N. Exon Smith NewModule->File = Entry; 151a897f7cdSDuncan P. N. Exon Smith NewModule->ImportLoc = ImportLoc; 152a897f7cdSDuncan P. N. Exon Smith NewModule->InputFilesValidationTimestamp = 0; 153d44252ecSDouglas Gregor 154a897f7cdSDuncan P. N. Exon Smith if (NewModule->Kind == MK_ImplicitModule) { 155a897f7cdSDuncan P. N. Exon Smith std::string TimestampFilename = NewModule->getTimestampFilename(); 156fc51490bSJonas Devlieghere llvm::vfs::Status Status; 157f430da4dSDmitri Gribenko // A cached stat value would be fine as well. 158f430da4dSDmitri Gribenko if (!FileMgr.getNoncachedStatValue(TimestampFilename, Status)) 159a897f7cdSDuncan P. N. Exon Smith NewModule->InputFilesValidationTimestamp = 160ac71c8e2SPavel Labath llvm::sys::toTimeT(Status.getLastModificationTime()); 161f430da4dSDmitri Gribenko } 162f430da4dSDmitri Gribenko 163d44252ecSDouglas Gregor // Load the contents of the module 1645cd06f26SRafael Espindola if (std::unique_ptr<llvm::MemoryBuffer> Buffer = lookupBuffer(FileName)) { 165d44252ecSDouglas Gregor // The buffer was already provided for us. 1660a2be46cSDuncan P. N. Exon Smith NewModule->Buffer = &ModuleCache->addBuiltPCM(FileName, std::move(Buffer)); 16749092d13SAdrian Prantl // Since the cached buffer is reused, it is safe to close the file 16849092d13SAdrian Prantl // descriptor that was opened while stat()ing the PCM in 16949092d13SAdrian Prantl // lookupModuleFile() above, it won't be needed any longer. 17049092d13SAdrian Prantl Entry->closeFile(); 1718bef5cd4SDuncan P. N. Exon Smith } else if (llvm::MemoryBuffer *Buffer = 1720a2be46cSDuncan P. N. Exon Smith getModuleCache().lookupPCM(FileName)) { 173030d7d6dSDuncan P. N. Exon Smith NewModule->Buffer = Buffer; 17449092d13SAdrian Prantl // As above, the file descriptor is no longer needed. 17549092d13SAdrian Prantl Entry->closeFile(); 1760a2be46cSDuncan P. N. Exon Smith } else if (getModuleCache().shouldBuildPCM(FileName)) { 1770a2be46cSDuncan P. N. Exon Smith // Report that the module is out of date, since we tried (and failed) to 1780a2be46cSDuncan P. N. Exon Smith // import it earlier. 1790a2be46cSDuncan P. N. Exon Smith Entry->closeFile(); 1800a2be46cSDuncan P. N. Exon Smith return OutOfDate; 181d44252ecSDouglas Gregor } else { 182d44252ecSDouglas Gregor // Open the AST file. 18326308a68SDuncan P. N. Exon Smith llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf((std::error_code())); 184d44252ecSDouglas Gregor if (FileName == "-") { 185a885796dSBenjamin Kramer Buf = llvm::MemoryBuffer::getSTDIN(); 1869801b253SBen Langmuir } else { 18749092d13SAdrian Prantl // Get a buffer of the file and close the file descriptor when done. 188*122705b9SDuncan P. N. Exon Smith Buf = FileMgr.getBufferForFile(NewModule->File, /*isVolatile=*/false); 1899801b253SBen Langmuir } 190d44252ecSDouglas Gregor 191a885796dSBenjamin Kramer if (!Buf) { 192a885796dSBenjamin Kramer ErrorStr = Buf.getError().message(); 1937029ce1aSDouglas Gregor return Missing; 194d44252ecSDouglas Gregor } 195d44252ecSDouglas Gregor 1960a2be46cSDuncan P. N. Exon Smith NewModule->Buffer = &getModuleCache().addPCM(FileName, std::move(*Buf)); 197a885796dSBenjamin Kramer } 198a885796dSBenjamin Kramer 199bb165fb0SAdrian Prantl // Initialize the stream. 200a897f7cdSDuncan P. N. Exon Smith NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer); 201487ea14aSBen Langmuir 202688b69adSDuncan P. N. Exon Smith // Read the signature eagerly now so that we can check it. Avoid calling 203688b69adSDuncan P. N. Exon Smith // ReadSignature unless there's something to check though. 204688b69adSDuncan P. N. Exon Smith if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data), 205f91b6f81SVolodymyr Sapsai ExpectedSignature, ErrorStr)) 206ed982584SBen Langmuir return OutOfDate; 207a897f7cdSDuncan P. N. Exon Smith 20826308a68SDuncan P. N. Exon Smith // We're keeping this module. Store it everywhere. 20926308a68SDuncan P. N. Exon Smith Module = Modules[Entry] = NewModule.get(); 210d44252ecSDouglas Gregor 21126308a68SDuncan P. N. Exon Smith updateModuleImports(*NewModule, ImportedBy, ImportLoc); 2126fb03aeaSDouglas Gregor 21326308a68SDuncan P. N. Exon Smith if (!NewModule->isModule()) 21426308a68SDuncan P. N. Exon Smith PCHChain.push_back(NewModule.get()); 21526308a68SDuncan P. N. Exon Smith if (!ImportedBy) 21626308a68SDuncan P. N. Exon Smith Roots.push_back(NewModule.get()); 2173b99db55SRichard Smith 218a897f7cdSDuncan P. N. Exon Smith Chain.push_back(std::move(NewModule)); 2193b99db55SRichard Smith return NewlyLoaded; 220d44252ecSDouglas Gregor } 221d44252ecSDouglas Gregor 2229801b253SBen Langmuir void ModuleManager::removeModules( 2238e6bc197SDuncan P. N. Exon Smith ModuleIterator First, 2249801b253SBen Langmuir llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully, 2257029ce1aSDouglas Gregor ModuleMap *modMap) { 2268e6bc197SDuncan P. N. Exon Smith auto Last = end(); 2278e6bc197SDuncan P. N. Exon Smith if (First == Last) 228188dbef2SDouglas Gregor return; 229188dbef2SDouglas Gregor 230a50dbb20SBen Langmuir // Explicitly clear VisitOrder since we might not notice it is stale. 231a50dbb20SBen Langmuir VisitOrder.clear(); 232a50dbb20SBen Langmuir 233188dbef2SDouglas Gregor // Collect the set of module file pointers that we'll be removing. 23496a06e0eSDuncan P. N. Exon Smith llvm::SmallPtrSet<ModuleFile *, 4> victimSet( 2358e6bc197SDuncan P. N. Exon Smith (llvm::pointer_iterator<ModuleIterator>(First)), 2368e6bc197SDuncan P. N. Exon Smith (llvm::pointer_iterator<ModuleIterator>(Last))); 237188dbef2SDouglas Gregor 2389eff8b14SManuel Klimek auto IsVictim = [&](ModuleFile *MF) { 2399eff8b14SManuel Klimek return victimSet.count(MF); 2409eff8b14SManuel Klimek }; 241188dbef2SDouglas Gregor // Remove any references to the now-destroyed modules. 242073ec350SDuncan P. N. Exon Smith for (auto I = begin(); I != First; ++I) { 243073ec350SDuncan P. N. Exon Smith I->Imports.remove_if(IsVictim); 2448e6bc197SDuncan P. N. Exon Smith I->ImportedBy.remove_if(IsVictim); 245073ec350SDuncan P. N. Exon Smith } 2469eff8b14SManuel Klimek Roots.erase(std::remove_if(Roots.begin(), Roots.end(), IsVictim), 2479eff8b14SManuel Klimek Roots.end()); 248188dbef2SDouglas Gregor 24916fe4d17SRichard Smith // Remove the modules from the PCH chain. 2508e6bc197SDuncan P. N. Exon Smith for (auto I = First; I != Last; ++I) { 25196a06e0eSDuncan P. N. Exon Smith if (!I->isModule()) { 25275e74e07SFangrui Song PCHChain.erase(llvm::find(PCHChain, &*I), PCHChain.end()); 25316fe4d17SRichard Smith break; 25416fe4d17SRichard Smith } 25516fe4d17SRichard Smith } 25616fe4d17SRichard Smith 257188dbef2SDouglas Gregor // Delete the modules and erase them from the various structures. 2588e6bc197SDuncan P. N. Exon Smith for (ModuleIterator victim = First; victim != Last; ++victim) { 25996a06e0eSDuncan P. N. Exon Smith Modules.erase(victim->File); 260ca39214fSBen Langmuir 2617029ce1aSDouglas Gregor if (modMap) { 26296a06e0eSDuncan P. N. Exon Smith StringRef ModuleName = victim->ModuleName; 2637029ce1aSDouglas Gregor if (Module *mod = modMap->findModule(ModuleName)) { 264a13603a2SCraig Topper mod->setASTFile(nullptr); 2657029ce1aSDouglas Gregor } 2667029ce1aSDouglas Gregor } 267188dbef2SDouglas Gregor } 268188dbef2SDouglas Gregor 269a897f7cdSDuncan P. N. Exon Smith // Delete the modules. 2708e6bc197SDuncan P. N. Exon Smith Chain.erase(Chain.begin() + (First - begin()), Chain.end()); 271188dbef2SDouglas Gregor } 272188dbef2SDouglas Gregor 2735cd06f26SRafael Espindola void 2745cd06f26SRafael Espindola ModuleManager::addInMemoryBuffer(StringRef FileName, 2755cd06f26SRafael Espindola std::unique_ptr<llvm::MemoryBuffer> Buffer) { 2765cd06f26SRafael Espindola const FileEntry *Entry = 2775cd06f26SRafael Espindola FileMgr.getVirtualFile(FileName, Buffer->getBufferSize(), 0); 2785cd06f26SRafael Espindola InMemoryBuffers[Entry] = std::move(Buffer); 279d44252ecSDouglas Gregor } 280d44252ecSDouglas Gregor 281e97cd90aSDouglas Gregor ModuleManager::VisitState *ModuleManager::allocateVisitState() { 282e97cd90aSDouglas Gregor // Fast path: if we have a cached state, use it. 283e97cd90aSDouglas Gregor if (FirstVisitState) { 284e97cd90aSDouglas Gregor VisitState *Result = FirstVisitState; 285e97cd90aSDouglas Gregor FirstVisitState = FirstVisitState->NextState; 286a13603a2SCraig Topper Result->NextState = nullptr; 287e97cd90aSDouglas Gregor return Result; 288e97cd90aSDouglas Gregor } 289e97cd90aSDouglas Gregor 290e97cd90aSDouglas Gregor // Allocate and return a new state. 291e97cd90aSDouglas Gregor return new VisitState(size()); 292e97cd90aSDouglas Gregor } 293e97cd90aSDouglas Gregor 294e97cd90aSDouglas Gregor void ModuleManager::returnVisitState(VisitState *State) { 295a13603a2SCraig Topper assert(State->NextState == nullptr && "Visited state is in list?"); 296e97cd90aSDouglas Gregor State->NextState = FirstVisitState; 297e97cd90aSDouglas Gregor FirstVisitState = State; 298e97cd90aSDouglas Gregor } 299e97cd90aSDouglas Gregor 3007211ac15SDouglas Gregor void ModuleManager::setGlobalIndex(GlobalModuleIndex *Index) { 3017211ac15SDouglas Gregor GlobalIndex = Index; 302603cd869SDouglas Gregor if (!GlobalIndex) { 303603cd869SDouglas Gregor ModulesInCommonWithGlobalIndex.clear(); 304603cd869SDouglas Gregor return; 3057029ce1aSDouglas Gregor } 306603cd869SDouglas Gregor 307603cd869SDouglas Gregor // Notify the global module index about all of the modules we've already 308603cd869SDouglas Gregor // loaded. 309a897f7cdSDuncan P. N. Exon Smith for (ModuleFile &M : *this) 310a897f7cdSDuncan P. N. Exon Smith if (!GlobalIndex->loadedModuleFile(&M)) 311a897f7cdSDuncan P. N. Exon Smith ModulesInCommonWithGlobalIndex.push_back(&M); 312603cd869SDouglas Gregor } 313603cd869SDouglas Gregor 314603cd869SDouglas Gregor void ModuleManager::moduleFileAccepted(ModuleFile *MF) { 315603cd869SDouglas Gregor if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF)) 316603cd869SDouglas Gregor return; 317603cd869SDouglas Gregor 318603cd869SDouglas Gregor ModulesInCommonWithGlobalIndex.push_back(MF); 3197211ac15SDouglas Gregor } 3207211ac15SDouglas Gregor 3218bef5cd4SDuncan P. N. Exon Smith ModuleManager::ModuleManager(FileManager &FileMgr, 3228bef5cd4SDuncan P. N. Exon Smith InMemoryModuleCache &ModuleCache, 323d30446fdSBoris Kolpackov const PCHContainerReader &PCHContainerRdr, 324d30446fdSBoris Kolpackov const HeaderSearch &HeaderSearchInfo) 3258bef5cd4SDuncan P. N. Exon Smith : FileMgr(FileMgr), ModuleCache(&ModuleCache), 3268bef5cd4SDuncan P. N. Exon Smith PCHContainerRdr(PCHContainerRdr), HeaderSearchInfo(HeaderSearchInfo) {} 327d44252ecSDouglas Gregor 328a897f7cdSDuncan P. N. Exon Smith ModuleManager::~ModuleManager() { delete FirstVisitState; } 329d44252ecSDouglas Gregor 3309a9efbafSBenjamin Kramer void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor, 3314dd9b43cSCraig Topper llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) { 3327211ac15SDouglas Gregor // If the visitation order vector is the wrong size, recompute the order. 333e41d7feaSDouglas Gregor if (VisitOrder.size() != Chain.size()) { 334d44252ecSDouglas Gregor unsigned N = size(); 335e41d7feaSDouglas Gregor VisitOrder.clear(); 336e41d7feaSDouglas Gregor VisitOrder.reserve(N); 337d44252ecSDouglas Gregor 338d44252ecSDouglas Gregor // Record the number of incoming edges for each module. When we 339d44252ecSDouglas Gregor // encounter a module with no incoming edges, push it into the queue 340d44252ecSDouglas Gregor // to seed the queue. 341de3ef502SDouglas Gregor SmallVector<ModuleFile *, 4> Queue; 342d44252ecSDouglas Gregor Queue.reserve(N); 343bdb259d2SDouglas Gregor llvm::SmallVector<unsigned, 4> UnusedIncomingEdges; 344a7c535b3SRichard Smith UnusedIncomingEdges.resize(size()); 34596a06e0eSDuncan P. N. Exon Smith for (ModuleFile &M : llvm::reverse(*this)) { 34696a06e0eSDuncan P. N. Exon Smith unsigned Size = M.ImportedBy.size(); 34796a06e0eSDuncan P. N. Exon Smith UnusedIncomingEdges[M.Index] = Size; 348a7c535b3SRichard Smith if (!Size) 34996a06e0eSDuncan P. N. Exon Smith Queue.push_back(&M); 350d44252ecSDouglas Gregor } 351d44252ecSDouglas Gregor 352e41d7feaSDouglas Gregor // Traverse the graph, making sure to visit a module before visiting any 353e41d7feaSDouglas Gregor // of its dependencies. 354a7c535b3SRichard Smith while (!Queue.empty()) { 355a7c535b3SRichard Smith ModuleFile *CurrentModule = Queue.pop_back_val(); 356e41d7feaSDouglas Gregor VisitOrder.push_back(CurrentModule); 357d44252ecSDouglas Gregor 358d44252ecSDouglas Gregor // For any module that this module depends on, push it on the 359d44252ecSDouglas Gregor // stack (if it hasn't already been marked as visited). 360a7c535b3SRichard Smith for (auto M = CurrentModule->Imports.rbegin(), 361a7c535b3SRichard Smith MEnd = CurrentModule->Imports.rend(); 362d44252ecSDouglas Gregor M != MEnd; ++M) { 363d44252ecSDouglas Gregor // Remove our current module as an impediment to visiting the 364d44252ecSDouglas Gregor // module we depend on. If we were the last unvisited module 365d44252ecSDouglas Gregor // that depends on this particular module, push it into the 366d44252ecSDouglas Gregor // queue to be visited. 367bdb259d2SDouglas Gregor unsigned &NumUnusedEdges = UnusedIncomingEdges[(*M)->Index]; 368d44252ecSDouglas Gregor if (NumUnusedEdges && (--NumUnusedEdges == 0)) 369d44252ecSDouglas Gregor Queue.push_back(*M); 370d44252ecSDouglas Gregor } 371d44252ecSDouglas Gregor } 372e41d7feaSDouglas Gregor 373e41d7feaSDouglas Gregor assert(VisitOrder.size() == N && "Visitation order is wrong?"); 3747211ac15SDouglas Gregor 375e97cd90aSDouglas Gregor delete FirstVisitState; 376a13603a2SCraig Topper FirstVisitState = nullptr; 377e41d7feaSDouglas Gregor } 378e41d7feaSDouglas Gregor 379e97cd90aSDouglas Gregor VisitState *State = allocateVisitState(); 380e97cd90aSDouglas Gregor unsigned VisitNumber = State->NextVisitNumber++; 381e41d7feaSDouglas Gregor 3827211ac15SDouglas Gregor // If the caller has provided us with a hit-set that came from the global 3837211ac15SDouglas Gregor // module index, mark every module file in common with the global module 3847211ac15SDouglas Gregor // index that is *not* in that set as 'visited'. 3857211ac15SDouglas Gregor if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) { 3867211ac15SDouglas Gregor for (unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I) 3877211ac15SDouglas Gregor { 3887211ac15SDouglas Gregor ModuleFile *M = ModulesInCommonWithGlobalIndex[I]; 3897029ce1aSDouglas Gregor if (!ModuleFilesHit->count(M)) 390e97cd90aSDouglas Gregor State->VisitNumber[M->Index] = VisitNumber; 3917211ac15SDouglas Gregor } 3927211ac15SDouglas Gregor } 3937211ac15SDouglas Gregor 394e41d7feaSDouglas Gregor for (unsigned I = 0, N = VisitOrder.size(); I != N; ++I) { 395e41d7feaSDouglas Gregor ModuleFile *CurrentModule = VisitOrder[I]; 396e41d7feaSDouglas Gregor // Should we skip this module file? 397e97cd90aSDouglas Gregor if (State->VisitNumber[CurrentModule->Index] == VisitNumber) 398e41d7feaSDouglas Gregor continue; 399e41d7feaSDouglas Gregor 400e41d7feaSDouglas Gregor // Visit the module. 401e97cd90aSDouglas Gregor assert(State->VisitNumber[CurrentModule->Index] == VisitNumber - 1); 402e97cd90aSDouglas Gregor State->VisitNumber[CurrentModule->Index] = VisitNumber; 4039a9efbafSBenjamin Kramer if (!Visitor(*CurrentModule)) 404e41d7feaSDouglas Gregor continue; 405e41d7feaSDouglas Gregor 406e41d7feaSDouglas Gregor // The visitor has requested that cut off visitation of any 407e41d7feaSDouglas Gregor // module that the current module depends on. To indicate this 408e41d7feaSDouglas Gregor // behavior, we mark all of the reachable modules as having been visited. 409e41d7feaSDouglas Gregor ModuleFile *NextModule = CurrentModule; 410e41d7feaSDouglas Gregor do { 411e41d7feaSDouglas Gregor // For any module that this module depends on, push it on the 412e41d7feaSDouglas Gregor // stack (if it hasn't already been marked as visited). 413e41d7feaSDouglas Gregor for (llvm::SetVector<ModuleFile *>::iterator 414e41d7feaSDouglas Gregor M = NextModule->Imports.begin(), 415e41d7feaSDouglas Gregor MEnd = NextModule->Imports.end(); 416e41d7feaSDouglas Gregor M != MEnd; ++M) { 417e97cd90aSDouglas Gregor if (State->VisitNumber[(*M)->Index] != VisitNumber) { 418e97cd90aSDouglas Gregor State->Stack.push_back(*M); 419e97cd90aSDouglas Gregor State->VisitNumber[(*M)->Index] = VisitNumber; 420e41d7feaSDouglas Gregor } 421e41d7feaSDouglas Gregor } 422e41d7feaSDouglas Gregor 423e97cd90aSDouglas Gregor if (State->Stack.empty()) 424e41d7feaSDouglas Gregor break; 425e41d7feaSDouglas Gregor 426e41d7feaSDouglas Gregor // Pop the next module off the stack. 42725284cc9SRobert Wilhelm NextModule = State->Stack.pop_back_val(); 428e41d7feaSDouglas Gregor } while (true); 429e41d7feaSDouglas Gregor } 430e97cd90aSDouglas Gregor 431e97cd90aSDouglas Gregor returnVisitState(State); 432d44252ecSDouglas Gregor } 433d44252ecSDouglas Gregor 4347029ce1aSDouglas Gregor bool ModuleManager::lookupModuleFile(StringRef FileName, 4357029ce1aSDouglas Gregor off_t ExpectedSize, 4367029ce1aSDouglas Gregor time_t ExpectedModTime, 4377029ce1aSDouglas Gregor const FileEntry *&File) { 4383bd6d7fbSRichard Smith if (FileName == "-") { 4393bd6d7fbSRichard Smith File = nullptr; 4403bd6d7fbSRichard Smith return false; 4413bd6d7fbSRichard Smith } 4423bd6d7fbSRichard Smith 44305f82ba2SBen Langmuir // Open the file immediately to ensure there is no race between stat'ing and 44405f82ba2SBen Langmuir // opening the file. 4458d323d15SHarlan Haskins auto FileOrErr = FileMgr.getFile(FileName, /*OpenFile=*/true, 4468d323d15SHarlan Haskins /*CacheFailure=*/false); 4478d323d15SHarlan Haskins if (!FileOrErr) { 4488d323d15SHarlan Haskins File = nullptr; 4497029ce1aSDouglas Gregor return false; 4508d323d15SHarlan Haskins } 4518d323d15SHarlan Haskins File = *FileOrErr; 4527029ce1aSDouglas Gregor 4537029ce1aSDouglas Gregor if ((ExpectedSize && ExpectedSize != File->getSize()) || 454027731d7SBen Langmuir (ExpectedModTime && ExpectedModTime != File->getModificationTime())) 455027731d7SBen Langmuir // Do not destroy File, as it may be referenced. If we need to rebuild it, 456027731d7SBen Langmuir // it will be destroyed by removeModules. 4577029ce1aSDouglas Gregor return true; 4587029ce1aSDouglas Gregor 4597029ce1aSDouglas Gregor return false; 4607029ce1aSDouglas Gregor } 4617029ce1aSDouglas Gregor 4629d7c1a2aSDouglas Gregor #ifndef NDEBUG 4639d7c1a2aSDouglas Gregor namespace llvm { 464b7d89107SEugene Zelenko 4659d7c1a2aSDouglas Gregor template<> 4669d7c1a2aSDouglas Gregor struct GraphTraits<ModuleManager> { 467b7d89107SEugene Zelenko using NodeRef = ModuleFile *; 468b7d89107SEugene Zelenko using ChildIteratorType = llvm::SetVector<ModuleFile *>::const_iterator; 469b7d89107SEugene Zelenko using nodes_iterator = pointer_iterator<ModuleManager::ModuleConstIterator>; 4709d7c1a2aSDouglas Gregor 471f2187ed3STim Shen static ChildIteratorType child_begin(NodeRef Node) { 4729d7c1a2aSDouglas Gregor return Node->Imports.begin(); 4739d7c1a2aSDouglas Gregor } 4749d7c1a2aSDouglas Gregor 475f2187ed3STim Shen static ChildIteratorType child_end(NodeRef Node) { 4769d7c1a2aSDouglas Gregor return Node->Imports.end(); 4779d7c1a2aSDouglas Gregor } 4789d7c1a2aSDouglas Gregor 4799d7c1a2aSDouglas Gregor static nodes_iterator nodes_begin(const ModuleManager &Manager) { 48096a06e0eSDuncan P. N. Exon Smith return nodes_iterator(Manager.begin()); 4819d7c1a2aSDouglas Gregor } 4829d7c1a2aSDouglas Gregor 4839d7c1a2aSDouglas Gregor static nodes_iterator nodes_end(const ModuleManager &Manager) { 48496a06e0eSDuncan P. N. Exon Smith return nodes_iterator(Manager.end()); 4859d7c1a2aSDouglas Gregor } 4869d7c1a2aSDouglas Gregor }; 4879d7c1a2aSDouglas Gregor 4889d7c1a2aSDouglas Gregor template<> 4899d7c1a2aSDouglas Gregor struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits { 4909d7c1a2aSDouglas Gregor explicit DOTGraphTraits(bool IsSimple = false) 4919d7c1a2aSDouglas Gregor : DefaultDOTGraphTraits(IsSimple) {} 4929d7c1a2aSDouglas Gregor 493b7d89107SEugene Zelenko static bool renderGraphFromBottomUp() { return true; } 4949d7c1a2aSDouglas Gregor 495de3ef502SDouglas Gregor std::string getNodeLabel(ModuleFile *M, const ModuleManager&) { 496beee15e7SBen Langmuir return M->ModuleName; 4979d7c1a2aSDouglas Gregor } 4989d7c1a2aSDouglas Gregor }; 499b7d89107SEugene Zelenko 500b7d89107SEugene Zelenko } // namespace llvm 5019d7c1a2aSDouglas Gregor 5029d7c1a2aSDouglas Gregor void ModuleManager::viewGraph() { 5039d7c1a2aSDouglas Gregor llvm::ViewGraph(*this, "Modules"); 5049d7c1a2aSDouglas Gregor } 5059d7c1a2aSDouglas Gregor #endif 506