1 //===- Module.cpp - Describe a module -------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the Module class, which describes a module in the source
12 //===----------------------------------------------------------------------===//
14 #include "clang/Basic/Module.h"
15 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/LangOptions.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
35 using namespace clang
;
37 Module::Module(StringRef Name
, SourceLocation DefinitionLoc
, Module
*Parent
,
38 bool IsFramework
, bool IsExplicit
, unsigned VisibilityID
)
39 : Name(Name
), DefinitionLoc(DefinitionLoc
), Parent(Parent
),
40 VisibilityID(VisibilityID
), IsUnimportable(false),
41 HasIncompatibleModuleFile(false), IsAvailable(true),
42 IsFromModuleFile(false), IsFramework(IsFramework
), IsExplicit(IsExplicit
),
43 IsSystem(false), IsExternC(false), IsInferred(false),
44 InferSubmodules(false), InferExplicitSubmodules(false),
45 InferExportWildcard(false), ConfigMacrosExhaustive(false),
46 NoUndeclaredIncludes(false), ModuleMapIsPrivate(false),
47 NameVisibility(Hidden
) {
49 IsAvailable
= Parent
->isAvailable();
50 IsUnimportable
= Parent
->isUnimportable();
51 IsSystem
= Parent
->IsSystem
;
52 IsExternC
= Parent
->IsExternC
;
53 NoUndeclaredIncludes
= Parent
->NoUndeclaredIncludes
;
54 ModuleMapIsPrivate
= Parent
->ModuleMapIsPrivate
;
56 Parent
->SubModuleIndex
[Name
] = Parent
->SubModules
.size();
57 Parent
->SubModules
.push_back(this);
62 for (auto *Submodule
: SubModules
) {
67 static bool isPlatformEnvironment(const TargetInfo
&Target
, StringRef Feature
) {
68 StringRef Platform
= Target
.getPlatformName();
69 StringRef Env
= Target
.getTriple().getEnvironmentName();
71 // Attempt to match platform and environment.
72 if (Platform
== Feature
|| Target
.getTriple().getOSName() == Feature
||
76 auto CmpPlatformEnv
= [](StringRef LHS
, StringRef RHS
) {
77 auto Pos
= LHS
.find('-');
78 if (Pos
== StringRef::npos
)
80 SmallString
<128> NewLHS
= LHS
.slice(0, Pos
);
81 NewLHS
+= LHS
.slice(Pos
+1, LHS
.size());
85 SmallString
<128> PlatformEnv
= Target
.getTriple().getOSAndEnvironmentName();
86 // Darwin has different but equivalent variants for simulators, example:
87 // 1. x86_64-apple-ios-simulator
88 // 2. x86_64-apple-iossimulator
89 // where both are valid examples of the same platform+environment but in the
90 // variant (2) the simulator is hardcoded as part of the platform name. Both
91 // forms above should match for "iossimulator" requirement.
92 if (Target
.getTriple().isOSDarwin() && PlatformEnv
.endswith("simulator"))
93 return PlatformEnv
== Feature
|| CmpPlatformEnv(PlatformEnv
, Feature
);
95 return PlatformEnv
== Feature
;
98 /// Determine whether a translation unit built using the current
99 /// language options has the given feature.
100 static bool hasFeature(StringRef Feature
, const LangOptions
&LangOpts
,
101 const TargetInfo
&Target
) {
102 bool HasFeature
= llvm::StringSwitch
<bool>(Feature
)
103 .Case("altivec", LangOpts
.AltiVec
)
104 .Case("blocks", LangOpts
.Blocks
)
105 .Case("coroutines", LangOpts
.Coroutines
)
106 .Case("cplusplus", LangOpts
.CPlusPlus
)
107 .Case("cplusplus11", LangOpts
.CPlusPlus11
)
108 .Case("cplusplus14", LangOpts
.CPlusPlus14
)
109 .Case("cplusplus17", LangOpts
.CPlusPlus17
)
110 .Case("cplusplus20", LangOpts
.CPlusPlus20
)
111 .Case("cplusplus23", LangOpts
.CPlusPlus23
)
112 .Case("cplusplus26", LangOpts
.CPlusPlus26
)
113 .Case("c99", LangOpts
.C99
)
114 .Case("c11", LangOpts
.C11
)
115 .Case("c17", LangOpts
.C17
)
116 .Case("c23", LangOpts
.C23
)
117 .Case("freestanding", LangOpts
.Freestanding
)
118 .Case("gnuinlineasm", LangOpts
.GNUAsm
)
119 .Case("objc", LangOpts
.ObjC
)
120 .Case("objc_arc", LangOpts
.ObjCAutoRefCount
)
121 .Case("opencl", LangOpts
.OpenCL
)
122 .Case("tls", Target
.isTLSSupported())
123 .Case("zvector", LangOpts
.ZVector
)
124 .Default(Target
.hasFeature(Feature
) ||
125 isPlatformEnvironment(Target
, Feature
));
127 HasFeature
= llvm::is_contained(LangOpts
.ModuleFeatures
, Feature
);
131 bool Module::isUnimportable(const LangOptions
&LangOpts
,
132 const TargetInfo
&Target
, Requirement
&Req
,
133 Module
*&ShadowingModule
) const {
137 for (const Module
*Current
= this; Current
; Current
= Current
->Parent
) {
138 if (Current
->ShadowingModule
) {
139 ShadowingModule
= Current
->ShadowingModule
;
142 for (unsigned I
= 0, N
= Current
->Requirements
.size(); I
!= N
; ++I
) {
143 if (hasFeature(Current
->Requirements
[I
].first
, LangOpts
, Target
) !=
144 Current
->Requirements
[I
].second
) {
145 Req
= Current
->Requirements
[I
];
151 llvm_unreachable("could not find a reason why module is unimportable");
154 // The -fmodule-name option tells the compiler to textually include headers in
155 // the specified module, meaning Clang won't build the specified module. This
156 // is useful in a number of situations, for instance, when building a library
157 // that vends a module map, one might want to avoid hitting intermediate build
158 // products containing the module map or avoid finding the system installed
159 // modulemap for that library.
160 bool Module::isForBuilding(const LangOptions
&LangOpts
) const {
161 StringRef TopLevelName
= getTopLevelModuleName();
162 StringRef CurrentModule
= LangOpts
.CurrentModule
;
164 // When building framework Foo, we want to make sure that Foo *and*
165 // Foo_Private are textually included and no modules are built for both.
166 if (getTopLevelModule()->IsFramework
&&
167 CurrentModule
== LangOpts
.ModuleName
&&
168 !CurrentModule
.endswith("_Private") && TopLevelName
.endswith("_Private"))
169 TopLevelName
= TopLevelName
.drop_back(8);
171 return TopLevelName
== CurrentModule
;
174 bool Module::isAvailable(const LangOptions
&LangOpts
, const TargetInfo
&Target
,
176 UnresolvedHeaderDirective
&MissingHeader
,
177 Module
*&ShadowingModule
) const {
181 if (isUnimportable(LangOpts
, Target
, Req
, ShadowingModule
))
184 // FIXME: All missing headers are listed on the top-level module. Should we
186 for (const Module
*Current
= this; Current
; Current
= Current
->Parent
) {
187 if (!Current
->MissingHeaders
.empty()) {
188 MissingHeader
= Current
->MissingHeaders
.front();
193 llvm_unreachable("could not find a reason why module is unavailable");
196 bool Module::isSubModuleOf(const Module
*Other
) const {
197 for (auto *Parent
= this; Parent
; Parent
= Parent
->Parent
) {
204 const Module
*Module::getTopLevelModule() const {
205 const Module
*Result
= this;
206 while (Result
->Parent
)
207 Result
= Result
->Parent
;
212 static StringRef
getModuleNameFromComponent(
213 const std::pair
<std::string
, SourceLocation
> &IdComponent
) {
214 return IdComponent
.first
;
217 static StringRef
getModuleNameFromComponent(StringRef R
) { return R
; }
219 template<typename InputIter
>
220 static void printModuleId(raw_ostream
&OS
, InputIter Begin
, InputIter End
,
221 bool AllowStringLiterals
= true) {
222 for (InputIter It
= Begin
; It
!= End
; ++It
) {
226 StringRef Name
= getModuleNameFromComponent(*It
);
227 if (!AllowStringLiterals
|| isValidAsciiIdentifier(Name
))
231 OS
.write_escaped(Name
);
237 template<typename Container
>
238 static void printModuleId(raw_ostream
&OS
, const Container
&C
) {
239 return printModuleId(OS
, C
.begin(), C
.end());
242 std::string
Module::getFullModuleName(bool AllowStringLiterals
) const {
243 SmallVector
<StringRef
, 2> Names
;
245 // Build up the set of module names (from innermost to outermost).
246 for (const Module
*M
= this; M
; M
= M
->Parent
)
247 Names
.push_back(M
->Name
);
251 llvm::raw_string_ostream
Out(Result
);
252 printModuleId(Out
, Names
.rbegin(), Names
.rend(), AllowStringLiterals
);
258 bool Module::fullModuleNameIs(ArrayRef
<StringRef
> nameParts
) const {
259 for (const Module
*M
= this; M
; M
= M
->Parent
) {
260 if (nameParts
.empty() || M
->Name
!= nameParts
.back())
262 nameParts
= nameParts
.drop_back();
264 return nameParts
.empty();
267 OptionalDirectoryEntryRef
Module::getEffectiveUmbrellaDir() const {
268 if (Umbrella
&& Umbrella
.is
<FileEntryRef
>())
269 return Umbrella
.get
<FileEntryRef
>().getDir();
270 if (Umbrella
&& Umbrella
.is
<DirectoryEntryRef
>())
271 return Umbrella
.get
<DirectoryEntryRef
>();
275 void Module::addTopHeader(FileEntryRef File
) {
277 TopHeaders
.insert(File
);
280 ArrayRef
<FileEntryRef
> Module::getTopHeaders(FileManager
&FileMgr
) {
281 if (!TopHeaderNames
.empty()) {
282 for (StringRef TopHeaderName
: TopHeaderNames
)
283 if (auto FE
= FileMgr
.getOptionalFileRef(TopHeaderName
))
284 TopHeaders
.insert(*FE
);
285 TopHeaderNames
.clear();
288 return llvm::ArrayRef(TopHeaders
.begin(), TopHeaders
.end());
291 bool Module::directlyUses(const Module
*Requested
) {
292 auto *Top
= getTopLevelModule();
294 // A top-level module implicitly uses itself.
295 if (Requested
->isSubModuleOf(Top
))
298 for (auto *Use
: Top
->DirectUses
)
299 if (Requested
->isSubModuleOf(Use
))
302 // Anyone is allowed to use our builtin stddef.h and its accompanying module.
303 if (!Requested
->Parent
&& Requested
->Name
== "_Builtin_stddef_max_align_t")
306 if (NoUndeclaredIncludes
)
307 UndeclaredUses
.insert(Requested
);
312 void Module::addRequirement(StringRef Feature
, bool RequiredState
,
313 const LangOptions
&LangOpts
,
314 const TargetInfo
&Target
) {
315 Requirements
.push_back(Requirement(std::string(Feature
), RequiredState
));
317 // If this feature is currently available, we're done.
318 if (hasFeature(Feature
, LangOpts
, Target
) == RequiredState
)
321 markUnavailable(/*Unimportable*/true);
324 void Module::markUnavailable(bool Unimportable
) {
325 auto needUpdate
= [Unimportable
](Module
*M
) {
326 return M
->IsAvailable
|| (!M
->IsUnimportable
&& Unimportable
);
329 if (!needUpdate(this))
332 SmallVector
<Module
*, 2> Stack
;
333 Stack
.push_back(this);
334 while (!Stack
.empty()) {
335 Module
*Current
= Stack
.back();
338 if (!needUpdate(Current
))
341 Current
->IsAvailable
= false;
342 Current
->IsUnimportable
|= Unimportable
;
343 for (auto *Submodule
: Current
->submodules()) {
344 if (needUpdate(Submodule
))
345 Stack
.push_back(Submodule
);
350 Module
*Module::findSubmodule(StringRef Name
) const {
351 llvm::StringMap
<unsigned>::const_iterator Pos
= SubModuleIndex
.find(Name
);
352 if (Pos
== SubModuleIndex
.end())
355 return SubModules
[Pos
->getValue()];
358 Module
*Module::findOrInferSubmodule(StringRef Name
) {
359 llvm::StringMap
<unsigned>::const_iterator Pos
= SubModuleIndex
.find(Name
);
360 if (Pos
!= SubModuleIndex
.end())
361 return SubModules
[Pos
->getValue()];
362 if (!InferSubmodules
)
364 Module
*Result
= new Module(Name
, SourceLocation(), this, false, InferExplicitSubmodules
, 0);
365 Result
->InferExplicitSubmodules
= InferExplicitSubmodules
;
366 Result
->InferSubmodules
= InferSubmodules
;
367 Result
->InferExportWildcard
= InferExportWildcard
;
368 if (Result
->InferExportWildcard
)
369 Result
->Exports
.push_back(Module::ExportDecl(nullptr, true));
373 void Module::getExportedModules(SmallVectorImpl
<Module
*> &Exported
) const {
374 // All non-explicit submodules are exported.
375 for (std::vector
<Module
*>::const_iterator I
= SubModules
.begin(),
376 E
= SubModules
.end();
379 if (!Mod
->IsExplicit
)
380 Exported
.push_back(Mod
);
383 // Find re-exported modules by filtering the list of imported modules.
384 bool AnyWildcard
= false;
385 bool UnrestrictedWildcard
= false;
386 SmallVector
<Module
*, 4> WildcardRestrictions
;
387 for (unsigned I
= 0, N
= Exports
.size(); I
!= N
; ++I
) {
388 Module
*Mod
= Exports
[I
].getPointer();
389 if (!Exports
[I
].getInt()) {
390 // Export a named module directly; no wildcards involved.
391 Exported
.push_back(Mod
);
396 // Wildcard export: export all of the imported modules that match
397 // the given pattern.
399 if (UnrestrictedWildcard
)
402 if (Module
*Restriction
= Exports
[I
].getPointer())
403 WildcardRestrictions
.push_back(Restriction
);
405 WildcardRestrictions
.clear();
406 UnrestrictedWildcard
= true;
410 // If there were any wildcards, push any imported modules that were
411 // re-exported by the wildcard restriction.
415 for (unsigned I
= 0, N
= Imports
.size(); I
!= N
; ++I
) {
416 Module
*Mod
= Imports
[I
];
417 bool Acceptable
= UnrestrictedWildcard
;
419 // Check whether this module meets one of the restrictions.
420 for (unsigned R
= 0, NR
= WildcardRestrictions
.size(); R
!= NR
; ++R
) {
421 Module
*Restriction
= WildcardRestrictions
[R
];
422 if (Mod
== Restriction
|| Mod
->isSubModuleOf(Restriction
)) {
432 Exported
.push_back(Mod
);
436 void Module::buildVisibleModulesCache() const {
437 assert(VisibleModulesCache
.empty() && "cache does not need building");
439 // This module is visible to itself.
440 VisibleModulesCache
.insert(this);
442 // Every imported module is visible.
443 SmallVector
<Module
*, 16> Stack(Imports
.begin(), Imports
.end());
444 while (!Stack
.empty()) {
445 Module
*CurrModule
= Stack
.pop_back_val();
447 // Every module transitively exported by an imported module is visible.
448 if (VisibleModulesCache
.insert(CurrModule
).second
)
449 CurrModule
->getExportedModules(Stack
);
453 void Module::print(raw_ostream
&OS
, unsigned Indent
, bool Dump
) const {
460 printModuleId(OS
, &Name
, &Name
+ 1);
462 if (IsSystem
|| IsExternC
) {
463 OS
.indent(Indent
+ 2);
472 if (!Requirements
.empty()) {
473 OS
.indent(Indent
+ 2);
475 for (unsigned I
= 0, N
= Requirements
.size(); I
!= N
; ++I
) {
478 if (!Requirements
[I
].second
)
480 OS
<< Requirements
[I
].first
;
485 if (std::optional
<Header
> H
= getUmbrellaHeaderAsWritten()) {
486 OS
.indent(Indent
+ 2);
487 OS
<< "umbrella header \"";
488 OS
.write_escaped(H
->NameAsWritten
);
490 } else if (std::optional
<DirectoryName
> D
= getUmbrellaDirAsWritten()) {
491 OS
.indent(Indent
+ 2);
493 OS
.write_escaped(D
->NameAsWritten
);
497 if (!ConfigMacros
.empty() || ConfigMacrosExhaustive
) {
498 OS
.indent(Indent
+ 2);
499 OS
<< "config_macros ";
500 if (ConfigMacrosExhaustive
)
501 OS
<< "[exhaustive]";
502 for (unsigned I
= 0, N
= ConfigMacros
.size(); I
!= N
; ++I
) {
505 OS
<< ConfigMacros
[I
];
513 } Kinds
[] = {{"", HK_Normal
},
514 {"textual ", HK_Textual
},
515 {"private ", HK_Private
},
516 {"private textual ", HK_PrivateTextual
},
517 {"exclude ", HK_Excluded
}};
519 for (auto &K
: Kinds
) {
520 assert(&K
== &Kinds
[K
.Kind
] && "kinds in wrong order");
521 for (auto &H
: Headers
[K
.Kind
]) {
522 OS
.indent(Indent
+ 2);
523 OS
<< K
.Prefix
<< "header \"";
524 OS
.write_escaped(H
.NameAsWritten
);
525 OS
<< "\" { size " << H
.Entry
.getSize()
526 << " mtime " << H
.Entry
.getModificationTime() << " }\n";
529 for (auto *Unresolved
: {&UnresolvedHeaders
, &MissingHeaders
}) {
530 for (auto &U
: *Unresolved
) {
531 OS
.indent(Indent
+ 2);
532 OS
<< Kinds
[U
.Kind
].Prefix
<< "header \"";
533 OS
.write_escaped(U
.FileName
);
535 if (U
.Size
|| U
.ModTime
) {
538 OS
<< " size " << *U
.Size
;
540 OS
<< " mtime " << *U
.ModTime
;
547 if (!ExportAsModule
.empty()) {
548 OS
.indent(Indent
+ 2);
549 OS
<< "export_as" << ExportAsModule
<< "\n";
552 for (auto *Submodule
: submodules())
553 // Print inferred subframework modules so that we don't need to re-infer
554 // them (requires expensive directory iteration + stat calls) when we build
555 // the module. Regular inferred submodules are OK, as we need to look at all
556 // those header files anyway.
557 if (!Submodule
->IsInferred
|| Submodule
->IsFramework
)
558 Submodule
->print(OS
, Indent
+ 2, Dump
);
560 for (unsigned I
= 0, N
= Exports
.size(); I
!= N
; ++I
) {
561 OS
.indent(Indent
+ 2);
563 if (Module
*Restriction
= Exports
[I
].getPointer()) {
564 OS
<< Restriction
->getFullModuleName(true);
565 if (Exports
[I
].getInt())
573 for (unsigned I
= 0, N
= UnresolvedExports
.size(); I
!= N
; ++I
) {
574 OS
.indent(Indent
+ 2);
576 printModuleId(OS
, UnresolvedExports
[I
].Id
);
577 if (UnresolvedExports
[I
].Wildcard
)
578 OS
<< (UnresolvedExports
[I
].Id
.empty() ? "*" : ".*");
583 for (Module
*M
: Imports
) {
584 OS
.indent(Indent
+ 2);
585 llvm::errs() << "import " << M
->getFullModuleName() << "\n";
589 for (unsigned I
= 0, N
= DirectUses
.size(); I
!= N
; ++I
) {
590 OS
.indent(Indent
+ 2);
592 OS
<< DirectUses
[I
]->getFullModuleName(true);
596 for (unsigned I
= 0, N
= UnresolvedDirectUses
.size(); I
!= N
; ++I
) {
597 OS
.indent(Indent
+ 2);
599 printModuleId(OS
, UnresolvedDirectUses
[I
]);
603 for (unsigned I
= 0, N
= LinkLibraries
.size(); I
!= N
; ++I
) {
604 OS
.indent(Indent
+ 2);
606 if (LinkLibraries
[I
].IsFramework
)
609 OS
.write_escaped(LinkLibraries
[I
].Library
);
613 for (unsigned I
= 0, N
= UnresolvedConflicts
.size(); I
!= N
; ++I
) {
614 OS
.indent(Indent
+ 2);
616 printModuleId(OS
, UnresolvedConflicts
[I
].Id
);
618 OS
.write_escaped(UnresolvedConflicts
[I
].Message
);
622 for (unsigned I
= 0, N
= Conflicts
.size(); I
!= N
; ++I
) {
623 OS
.indent(Indent
+ 2);
625 OS
<< Conflicts
[I
].Other
->getFullModuleName(true);
627 OS
.write_escaped(Conflicts
[I
].Message
);
631 if (InferSubmodules
) {
632 OS
.indent(Indent
+ 2);
633 if (InferExplicitSubmodules
)
635 OS
<< "module * {\n";
636 if (InferExportWildcard
) {
637 OS
.indent(Indent
+ 4);
640 OS
.indent(Indent
+ 2);
648 LLVM_DUMP_METHOD
void Module::dump() const {
649 print(llvm::errs(), 0, true);
652 void VisibleModuleSet::setVisible(Module
*M
, SourceLocation Loc
,
653 VisibleCallback Vis
, ConflictCallback Cb
) {
654 // We can't import a global module fragment so the location can be invalid.
655 assert((M
->isGlobalModule() || Loc
.isValid()) &&
656 "setVisible expects a valid import location");
664 Visiting
*ExportedBy
;
667 std::function
<void(Visiting
)> VisitModule
= [&](Visiting V
) {
668 // Nothing to do for a module that's already visible.
669 unsigned ID
= V
.M
->getVisibilityID();
670 if (ImportLocs
.size() <= ID
)
671 ImportLocs
.resize(ID
+ 1);
672 else if (ImportLocs
[ID
].isValid())
675 ImportLocs
[ID
] = Loc
;
678 // Make any exported modules visible.
679 SmallVector
<Module
*, 16> Exports
;
680 V
.M
->getExportedModules(Exports
);
681 for (Module
*E
: Exports
) {
682 // Don't import non-importable modules.
683 if (!E
->isUnimportable())
684 VisitModule({E
, &V
});
687 for (auto &C
: V
.M
->Conflicts
) {
688 if (isVisible(C
.Other
)) {
689 llvm::SmallVector
<Module
*, 8> Path
;
690 for (Visiting
*I
= &V
; I
; I
= I
->ExportedBy
)
691 Path
.push_back(I
->M
);
692 Cb(Path
, C
.Other
, C
.Message
);
696 VisitModule({M
, nullptr});
699 void VisibleModuleSet::makeTransitiveImportsVisible(Module
*M
,
702 ConflictCallback Cb
) {
703 for (auto *I
: M
->Imports
)
704 setVisible(I
, Loc
, Vis
, Cb
);
707 ASTSourceDescriptor::ASTSourceDescriptor(Module
&M
)
708 : Signature(M
.Signature
), ClangModule(&M
) {
710 Path
= M
.Directory
->getName();
711 if (auto File
= M
.getASTFile())
712 ASTFile
= File
->getName();
715 std::string
ASTSourceDescriptor::getModuleName() const {
717 return ClangModule
->Name
;
719 return std::string(PCHModuleName
);