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   const FileEntry *findHeader(Module *M,
332                               const Module::UnresolvedHeaderDirective &Header,
333                               SmallVectorImpl<char> &RelativePathName,
334                               bool &NeedsFramework);
335 
336   /// Resolve the given header directive.
337   ///
338   /// \param M The module in which we're resolving the header directive.
339   /// \param Header The header directive to resolve.
340   /// \param NeedsFramework If M is not a framework but a missing header would
341   ///        be found in case M was, set it to true. False otherwise.
342   void resolveHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
343                      bool &NeedsFramework);
344 
345   /// Attempt to resolve the specified header directive as naming a builtin
346   /// header.
347   /// \return \c true if a corresponding builtin header was found.
348   bool resolveAsBuiltinHeader(Module *M,
349                               const Module::UnresolvedHeaderDirective &Header);
350 
351   /// Looks up the modules that \p File corresponds to.
352   ///
353   /// If \p File represents a builtin header within Clang's builtin include
354   /// directory, this also loads all of the module maps to see if it will get
355   /// associated with a specific module (e.g. in /usr/include).
356   HeadersMap::iterator findKnownHeader(const FileEntry *File);
357 
358   /// Searches for a module whose umbrella directory contains \p File.
359   ///
360   /// \param File The header to search for.
361   ///
362   /// \param IntermediateDirs On success, contains the set of directories
363   /// searched before finding \p File.
364   KnownHeader findHeaderInUmbrellaDirs(const FileEntry *File,
365                     SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs);
366 
367   /// Given that \p File is not in the Headers map, look it up within
368   /// umbrella directories and find or create a module for it.
369   KnownHeader findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File);
370 
371   /// A convenience method to determine if \p File is (possibly nested)
372   /// in an umbrella directory.
373   bool isHeaderInUmbrellaDirs(const FileEntry *File) {
374     SmallVector<const DirectoryEntry *, 2> IntermediateDirs;
375     return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
376   }
377 
378   Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
379                                Attributes Attrs, Module *Parent);
380 
381 public:
382   /// Construct a new module map.
383   ///
384   /// \param SourceMgr The source manager used to find module files and headers.
385   /// This source manager should be shared with the header-search mechanism,
386   /// since they will refer to the same headers.
387   ///
388   /// \param Diags A diagnostic engine used for diagnostics.
389   ///
390   /// \param LangOpts Language options for this translation unit.
391   ///
392   /// \param Target The target for this translation unit.
393   ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
394             const LangOptions &LangOpts, const TargetInfo *Target,
395             HeaderSearch &HeaderInfo);
396 
397   /// Destroy the module map.
398   ~ModuleMap();
399 
400   /// Set the target information.
401   void setTarget(const TargetInfo &Target);
402 
403   /// Set the directory that contains Clang-supplied include
404   /// files, such as our stdarg.h or tgmath.h.
405   void setBuiltinIncludeDir(const DirectoryEntry *Dir) {
406     BuiltinIncludeDir = Dir;
407   }
408 
409   /// Get the directory that contains Clang-supplied include files.
410   const DirectoryEntry *getBuiltinDir() const {
411     return BuiltinIncludeDir;
412   }
413 
414   /// Is this a compiler builtin header?
415   static bool isBuiltinHeader(StringRef FileName);
416   bool isBuiltinHeader(const FileEntry *File);
417 
418   /// Add a module map callback.
419   void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
420     Callbacks.push_back(std::move(Callback));
421   }
422 
423   /// Retrieve the module that owns the given header file, if any. Note that
424   /// this does not implicitly load module maps, except for builtin headers,
425   /// and does not consult the external source. (Those checks are the
426   /// responsibility of \ref HeaderSearch.)
427   ///
428   /// \param File The header file that is likely to be included.
429   ///
430   /// \param AllowTextual If \c true and \p File is a textual header, return
431   /// its owning module. Otherwise, no KnownHeader will be returned if the
432   /// file is only known as a textual header.
433   ///
434   /// \returns The module KnownHeader, which provides the module that owns the
435   /// given header file.  The KnownHeader is default constructed to indicate
436   /// that no module owns this header file.
437   KnownHeader findModuleForHeader(const FileEntry *File,
438                                   bool AllowTextual = false);
439 
440   /// Retrieve all the modules that contain the given header file. Note that
441   /// this does not implicitly load module maps, except for builtin headers,
442   /// and does not consult the external source. (Those checks are the
443   /// responsibility of \ref HeaderSearch.)
444   ///
445   /// Typically, \ref findModuleForHeader should be used instead, as it picks
446   /// the preferred module for the header.
447   ArrayRef<KnownHeader> findAllModulesForHeader(const FileEntry *File);
448 
449   /// Like \ref findAllModulesForHeader, but do not attempt to infer module
450   /// ownership from umbrella headers if we've not already done so.
451   ArrayRef<KnownHeader>
452   findResolvedModulesForHeader(const FileEntry *File) const;
453 
454   /// Resolve all lazy header directives for the specified file.
455   ///
456   /// This ensures that the HeaderFileInfo on HeaderSearch is up to date. This
457   /// is effectively internal, but is exposed so HeaderSearch can call it.
458   void resolveHeaderDirectives(const FileEntry *File) const;
459 
460   /// Resolve all lazy header directives for the specified module.
461   void resolveHeaderDirectives(Module *Mod) const;
462 
463   /// Reports errors if a module must not include a specific file.
464   ///
465   /// \param RequestingModule The module including a file.
466   ///
467   /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in
468   ///        the interface of RequestingModule, \c false if it's in the
469   ///        implementation of RequestingModule. Value is ignored and
470   ///        meaningless if RequestingModule is nullptr.
471   ///
472   /// \param FilenameLoc The location of the inclusion's filename.
473   ///
474   /// \param Filename The included filename as written.
475   ///
476   /// \param File The included file.
477   void diagnoseHeaderInclusion(Module *RequestingModule,
478                                bool RequestingModuleIsModuleInterface,
479                                SourceLocation FilenameLoc, StringRef Filename,
480                                const FileEntry *File);
481 
482   /// Determine whether the given header is part of a module
483   /// marked 'unavailable'.
484   bool isHeaderInUnavailableModule(const FileEntry *Header) const;
485 
486   /// Determine whether the given header is unavailable as part
487   /// of the specified module.
488   bool isHeaderUnavailableInModule(const FileEntry *Header,
489                                    const Module *RequestingModule) const;
490 
491   /// Retrieve a module with the given name.
492   ///
493   /// \param Name The name of the module to look up.
494   ///
495   /// \returns The named module, if known; otherwise, returns null.
496   Module *findModule(StringRef Name) const;
497 
498   /// Retrieve a module with the given name using lexical name lookup,
499   /// starting at the given context.
500   ///
501   /// \param Name The name of the module to look up.
502   ///
503   /// \param Context The module context, from which we will perform lexical
504   /// name lookup.
505   ///
506   /// \returns The named module, if known; otherwise, returns null.
507   Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
508 
509   /// Retrieve a module with the given name within the given context,
510   /// using direct (qualified) name lookup.
511   ///
512   /// \param Name The name of the module to look up.
513   ///
514   /// \param Context The module for which we will look for a submodule. If
515   /// null, we will look for a top-level module.
516   ///
517   /// \returns The named submodule, if known; otherwose, returns null.
518   Module *lookupModuleQualified(StringRef Name, Module *Context) const;
519 
520   /// Find a new module or submodule, or create it if it does not already
521   /// exist.
522   ///
523   /// \param Name The name of the module to find or create.
524   ///
525   /// \param Parent The module that will act as the parent of this submodule,
526   /// or nullptr to indicate that this is a top-level module.
527   ///
528   /// \param IsFramework Whether this is a framework module.
529   ///
530   /// \param IsExplicit Whether this is an explicit submodule.
531   ///
532   /// \returns The found or newly-created module, along with a boolean value
533   /// that will be true if the module is newly-created.
534   std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
535                                                bool IsFramework,
536                                                bool IsExplicit);
537 
538   /// Create a global module fragment for a C++ module unit.
539   ///
540   /// We model the global module fragment as a submodule of the module
541   /// interface unit. Unfortunately, we can't create the module interface
542   /// unit's Module until later, because we don't know what it will be called.
543   Module *createGlobalModuleFragmentForModuleUnit(SourceLocation Loc);
544 
545   /// Create a global module fragment for a C++ module interface unit.
546   Module *createPrivateModuleFragmentForInterfaceUnit(Module *Parent,
547                                                       SourceLocation Loc);
548 
549   /// Create a new module for a C++ module interface unit.
550   /// The module must not already exist, and will be configured for the current
551   /// compilation.
552   ///
553   /// Note that this also sets the current module to the newly-created module.
554   ///
555   /// \returns The newly-created module.
556   Module *createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name,
557                                        Module *GlobalModule);
558 
559   /// Create a header module from the specified list of headers.
560   Module *createHeaderModule(StringRef Name, ArrayRef<Module::Header> Headers);
561 
562   /// Infer the contents of a framework module map from the given
563   /// framework directory.
564   Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
565                                bool IsSystem, Module *Parent);
566 
567   /// Create a new top-level module that is shadowed by
568   /// \p ShadowingModule.
569   Module *createShadowedModule(StringRef Name, bool IsFramework,
570                                Module *ShadowingModule);
571 
572   /// Creates a new declaration scope for module names, allowing
573   /// previously defined modules to shadow definitions from the new scope.
574   ///
575   /// \note Module names from earlier scopes will shadow names from the new
576   /// scope, which is the opposite of how shadowing works for variables.
577   void finishModuleDeclarationScope() { CurrentModuleScopeID += 1; }
578 
579   bool mayShadowNewModule(Module *ExistingModule) {
580     assert(!ExistingModule->Parent && "expected top-level module");
581     assert(ModuleScopeIDs.count(ExistingModule) && "unknown module");
582     return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
583   }
584 
585   /// Retrieve the module map file containing the definition of the given
586   /// module.
587   ///
588   /// \param Module The module whose module map file will be returned, if known.
589   ///
590   /// \returns The file entry for the module map file containing the given
591   /// module, or nullptr if the module definition was inferred.
592   const FileEntry *getContainingModuleMapFile(const Module *Module) const;
593 
594   /// Get the module map file that (along with the module name) uniquely
595   /// identifies this module.
596   ///
597   /// The particular module that \c Name refers to may depend on how the module
598   /// was found in header search. However, the combination of \c Name and
599   /// this module map will be globally unique for top-level modules. In the case
600   /// of inferred modules, returns the module map that allowed the inference
601   /// (e.g. contained 'module *'). Otherwise, returns
602   /// getContainingModuleMapFile().
603   const FileEntry *getModuleMapFileForUniquing(const Module *M) const;
604 
605   void setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap);
606 
607   /// Get any module map files other than getModuleMapFileForUniquing(M)
608   /// that define submodules of a top-level module \p M. This is cheaper than
609   /// getting the module map file for each submodule individually, since the
610   /// expected number of results is very small.
611   AdditionalModMapsSet *getAdditionalModuleMapFiles(const Module *M) {
612     auto I = AdditionalModMaps.find(M);
613     if (I == AdditionalModMaps.end())
614       return nullptr;
615     return &I->second;
616   }
617 
618   void addAdditionalModuleMapFile(const Module *M, const FileEntry *ModuleMap);
619 
620   /// Resolve all of the unresolved exports in the given module.
621   ///
622   /// \param Mod The module whose exports should be resolved.
623   ///
624   /// \param Complain Whether to emit diagnostics for failures.
625   ///
626   /// \returns true if any errors were encountered while resolving exports,
627   /// false otherwise.
628   bool resolveExports(Module *Mod, bool Complain);
629 
630   /// Resolve all of the unresolved uses in the given module.
631   ///
632   /// \param Mod The module whose uses should be resolved.
633   ///
634   /// \param Complain Whether to emit diagnostics for failures.
635   ///
636   /// \returns true if any errors were encountered while resolving uses,
637   /// false otherwise.
638   bool resolveUses(Module *Mod, bool Complain);
639 
640   /// Resolve all of the unresolved conflicts in the given module.
641   ///
642   /// \param Mod The module whose conflicts should be resolved.
643   ///
644   /// \param Complain Whether to emit diagnostics for failures.
645   ///
646   /// \returns true if any errors were encountered while resolving conflicts,
647   /// false otherwise.
648   bool resolveConflicts(Module *Mod, bool Complain);
649 
650   /// Sets the umbrella header of the given module to the given
651   /// header.
652   void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
653                          Twine NameAsWritten);
654 
655   /// Sets the umbrella directory of the given module to the given
656   /// directory.
657   void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
658                       Twine NameAsWritten);
659 
660   /// Adds this header to the given module.
661   /// \param Role The role of the header wrt the module.
662   void addHeader(Module *Mod, Module::Header Header,
663                  ModuleHeaderRole Role, bool Imported = false);
664 
665   /// Marks this header as being excluded from the given module.
666   void excludeHeader(Module *Mod, Module::Header Header);
667 
668   /// Parse the given module map file, and record any modules we
669   /// encounter.
670   ///
671   /// \param File The file to be parsed.
672   ///
673   /// \param IsSystem Whether this module map file is in a system header
674   /// directory, and therefore should be considered a system module.
675   ///
676   /// \param HomeDir The directory in which relative paths within this module
677   ///        map file will be resolved.
678   ///
679   /// \param ID The FileID of the file to process, if we've already entered it.
680   ///
681   /// \param Offset [inout] On input the offset at which to start parsing. On
682   ///        output, the offset at which the module map terminated.
683   ///
684   /// \param ExternModuleLoc The location of the "extern module" declaration
685   ///        that caused us to load this module map file, if any.
686   ///
687   /// \returns true if an error occurred, false otherwise.
688   bool parseModuleMapFile(const FileEntry *File, bool IsSystem,
689                           const DirectoryEntry *HomeDir,
690                           FileID ID = FileID(), unsigned *Offset = nullptr,
691                           SourceLocation ExternModuleLoc = SourceLocation());
692 
693   /// Dump the contents of the module map, for debugging purposes.
694   void dump();
695 
696   using module_iterator = llvm::StringMap<Module *>::const_iterator;
697 
698   module_iterator module_begin() const { return Modules.begin(); }
699   module_iterator module_end()   const { return Modules.end(); }
700 
701   /// Cache a module load.  M might be nullptr.
702   void cacheModuleLoad(const IdentifierInfo &II, Module *M) {
703     CachedModuleLoads[&II] = M;
704   }
705 
706   /// Return a cached module load.
707   llvm::Optional<Module *> getCachedModuleLoad(const IdentifierInfo &II) {
708     auto I = CachedModuleLoads.find(&II);
709     if (I == CachedModuleLoads.end())
710       return None;
711     return I->second;
712   }
713 };
714 
715 } // namespace clang
716 
717 #endif // LLVM_CLANG_LEX_MODULEMAP_H
718