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