Back to home page

EIC code displayed by LXR

 
 

    


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

0001 //===- ModuleMap.h - Describe the layout of modules -------------*- 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 // This file defines the ModuleMap interface, which describes the layout of a
0010 // module as it relates to headers.
0011 //
0012 //===----------------------------------------------------------------------===//
0013 
0014 #ifndef LLVM_CLANG_LEX_MODULEMAP_H
0015 #define LLVM_CLANG_LEX_MODULEMAP_H
0016 
0017 #include "clang/Basic/IdentifierTable.h"
0018 #include "clang/Basic/LangOptions.h"
0019 #include "clang/Basic/Module.h"
0020 #include "clang/Basic/SourceLocation.h"
0021 #include "llvm/ADT/ArrayRef.h"
0022 #include "llvm/ADT/DenseMap.h"
0023 #include "llvm/ADT/DenseSet.h"
0024 #include "llvm/ADT/PointerIntPair.h"
0025 #include "llvm/ADT/SmallVector.h"
0026 #include "llvm/ADT/StringMap.h"
0027 #include "llvm/ADT/StringRef.h"
0028 #include "llvm/ADT/StringSet.h"
0029 #include "llvm/ADT/TinyPtrVector.h"
0030 #include "llvm/ADT/Twine.h"
0031 #include <ctime>
0032 #include <memory>
0033 #include <optional>
0034 #include <string>
0035 #include <utility>
0036 
0037 namespace clang {
0038 
0039 class DiagnosticsEngine;
0040 class DirectoryEntry;
0041 class FileEntry;
0042 class FileManager;
0043 class HeaderSearch;
0044 class SourceManager;
0045 
0046 /// A mechanism to observe the actions of the module map parser as it
0047 /// reads module map files.
0048 class ModuleMapCallbacks {
0049   virtual void anchor();
0050 
0051 public:
0052   virtual ~ModuleMapCallbacks() = default;
0053 
0054   /// Called when a module map file has been read.
0055   ///
0056   /// \param FileStart A SourceLocation referring to the start of the file's
0057   /// contents.
0058   /// \param File The file itself.
0059   /// \param IsSystem Whether this is a module map from a system include path.
0060   virtual void moduleMapFileRead(SourceLocation FileStart, FileEntryRef File,
0061                                  bool IsSystem) {}
0062 
0063   /// Called when a header is added during module map parsing.
0064   ///
0065   /// \param Filename The header file itself.
0066   virtual void moduleMapAddHeader(StringRef Filename) {}
0067 
0068   /// Called when an umbrella header is added during module map parsing.
0069   ///
0070   /// \param Header The umbrella header to collect.
0071   virtual void moduleMapAddUmbrellaHeader(FileEntryRef Header) {}
0072 };
0073 
0074 class ModuleMap {
0075   SourceManager &SourceMgr;
0076   DiagnosticsEngine &Diags;
0077   const LangOptions &LangOpts;
0078   const TargetInfo *Target;
0079   HeaderSearch &HeaderInfo;
0080 
0081   llvm::SmallVector<std::unique_ptr<ModuleMapCallbacks>, 1> Callbacks;
0082 
0083   /// The directory used for Clang-supplied, builtin include headers,
0084   /// such as "stdint.h".
0085   OptionalDirectoryEntryRef BuiltinIncludeDir;
0086 
0087   /// Language options used to parse the module map itself.
0088   ///
0089   /// These are always simple C language options.
0090   LangOptions MMapLangOpts;
0091 
0092   /// The module that the main source file is associated with (the module
0093   /// named LangOpts::CurrentModule, if we've loaded it).
0094   Module *SourceModule = nullptr;
0095 
0096   /// The allocator for all (sub)modules.
0097   llvm::SpecificBumpPtrAllocator<Module> ModulesAlloc;
0098 
0099   /// Submodules of the current module that have not yet been attached to it.
0100   /// (Relationship is set up if/when we create an enclosing module.)
0101   llvm::SmallVector<Module *, 8> PendingSubmodules;
0102 
0103   /// The top-level modules that are known.
0104   llvm::StringMap<Module *> Modules;
0105 
0106   /// Module loading cache that includes submodules, indexed by IdentifierInfo.
0107   /// nullptr is stored for modules that are known to fail to load.
0108   llvm::DenseMap<const IdentifierInfo *, Module *> CachedModuleLoads;
0109 
0110   /// Shadow modules created while building this module map.
0111   llvm::SmallVector<Module*, 2> ShadowModules;
0112 
0113   /// The number of modules we have created in total.
0114   unsigned NumCreatedModules = 0;
0115 
0116   /// In case a module has a export_as entry, it might have a pending link
0117   /// name to be determined if that module is imported.
0118   llvm::StringMap<llvm::StringSet<>> PendingLinkAsModule;
0119 
0120 public:
0121   /// Use PendingLinkAsModule information to mark top level link names that
0122   /// are going to be replaced by export_as aliases.
0123   void resolveLinkAsDependencies(Module *Mod);
0124 
0125   /// Make module to use export_as as the link dependency name if enough
0126   /// information is available or add it to a pending list otherwise.
0127   void addLinkAsDependency(Module *Mod);
0128 
0129   /// Flags describing the role of a module header.
0130   enum ModuleHeaderRole {
0131     /// This header is normally included in the module.
0132     NormalHeader  = 0x0,
0133 
0134     /// This header is included but private.
0135     PrivateHeader = 0x1,
0136 
0137     /// This header is part of the module (for layering purposes) but
0138     /// should be textually included.
0139     TextualHeader = 0x2,
0140 
0141     /// This header is explicitly excluded from the module.
0142     ExcludedHeader = 0x4,
0143 
0144     // Caution: Adding an enumerator needs other changes.
0145     // Adjust the number of bits for KnownHeader::Storage.
0146     // Adjust the HeaderFileInfoTrait::ReadData streaming.
0147     // Adjust the HeaderFileInfoTrait::EmitData streaming.
0148     // Adjust ModuleMap::addHeader.
0149   };
0150 
0151   /// Convert a header kind to a role. Requires Kind to not be HK_Excluded.
0152   static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind);
0153 
0154   /// Convert a header role to a kind.
0155   static Module::HeaderKind headerRoleToKind(ModuleHeaderRole Role);
0156 
0157   /// Check if the header with the given role is a modular one.
0158   static bool isModular(ModuleHeaderRole Role);
0159 
0160   /// A header that is known to reside within a given module,
0161   /// whether it was included or excluded.
0162   class KnownHeader {
0163     llvm::PointerIntPair<Module *, 3, ModuleHeaderRole> Storage;
0164 
0165   public:
0166     KnownHeader() : Storage(nullptr, NormalHeader) {}
0167     KnownHeader(Module *M, ModuleHeaderRole Role) : Storage(M, Role) {}
0168 
0169     friend bool operator==(const KnownHeader &A, const KnownHeader &B) {
0170       return A.Storage == B.Storage;
0171     }
0172     friend bool operator!=(const KnownHeader &A, const KnownHeader &B) {
0173       return A.Storage != B.Storage;
0174     }
0175 
0176     /// Retrieve the module the header is stored in.
0177     Module *getModule() const { return Storage.getPointer(); }
0178 
0179     /// The role of this header within the module.
0180     ModuleHeaderRole getRole() const { return Storage.getInt(); }
0181 
0182     /// Whether this header is available in the module.
0183     bool isAvailable() const {
0184       return getRole() != ExcludedHeader && getModule()->isAvailable();
0185     }
0186 
0187     /// Whether this header is accessible from the specified module.
0188     bool isAccessibleFrom(Module *M) const {
0189       return !(getRole() & PrivateHeader) ||
0190              (M && M->getTopLevelModule() == getModule()->getTopLevelModule());
0191     }
0192 
0193     // Whether this known header is valid (i.e., it has an
0194     // associated module).
0195     explicit operator bool() const {
0196       return Storage.getPointer() != nullptr;
0197     }
0198   };
0199 
0200   using AdditionalModMapsSet = llvm::DenseSet<FileEntryRef>;
0201 
0202 private:
0203   friend class ModuleMapParser;
0204 
0205   using HeadersMap = llvm::DenseMap<FileEntryRef, SmallVector<KnownHeader, 1>>;
0206 
0207   /// Mapping from each header to the module that owns the contents of
0208   /// that header.
0209   HeadersMap Headers;
0210 
0211   /// Map from file sizes to modules with lazy header directives of that size.
0212   mutable llvm::DenseMap<off_t, llvm::TinyPtrVector<Module*>> LazyHeadersBySize;
0213 
0214   /// Map from mtimes to modules with lazy header directives with those mtimes.
0215   mutable llvm::DenseMap<time_t, llvm::TinyPtrVector<Module*>>
0216               LazyHeadersByModTime;
0217 
0218   /// Mapping from directories with umbrella headers to the module
0219   /// that is generated from the umbrella header.
0220   ///
0221   /// This mapping is used to map headers that haven't explicitly been named
0222   /// in the module map over to the module that includes them via its umbrella
0223   /// header.
0224   llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs;
0225 
0226   /// A generation counter that is used to test whether modules of the
0227   /// same name may shadow or are illegal redefinitions.
0228   ///
0229   /// Modules from earlier scopes may shadow modules from later ones.
0230   /// Modules from the same scope may not have the same name.
0231   unsigned CurrentModuleScopeID = 0;
0232 
0233   llvm::DenseMap<Module *, unsigned> ModuleScopeIDs;
0234 
0235   /// The set of attributes that can be attached to a module.
0236   struct Attributes {
0237     /// Whether this is a system module.
0238     LLVM_PREFERRED_TYPE(bool)
0239     unsigned IsSystem : 1;
0240 
0241     /// Whether this is an extern "C" module.
0242     LLVM_PREFERRED_TYPE(bool)
0243     unsigned IsExternC : 1;
0244 
0245     /// Whether this is an exhaustive set of configuration macros.
0246     LLVM_PREFERRED_TYPE(bool)
0247     unsigned IsExhaustive : 1;
0248 
0249     /// Whether files in this module can only include non-modular headers
0250     /// and headers from used modules.
0251     LLVM_PREFERRED_TYPE(bool)
0252     unsigned NoUndeclaredIncludes : 1;
0253 
0254     Attributes()
0255         : IsSystem(false), IsExternC(false), IsExhaustive(false),
0256           NoUndeclaredIncludes(false) {}
0257   };
0258 
0259   /// A directory for which framework modules can be inferred.
0260   struct InferredDirectory {
0261     /// Whether to infer modules from this directory.
0262     LLVM_PREFERRED_TYPE(bool)
0263     unsigned InferModules : 1;
0264 
0265     /// The attributes to use for inferred modules.
0266     Attributes Attrs;
0267 
0268     /// If \c InferModules is non-zero, the module map file that allowed
0269     /// inferred modules.  Otherwise, invalid.
0270     FileID ModuleMapFID;
0271 
0272     /// The names of modules that cannot be inferred within this
0273     /// directory.
0274     SmallVector<std::string, 2> ExcludedModules;
0275 
0276     InferredDirectory() : InferModules(false) {}
0277   };
0278 
0279   /// A mapping from directories to information about inferring
0280   /// framework modules from within those directories.
0281   llvm::DenseMap<const DirectoryEntry *, InferredDirectory> InferredDirectories;
0282 
0283   /// A mapping from an inferred module to the module map that allowed the
0284   /// inference.
0285   llvm::DenseMap<const Module *, FileID> InferredModuleAllowedBy;
0286 
0287   llvm::DenseMap<const Module *, AdditionalModMapsSet> AdditionalModMaps;
0288 
0289   /// Describes whether we haved parsed a particular file as a module
0290   /// map.
0291   llvm::DenseMap<const FileEntry *, bool> ParsedModuleMap;
0292 
0293   /// Resolve the given export declaration into an actual export
0294   /// declaration.
0295   ///
0296   /// \param Mod The module in which we're resolving the export declaration.
0297   ///
0298   /// \param Unresolved The export declaration to resolve.
0299   ///
0300   /// \param Complain Whether this routine should complain about unresolvable
0301   /// exports.
0302   ///
0303   /// \returns The resolved export declaration, which will have a NULL pointer
0304   /// if the export could not be resolved.
0305   Module::ExportDecl
0306   resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved,
0307                 bool Complain) const;
0308 
0309   /// Resolve the given module id to an actual module.
0310   ///
0311   /// \param Id The module-id to resolve.
0312   ///
0313   /// \param Mod The module in which we're resolving the module-id.
0314   ///
0315   /// \param Complain Whether this routine should complain about unresolvable
0316   /// module-ids.
0317   ///
0318   /// \returns The resolved module, or null if the module-id could not be
0319   /// resolved.
0320   Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const;
0321 
0322   /// Add an unresolved header to a module.
0323   ///
0324   /// \param Mod The module in which we're adding the unresolved header
0325   ///        directive.
0326   /// \param Header The unresolved header directive.
0327   /// \param NeedsFramework If Mod is not a framework but a missing header would
0328   ///        be found in case Mod was, set it to true. False otherwise.
0329   void addUnresolvedHeader(Module *Mod,
0330                            Module::UnresolvedHeaderDirective Header,
0331                            bool &NeedsFramework);
0332 
0333   /// Look up the given header directive to find an actual header file.
0334   ///
0335   /// \param M The module in which we're resolving the header directive.
0336   /// \param Header The header directive to resolve.
0337   /// \param RelativePathName Filled in with the relative path name from the
0338   ///        module to the resolved header.
0339   /// \param NeedsFramework If M is not a framework but a missing header would
0340   ///        be found in case M was, set it to true. False otherwise.
0341   /// \return The resolved file, if any.
0342   OptionalFileEntryRef
0343   findHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
0344              SmallVectorImpl<char> &RelativePathName, bool &NeedsFramework);
0345 
0346   /// Resolve the given header directive.
0347   ///
0348   /// \param M The module in which we're resolving the header directive.
0349   /// \param Header The header directive to resolve.
0350   /// \param NeedsFramework If M is not a framework but a missing header would
0351   ///        be found in case M was, set it to true. False otherwise.
0352   void resolveHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
0353                      bool &NeedsFramework);
0354 
0355   /// Attempt to resolve the specified header directive as naming a builtin
0356   /// header.
0357   /// \return \c true if a corresponding builtin header was found.
0358   bool resolveAsBuiltinHeader(Module *M,
0359                               const Module::UnresolvedHeaderDirective &Header);
0360 
0361   /// Looks up the modules that \p File corresponds to.
0362   ///
0363   /// If \p File represents a builtin header within Clang's builtin include
0364   /// directory, this also loads all of the module maps to see if it will get
0365   /// associated with a specific module (e.g. in /usr/include).
0366   HeadersMap::iterator findKnownHeader(FileEntryRef File);
0367 
0368   /// Searches for a module whose umbrella directory contains \p File.
0369   ///
0370   /// \param File The header to search for.
0371   ///
0372   /// \param IntermediateDirs On success, contains the set of directories
0373   /// searched before finding \p File.
0374   KnownHeader findHeaderInUmbrellaDirs(
0375       FileEntryRef File, SmallVectorImpl<DirectoryEntryRef> &IntermediateDirs);
0376 
0377   /// Given that \p File is not in the Headers map, look it up within
0378   /// umbrella directories and find or create a module for it.
0379   KnownHeader findOrCreateModuleForHeaderInUmbrellaDir(FileEntryRef File);
0380 
0381   /// A convenience method to determine if \p File is (possibly nested)
0382   /// in an umbrella directory.
0383   bool isHeaderInUmbrellaDirs(FileEntryRef File) {
0384     SmallVector<DirectoryEntryRef, 2> IntermediateDirs;
0385     return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
0386   }
0387 
0388   Module *inferFrameworkModule(DirectoryEntryRef FrameworkDir, Attributes Attrs,
0389                                Module *Parent);
0390 
0391 public:
0392   /// Construct a new module map.
0393   ///
0394   /// \param SourceMgr The source manager used to find module files and headers.
0395   /// This source manager should be shared with the header-search mechanism,
0396   /// since they will refer to the same headers.
0397   ///
0398   /// \param Diags A diagnostic engine used for diagnostics.
0399   ///
0400   /// \param LangOpts Language options for this translation unit.
0401   ///
0402   /// \param Target The target for this translation unit.
0403   ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
0404             const LangOptions &LangOpts, const TargetInfo *Target,
0405             HeaderSearch &HeaderInfo);
0406 
0407   /// Destroy the module map.
0408   ~ModuleMap();
0409 
0410   /// Set the target information.
0411   void setTarget(const TargetInfo &Target);
0412 
0413   /// Set the directory that contains Clang-supplied include files, such as our
0414   /// stdarg.h or tgmath.h.
0415   void setBuiltinIncludeDir(DirectoryEntryRef Dir) { BuiltinIncludeDir = Dir; }
0416 
0417   /// Get the directory that contains Clang-supplied include files.
0418   OptionalDirectoryEntryRef getBuiltinDir() const { return BuiltinIncludeDir; }
0419 
0420   /// Is this a compiler builtin header?
0421   bool isBuiltinHeader(FileEntryRef File);
0422 
0423   bool shouldImportRelativeToBuiltinIncludeDir(StringRef FileName,
0424                                                Module *Module) const;
0425 
0426   /// Add a module map callback.
0427   void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
0428     Callbacks.push_back(std::move(Callback));
0429   }
0430 
0431   /// Retrieve the module that owns the given header file, if any. Note that
0432   /// this does not implicitly load module maps, except for builtin headers,
0433   /// and does not consult the external source. (Those checks are the
0434   /// responsibility of \ref HeaderSearch.)
0435   ///
0436   /// \param File The header file that is likely to be included.
0437   ///
0438   /// \param AllowTextual If \c true and \p File is a textual header, return
0439   /// its owning module. Otherwise, no KnownHeader will be returned if the
0440   /// file is only known as a textual header.
0441   ///
0442   /// \returns The module KnownHeader, which provides the module that owns the
0443   /// given header file.  The KnownHeader is default constructed to indicate
0444   /// that no module owns this header file.
0445   KnownHeader findModuleForHeader(FileEntryRef File, bool AllowTextual = false,
0446                                   bool AllowExcluded = false);
0447 
0448   /// Retrieve all the modules that contain the given header file. Note that
0449   /// this does not implicitly load module maps, except for builtin headers,
0450   /// and does not consult the external source. (Those checks are the
0451   /// responsibility of \ref HeaderSearch.)
0452   ///
0453   /// Typically, \ref findModuleForHeader should be used instead, as it picks
0454   /// the preferred module for the header.
0455   ArrayRef<KnownHeader> findAllModulesForHeader(FileEntryRef File);
0456 
0457   /// Like \ref findAllModulesForHeader, but do not attempt to infer module
0458   /// ownership from umbrella headers if we've not already done so.
0459   ArrayRef<KnownHeader> findResolvedModulesForHeader(FileEntryRef File) const;
0460 
0461   /// Resolve all lazy header directives for the specified file.
0462   ///
0463   /// This ensures that the HeaderFileInfo on HeaderSearch is up to date. This
0464   /// is effectively internal, but is exposed so HeaderSearch can call it.
0465   void resolveHeaderDirectives(const FileEntry *File) const;
0466 
0467   /// Resolve lazy header directives for the specified module. If File is
0468   /// provided, only headers with same size and modtime are resolved. If File
0469   /// is not set, all headers are resolved.
0470   void resolveHeaderDirectives(Module *Mod,
0471                                std::optional<const FileEntry *> File) const;
0472 
0473   /// Reports errors if a module must not include a specific file.
0474   ///
0475   /// \param RequestingModule The module including a file.
0476   ///
0477   /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in
0478   ///        the interface of RequestingModule, \c false if it's in the
0479   ///        implementation of RequestingModule. Value is ignored and
0480   ///        meaningless if RequestingModule is nullptr.
0481   ///
0482   /// \param FilenameLoc The location of the inclusion's filename.
0483   ///
0484   /// \param Filename The included filename as written.
0485   ///
0486   /// \param File The included file.
0487   void diagnoseHeaderInclusion(Module *RequestingModule,
0488                                bool RequestingModuleIsModuleInterface,
0489                                SourceLocation FilenameLoc, StringRef Filename,
0490                                FileEntryRef File);
0491 
0492   /// Determine whether the given header is part of a module
0493   /// marked 'unavailable'.
0494   bool isHeaderInUnavailableModule(FileEntryRef Header) const;
0495 
0496   /// Determine whether the given header is unavailable as part
0497   /// of the specified module.
0498   bool isHeaderUnavailableInModule(FileEntryRef Header,
0499                                    const Module *RequestingModule) const;
0500 
0501   /// Retrieve a module with the given name.
0502   ///
0503   /// \param Name The name of the module to look up.
0504   ///
0505   /// \returns The named module, if known; otherwise, returns null.
0506   Module *findModule(StringRef Name) const;
0507 
0508   Module *findOrInferSubmodule(Module *Parent, StringRef Name);
0509 
0510   /// Retrieve a module with the given name using lexical name lookup,
0511   /// starting at the given context.
0512   ///
0513   /// \param Name The name of the module to look up.
0514   ///
0515   /// \param Context The module context, from which we will perform lexical
0516   /// name lookup.
0517   ///
0518   /// \returns The named module, if known; otherwise, returns null.
0519   Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
0520 
0521   /// Retrieve a module with the given name within the given context,
0522   /// using direct (qualified) name lookup.
0523   ///
0524   /// \param Name The name of the module to look up.
0525   ///
0526   /// \param Context The module for which we will look for a submodule. If
0527   /// null, we will look for a top-level module.
0528   ///
0529   /// \returns The named submodule, if known; otherwose, returns null.
0530   Module *lookupModuleQualified(StringRef Name, Module *Context) const;
0531 
0532   /// Find a new module or submodule, or create it if it does not already
0533   /// exist.
0534   ///
0535   /// \param Name The name of the module to find or create.
0536   ///
0537   /// \param Parent The module that will act as the parent of this submodule,
0538   /// or nullptr to indicate that this is a top-level module.
0539   ///
0540   /// \param IsFramework Whether this is a framework module.
0541   ///
0542   /// \param IsExplicit Whether this is an explicit submodule.
0543   ///
0544   /// \returns The found or newly-created module, along with a boolean value
0545   /// that will be true if the module is newly-created.
0546   std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
0547                                                bool IsFramework,
0548                                                bool IsExplicit);
0549   /// Call \c ModuleMap::findOrCreateModule and throw away the information
0550   /// whether the module was found or created.
0551   Module *findOrCreateModuleFirst(StringRef Name, Module *Parent,
0552                                   bool IsFramework, bool IsExplicit) {
0553     return findOrCreateModule(Name, Parent, IsFramework, IsExplicit).first;
0554   }
0555   /// Create new submodule, assuming it does not exist. This function can only
0556   /// be called when it is guaranteed that this submodule does not exist yet.
0557   /// The parameters have same semantics as \c ModuleMap::findOrCreateModule.
0558   Module *createModule(StringRef Name, Module *Parent, bool IsFramework,
0559                        bool IsExplicit);
0560 
0561   /// Create a global module fragment for a C++ module unit.
0562   ///
0563   /// We model the global module fragment as a submodule of the module
0564   /// interface unit. Unfortunately, we can't create the module interface
0565   /// unit's Module until later, because we don't know what it will be called
0566   /// usually. See C++20 [module.unit]/7.2 for the case we could know its
0567   /// parent.
0568   Module *createGlobalModuleFragmentForModuleUnit(SourceLocation Loc,
0569                                                   Module *Parent = nullptr);
0570   Module *createImplicitGlobalModuleFragmentForModuleUnit(SourceLocation Loc,
0571                                                           Module *Parent);
0572 
0573   /// Create a global module fragment for a C++ module interface unit.
0574   Module *createPrivateModuleFragmentForInterfaceUnit(Module *Parent,
0575                                                       SourceLocation Loc);
0576 
0577   /// Create a new C++ module with the specified kind, and reparent any pending
0578   /// global module fragment(s) to it.
0579   Module *createModuleUnitWithKind(SourceLocation Loc, StringRef Name,
0580                                    Module::ModuleKind Kind);
0581 
0582   /// Create a new module for a C++ module interface unit.
0583   /// The module must not already exist, and will be configured for the current
0584   /// compilation.
0585   ///
0586   /// Note that this also sets the current module to the newly-created module.
0587   ///
0588   /// \returns The newly-created module.
0589   Module *createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name);
0590 
0591   /// Create a new module for a C++ module implementation unit.
0592   /// The interface module for this implementation (implicitly imported) must
0593   /// exist and be loaded and present in the modules map.
0594   ///
0595   /// \returns The newly-created module.
0596   Module *createModuleForImplementationUnit(SourceLocation Loc, StringRef Name);
0597 
0598   /// Create a C++20 header unit.
0599   Module *createHeaderUnit(SourceLocation Loc, StringRef Name,
0600                            Module::Header H);
0601 
0602   /// Infer the contents of a framework module map from the given
0603   /// framework directory.
0604   Module *inferFrameworkModule(DirectoryEntryRef FrameworkDir, bool IsSystem,
0605                                Module *Parent);
0606 
0607   /// Create a new top-level module that is shadowed by
0608   /// \p ShadowingModule.
0609   Module *createShadowedModule(StringRef Name, bool IsFramework,
0610                                Module *ShadowingModule);
0611 
0612   /// Creates a new declaration scope for module names, allowing
0613   /// previously defined modules to shadow definitions from the new scope.
0614   ///
0615   /// \note Module names from earlier scopes will shadow names from the new
0616   /// scope, which is the opposite of how shadowing works for variables.
0617   void finishModuleDeclarationScope() { CurrentModuleScopeID += 1; }
0618 
0619   bool mayShadowNewModule(Module *ExistingModule) {
0620     assert(!ExistingModule->Parent && "expected top-level module");
0621     assert(ModuleScopeIDs.count(ExistingModule) && "unknown module");
0622     return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
0623   }
0624 
0625   /// Check whether a framework module can be inferred in the given directory.
0626   bool canInferFrameworkModule(const DirectoryEntry *Dir) const {
0627     auto It = InferredDirectories.find(Dir);
0628     return It != InferredDirectories.end() && It->getSecond().InferModules;
0629   }
0630 
0631   /// Retrieve the module map file containing the definition of the given
0632   /// module.
0633   ///
0634   /// \param Module The module whose module map file will be returned, if known.
0635   ///
0636   /// \returns The FileID for the module map file containing the given module,
0637   /// invalid if the module definition was inferred.
0638   FileID getContainingModuleMapFileID(const Module *Module) const;
0639   OptionalFileEntryRef getContainingModuleMapFile(const Module *Module) const;
0640 
0641   /// Get the module map file that (along with the module name) uniquely
0642   /// identifies this module.
0643   ///
0644   /// The particular module that \c Name refers to may depend on how the module
0645   /// was found in header search. However, the combination of \c Name and
0646   /// this module map will be globally unique for top-level modules. In the case
0647   /// of inferred modules, returns the module map that allowed the inference
0648   /// (e.g. contained 'module *'). Otherwise, returns
0649   /// getContainingModuleMapFile().
0650   FileID getModuleMapFileIDForUniquing(const Module *M) const;
0651   OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const;
0652 
0653   void setInferredModuleAllowedBy(Module *M, FileID ModMapFID);
0654 
0655   /// Canonicalize \p Path in a manner suitable for a module map file. In
0656   /// particular, this canonicalizes the parent directory separately from the
0657   /// filename so that it does not affect header resolution relative to the
0658   /// modulemap.
0659   ///
0660   /// \returns an error code if any filesystem operations failed. In this case
0661   /// \p Path is not modified.
0662   std::error_code canonicalizeModuleMapPath(SmallVectorImpl<char> &Path);
0663 
0664   /// Get any module map files other than getModuleMapFileForUniquing(M)
0665   /// that define submodules of a top-level module \p M. This is cheaper than
0666   /// getting the module map file for each submodule individually, since the
0667   /// expected number of results is very small.
0668   AdditionalModMapsSet *getAdditionalModuleMapFiles(const Module *M) {
0669     auto I = AdditionalModMaps.find(M);
0670     if (I == AdditionalModMaps.end())
0671       return nullptr;
0672     return &I->second;
0673   }
0674 
0675   void addAdditionalModuleMapFile(const Module *M, FileEntryRef ModuleMap);
0676 
0677   /// Resolve all of the unresolved exports in the given module.
0678   ///
0679   /// \param Mod The module whose exports should be resolved.
0680   ///
0681   /// \param Complain Whether to emit diagnostics for failures.
0682   ///
0683   /// \returns true if any errors were encountered while resolving exports,
0684   /// false otherwise.
0685   bool resolveExports(Module *Mod, bool Complain);
0686 
0687   /// Resolve all of the unresolved uses in the given module.
0688   ///
0689   /// \param Mod The module whose uses should be resolved.
0690   ///
0691   /// \param Complain Whether to emit diagnostics for failures.
0692   ///
0693   /// \returns true if any errors were encountered while resolving uses,
0694   /// false otherwise.
0695   bool resolveUses(Module *Mod, bool Complain);
0696 
0697   /// Resolve all of the unresolved conflicts in the given module.
0698   ///
0699   /// \param Mod The module whose conflicts should be resolved.
0700   ///
0701   /// \param Complain Whether to emit diagnostics for failures.
0702   ///
0703   /// \returns true if any errors were encountered while resolving conflicts,
0704   /// false otherwise.
0705   bool resolveConflicts(Module *Mod, bool Complain);
0706 
0707   /// Sets the umbrella header of the given module to the given header.
0708   void
0709   setUmbrellaHeaderAsWritten(Module *Mod, FileEntryRef UmbrellaHeader,
0710                              const Twine &NameAsWritten,
0711                              const Twine &PathRelativeToRootModuleDirectory);
0712 
0713   /// Sets the umbrella directory of the given module to the given directory.
0714   void setUmbrellaDirAsWritten(Module *Mod, DirectoryEntryRef UmbrellaDir,
0715                                const Twine &NameAsWritten,
0716                                const Twine &PathRelativeToRootModuleDirectory);
0717 
0718   /// Adds this header to the given module.
0719   /// \param Role The role of the header wrt the module.
0720   void addHeader(Module *Mod, Module::Header Header,
0721                  ModuleHeaderRole Role, bool Imported = false);
0722 
0723   /// Parse the given module map file, and record any modules we
0724   /// encounter.
0725   ///
0726   /// \param File The file to be parsed.
0727   ///
0728   /// \param IsSystem Whether this module map file is in a system header
0729   /// directory, and therefore should be considered a system module.
0730   ///
0731   /// \param HomeDir The directory in which relative paths within this module
0732   ///        map file will be resolved.
0733   ///
0734   /// \param ID The FileID of the file to process, if we've already entered it.
0735   ///
0736   /// \param Offset [inout] On input the offset at which to start parsing. On
0737   ///        output, the offset at which the module map terminated.
0738   ///
0739   /// \param ExternModuleLoc The location of the "extern module" declaration
0740   ///        that caused us to load this module map file, if any.
0741   ///
0742   /// \returns true if an error occurred, false otherwise.
0743   bool parseModuleMapFile(FileEntryRef File, bool IsSystem,
0744                           DirectoryEntryRef HomeDir, FileID ID = FileID(),
0745                           unsigned *Offset = nullptr,
0746                           SourceLocation ExternModuleLoc = SourceLocation());
0747 
0748   /// Dump the contents of the module map, for debugging purposes.
0749   void dump();
0750 
0751   using module_iterator = llvm::StringMap<Module *>::const_iterator;
0752 
0753   module_iterator module_begin() const { return Modules.begin(); }
0754   module_iterator module_end()   const { return Modules.end(); }
0755   llvm::iterator_range<module_iterator> modules() const {
0756     return {module_begin(), module_end()};
0757   }
0758 
0759   /// Cache a module load.  M might be nullptr.
0760   void cacheModuleLoad(const IdentifierInfo &II, Module *M) {
0761     CachedModuleLoads[&II] = M;
0762   }
0763 
0764   /// Return a cached module load.
0765   std::optional<Module *> getCachedModuleLoad(const IdentifierInfo &II) {
0766     auto I = CachedModuleLoads.find(&II);
0767     if (I == CachedModuleLoads.end())
0768       return std::nullopt;
0769     return I->second;
0770   }
0771 };
0772 
0773 } // namespace clang
0774 
0775 #endif // LLVM_CLANG_LEX_MODULEMAP_H