1 //===- ModuleMap.h - Describe the layout of modules -------------*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the ModuleMap interface, which describes the layout of a
10 // module as it relates to headers.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_LEX_MODULEMAP_H
15 #define LLVM_CLANG_LEX_MODULEMAP_H
16 
17 #include "clang/Basic/IdentifierTable.h"
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/Basic/Module.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/PointerIntPair.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/StringSet.h"
29 #include "llvm/ADT/TinyPtrVector.h"
30 #include "llvm/ADT/Twine.h"
31 #include <ctime>
32 #include <memory>
33 #include <string>
34 #include <utility>
35 
36 namespace clang {
37 
38 class DiagnosticsEngine;
39 class DirectoryEntry;
40 class FileEntry;
41 class FileManager;
42 class HeaderSearch;
43 class SourceManager;
44 
45 /// A mechanism to observe the actions of the module map parser as it
46 /// reads module map files.
47 class ModuleMapCallbacks {
48   virtual void anchor();
49 
50 public:
51   virtual ~ModuleMapCallbacks() = default;
52 
53   /// Called when a module map file has been read.
54   ///
55   /// \param FileStart A SourceLocation referring to the start of the file's
56   /// contents.
57   /// \param File The file itself.
58   /// \param IsSystem Whether this is a module map from a system include path.
59   virtual void moduleMapFileRead(SourceLocation FileStart,
60                                  const FileEntry &File, bool IsSystem) {}
61 
62   /// Called when a header is added during module map parsing.
63   ///
64   /// \param Filename The header file itself.
65   virtual void moduleMapAddHeader(StringRef Filename) {}
66 
67   /// Called when an umbrella header is added during module map parsing.
68   ///
69   /// \param FileMgr FileManager instance
70   /// \param Header The umbrella header to collect.
71   virtual void moduleMapAddUmbrellaHeader(FileManager *FileMgr,
72                                           const FileEntry *Header) {}
73 };
74 
75 class ModuleMap {
76   SourceManager &SourceMgr;
77   DiagnosticsEngine &Diags;
78   const LangOptions &LangOpts;
79   const TargetInfo *Target;
80   HeaderSearch &HeaderInfo;
81 
82   llvm::SmallVector<std::unique_ptr<ModuleMapCallbacks>, 1> Callbacks;
83 
84   /// The directory used for Clang-supplied, builtin include headers,
85   /// such as "stdint.h".
86   const DirectoryEntry *BuiltinIncludeDir = nullptr;
87 
88   /// Language options used to parse the module map itself.
89   ///
90   /// These are always simple C language options.
91   LangOptions MMapLangOpts;
92 
93   /// The module that the main source file is associated with (the module
94   /// named LangOpts::CurrentModule, if we've loaded it).
95   Module *SourceModule = nullptr;
96 
97   /// Submodules of the current module that have not yet been attached to it.
98   /// (Ownership is transferred if/when we create an enclosing module.)
99   llvm::SmallVector<std::unique_ptr<Module>, 8> PendingSubmodules;
100 
101   /// The top-level modules that are known.
102   llvm::StringMap<Module *> Modules;
103 
104   /// Module loading cache that includes submodules, indexed by IdentifierInfo.
105   /// nullptr is stored for modules that are known to fail to load.
106   llvm::DenseMap<const IdentifierInfo *, Module *> CachedModuleLoads;
107 
108   /// Shadow modules created while building this module map.
109   llvm::SmallVector<Module*, 2> ShadowModules;
110 
111   /// The number of modules we have created in total.
112   unsigned NumCreatedModules = 0;
113 
114   /// In case a module has a export_as entry, it might have a pending link
115   /// name to be determined if that module is imported.
116   llvm::StringMap<llvm::StringSet<>> PendingLinkAsModule;
117 
118 public:
119   /// Use PendingLinkAsModule information to mark top level link names that
120   /// are going to be replaced by export_as aliases.
121   void resolveLinkAsDependencies(Module *Mod);
122 
123   /// Make module to use export_as as the link dependency name if enough
124   /// information is available or add it to a pending list otherwise.
125   void addLinkAsDependency(Module *Mod);
126 
127   /// Flags describing the role of a module header.
128   enum ModuleHeaderRole {
129     /// This header is normally included in the module.
130     NormalHeader  = 0x0,
131 
132     /// This header is included but private.
133     PrivateHeader = 0x1,
134 
135     /// This header is part of the module (for layering purposes) but
136     /// should be textually included.
137     TextualHeader = 0x2,
138 
139     // Caution: Adding an enumerator needs other changes.
140     // Adjust the number of bits for KnownHeader::Storage.
141     // Adjust the bitfield HeaderFileInfo::HeaderRole size.
142     // Adjust the HeaderFileInfoTrait::ReadData streaming.
143     // Adjust the HeaderFileInfoTrait::EmitData streaming.
144     // Adjust ModuleMap::addHeader.
145   };
146 
147   /// Convert a header kind to a role. Requires Kind to not be HK_Excluded.
148   static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind);
149 
150   /// Convert a header role to a kind.
151   static Module::HeaderKind headerRoleToKind(ModuleHeaderRole Role);
152 
153   /// A header that is known to reside within a given module,
154   /// whether it was included or excluded.
155   class KnownHeader {
156     llvm::PointerIntPair<Module *, 2, ModuleHeaderRole> Storage;
157 
158   public:
159     KnownHeader() : Storage(nullptr, NormalHeader) {}
160     KnownHeader(Module *M, ModuleHeaderRole Role) : Storage(M, Role) {}
161 
162     friend bool operator==(const KnownHeader &A, const KnownHeader &B) {
163       return A.Storage == B.Storage;
164     }
165     friend bool operator!=(const KnownHeader &A, const KnownHeader &B) {
166       return A.Storage != B.Storage;
167     }
168 
169     /// Retrieve the module the header is stored in.
170     Module *getModule() const { return Storage.getPointer(); }
171 
172     /// The role of this header within the module.
173     ModuleHeaderRole getRole() const { return Storage.getInt(); }
174 
175     /// Whether this header is available in the module.
176     bool isAvailable() const {
177       return getModule()->isAvailable();
178     }
179 
180     /// Whether this header is accessible from the specified module.
181     bool isAccessibleFrom(Module *M) const {
182       return !(getRole() & PrivateHeader) ||
183              (M && M->getTopLevelModule() == getModule()->getTopLevelModule());
184     }
185 
186     // Whether this known header is valid (i.e., it has an
187     // associated module).
188     explicit operator bool() const {
189       return Storage.getPointer() != nullptr;
190     }
191   };
192 
193   using AdditionalModMapsSet = llvm::SmallPtrSet<const FileEntry *, 1>;
194 
195 private:
196   friend class ModuleMapParser;
197 
198   using HeadersMap =
199       llvm::DenseMap<const FileEntry *, SmallVector<KnownHeader, 1>>;
200 
201   /// Mapping from each header to the module that owns the contents of
202   /// that header.
203   HeadersMap Headers;
204 
205   /// Map from file sizes to modules with lazy header directives of that size.
206   mutable llvm::DenseMap<off_t, llvm::TinyPtrVector<Module*>> LazyHeadersBySize;
207 
208   /// Map from mtimes to modules with lazy header directives with those mtimes.
209   mutable llvm::DenseMap<time_t, llvm::TinyPtrVector<Module*>>
210               LazyHeadersByModTime;
211 
212   /// Mapping from directories with umbrella headers to the module
213   /// that is generated from the umbrella header.
214   ///
215   /// This mapping is used to map headers that haven't explicitly been named
216   /// in the module map over to the module that includes them via its umbrella
217   /// header.
218   llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs;
219 
220   /// A generation counter that is used to test whether modules of the
221   /// same name may shadow or are illegal redefinitions.
222   ///
223   /// Modules from earlier scopes may shadow modules from later ones.
224   /// Modules from the same scope may not have the same name.
225   unsigned CurrentModuleScopeID = 0;
226 
227   llvm::DenseMap<Module *, unsigned> ModuleScopeIDs;
228 
229   /// The set of attributes that can be attached to a module.
230   struct Attributes {
231     /// Whether this is a system module.
232     unsigned IsSystem : 1;
233 
234     /// Whether this is an extern "C" module.
235     unsigned IsExternC : 1;
236 
237     /// Whether this is an exhaustive set of configuration macros.
238     unsigned IsExhaustive : 1;
239 
240     /// Whether files in this module can only include non-modular headers
241     /// and headers from used modules.
242     unsigned NoUndeclaredIncludes : 1;
243 
244     Attributes()
245         : IsSystem(false), IsExternC(false), IsExhaustive(false),
246           NoUndeclaredIncludes(false) {}
247   };
248 
249   /// A directory for which framework modules can be inferred.
250   struct InferredDirectory {
251     /// Whether to infer modules from this directory.
252     unsigned InferModules : 1;
253 
254     /// The attributes to use for inferred modules.
255     Attributes Attrs;
256 
257     /// If \c InferModules is non-zero, the module map file that allowed
258     /// inferred modules.  Otherwise, nullptr.
259     const FileEntry *ModuleMapFile;
260 
261     /// The names of modules that cannot be inferred within this
262     /// directory.
263     SmallVector<std::string, 2> ExcludedModules;
264 
265     InferredDirectory() : InferModules(false) {}
266   };
267 
268   /// A mapping from directories to information about inferring
269   /// framework modules from within those directories.
270   llvm::DenseMap<const DirectoryEntry *, InferredDirectory> InferredDirectories;
271 
272   /// A mapping from an inferred module to the module map that allowed the
273   /// inference.
274   llvm::DenseMap<const Module *, const FileEntry *> InferredModuleAllowedBy;
275 
276   llvm::DenseMap<const Module *, AdditionalModMapsSet> AdditionalModMaps;
277 
278   /// Describes whether we haved parsed a particular file as a module
279   /// map.
280   llvm::DenseMap<const FileEntry *, bool> ParsedModuleMap;
281 
282   /// Resolve the given export declaration into an actual export
283   /// declaration.
284   ///
285   /// \param Mod The module in which we're resolving the export declaration.
286   ///
287   /// \param Unresolved The export declaration to resolve.
288   ///
289   /// \param Complain Whether this routine should complain about unresolvable
290   /// exports.
291   ///
292   /// \returns The resolved export declaration, which will have a NULL pointer
293   /// if the export could not be resolved.
294   Module::ExportDecl
295   resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved,
296                 bool Complain) const;
297 
298   /// Resolve the given module id to an actual module.
299   ///
300   /// \param Id The module-id to resolve.
301   ///
302   /// \param Mod The module in which we're resolving the module-id.
303   ///
304   /// \param Complain Whether this routine should complain about unresolvable
305   /// module-ids.
306   ///
307   /// \returns The resolved module, or null if the module-id could not be
308   /// resolved.
309   Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const;
310 
311   /// Add an unresolved header to a module.
312   ///
313   /// \param Mod The module in which we're adding the unresolved header
314   ///        directive.
315   /// \param Header The unresolved header directive.
316   /// \param NeedsFramework If Mod is not a framework but a missing header would
317   ///        be found in case Mod was, set it to true. False otherwise.
318   void addUnresolvedHeader(Module *Mod,
319                            Module::UnresolvedHeaderDirective Header,
320                            bool &NeedsFramework);
321 
322   /// Look up the given header directive to find an actual header file.
323   ///
324   /// \param M The module in which we're resolving the header directive.
325   /// \param Header The header directive to resolve.
326   /// \param RelativePathName Filled in with the relative path name from the
327   ///        module to the resolved header.
328   /// \param NeedsFramework If M is not a framework but a missing header would
329   ///        be found in case M was, set it to true. False otherwise.
330   /// \return The resolved file, if any.
331   Optional<FileEntryRef>
332   findHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
333              SmallVectorImpl<char> &RelativePathName, bool &NeedsFramework);
334 
335   /// Resolve the given header directive.
336   ///
337   /// \param M The module in which we're resolving the header directive.
338   /// \param Header The header directive to resolve.
339   /// \param NeedsFramework If M is not a framework but a missing header would
340   ///        be found in case M was, set it to true. False otherwise.
341   void resolveHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
342                      bool &NeedsFramework);
343 
344   /// Attempt to resolve the specified header directive as naming a builtin
345   /// header.
346   /// \return \c true if a corresponding builtin header was found.
347   bool resolveAsBuiltinHeader(Module *M,
348                               const Module::UnresolvedHeaderDirective &Header);
349 
350   /// Looks up the modules that \p File corresponds to.
351   ///
352   /// If \p File represents a builtin header within Clang's builtin include
353   /// directory, this also loads all of the module maps to see if it will get
354   /// associated with a specific module (e.g. in /usr/include).
355   HeadersMap::iterator findKnownHeader(const FileEntry *File);
356 
357   /// Searches for a module whose umbrella directory contains \p File.
358   ///
359   /// \param File The header to search for.
360   ///
361   /// \param IntermediateDirs On success, contains the set of directories
362   /// searched before finding \p File.
363   KnownHeader findHeaderInUmbrellaDirs(const FileEntry *File,
364                     SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs);
365 
366   /// Given that \p File is not in the Headers map, look it up within
367   /// umbrella directories and find or create a module for it.
368   KnownHeader findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File);
369 
370   /// A convenience method to determine if \p File is (possibly nested)
371   /// in an umbrella directory.
372   bool isHeaderInUmbrellaDirs(const FileEntry *File) {
373     SmallVector<const DirectoryEntry *, 2> IntermediateDirs;
374     return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
375   }
376 
377   Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
378                                Attributes Attrs, Module *Parent);
379 
380 public:
381   /// Construct a new module map.
382   ///
383   /// \param SourceMgr The source manager used to find module files and headers.
384   /// This source manager should be shared with the header-search mechanism,
385   /// since they will refer to the same headers.
386   ///
387   /// \param Diags A diagnostic engine used for diagnostics.
388   ///
389   /// \param LangOpts Language options for this translation unit.
390   ///
391   /// \param Target The target for this translation unit.
392   ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
393             const LangOptions &LangOpts, const TargetInfo *Target,
394             HeaderSearch &HeaderInfo);
395 
396   /// Destroy the module map.
397   ~ModuleMap();
398 
399   /// Set the target information.
400   void setTarget(const TargetInfo &Target);
401 
402   /// Set the directory that contains Clang-supplied include
403   /// files, such as our stdarg.h or tgmath.h.
404   void setBuiltinIncludeDir(const DirectoryEntry *Dir) {
405     BuiltinIncludeDir = Dir;
406   }
407 
408   /// Get the directory that contains Clang-supplied include files.
409   const DirectoryEntry *getBuiltinDir() const {
410     return BuiltinIncludeDir;
411   }
412 
413   /// Is this a compiler builtin header?
414   static bool isBuiltinHeader(StringRef FileName);
415   bool isBuiltinHeader(const FileEntry *File);
416 
417   /// Add a module map callback.
418   void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
419     Callbacks.push_back(std::move(Callback));
420   }
421 
422   /// Retrieve the module that owns the given header file, if any. Note that
423   /// this does not implicitly load module maps, except for builtin headers,
424   /// and does not consult the external source. (Those checks are the
425   /// responsibility of \ref HeaderSearch.)
426   ///
427   /// \param File The header file that is likely to be included.
428   ///
429   /// \param AllowTextual If \c true and \p File is a textual header, return
430   /// its owning module. Otherwise, no KnownHeader will be returned if the
431   /// file is only known as a textual header.
432   ///
433   /// \returns The module KnownHeader, which provides the module that owns the
434   /// given header file.  The KnownHeader is default constructed to indicate
435   /// that no module owns this header file.
436   KnownHeader findModuleForHeader(const FileEntry *File,
437                                   bool AllowTextual = false);
438 
439   /// Retrieve all the modules that contain the given header file. Note that
440   /// this does not implicitly load module maps, except for builtin headers,
441   /// and does not consult the external source. (Those checks are the
442   /// responsibility of \ref HeaderSearch.)
443   ///
444   /// Typically, \ref findModuleForHeader should be used instead, as it picks
445   /// the preferred module for the header.
446   ArrayRef<KnownHeader> findAllModulesForHeader(const FileEntry *File);
447 
448   /// Like \ref findAllModulesForHeader, but do not attempt to infer module
449   /// ownership from umbrella headers if we've not already done so.
450   ArrayRef<KnownHeader>
451   findResolvedModulesForHeader(const FileEntry *File) const;
452 
453   /// Resolve all lazy header directives for the specified file.
454   ///
455   /// This ensures that the HeaderFileInfo on HeaderSearch is up to date. This
456   /// is effectively internal, but is exposed so HeaderSearch can call it.
457   void resolveHeaderDirectives(const FileEntry *File) const;
458 
459   /// Resolve lazy header directives for the specified module. If File is
460   /// provided, only headers with same size and modtime are resolved. If File
461   /// is not set, all headers are resolved.
462   void resolveHeaderDirectives(Module *Mod,
463                                llvm::Optional<const FileEntry *> File) const;
464 
465   /// Reports errors if a module must not include a specific file.
466   ///
467   /// \param RequestingModule The module including a file.
468   ///
469   /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in
470   ///        the interface of RequestingModule, \c false if it's in the
471   ///        implementation of RequestingModule. Value is ignored and
472   ///        meaningless if RequestingModule is nullptr.
473   ///
474   /// \param FilenameLoc The location of the inclusion's filename.
475   ///
476   /// \param Filename The included filename as written.
477   ///
478   /// \param File The included file.
479   void diagnoseHeaderInclusion(Module *RequestingModule,
480                                bool RequestingModuleIsModuleInterface,
481                                SourceLocation FilenameLoc, StringRef Filename,
482                                FileEntryRef File);
483 
484   /// Determine whether the given header is part of a module
485   /// marked 'unavailable'.
486   bool isHeaderInUnavailableModule(const FileEntry *Header) const;
487 
488   /// Determine whether the given header is unavailable as part
489   /// of the specified module.
490   bool isHeaderUnavailableInModule(const FileEntry *Header,
491                                    const Module *RequestingModule) const;
492 
493   /// Retrieve a module with the given name.
494   ///
495   /// \param Name The name of the module to look up.
496   ///
497   /// \returns The named module, if known; otherwise, returns null.
498   Module *findModule(StringRef Name) const;
499 
500   /// Retrieve a module with the given name using lexical name lookup,
501   /// starting at the given context.
502   ///
503   /// \param Name The name of the module to look up.
504   ///
505   /// \param Context The module context, from which we will perform lexical
506   /// name lookup.
507   ///
508   /// \returns The named module, if known; otherwise, returns null.
509   Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
510 
511   /// Retrieve a module with the given name within the given context,
512   /// using direct (qualified) name lookup.
513   ///
514   /// \param Name The name of the module to look up.
515   ///
516   /// \param Context The module for which we will look for a submodule. If
517   /// null, we will look for a top-level module.
518   ///
519   /// \returns The named submodule, if known; otherwose, returns null.
520   Module *lookupModuleQualified(StringRef Name, Module *Context) const;
521 
522   /// Find a new module or submodule, or create it if it does not already
523   /// exist.
524   ///
525   /// \param Name The name of the module to find or create.
526   ///
527   /// \param Parent The module that will act as the parent of this submodule,
528   /// or nullptr to indicate that this is a top-level module.
529   ///
530   /// \param IsFramework Whether this is a framework module.
531   ///
532   /// \param IsExplicit Whether this is an explicit submodule.
533   ///
534   /// \returns The found or newly-created module, along with a boolean value
535   /// that will be true if the module is newly-created.
536   std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
537                                                bool IsFramework,
538                                                bool IsExplicit);
539 
540   /// Create a global module fragment for a C++ module unit.
541   ///
542   /// We model the global module fragment as a submodule of the module
543   /// interface unit. Unfortunately, we can't create the module interface
544   /// unit's Module until later, because we don't know what it will be called
545   /// usually. See C++20 [module.unit]/7.2 for the case we could know its
546   /// parent.
547   Module *createGlobalModuleFragmentForModuleUnit(SourceLocation Loc,
548                                                   Module *Parent = nullptr);
549 
550   /// Create a global module fragment for a C++ module interface unit.
551   Module *createPrivateModuleFragmentForInterfaceUnit(Module *Parent,
552                                                       SourceLocation Loc);
553 
554   /// Create a new module for a C++ module interface unit.
555   /// The module must not already exist, and will be configured for the current
556   /// compilation.
557   ///
558   /// Note that this also sets the current module to the newly-created module.
559   ///
560   /// \returns The newly-created module.
561   Module *createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name,
562                                        Module *GlobalModule);
563 
564   /// Create a header module from the specified list of headers.
565   Module *createHeaderModule(StringRef Name, ArrayRef<Module::Header> Headers);
566 
567   /// Create a C++20 header unit.
568   Module *createHeaderUnit(SourceLocation Loc, StringRef Name,
569                            Module::Header H);
570 
571   /// Infer the contents of a framework module map from the given
572   /// framework directory.
573   Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
574                                bool IsSystem, Module *Parent);
575 
576   /// Create a new top-level module that is shadowed by
577   /// \p ShadowingModule.
578   Module *createShadowedModule(StringRef Name, bool IsFramework,
579                                Module *ShadowingModule);
580 
581   /// Creates a new declaration scope for module names, allowing
582   /// previously defined modules to shadow definitions from the new scope.
583   ///
584   /// \note Module names from earlier scopes will shadow names from the new
585   /// scope, which is the opposite of how shadowing works for variables.
586   void finishModuleDeclarationScope() { CurrentModuleScopeID += 1; }
587 
588   bool mayShadowNewModule(Module *ExistingModule) {
589     assert(!ExistingModule->Parent && "expected top-level module");
590     assert(ModuleScopeIDs.count(ExistingModule) && "unknown module");
591     return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
592   }
593 
594   /// Check whether a framework module can be inferred in the given directory.
595   bool canInferFrameworkModule(const DirectoryEntry *Dir) const {
596     auto It = InferredDirectories.find(Dir);
597     return It != InferredDirectories.end() && It->getSecond().InferModules;
598   }
599 
600   /// Retrieve the module map file containing the definition of the given
601   /// module.
602   ///
603   /// \param Module The module whose module map file will be returned, if known.
604   ///
605   /// \returns The file entry for the module map file containing the given
606   /// module, or nullptr if the module definition was inferred.
607   const FileEntry *getContainingModuleMapFile(const Module *Module) const;
608 
609   /// Get the module map file that (along with the module name) uniquely
610   /// identifies this module.
611   ///
612   /// The particular module that \c Name refers to may depend on how the module
613   /// was found in header search. However, the combination of \c Name and
614   /// this module map will be globally unique for top-level modules. In the case
615   /// of inferred modules, returns the module map that allowed the inference
616   /// (e.g. contained 'module *'). Otherwise, returns
617   /// getContainingModuleMapFile().
618   const FileEntry *getModuleMapFileForUniquing(const Module *M) const;
619 
620   void setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap);
621 
622   /// Get any module map files other than getModuleMapFileForUniquing(M)
623   /// that define submodules of a top-level module \p M. This is cheaper than
624   /// getting the module map file for each submodule individually, since the
625   /// expected number of results is very small.
626   AdditionalModMapsSet *getAdditionalModuleMapFiles(const Module *M) {
627     auto I = AdditionalModMaps.find(M);
628     if (I == AdditionalModMaps.end())
629       return nullptr;
630     return &I->second;
631   }
632 
633   void addAdditionalModuleMapFile(const Module *M, const FileEntry *ModuleMap);
634 
635   /// Resolve all of the unresolved exports in the given module.
636   ///
637   /// \param Mod The module whose exports should be resolved.
638   ///
639   /// \param Complain Whether to emit diagnostics for failures.
640   ///
641   /// \returns true if any errors were encountered while resolving exports,
642   /// false otherwise.
643   bool resolveExports(Module *Mod, bool Complain);
644 
645   /// Resolve all of the unresolved uses in the given module.
646   ///
647   /// \param Mod The module whose uses should be resolved.
648   ///
649   /// \param Complain Whether to emit diagnostics for failures.
650   ///
651   /// \returns true if any errors were encountered while resolving uses,
652   /// false otherwise.
653   bool resolveUses(Module *Mod, bool Complain);
654 
655   /// Resolve all of the unresolved conflicts in the given module.
656   ///
657   /// \param Mod The module whose conflicts should be resolved.
658   ///
659   /// \param Complain Whether to emit diagnostics for failures.
660   ///
661   /// \returns true if any errors were encountered while resolving conflicts,
662   /// false otherwise.
663   bool resolveConflicts(Module *Mod, bool Complain);
664 
665   /// Sets the umbrella header of the given module to the given
666   /// header.
667   void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
668                          const Twine &NameAsWritten,
669                          const Twine &PathRelativeToRootModuleDirectory);
670 
671   /// Sets the umbrella directory of the given module to the given
672   /// directory.
673   void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
674                       const Twine &NameAsWritten,
675                       const Twine &PathRelativeToRootModuleDirectory);
676 
677   /// Adds this header to the given module.
678   /// \param Role The role of the header wrt the module.
679   void addHeader(Module *Mod, Module::Header Header,
680                  ModuleHeaderRole Role, bool Imported = false);
681 
682   /// Marks this header as being excluded from the given module.
683   void excludeHeader(Module *Mod, Module::Header Header);
684 
685   /// Parse the given module map file, and record any modules we
686   /// encounter.
687   ///
688   /// \param File The file to be parsed.
689   ///
690   /// \param IsSystem Whether this module map file is in a system header
691   /// directory, and therefore should be considered a system module.
692   ///
693   /// \param HomeDir The directory in which relative paths within this module
694   ///        map file will be resolved.
695   ///
696   /// \param ID The FileID of the file to process, if we've already entered it.
697   ///
698   /// \param Offset [inout] On input the offset at which to start parsing. On
699   ///        output, the offset at which the module map terminated.
700   ///
701   /// \param ExternModuleLoc The location of the "extern module" declaration
702   ///        that caused us to load this module map file, if any.
703   ///
704   /// \returns true if an error occurred, false otherwise.
705   bool parseModuleMapFile(const FileEntry *File, bool IsSystem,
706                           const DirectoryEntry *HomeDir,
707                           FileID ID = FileID(), unsigned *Offset = nullptr,
708                           SourceLocation ExternModuleLoc = SourceLocation());
709 
710   /// Dump the contents of the module map, for debugging purposes.
711   void dump();
712 
713   using module_iterator = llvm::StringMap<Module *>::const_iterator;
714 
715   module_iterator module_begin() const { return Modules.begin(); }
716   module_iterator module_end()   const { return Modules.end(); }
717   llvm::iterator_range<module_iterator> modules() const {
718     return {module_begin(), module_end()};
719   }
720 
721   /// Cache a module load.  M might be nullptr.
722   void cacheModuleLoad(const IdentifierInfo &II, Module *M) {
723     CachedModuleLoads[&II] = M;
724   }
725 
726   /// Return a cached module load.
727   llvm::Optional<Module *> getCachedModuleLoad(const IdentifierInfo &II) {
728     auto I = CachedModuleLoads.find(&II);
729     if (I == CachedModuleLoads.end())
730       return None;
731     return I->second;
732   }
733 };
734 
735 } // namespace clang
736 
737 #endif // LLVM_CLANG_LEX_MODULEMAP_H
738