1 //===- ModuleMap.h - Describe the layout of modules -------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the ModuleMap interface, which describes the layout of a
10 // module as it relates to headers.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LEX_MODULEMAP_H
15 #define LLVM_CLANG_LEX_MODULEMAP_H
17 #include "clang/Basic/LangOptions.h"
18 #include "clang/Basic/Module.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/PointerIntPair.h"
23 #include "llvm/ADT/StringSet.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/TinyPtrVector.h"
29 #include "llvm/ADT/Twine.h"
37 class DiagnosticsEngine;
44 /// A mechanism to observe the actions of the module map parser as it
45 /// reads module map files.
46 class ModuleMapCallbacks {
47 virtual void anchor();
50 virtual ~ModuleMapCallbacks() = default;
52 /// Called when a module map file has been read.
54 /// \param FileStart A SourceLocation referring to the start of the file's
56 /// \param File The file itself.
57 /// \param IsSystem Whether this is a module map from a system include path.
58 virtual void moduleMapFileRead(SourceLocation FileStart,
59 const FileEntry &File, bool IsSystem) {}
61 /// Called when a header is added during module map parsing.
63 /// \param Filename The header file itself.
64 virtual void moduleMapAddHeader(StringRef Filename) {}
66 /// Called when an umbrella header is added during module map parsing.
68 /// \param FileMgr FileManager instance
69 /// \param Header The umbrella header to collect.
70 virtual void moduleMapAddUmbrellaHeader(FileManager *FileMgr,
71 const FileEntry *Header) {}
75 SourceManager &SourceMgr;
76 DiagnosticsEngine &Diags;
77 const LangOptions &LangOpts;
78 const TargetInfo *Target;
79 HeaderSearch &HeaderInfo;
81 llvm::SmallVector<std::unique_ptr<ModuleMapCallbacks>, 1> Callbacks;
83 /// The directory used for Clang-supplied, builtin include headers,
84 /// such as "stdint.h".
85 const DirectoryEntry *BuiltinIncludeDir = nullptr;
87 /// Language options used to parse the module map itself.
89 /// These are always simple C language options.
90 LangOptions MMapLangOpts;
92 /// The module that the main source file is associated with (the module
93 /// named LangOpts::CurrentModule, if we've loaded it).
94 Module *SourceModule = nullptr;
96 /// Submodules of the current module that have not yet been attached to it.
97 /// (Ownership is transferred if/when we create an enclosing module.)
98 llvm::SmallVector<std::unique_ptr<Module>, 8> PendingSubmodules;
100 /// The top-level modules that are known.
101 llvm::StringMap<Module *> Modules;
103 /// Shadow modules created while building this module map.
104 llvm::SmallVector<Module*, 2> ShadowModules;
106 /// The number of modules we have created in total.
107 unsigned NumCreatedModules = 0;
109 /// In case a module has a export_as entry, it might have a pending link
110 /// name to be determined if that module is imported.
111 llvm::StringMap<llvm::StringSet<>> PendingLinkAsModule;
114 /// Use PendingLinkAsModule information to mark top level link names that
115 /// are going to be replaced by export_as aliases.
116 void resolveLinkAsDependencies(Module *Mod);
118 /// Make module to use export_as as the link dependency name if enough
119 /// information is available or add it to a pending list otherwise.
120 void addLinkAsDependency(Module *Mod);
122 /// Flags describing the role of a module header.
123 enum ModuleHeaderRole {
124 /// This header is normally included in the module.
127 /// This header is included but private.
130 /// This header is part of the module (for layering purposes) but
131 /// should be textually included.
134 // Caution: Adding an enumerator needs other changes.
135 // Adjust the number of bits for KnownHeader::Storage.
136 // Adjust the bitfield HeaderFileInfo::HeaderRole size.
137 // Adjust the HeaderFileInfoTrait::ReadData streaming.
138 // Adjust the HeaderFileInfoTrait::EmitData streaming.
139 // Adjust ModuleMap::addHeader.
142 /// Convert a header kind to a role. Requires Kind to not be HK_Excluded.
143 static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind);
145 /// Convert a header role to a kind.
146 static Module::HeaderKind headerRoleToKind(ModuleHeaderRole Role);
148 /// A header that is known to reside within a given module,
149 /// whether it was included or excluded.
151 llvm::PointerIntPair<Module *, 2, ModuleHeaderRole> Storage;
154 KnownHeader() : Storage(nullptr, NormalHeader) {}
155 KnownHeader(Module *M, ModuleHeaderRole Role) : Storage(M, Role) {}
157 friend bool operator==(const KnownHeader &A, const KnownHeader &B) {
158 return A.Storage == B.Storage;
160 friend bool operator!=(const KnownHeader &A, const KnownHeader &B) {
161 return A.Storage != B.Storage;
164 /// Retrieve the module the header is stored in.
165 Module *getModule() const { return Storage.getPointer(); }
167 /// The role of this header within the module.
168 ModuleHeaderRole getRole() const { return Storage.getInt(); }
170 /// Whether this header is available in the module.
171 bool isAvailable() const {
172 return getModule()->isAvailable();
175 /// Whether this header is accessible from the specified module.
176 bool isAccessibleFrom(Module *M) const {
177 return !(getRole() & PrivateHeader) ||
178 (M && M->getTopLevelModule() == getModule()->getTopLevelModule());
181 // Whether this known header is valid (i.e., it has an
182 // associated module).
183 explicit operator bool() const {
184 return Storage.getPointer() != nullptr;
188 using AdditionalModMapsSet = llvm::SmallPtrSet<const FileEntry *, 1>;
191 friend class ModuleMapParser;
194 llvm::DenseMap<const FileEntry *, SmallVector<KnownHeader, 1>>;
196 /// Mapping from each header to the module that owns the contents of
200 /// Map from file sizes to modules with lazy header directives of that size.
201 mutable llvm::DenseMap<off_t, llvm::TinyPtrVector<Module*>> LazyHeadersBySize;
203 /// Map from mtimes to modules with lazy header directives with those mtimes.
204 mutable llvm::DenseMap<time_t, llvm::TinyPtrVector<Module*>>
205 LazyHeadersByModTime;
207 /// Mapping from directories with umbrella headers to the module
208 /// that is generated from the umbrella header.
210 /// This mapping is used to map headers that haven't explicitly been named
211 /// in the module map over to the module that includes them via its umbrella
213 llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs;
215 /// A generation counter that is used to test whether modules of the
216 /// same name may shadow or are illegal redefinitions.
218 /// Modules from earlier scopes may shadow modules from later ones.
219 /// Modules from the same scope may not have the same name.
220 unsigned CurrentModuleScopeID = 0;
222 llvm::DenseMap<Module *, unsigned> ModuleScopeIDs;
224 /// The set of attributes that can be attached to a module.
226 /// Whether this is a system module.
227 unsigned IsSystem : 1;
229 /// Whether this is an extern "C" module.
230 unsigned IsExternC : 1;
232 /// Whether this is an exhaustive set of configuration macros.
233 unsigned IsExhaustive : 1;
235 /// Whether files in this module can only include non-modular headers
236 /// and headers from used modules.
237 unsigned NoUndeclaredIncludes : 1;
240 : IsSystem(false), IsExternC(false), IsExhaustive(false),
241 NoUndeclaredIncludes(false) {}
244 /// A directory for which framework modules can be inferred.
245 struct InferredDirectory {
246 /// Whether to infer modules from this directory.
247 unsigned InferModules : 1;
249 /// The attributes to use for inferred modules.
252 /// If \c InferModules is non-zero, the module map file that allowed
253 /// inferred modules. Otherwise, nullptr.
254 const FileEntry *ModuleMapFile;
256 /// The names of modules that cannot be inferred within this
258 SmallVector<std::string, 2> ExcludedModules;
260 InferredDirectory() : InferModules(false) {}
263 /// A mapping from directories to information about inferring
264 /// framework modules from within those directories.
265 llvm::DenseMap<const DirectoryEntry *, InferredDirectory> InferredDirectories;
267 /// A mapping from an inferred module to the module map that allowed the
269 llvm::DenseMap<const Module *, const FileEntry *> InferredModuleAllowedBy;
271 llvm::DenseMap<const Module *, AdditionalModMapsSet> AdditionalModMaps;
273 /// Describes whether we haved parsed a particular file as a module
275 llvm::DenseMap<const FileEntry *, bool> ParsedModuleMap;
277 /// Resolve the given export declaration into an actual export
280 /// \param Mod The module in which we're resolving the export declaration.
282 /// \param Unresolved The export declaration to resolve.
284 /// \param Complain Whether this routine should complain about unresolvable
287 /// \returns The resolved export declaration, which will have a NULL pointer
288 /// if the export could not be resolved.
290 resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved,
291 bool Complain) const;
293 /// Resolve the given module id to an actual module.
295 /// \param Id The module-id to resolve.
297 /// \param Mod The module in which we're resolving the module-id.
299 /// \param Complain Whether this routine should complain about unresolvable
302 /// \returns The resolved module, or null if the module-id could not be
304 Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const;
306 /// Add an unresolved header to a module.
308 /// \param Mod The module in which we're adding the unresolved header
310 /// \param Header The unresolved header directive.
311 /// \param NeedsFramework If Mod is not a framework but a missing header would
312 /// be found in case Mod was, set it to true. False otherwise.
313 void addUnresolvedHeader(Module *Mod,
314 Module::UnresolvedHeaderDirective Header,
315 bool &NeedsFramework);
317 /// Look up the given header directive to find an actual header file.
319 /// \param M The module in which we're resolving the header directive.
320 /// \param Header The header directive to resolve.
321 /// \param RelativePathName Filled in with the relative path name from the
322 /// module to the resolved header.
323 /// \param NeedsFramework If M is not a framework but a missing header would
324 /// be found in case M was, set it to true. False otherwise.
325 /// \return The resolved file, if any.
326 const FileEntry *findHeader(Module *M,
327 const Module::UnresolvedHeaderDirective &Header,
328 SmallVectorImpl<char> &RelativePathName,
329 bool &NeedsFramework);
331 /// Resolve the given header directive.
333 /// \param M The module in which we're resolving the header directive.
334 /// \param Header The header directive to resolve.
335 /// \param NeedsFramework If M is not a framework but a missing header would
336 /// be found in case M was, set it to true. False otherwise.
337 void resolveHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
338 bool &NeedsFramework);
340 /// Attempt to resolve the specified header directive as naming a builtin
342 /// \return \c true if a corresponding builtin header was found.
343 bool resolveAsBuiltinHeader(Module *M,
344 const Module::UnresolvedHeaderDirective &Header);
346 /// Looks up the modules that \p File corresponds to.
348 /// If \p File represents a builtin header within Clang's builtin include
349 /// directory, this also loads all of the module maps to see if it will get
350 /// associated with a specific module (e.g. in /usr/include).
351 HeadersMap::iterator findKnownHeader(const FileEntry *File);
353 /// Searches for a module whose umbrella directory contains \p File.
355 /// \param File The header to search for.
357 /// \param IntermediateDirs On success, contains the set of directories
358 /// searched before finding \p File.
359 KnownHeader findHeaderInUmbrellaDirs(const FileEntry *File,
360 SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs);
362 /// Given that \p File is not in the Headers map, look it up within
363 /// umbrella directories and find or create a module for it.
364 KnownHeader findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File);
366 /// A convenience method to determine if \p File is (possibly nested)
367 /// in an umbrella directory.
368 bool isHeaderInUmbrellaDirs(const FileEntry *File) {
369 SmallVector<const DirectoryEntry *, 2> IntermediateDirs;
370 return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
373 Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
374 Attributes Attrs, Module *Parent);
377 /// Construct a new module map.
379 /// \param SourceMgr The source manager used to find module files and headers.
380 /// This source manager should be shared with the header-search mechanism,
381 /// since they will refer to the same headers.
383 /// \param Diags A diagnostic engine used for diagnostics.
385 /// \param LangOpts Language options for this translation unit.
387 /// \param Target The target for this translation unit.
388 ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
389 const LangOptions &LangOpts, const TargetInfo *Target,
390 HeaderSearch &HeaderInfo);
392 /// Destroy the module map.
395 /// Set the target information.
396 void setTarget(const TargetInfo &Target);
398 /// Set the directory that contains Clang-supplied include
399 /// files, such as our stdarg.h or tgmath.h.
400 void setBuiltinIncludeDir(const DirectoryEntry *Dir) {
401 BuiltinIncludeDir = Dir;
404 /// Get the directory that contains Clang-supplied include files.
405 const DirectoryEntry *getBuiltinDir() const {
406 return BuiltinIncludeDir;
409 /// Is this a compiler builtin header?
410 static bool isBuiltinHeader(StringRef FileName);
412 /// Add a module map callback.
413 void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
414 Callbacks.push_back(std::move(Callback));
417 /// Retrieve the module that owns the given header file, if any.
419 /// \param File The header file that is likely to be included.
421 /// \param AllowTextual If \c true and \p File is a textual header, return
422 /// its owning module. Otherwise, no KnownHeader will be returned if the
423 /// file is only known as a textual header.
425 /// \returns The module KnownHeader, which provides the module that owns the
426 /// given header file. The KnownHeader is default constructed to indicate
427 /// that no module owns this header file.
428 KnownHeader findModuleForHeader(const FileEntry *File,
429 bool AllowTextual = false);
431 /// Retrieve all the modules that contain the given header file. This
432 /// may not include umbrella modules, nor information from external sources,
433 /// if they have not yet been inferred / loaded.
435 /// Typically, \ref findModuleForHeader should be used instead, as it picks
436 /// the preferred module for the header.
437 ArrayRef<KnownHeader> findAllModulesForHeader(const FileEntry *File) const;
439 /// Resolve all lazy header directives for the specified file.
441 /// This ensures that the HeaderFileInfo on HeaderSearch is up to date. This
442 /// is effectively internal, but is exposed so HeaderSearch can call it.
443 void resolveHeaderDirectives(const FileEntry *File) const;
445 /// Resolve all lazy header directives for the specified module.
446 void resolveHeaderDirectives(Module *Mod) const;
448 /// Reports errors if a module must not include a specific file.
450 /// \param RequestingModule The module including a file.
452 /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in
453 /// the interface of RequestingModule, \c false if it's in the
454 /// implementation of RequestingModule. Value is ignored and
455 /// meaningless if RequestingModule is nullptr.
457 /// \param FilenameLoc The location of the inclusion's filename.
459 /// \param Filename The included filename as written.
461 /// \param File The included file.
462 void diagnoseHeaderInclusion(Module *RequestingModule,
463 bool RequestingModuleIsModuleInterface,
464 SourceLocation FilenameLoc, StringRef Filename,
465 const FileEntry *File);
467 /// Determine whether the given header is part of a module
468 /// marked 'unavailable'.
469 bool isHeaderInUnavailableModule(const FileEntry *Header) const;
471 /// Determine whether the given header is unavailable as part
472 /// of the specified module.
473 bool isHeaderUnavailableInModule(const FileEntry *Header,
474 const Module *RequestingModule) const;
476 /// Retrieve a module with the given name.
478 /// \param Name The name of the module to look up.
480 /// \returns The named module, if known; otherwise, returns null.
481 Module *findModule(StringRef Name) const;
483 /// Retrieve a module with the given name using lexical name lookup,
484 /// starting at the given context.
486 /// \param Name The name of the module to look up.
488 /// \param Context The module context, from which we will perform lexical
491 /// \returns The named module, if known; otherwise, returns null.
492 Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
494 /// Retrieve a module with the given name within the given context,
495 /// using direct (qualified) name lookup.
497 /// \param Name The name of the module to look up.
499 /// \param Context The module for which we will look for a submodule. If
500 /// null, we will look for a top-level module.
502 /// \returns The named submodule, if known; otherwose, returns null.
503 Module *lookupModuleQualified(StringRef Name, Module *Context) const;
505 /// Find a new module or submodule, or create it if it does not already
508 /// \param Name The name of the module to find or create.
510 /// \param Parent The module that will act as the parent of this submodule,
511 /// or nullptr to indicate that this is a top-level module.
513 /// \param IsFramework Whether this is a framework module.
515 /// \param IsExplicit Whether this is an explicit submodule.
517 /// \returns The found or newly-created module, along with a boolean value
518 /// that will be true if the module is newly-created.
519 std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
523 /// Create a global module fragment for a C++ module unit.
525 /// We model the global module fragment as a submodule of the module
526 /// interface unit. Unfortunately, we can't create the module interface
527 /// unit's Module until later, because we don't know what it will be called.
528 Module *createGlobalModuleFragmentForModuleUnit(SourceLocation Loc);
530 /// Create a global module fragment for a C++ module interface unit.
531 Module *createPrivateModuleFragmentForInterfaceUnit(Module *Parent,
534 /// Create a new module for a C++ module interface unit.
535 /// The module must not already exist, and will be configured for the current
538 /// Note that this also sets the current module to the newly-created module.
540 /// \returns The newly-created module.
541 Module *createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name,
542 Module *GlobalModule);
544 /// Create a header module from the specified list of headers.
545 Module *createHeaderModule(StringRef Name, ArrayRef<Module::Header> Headers);
547 /// Infer the contents of a framework module map from the given
548 /// framework directory.
549 Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir,
550 bool IsSystem, Module *Parent);
552 /// Create a new top-level module that is shadowed by
553 /// \p ShadowingModule.
554 Module *createShadowedModule(StringRef Name, bool IsFramework,
555 Module *ShadowingModule);
557 /// Creates a new declaration scope for module names, allowing
558 /// previously defined modules to shadow definitions from the new scope.
560 /// \note Module names from earlier scopes will shadow names from the new
561 /// scope, which is the opposite of how shadowing works for variables.
562 void finishModuleDeclarationScope() { CurrentModuleScopeID += 1; }
564 bool mayShadowNewModule(Module *ExistingModule) {
565 assert(!ExistingModule->Parent && "expected top-level module");
566 assert(ModuleScopeIDs.count(ExistingModule) && "unknown module");
567 return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
570 /// Retrieve the module map file containing the definition of the given
573 /// \param Module The module whose module map file will be returned, if known.
575 /// \returns The file entry for the module map file containing the given
576 /// module, or nullptr if the module definition was inferred.
577 const FileEntry *getContainingModuleMapFile(const Module *Module) const;
579 /// Get the module map file that (along with the module name) uniquely
580 /// identifies this module.
582 /// The particular module that \c Name refers to may depend on how the module
583 /// was found in header search. However, the combination of \c Name and
584 /// this module map will be globally unique for top-level modules. In the case
585 /// of inferred modules, returns the module map that allowed the inference
586 /// (e.g. contained 'module *'). Otherwise, returns
587 /// getContainingModuleMapFile().
588 const FileEntry *getModuleMapFileForUniquing(const Module *M) const;
590 void setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap);
592 /// Get any module map files other than getModuleMapFileForUniquing(M)
593 /// that define submodules of a top-level module \p M. This is cheaper than
594 /// getting the module map file for each submodule individually, since the
595 /// expected number of results is very small.
596 AdditionalModMapsSet *getAdditionalModuleMapFiles(const Module *M) {
597 auto I = AdditionalModMaps.find(M);
598 if (I == AdditionalModMaps.end())
603 void addAdditionalModuleMapFile(const Module *M, const FileEntry *ModuleMap) {
604 AdditionalModMaps[M].insert(ModuleMap);
607 /// Resolve all of the unresolved exports in the given module.
609 /// \param Mod The module whose exports should be resolved.
611 /// \param Complain Whether to emit diagnostics for failures.
613 /// \returns true if any errors were encountered while resolving exports,
615 bool resolveExports(Module *Mod, bool Complain);
617 /// Resolve all of the unresolved uses in the given module.
619 /// \param Mod The module whose uses should be resolved.
621 /// \param Complain Whether to emit diagnostics for failures.
623 /// \returns true if any errors were encountered while resolving uses,
625 bool resolveUses(Module *Mod, bool Complain);
627 /// Resolve all of the unresolved conflicts in the given module.
629 /// \param Mod The module whose conflicts should be resolved.
631 /// \param Complain Whether to emit diagnostics for failures.
633 /// \returns true if any errors were encountered while resolving conflicts,
635 bool resolveConflicts(Module *Mod, bool Complain);
637 /// Sets the umbrella header of the given module to the given
639 void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
640 Twine NameAsWritten);
642 /// Sets the umbrella directory of the given module to the given
644 void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
645 Twine NameAsWritten);
647 /// Adds this header to the given module.
648 /// \param Role The role of the header wrt the module.
649 void addHeader(Module *Mod, Module::Header Header,
650 ModuleHeaderRole Role, bool Imported = false);
652 /// Marks this header as being excluded from the given module.
653 void excludeHeader(Module *Mod, Module::Header Header);
655 /// Parse the given module map file, and record any modules we
658 /// \param File The file to be parsed.
660 /// \param IsSystem Whether this module map file is in a system header
661 /// directory, and therefore should be considered a system module.
663 /// \param HomeDir The directory in which relative paths within this module
664 /// map file will be resolved.
666 /// \param ID The FileID of the file to process, if we've already entered it.
668 /// \param Offset [inout] On input the offset at which to start parsing. On
669 /// output, the offset at which the module map terminated.
671 /// \param ExternModuleLoc The location of the "extern module" declaration
672 /// that caused us to load this module map file, if any.
674 /// \returns true if an error occurred, false otherwise.
675 bool parseModuleMapFile(const FileEntry *File, bool IsSystem,
676 const DirectoryEntry *HomeDir,
677 FileID ID = FileID(), unsigned *Offset = nullptr,
678 SourceLocation ExternModuleLoc = SourceLocation());
680 /// Dump the contents of the module map, for debugging purposes.
683 using module_iterator = llvm::StringMap<Module *>::const_iterator;
685 module_iterator module_begin() const { return Modules.begin(); }
686 module_iterator module_end() const { return Modules.end(); }
691 #endif // LLVM_CLANG_LEX_MODULEMAP_H