Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:36:50

0001 //===- Module.h - Describe a module -----------------------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 /// \file
0010 /// Defines the clang::Module class, which describes a module in the
0011 /// source code.
0012 //
0013 //===----------------------------------------------------------------------===//
0014 
0015 #ifndef LLVM_CLANG_BASIC_MODULE_H
0016 #define LLVM_CLANG_BASIC_MODULE_H
0017 
0018 #include "clang/Basic/DirectoryEntry.h"
0019 #include "clang/Basic/FileEntry.h"
0020 #include "clang/Basic/SourceLocation.h"
0021 #include "llvm/ADT/ArrayRef.h"
0022 #include "llvm/ADT/DenseSet.h"
0023 #include "llvm/ADT/PointerIntPair.h"
0024 #include "llvm/ADT/STLExtras.h"
0025 #include "llvm/ADT/SetVector.h"
0026 #include "llvm/ADT/SmallVector.h"
0027 #include "llvm/ADT/StringMap.h"
0028 #include "llvm/ADT/StringRef.h"
0029 #include "llvm/ADT/iterator_range.h"
0030 #include <array>
0031 #include <cassert>
0032 #include <cstdint>
0033 #include <ctime>
0034 #include <iterator>
0035 #include <optional>
0036 #include <string>
0037 #include <utility>
0038 #include <variant>
0039 #include <vector>
0040 
0041 namespace llvm {
0042 
0043 class raw_ostream;
0044 
0045 } // namespace llvm
0046 
0047 namespace clang {
0048 
0049 class FileManager;
0050 class LangOptions;
0051 class ModuleMap;
0052 class TargetInfo;
0053 
0054 /// Describes the name of a module.
0055 using ModuleId = SmallVector<std::pair<std::string, SourceLocation>, 2>;
0056 
0057 /// The signature of a module, which is a hash of the AST content.
0058 struct ASTFileSignature : std::array<uint8_t, 20> {
0059   using BaseT = std::array<uint8_t, 20>;
0060 
0061   static constexpr size_t size = std::tuple_size<BaseT>::value;
0062 
0063   ASTFileSignature(BaseT S = {{0}}) : BaseT(std::move(S)) {}
0064 
0065   explicit operator bool() const { return *this != BaseT({{0}}); }
0066 
0067   /// Returns the value truncated to the size of an uint64_t.
0068   uint64_t truncatedValue() const {
0069     uint64_t Value = 0;
0070     static_assert(sizeof(*this) >= sizeof(uint64_t), "No need to truncate.");
0071     for (unsigned I = 0; I < sizeof(uint64_t); ++I)
0072       Value |= static_cast<uint64_t>((*this)[I]) << (I * 8);
0073     return Value;
0074   }
0075 
0076   static ASTFileSignature create(std::array<uint8_t, 20> Bytes) {
0077     return ASTFileSignature(std::move(Bytes));
0078   }
0079 
0080   static ASTFileSignature createDISentinel() {
0081     ASTFileSignature Sentinel;
0082     Sentinel.fill(0xFF);
0083     return Sentinel;
0084   }
0085 
0086   static ASTFileSignature createDummy() {
0087     ASTFileSignature Dummy;
0088     Dummy.fill(0x00);
0089     return Dummy;
0090   }
0091 
0092   template <typename InputIt>
0093   static ASTFileSignature create(InputIt First, InputIt Last) {
0094     assert(std::distance(First, Last) == size &&
0095            "Wrong amount of bytes to create an ASTFileSignature");
0096 
0097     ASTFileSignature Signature;
0098     std::copy(First, Last, Signature.begin());
0099     return Signature;
0100   }
0101 };
0102 
0103 /// Required to construct a Module.
0104 ///
0105 /// This tag type is only constructible by ModuleMap, guaranteeing it ownership
0106 /// of all Module instances.
0107 class ModuleConstructorTag {
0108   explicit ModuleConstructorTag() = default;
0109   friend ModuleMap;
0110 };
0111 
0112 /// Describes a module or submodule.
0113 ///
0114 /// Aligned to 8 bytes to allow for llvm::PointerIntPair<Module *, 3>.
0115 class alignas(8) Module {
0116 public:
0117   /// The name of this module.
0118   std::string Name;
0119 
0120   /// The location of the module definition.
0121   SourceLocation DefinitionLoc;
0122 
0123   // FIXME: Consider if reducing the size of this enum (having Partition and
0124   // Named modules only) then representing interface/implementation separately
0125   // is more efficient.
0126   enum ModuleKind {
0127     /// This is a module that was defined by a module map and built out
0128     /// of header files.
0129     ModuleMapModule,
0130 
0131     /// This is a C++20 header unit.
0132     ModuleHeaderUnit,
0133 
0134     /// This is a C++20 module interface unit.
0135     ModuleInterfaceUnit,
0136 
0137     /// This is a C++20 module implementation unit.
0138     ModuleImplementationUnit,
0139 
0140     /// This is a C++20 module partition interface.
0141     ModulePartitionInterface,
0142 
0143     /// This is a C++20 module partition implementation.
0144     ModulePartitionImplementation,
0145 
0146     /// This is the explicit Global Module Fragment of a modular TU.
0147     /// As per C++ [module.global.frag].
0148     ExplicitGlobalModuleFragment,
0149 
0150     /// This is the private module fragment within some C++ module.
0151     PrivateModuleFragment,
0152 
0153     /// This is an implicit fragment of the global module which contains
0154     /// only language linkage declarations (made in the purview of the
0155     /// named module).
0156     ImplicitGlobalModuleFragment,
0157   };
0158 
0159   /// The kind of this module.
0160   ModuleKind Kind = ModuleMapModule;
0161 
0162   /// The parent of this module. This will be NULL for the top-level
0163   /// module.
0164   Module *Parent;
0165 
0166   /// The build directory of this module. This is the directory in
0167   /// which the module is notionally built, and relative to which its headers
0168   /// are found.
0169   OptionalDirectoryEntryRef Directory;
0170 
0171   /// The presumed file name for the module map defining this module.
0172   /// Only non-empty when building from preprocessed source.
0173   std::string PresumedModuleMapFile;
0174 
0175   /// The umbrella header or directory.
0176   std::variant<std::monostate, FileEntryRef, DirectoryEntryRef> Umbrella;
0177 
0178   /// The module signature.
0179   ASTFileSignature Signature;
0180 
0181   /// The name of the umbrella entry, as written in the module map.
0182   std::string UmbrellaAsWritten;
0183 
0184   // The path to the umbrella entry relative to the root module's \c Directory.
0185   std::string UmbrellaRelativeToRootModuleDirectory;
0186 
0187   /// The module through which entities defined in this module will
0188   /// eventually be exposed, for use in "private" modules.
0189   std::string ExportAsModule;
0190 
0191   /// For the debug info, the path to this module's .apinotes file, if any.
0192   std::string APINotesFile;
0193 
0194   /// Does this Module is a named module of a standard named module?
0195   bool isNamedModule() const {
0196     switch (Kind) {
0197     case ModuleInterfaceUnit:
0198     case ModuleImplementationUnit:
0199     case ModulePartitionInterface:
0200     case ModulePartitionImplementation:
0201     case PrivateModuleFragment:
0202       return true;
0203     default:
0204       return false;
0205     }
0206   }
0207 
0208   /// Does this Module scope describe a fragment of the global module within
0209   /// some C++ module.
0210   bool isGlobalModule() const {
0211     return isExplicitGlobalModule() || isImplicitGlobalModule();
0212   }
0213   bool isExplicitGlobalModule() const {
0214     return Kind == ExplicitGlobalModuleFragment;
0215   }
0216   bool isImplicitGlobalModule() const {
0217     return Kind == ImplicitGlobalModuleFragment;
0218   }
0219 
0220   bool isPrivateModule() const { return Kind == PrivateModuleFragment; }
0221 
0222   bool isModuleMapModule() const { return Kind == ModuleMapModule; }
0223 
0224 private:
0225   /// The submodules of this module, indexed by name.
0226   std::vector<Module *> SubModules;
0227 
0228   /// A mapping from the submodule name to the index into the
0229   /// \c SubModules vector at which that submodule resides.
0230   mutable llvm::StringMap<unsigned> SubModuleIndex;
0231 
0232   /// The AST file if this is a top-level module which has a
0233   /// corresponding serialized AST file, or null otherwise.
0234   OptionalFileEntryRef ASTFile;
0235 
0236   /// The top-level headers associated with this module.
0237   llvm::SmallSetVector<FileEntryRef, 2> TopHeaders;
0238 
0239   /// top-level header filenames that aren't resolved to FileEntries yet.
0240   std::vector<std::string> TopHeaderNames;
0241 
0242   /// Cache of modules visible to lookup in this module.
0243   mutable llvm::DenseSet<const Module*> VisibleModulesCache;
0244 
0245   /// The ID used when referencing this module within a VisibleModuleSet.
0246   unsigned VisibilityID;
0247 
0248 public:
0249   enum HeaderKind {
0250     HK_Normal,
0251     HK_Textual,
0252     HK_Private,
0253     HK_PrivateTextual,
0254     HK_Excluded
0255   };
0256   /// Information about a header directive as found in the module map
0257   /// file.
0258   struct Header {
0259     std::string NameAsWritten;
0260     std::string PathRelativeToRootModuleDirectory;
0261     FileEntryRef Entry;
0262   };
0263 
0264 private:
0265   static const int NumHeaderKinds = HK_Excluded + 1;
0266   // The begin index for a HeaderKind also acts the end index of HeaderKind - 1.
0267   // The extra element at the end acts as the end index of the last HeaderKind.
0268   unsigned HeaderKindBeginIndex[NumHeaderKinds + 1] = {};
0269   SmallVector<Header, 2> HeadersStorage;
0270 
0271 public:
0272   ArrayRef<Header> getAllHeaders() const { return HeadersStorage; }
0273   ArrayRef<Header> getHeaders(HeaderKind HK) const {
0274     assert(HK < NumHeaderKinds && "Invalid Module::HeaderKind");
0275     auto BeginIt = HeadersStorage.begin() + HeaderKindBeginIndex[HK];
0276     auto EndIt = HeadersStorage.begin() + HeaderKindBeginIndex[HK + 1];
0277     return {BeginIt, EndIt};
0278   }
0279   void addHeader(HeaderKind HK, Header H) {
0280     assert(HK < NumHeaderKinds && "Invalid Module::HeaderKind");
0281     auto EndIt = HeadersStorage.begin() + HeaderKindBeginIndex[HK + 1];
0282     HeadersStorage.insert(EndIt, std::move(H));
0283     for (unsigned HKI = HK + 1; HKI != NumHeaderKinds + 1; ++HKI)
0284       ++HeaderKindBeginIndex[HKI];
0285   }
0286 
0287   /// Information about a directory name as found in the module map file.
0288   struct DirectoryName {
0289     std::string NameAsWritten;
0290     std::string PathRelativeToRootModuleDirectory;
0291     DirectoryEntryRef Entry;
0292   };
0293 
0294   /// Stored information about a header directive that was found in the
0295   /// module map file but has not been resolved to a file.
0296   struct UnresolvedHeaderDirective {
0297     HeaderKind Kind = HK_Normal;
0298     SourceLocation FileNameLoc;
0299     std::string FileName;
0300     bool IsUmbrella = false;
0301     bool HasBuiltinHeader = false;
0302     std::optional<off_t> Size;
0303     std::optional<time_t> ModTime;
0304   };
0305 
0306   /// Headers that are mentioned in the module map file but that we have not
0307   /// yet attempted to resolve to a file on the file system.
0308   SmallVector<UnresolvedHeaderDirective, 1> UnresolvedHeaders;
0309 
0310   /// Headers that are mentioned in the module map file but could not be
0311   /// found on the file system.
0312   SmallVector<UnresolvedHeaderDirective, 1> MissingHeaders;
0313 
0314   struct Requirement {
0315     std::string FeatureName;
0316     bool RequiredState;
0317   };
0318 
0319   /// The set of language features required to use this module.
0320   ///
0321   /// If any of these requirements are not available, the \c IsAvailable bit
0322   /// will be false to indicate that this (sub)module is not available.
0323   SmallVector<Requirement, 2> Requirements;
0324 
0325   /// A module with the same name that shadows this module.
0326   Module *ShadowingModule = nullptr;
0327 
0328   /// Whether this module has declared itself unimportable, either because
0329   /// it's missing a requirement from \p Requirements or because it's been
0330   /// shadowed by another module.
0331   LLVM_PREFERRED_TYPE(bool)
0332   unsigned IsUnimportable : 1;
0333 
0334   /// Whether we tried and failed to load a module file for this module.
0335   LLVM_PREFERRED_TYPE(bool)
0336   unsigned HasIncompatibleModuleFile : 1;
0337 
0338   /// Whether this module is available in the current translation unit.
0339   ///
0340   /// If the module is missing headers or does not meet all requirements then
0341   /// this bit will be 0.
0342   LLVM_PREFERRED_TYPE(bool)
0343   unsigned IsAvailable : 1;
0344 
0345   /// Whether this module was loaded from a module file.
0346   LLVM_PREFERRED_TYPE(bool)
0347   unsigned IsFromModuleFile : 1;
0348 
0349   /// Whether this is a framework module.
0350   LLVM_PREFERRED_TYPE(bool)
0351   unsigned IsFramework : 1;
0352 
0353   /// Whether this is an explicit submodule.
0354   LLVM_PREFERRED_TYPE(bool)
0355   unsigned IsExplicit : 1;
0356 
0357   /// Whether this is a "system" module (which assumes that all
0358   /// headers in it are system headers).
0359   LLVM_PREFERRED_TYPE(bool)
0360   unsigned IsSystem : 1;
0361 
0362   /// Whether this is an 'extern "C"' module (which implicitly puts all
0363   /// headers in it within an 'extern "C"' block, and allows the module to be
0364   /// imported within such a block).
0365   LLVM_PREFERRED_TYPE(bool)
0366   unsigned IsExternC : 1;
0367 
0368   /// Whether this is an inferred submodule (module * { ... }).
0369   LLVM_PREFERRED_TYPE(bool)
0370   unsigned IsInferred : 1;
0371 
0372   /// Whether we should infer submodules for this module based on
0373   /// the headers.
0374   ///
0375   /// Submodules can only be inferred for modules with an umbrella header.
0376   LLVM_PREFERRED_TYPE(bool)
0377   unsigned InferSubmodules : 1;
0378 
0379   /// Whether, when inferring submodules, the inferred submodules
0380   /// should be explicit.
0381   LLVM_PREFERRED_TYPE(bool)
0382   unsigned InferExplicitSubmodules : 1;
0383 
0384   /// Whether, when inferring submodules, the inferr submodules should
0385   /// export all modules they import (e.g., the equivalent of "export *").
0386   LLVM_PREFERRED_TYPE(bool)
0387   unsigned InferExportWildcard : 1;
0388 
0389   /// Whether the set of configuration macros is exhaustive.
0390   ///
0391   /// When the set of configuration macros is exhaustive, meaning
0392   /// that no identifier not in this list should affect how the module is
0393   /// built.
0394   LLVM_PREFERRED_TYPE(bool)
0395   unsigned ConfigMacrosExhaustive : 1;
0396 
0397   /// Whether files in this module can only include non-modular headers
0398   /// and headers from used modules.
0399   LLVM_PREFERRED_TYPE(bool)
0400   unsigned NoUndeclaredIncludes : 1;
0401 
0402   /// Whether this module came from a "private" module map, found next
0403   /// to a regular (public) module map.
0404   LLVM_PREFERRED_TYPE(bool)
0405   unsigned ModuleMapIsPrivate : 1;
0406 
0407   /// Whether this C++20 named modules doesn't need an initializer.
0408   /// This is only meaningful for C++20 modules.
0409   LLVM_PREFERRED_TYPE(bool)
0410   unsigned NamedModuleHasInit : 1;
0411 
0412   /// Describes the visibility of the various names within a
0413   /// particular module.
0414   enum NameVisibilityKind {
0415     /// All of the names in this module are hidden.
0416     Hidden,
0417     /// All of the names in this module are visible.
0418     AllVisible
0419   };
0420 
0421   /// The visibility of names within this particular module.
0422   NameVisibilityKind NameVisibility;
0423 
0424   /// The location of the inferred submodule.
0425   SourceLocation InferredSubmoduleLoc;
0426 
0427   /// The set of modules imported by this module, and on which this
0428   /// module depends.
0429   llvm::SmallSetVector<Module *, 2> Imports;
0430 
0431   /// The set of top-level modules that affected the compilation of this module,
0432   /// but were not imported.
0433   llvm::SmallSetVector<Module *, 2> AffectingClangModules;
0434 
0435   /// Describes an exported module.
0436   ///
0437   /// The pointer is the module being re-exported, while the bit will be true
0438   /// to indicate that this is a wildcard export.
0439   using ExportDecl = llvm::PointerIntPair<Module *, 1, bool>;
0440 
0441   /// The set of export declarations.
0442   SmallVector<ExportDecl, 2> Exports;
0443 
0444   /// Describes an exported module that has not yet been resolved
0445   /// (perhaps because the module it refers to has not yet been loaded).
0446   struct UnresolvedExportDecl {
0447     /// The location of the 'export' keyword in the module map file.
0448     SourceLocation ExportLoc;
0449 
0450     /// The name of the module.
0451     ModuleId Id;
0452 
0453     /// Whether this export declaration ends in a wildcard, indicating
0454     /// that all of its submodules should be exported (rather than the named
0455     /// module itself).
0456     bool Wildcard;
0457   };
0458 
0459   /// The set of export declarations that have yet to be resolved.
0460   SmallVector<UnresolvedExportDecl, 2> UnresolvedExports;
0461 
0462   /// The directly used modules.
0463   SmallVector<Module *, 2> DirectUses;
0464 
0465   /// The set of use declarations that have yet to be resolved.
0466   SmallVector<ModuleId, 2> UnresolvedDirectUses;
0467 
0468   /// When \c NoUndeclaredIncludes is true, the set of modules this module tried
0469   /// to import but didn't because they are not direct uses.
0470   llvm::SmallSetVector<const Module *, 2> UndeclaredUses;
0471 
0472   /// A library or framework to link against when an entity from this
0473   /// module is used.
0474   struct LinkLibrary {
0475     LinkLibrary() = default;
0476     LinkLibrary(const std::string &Library, bool IsFramework)
0477         : Library(Library), IsFramework(IsFramework) {}
0478 
0479     /// The library to link against.
0480     ///
0481     /// This will typically be a library or framework name, but can also
0482     /// be an absolute path to the library or framework.
0483     std::string Library;
0484 
0485     /// Whether this is a framework rather than a library.
0486     bool IsFramework = false;
0487   };
0488 
0489   /// The set of libraries or frameworks to link against when
0490   /// an entity from this module is used.
0491   llvm::SmallVector<LinkLibrary, 2> LinkLibraries;
0492 
0493   /// Autolinking uses the framework name for linking purposes
0494   /// when this is false and the export_as name otherwise.
0495   bool UseExportAsModuleLinkName = false;
0496 
0497   /// The set of "configuration macros", which are macros that
0498   /// (intentionally) change how this module is built.
0499   std::vector<std::string> ConfigMacros;
0500 
0501   /// An unresolved conflict with another module.
0502   struct UnresolvedConflict {
0503     /// The (unresolved) module id.
0504     ModuleId Id;
0505 
0506     /// The message provided to the user when there is a conflict.
0507     std::string Message;
0508   };
0509 
0510   /// The list of conflicts for which the module-id has not yet been
0511   /// resolved.
0512   std::vector<UnresolvedConflict> UnresolvedConflicts;
0513 
0514   /// A conflict between two modules.
0515   struct Conflict {
0516     /// The module that this module conflicts with.
0517     Module *Other;
0518 
0519     /// The message provided to the user when there is a conflict.
0520     std::string Message;
0521   };
0522 
0523   /// The list of conflicts.
0524   std::vector<Conflict> Conflicts;
0525 
0526   /// Construct a new module or submodule.
0527   Module(ModuleConstructorTag, StringRef Name, SourceLocation DefinitionLoc,
0528          Module *Parent, bool IsFramework, bool IsExplicit,
0529          unsigned VisibilityID);
0530 
0531   ~Module();
0532 
0533   /// Determine whether this module has been declared unimportable.
0534   bool isUnimportable() const { return IsUnimportable; }
0535 
0536   /// Determine whether this module has been declared unimportable.
0537   ///
0538   /// \param LangOpts The language options used for the current
0539   /// translation unit.
0540   ///
0541   /// \param Target The target options used for the current translation unit.
0542   ///
0543   /// \param Req If this module is unimportable because of a missing
0544   /// requirement, this parameter will be set to one of the requirements that
0545   /// is not met for use of this module.
0546   ///
0547   /// \param ShadowingModule If this module is unimportable because it is
0548   /// shadowed, this parameter will be set to the shadowing module.
0549   bool isUnimportable(const LangOptions &LangOpts, const TargetInfo &Target,
0550                       Requirement &Req, Module *&ShadowingModule) const;
0551 
0552   /// Determine whether this module can be built in this compilation.
0553   bool isForBuilding(const LangOptions &LangOpts) const;
0554 
0555   /// Determine whether this module is available for use within the
0556   /// current translation unit.
0557   bool isAvailable() const { return IsAvailable; }
0558 
0559   /// Determine whether this module is available for use within the
0560   /// current translation unit.
0561   ///
0562   /// \param LangOpts The language options used for the current
0563   /// translation unit.
0564   ///
0565   /// \param Target The target options used for the current translation unit.
0566   ///
0567   /// \param Req If this module is unavailable because of a missing requirement,
0568   /// this parameter will be set to one of the requirements that is not met for
0569   /// use of this module.
0570   ///
0571   /// \param MissingHeader If this module is unavailable because of a missing
0572   /// header, this parameter will be set to one of the missing headers.
0573   ///
0574   /// \param ShadowingModule If this module is unavailable because it is
0575   /// shadowed, this parameter will be set to the shadowing module.
0576   bool isAvailable(const LangOptions &LangOpts,
0577                    const TargetInfo &Target,
0578                    Requirement &Req,
0579                    UnresolvedHeaderDirective &MissingHeader,
0580                    Module *&ShadowingModule) const;
0581 
0582   /// Determine whether this module is a submodule.
0583   bool isSubModule() const { return Parent != nullptr; }
0584 
0585   /// Check if this module is a (possibly transitive) submodule of \p Other.
0586   ///
0587   /// The 'A is a submodule of B' relation is a partial order based on the
0588   /// the parent-child relationship between individual modules.
0589   ///
0590   /// Returns \c false if \p Other is \c nullptr.
0591   bool isSubModuleOf(const Module *Other) const;
0592 
0593   /// Determine whether this module is a part of a framework,
0594   /// either because it is a framework module or because it is a submodule
0595   /// of a framework module.
0596   bool isPartOfFramework() const {
0597     for (const Module *Mod = this; Mod; Mod = Mod->Parent)
0598       if (Mod->IsFramework)
0599         return true;
0600 
0601     return false;
0602   }
0603 
0604   /// Determine whether this module is a subframework of another
0605   /// framework.
0606   bool isSubFramework() const {
0607     return IsFramework && Parent && Parent->isPartOfFramework();
0608   }
0609 
0610   /// Set the parent of this module. This should only be used if the parent
0611   /// could not be set during module creation.
0612   void setParent(Module *M) {
0613     assert(!Parent);
0614     Parent = M;
0615     Parent->SubModules.push_back(this);
0616   }
0617 
0618   /// Is this module have similar semantics as headers.
0619   bool isHeaderLikeModule() const {
0620     return isModuleMapModule() || isHeaderUnit();
0621   }
0622 
0623   /// Is this a module partition.
0624   bool isModulePartition() const {
0625     return Kind == ModulePartitionInterface ||
0626            Kind == ModulePartitionImplementation;
0627   }
0628 
0629   /// Is this a module partition implementation unit.
0630   bool isModulePartitionImplementation() const {
0631     return Kind == ModulePartitionImplementation;
0632   }
0633 
0634   /// Is this a module implementation.
0635   bool isModuleImplementation() const {
0636     return Kind == ModuleImplementationUnit;
0637   }
0638 
0639   /// Is this module a header unit.
0640   bool isHeaderUnit() const { return Kind == ModuleHeaderUnit; }
0641   // Is this a C++20 module interface or a partition.
0642   bool isInterfaceOrPartition() const {
0643     return Kind == ModuleInterfaceUnit || isModulePartition();
0644   }
0645 
0646   /// Is this a C++20 named module unit.
0647   bool isNamedModuleUnit() const {
0648     return isInterfaceOrPartition() || isModuleImplementation();
0649   }
0650 
0651   bool isModuleInterfaceUnit() const {
0652     return Kind == ModuleInterfaceUnit || Kind == ModulePartitionInterface;
0653   }
0654 
0655   bool isNamedModuleInterfaceHasInit() const { return NamedModuleHasInit; }
0656 
0657   /// Get the primary module interface name from a partition.
0658   StringRef getPrimaryModuleInterfaceName() const {
0659     // Technically, global module fragment belongs to global module. And global
0660     // module has no name: [module.unit]p6:
0661     //   The global module has no name, no module interface unit, and is not
0662     //   introduced by any module-declaration.
0663     //
0664     // <global> is the default name showed in module map.
0665     if (isGlobalModule())
0666       return "<global>";
0667 
0668     if (isModulePartition()) {
0669       auto pos = Name.find(':');
0670       return StringRef(Name.data(), pos);
0671     }
0672 
0673     if (isPrivateModule())
0674       return getTopLevelModuleName();
0675 
0676     return Name;
0677   }
0678 
0679   /// Retrieve the full name of this module, including the path from
0680   /// its top-level module.
0681   /// \param AllowStringLiterals If \c true, components that might not be
0682   ///        lexically valid as identifiers will be emitted as string literals.
0683   std::string getFullModuleName(bool AllowStringLiterals = false) const;
0684 
0685   /// Whether the full name of this module is equal to joining
0686   /// \p nameParts with "."s.
0687   ///
0688   /// This is more efficient than getFullModuleName().
0689   bool fullModuleNameIs(ArrayRef<StringRef> nameParts) const;
0690 
0691   /// Retrieve the top-level module for this (sub)module, which may
0692   /// be this module.
0693   Module *getTopLevelModule() {
0694     return const_cast<Module *>(
0695              const_cast<const Module *>(this)->getTopLevelModule());
0696   }
0697 
0698   /// Retrieve the top-level module for this (sub)module, which may
0699   /// be this module.
0700   const Module *getTopLevelModule() const;
0701 
0702   /// Retrieve the name of the top-level module.
0703   StringRef getTopLevelModuleName() const {
0704     return getTopLevelModule()->Name;
0705   }
0706 
0707   /// The serialized AST file for this module, if one was created.
0708   OptionalFileEntryRef getASTFile() const {
0709     return getTopLevelModule()->ASTFile;
0710   }
0711 
0712   /// Set the serialized AST file for the top-level module of this module.
0713   void setASTFile(OptionalFileEntryRef File) {
0714     assert((!getASTFile() || getASTFile() == File) && "file path changed");
0715     getTopLevelModule()->ASTFile = File;
0716   }
0717 
0718   /// Retrieve the umbrella directory as written.
0719   std::optional<DirectoryName> getUmbrellaDirAsWritten() const {
0720     if (const auto *Dir = std::get_if<DirectoryEntryRef>(&Umbrella))
0721       return DirectoryName{UmbrellaAsWritten,
0722                            UmbrellaRelativeToRootModuleDirectory, *Dir};
0723     return std::nullopt;
0724   }
0725 
0726   /// Retrieve the umbrella header as written.
0727   std::optional<Header> getUmbrellaHeaderAsWritten() const {
0728     if (const auto *Hdr = std::get_if<FileEntryRef>(&Umbrella))
0729       return Header{UmbrellaAsWritten, UmbrellaRelativeToRootModuleDirectory,
0730                     *Hdr};
0731     return std::nullopt;
0732   }
0733 
0734   /// Get the effective umbrella directory for this module: either the one
0735   /// explicitly written in the module map file, or the parent of the umbrella
0736   /// header.
0737   OptionalDirectoryEntryRef getEffectiveUmbrellaDir() const;
0738 
0739   /// Add a top-level header associated with this module.
0740   void addTopHeader(FileEntryRef File);
0741 
0742   /// Add a top-level header filename associated with this module.
0743   void addTopHeaderFilename(StringRef Filename) {
0744     TopHeaderNames.push_back(std::string(Filename));
0745   }
0746 
0747   /// The top-level headers associated with this module.
0748   ArrayRef<FileEntryRef> getTopHeaders(FileManager &FileMgr);
0749 
0750   /// Determine whether this module has declared its intention to
0751   /// directly use another module.
0752   bool directlyUses(const Module *Requested);
0753 
0754   /// Add the given feature requirement to the list of features
0755   /// required by this module.
0756   ///
0757   /// \param Feature The feature that is required by this module (and
0758   /// its submodules).
0759   ///
0760   /// \param RequiredState The required state of this feature: \c true
0761   /// if it must be present, \c false if it must be absent.
0762   ///
0763   /// \param LangOpts The set of language options that will be used to
0764   /// evaluate the availability of this feature.
0765   ///
0766   /// \param Target The target options that will be used to evaluate the
0767   /// availability of this feature.
0768   void addRequirement(StringRef Feature, bool RequiredState,
0769                       const LangOptions &LangOpts,
0770                       const TargetInfo &Target);
0771 
0772   /// Mark this module and all of its submodules as unavailable.
0773   void markUnavailable(bool Unimportable);
0774 
0775   /// Find the submodule with the given name.
0776   ///
0777   /// \returns The submodule if found, or NULL otherwise.
0778   Module *findSubmodule(StringRef Name) const;
0779 
0780   /// Get the Global Module Fragment (sub-module) for this module, it there is
0781   /// one.
0782   ///
0783   /// \returns The GMF sub-module if found, or NULL otherwise.
0784   Module *getGlobalModuleFragment() const;
0785 
0786   /// Get the Private Module Fragment (sub-module) for this module, it there is
0787   /// one.
0788   ///
0789   /// \returns The PMF sub-module if found, or NULL otherwise.
0790   Module *getPrivateModuleFragment() const;
0791 
0792   /// Determine whether the specified module would be visible to
0793   /// a lookup at the end of this module.
0794   ///
0795   /// FIXME: This may return incorrect results for (submodules of) the
0796   /// module currently being built, if it's queried before we see all
0797   /// of its imports.
0798   bool isModuleVisible(const Module *M) const {
0799     if (VisibleModulesCache.empty())
0800       buildVisibleModulesCache();
0801     return VisibleModulesCache.count(M);
0802   }
0803 
0804   unsigned getVisibilityID() const { return VisibilityID; }
0805 
0806   using submodule_iterator = std::vector<Module *>::iterator;
0807   using submodule_const_iterator = std::vector<Module *>::const_iterator;
0808 
0809   llvm::iterator_range<submodule_iterator> submodules() {
0810     return llvm::make_range(SubModules.begin(), SubModules.end());
0811   }
0812   llvm::iterator_range<submodule_const_iterator> submodules() const {
0813     return llvm::make_range(SubModules.begin(), SubModules.end());
0814   }
0815 
0816   /// Appends this module's list of exported modules to \p Exported.
0817   ///
0818   /// This provides a subset of immediately imported modules (the ones that are
0819   /// directly exported), not the complete set of exported modules.
0820   void getExportedModules(SmallVectorImpl<Module *> &Exported) const;
0821 
0822   static StringRef getModuleInputBufferName() {
0823     return "<module-includes>";
0824   }
0825 
0826   /// Print the module map for this module to the given stream.
0827   void print(raw_ostream &OS, unsigned Indent = 0, bool Dump = false) const;
0828 
0829   /// Dump the contents of this module to the given output stream.
0830   void dump() const;
0831 
0832 private:
0833   void buildVisibleModulesCache() const;
0834 };
0835 
0836 /// A set of visible modules.
0837 class VisibleModuleSet {
0838 public:
0839   VisibleModuleSet() = default;
0840   VisibleModuleSet(VisibleModuleSet &&O)
0841       : ImportLocs(std::move(O.ImportLocs)), Generation(O.Generation ? 1 : 0) {
0842     O.ImportLocs.clear();
0843     ++O.Generation;
0844   }
0845 
0846   /// Move from another visible modules set. Guaranteed to leave the source
0847   /// empty and bump the generation on both.
0848   VisibleModuleSet &operator=(VisibleModuleSet &&O) {
0849     ImportLocs = std::move(O.ImportLocs);
0850     O.ImportLocs.clear();
0851     ++O.Generation;
0852     ++Generation;
0853     return *this;
0854   }
0855 
0856   /// Get the current visibility generation. Incremented each time the
0857   /// set of visible modules changes in any way.
0858   unsigned getGeneration() const { return Generation; }
0859 
0860   /// Determine whether a module is visible.
0861   bool isVisible(const Module *M) const {
0862     return getImportLoc(M).isValid();
0863   }
0864 
0865   /// Get the location at which the import of a module was triggered.
0866   SourceLocation getImportLoc(const Module *M) const {
0867     return M->getVisibilityID() < ImportLocs.size()
0868                ? ImportLocs[M->getVisibilityID()]
0869                : SourceLocation();
0870   }
0871 
0872   /// A callback to call when a module is made visible (directly or
0873   /// indirectly) by a call to \ref setVisible.
0874   using VisibleCallback = llvm::function_ref<void(Module *M)>;
0875 
0876   /// A callback to call when a module conflict is found. \p Path
0877   /// consists of a sequence of modules from the conflicting module to the one
0878   /// made visible, where each was exported by the next.
0879   using ConflictCallback =
0880       llvm::function_ref<void(ArrayRef<Module *> Path, Module *Conflict,
0881                          StringRef Message)>;
0882 
0883   /// Make a specific module visible.
0884   void setVisible(Module *M, SourceLocation Loc,
0885                   VisibleCallback Vis = [](Module *) {},
0886                   ConflictCallback Cb = [](ArrayRef<Module *>, Module *,
0887                                            StringRef) {});
0888 private:
0889   /// Import locations for each visible module. Indexed by the module's
0890   /// VisibilityID.
0891   std::vector<SourceLocation> ImportLocs;
0892 
0893   /// Visibility generation, bumped every time the visibility state changes.
0894   unsigned Generation = 0;
0895 };
0896 
0897 } // namespace clang
0898 
0899 #endif // LLVM_CLANG_BASIC_MODULE_H