24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SetVector.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/iterator.h"
30#include "llvm/Support/DOTGraphTraits.h"
31#include "llvm/Support/Error.h"
32#include "llvm/Support/GraphWriter.h"
33#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/VirtualFileSystem.h"
42std::optional<ModuleFileKey>
45 StringRef ModuleCachePath = StringRef(Name).drop_back(SuffixLen);
46 StringRef ImplicitModuleSuffix = StringRef(Name).take_back(SuffixLen);
47 if (
auto *ModuleCacheDir = ModCache.getDirectoryPtr(ModuleCachePath))
53 ModCache.getInMemoryModuleCache().lookupPCM(Name, Size, ModTime))
56 if (
auto ModuleFile = FileMgr.getOptionalFileRef(Name,
true,
66 if (
const Module *Mod = HeaderSearchInfo.getModuleMap().findModule(Name))
74 std::optional<ModuleFileKey> Key =
makeKey(Name);
75 return Key ?
lookup(*Key) :
nullptr;
79 return Modules.lookup(Key);
82bool ModuleManager::isModuleFileOutOfDate(off_t Size, time_t ModTime,
84 time_t ExpectedModTime,
86 bool OutOfDate =
false;
87 if (ExpectedSize && ExpectedSize != Size) {
92 if (ExpectedModTime && ExpectedModTime != ModTime) {
100bool ModuleManager::checkSignature(ASTFileSignature Signature,
101 ASTFileSignature ExpectedSignature,
103 if (!ExpectedSignature || Signature == ExpectedSignature)
106 Signature ?
"signature mismatch" :
"could not read module signature";
114 ImportedBy->
Imports.insert(&MF);
125 ModuleFile *ImportedBy,
unsigned Generation, off_t ExpectedSize,
130 uint64_t InputFilesValidationTimestamp = 0;
132 InputFilesValidationTimestamp = ModCache.getModuleTimestamp(
FileName);
157 if (isModuleFileOutOfDate(ModuleEntry->Size, ModuleEntry->ModTime,
158 ExpectedSize, ExpectedModTime,
Result)) {
159 Result.setOutOfDate(ModuleEntry->InputFilesValidationStatus);
164 if (checkSignature(ModuleEntry->Signature, ExpectedSignature,
Result)) {
165 Result.setOutOfDate(ModuleEntry->InputFilesValidationStatus);
169 Result.Module = ModuleEntry;
176 off_t Size = ExpectedSize;
177 time_t ModTime = ExpectedModTime;
178 llvm::MemoryBuffer *ModuleBuffer =
nullptr;
179 std::unique_ptr<llvm::MemoryBuffer> NewFileBuffer =
nullptr;
180 if (llvm::MemoryBuffer *Buffer =
183 ModuleBuffer = Buffer;
184 }
else if (
getModuleCache().getInMemoryModuleCache().shouldBuildPCM(
194 auto Buf = [&]() ->
Expected<std::unique_ptr<llvm::MemoryBuffer>> {
195 assert(!
FileName.isInMemory() &&
"In-memory module not found");
198 if (
FileName.getImplicitModuleSuffixLength())
199 return ModCache.read(
FileName, Size, ModTime);
206 : FileMgr.getFileRef(
FileName,
true,
210 return Entry.takeError();
212 Size = Entry->getSize();
213 ModTime = Entry->getModificationTime();
217 return llvm::errorOrToExpected(
218 FileMgr.getBufferForFile(*Entry,
false,
225 Result.BufferError = llvm::toString(Buf.takeError());
230 NewFileBuffer = std::move(*Buf);
231 ModuleBuffer = NewFileBuffer.get();
235 auto NewModule = std::make_unique<ModuleFile>(
Type, *FileKey, Generation);
236 NewModule->Index = Chain.size();
238 NewModule->ImportLoc = ImportLoc;
239 NewModule->InputFilesValidationTimestamp = InputFilesValidationTimestamp;
240 NewModule->Size = Size;
241 NewModule->ModTime = ModTime;
242 NewModule->Buffer = ModuleBuffer;
244 NewModule->Data = PCHContainerRdr.ExtractPCH(*NewModule->Buffer);
247 if (isModuleFileOutOfDate(Size, ModTime, ExpectedSize, ExpectedModTime,
249 Result.setOutOfDate(NewModule->InputFilesValidationStatus);
255 if (ExpectedSignature && checkSignature(ReadSignature(NewModule->Data),
256 ExpectedSignature,
Result)) {
257 Result.setOutOfDate(NewModule->InputFilesValidationStatus);
263 FileName, std::move(NewFileBuffer), Size, ModTime);
266 Result.Module = Modules[*FileKey] = NewModule.get();
270 if (!NewModule->isModule())
271 PCHChain.push_back(NewModule.get());
273 Roots.push_back(NewModule.get());
275 Chain.push_back(std::move(NewModule));
290 (llvm::pointer_iterator<ModuleIterator>(
First)),
291 (llvm::pointer_iterator<ModuleIterator>(
Last)));
294 return victimSet.count(MF);
298 I->Imports.remove_if(IsVictim);
299 I->ImportedBy.remove_if(IsVictim);
301 llvm::erase_if(Roots, IsVictim);
305 if (!I->isModule()) {
306 PCHChain.erase(llvm::find(PCHChain, &*I), PCHChain.end());
313 Modules.erase(victim->FileKey);
315 Chain.erase(Chain.begin() + (
First -
begin()), Chain.end());
318std::unique_ptr<ModuleManager::VisitState> ModuleManager::allocateVisitState() {
320 if (FirstVisitState) {
321 auto Result = std::move(FirstVisitState);
322 FirstVisitState = std::move(
Result->NextState);
327 return std::make_unique<VisitState>(
size());
330void ModuleManager::returnVisitState(std::unique_ptr<VisitState> State) {
331 assert(State->NextState ==
nullptr &&
"Visited state is in list?");
332 State->NextState = std::move(FirstVisitState);
333 FirstVisitState = std::move(State);
339 ModulesInCommonWithGlobalIndex.clear();
346 if (!GlobalIndex->loadedModuleFile(&M))
347 ModulesInCommonWithGlobalIndex.push_back(&M);
351 if (!GlobalIndex || GlobalIndex->loadedModuleFile(MF))
354 ModulesInCommonWithGlobalIndex.push_back(MF);
360 : FileMgr(FileMgr), ModCache(ModCache), PCHContainerRdr(PCHContainerRdr),
361 HeaderSearchInfo(HeaderSearchInfo) {}
364 llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit) {
366 if (VisitOrder.size() != Chain.size()) {
369 VisitOrder.reserve(N);
377 UnusedIncomingEdges.resize(
size());
380 UnusedIncomingEdges[M.
Index] = Size;
387 while (!Queue.empty()) {
388 ModuleFile *CurrentModule = Queue.pop_back_val();
389 VisitOrder.push_back(CurrentModule);
398 unsigned &NumUnusedEdges = UnusedIncomingEdges[M->
Index];
399 if (NumUnusedEdges && (--NumUnusedEdges == 0))
404 assert(VisitOrder.size() == N &&
"Visitation order is wrong?");
406 FirstVisitState =
nullptr;
409 auto State = allocateVisitState();
410 unsigned VisitNumber = State->NextVisitNumber++;
415 if (ModuleFilesHit && !ModulesInCommonWithGlobalIndex.empty()) {
416 for (
unsigned I = 0, N = ModulesInCommonWithGlobalIndex.size(); I != N; ++I)
418 ModuleFile *M = ModulesInCommonWithGlobalIndex[I];
419 if (!ModuleFilesHit->count(M))
420 State->VisitNumber[M->
Index] = VisitNumber;
424 for (
unsigned I = 0, N = VisitOrder.size(); I != N; ++I) {
427 if (State->VisitNumber[CurrentModule->
Index] == VisitNumber)
431 assert(State->VisitNumber[CurrentModule->
Index] == VisitNumber - 1);
432 State->VisitNumber[CurrentModule->
Index] = VisitNumber;
433 if (!Visitor(*CurrentModule))
443 for (llvm::SetVector<ModuleFile *>::iterator
444 M = NextModule->
Imports.begin(),
445 MEnd = NextModule->
Imports.end();
447 if (State->VisitNumber[(*M)->Index] != VisitNumber) {
448 State->Stack.push_back(*M);
449 State->VisitNumber[(*M)->Index] = VisitNumber;
453 if (State->Stack.empty())
457 NextModule = State->Stack.pop_back_val();
461 returnVisitState(std::move(State));
505 llvm::ViewGraph(*
this,
"Modules");
Defines the clang::FileManager interface and associated types.
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
static void updateModuleImports(ModuleFile &MF, ModuleFile *ImportedBy, SourceLocation ImportLoc)
Implements support for file system lookup, file system caching, and directory search management.
A global index for a set of module files, providing information about the identifiers within those mo...
llvm::MemoryBuffer & addPCM(llvm::StringRef Filename, std::unique_ptr< llvm::MemoryBuffer > Buffer, off_t Size, time_t ModTime)
Store the PCM under the Filename.
The module cache used for compiling modules implicitly.
virtual InMemoryModuleCache & getInMemoryModuleCache()=0
Returns this process's view of the module cache.
Deduplication key for a loaded module file in ModuleManager.
Identifies a module file to be loaded.
bool isInMemory() const
Returns true iff this is an in-memory module file, false otherwise.
unsigned getImplicitModuleSuffixLength() const
Returns the suffix length for an implicit module name, zero otherwise.
Describes a module or submodule.
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
Encodes a location in the source.
The base class of the type hierarchy.
The result of attempting to add a new module.
@ Missing
The module file is missing.
@ NewlyLoaded
The module file was just loaded in response to this call.
@ AlreadyLoaded
The module file had already been loaded.
Information about a module that has been loaded by the ASTReader.
bool DirectlyImported
Whether this module has been directly imported by the user.
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
SourceLocation ImportLoc
The source location where this module was first imported.
unsigned Index
The index of this module in the list of modules.
llvm::SetVector< ModuleFile * > Imports
List of modules which this module directly imported.
ModuleKind Kind
The type of this module.
std::string ModuleName
The name of the module.
Manages the set of modules loaded by an AST reader.
AddModuleResult addModule(ModuleFileName FileName, ModuleKind Type, SourceLocation ImportLoc, ModuleFile *ImportedBy, unsigned Generation, off_t ExpectedSize, time_t ExpectedModTime, ASTFileSignature ExpectedSignature, ASTFileSignatureReader ReadSignature)
Attempts to create a new module and add it to the list of known modules.
ModuleFile * lookup(ModuleFileKey Key) const
Returns the module associated with the given module file key.
llvm::pointee_iterator< SmallVectorImpl< std::unique_ptr< ModuleFile > >::iterator > ModuleIterator
void moduleFileAccepted(ModuleFile *MF)
Notification from the AST reader that the given module file has been "accepted", and will not (can no...
ModuleManager(FileManager &FileMgr, ModuleCache &ModCache, const PCHContainerReader &PCHContainerRdr, const HeaderSearch &HeaderSearchInfo)
void viewGraph()
View the graphviz representation of the module graph.
ModuleCache & getModuleCache() const
ModuleIterator begin()
Forward iterator to traverse all loaded modules.
std::optional< ModuleFileKey > makeKey(const ModuleFileName &Name) const
Creates the deduplication key for use in ModuleManager.
void setGlobalIndex(GlobalModuleIndex *Index)
Set the global module index.
void removeModules(ModuleIterator First)
Remove the modules starting from First (to the end).
ModuleIterator end()
Forward iterator end-point to traverse all loaded modules.
void visit(llvm::function_ref< bool(ModuleFile &M)> Visitor, llvm::SmallPtrSetImpl< ModuleFile * > *ModuleFilesHit=nullptr)
Visit each of the modules.
unsigned size() const
Number of modules loaded.
ModuleFile * lookupByFileName(ModuleFileName FileName) const
Returns the module associated with the given module file name.
ASTFileSignature(*)(StringRef) ASTFileSignatureReader
ModuleFile * lookupByModuleName(StringRef ModName) const
Returns the module associated with the given module name.
@ Disabled
When the validation is disabled. For example, for a precompiled header.
@ NotStarted
Initial value, before the validation has been performed.
ModuleKind
Specifies the kind of module that has been loaded.
@ MK_ExplicitModule
File is an explicitly-loaded module.
@ MK_ImplicitModule
File is an implicitly-loaded module.
@ MK_PrebuiltModule
File is from a prebuilt module path.
Top level wrappers for InstallAPI frontend operations.
@ Result
The result type of a method or function.
Diagnostic wrappers for TextAPI types for error reporting.
The signature of a module, which is a hash of the AST content.
DOTGraphTraits(bool IsSimple=false)
std::string getNodeLabel(ModuleFile *M, const ModuleManager &)
static bool renderGraphFromBottomUp()
static ChildIteratorType child_end(NodeRef Node)
static nodes_iterator nodes_begin(const ModuleManager &Manager)
static ChildIteratorType child_begin(NodeRef Node)
pointer_iterator< ModuleManager::ModuleConstIterator > nodes_iterator
llvm::SetVector< ModuleFile * >::const_iterator ChildIteratorType
static nodes_iterator nodes_end(const ModuleManager &Manager)