clang 23.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"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/DenseSet.h"
25#include "llvm/ADT/PointerIntPair.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringMap.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/StringSet.h"
30#include "llvm/ADT/TinyPtrVector.h"
31#include "llvm/ADT/Twine.h"
32#include <ctime>
33#include <memory>
34#include <optional>
35#include <string>
36#include <utility>
37
38namespace clang {
39
41class DirectoryEntry;
42class FileEntry;
43class FileManager;
44class HeaderSearch;
45class SourceManager;
46
47/// A mechanism to observe the actions of the module map loader as it
48/// reads module map files.
50 virtual void anchor();
51
52public:
53 virtual ~ModuleMapCallbacks() = default;
54
55 /// Called when a module map file has been read.
56 ///
57 /// \param FileStart A SourceLocation referring to the start of the file's
58 /// contents.
59 /// \param File The file itself.
60 /// \param IsSystem Whether this is a module map from a system include path.
62 bool IsSystem) {}
63
64 /// Called when a header is added during module map parsing.
65 ///
66 /// \param Filename The header file itself.
67 virtual void moduleMapAddHeader(StringRef Filename) {}
68
69 /// Called when an umbrella header is added during module map parsing.
70 ///
71 /// \param Header The umbrella header to collect.
73};
74
75class 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 OptionalDirectoryEntryRef BuiltinIncludeDir;
87
88 /// The module that the main source file is associated with (the module
89 /// named LangOpts::CurrentModule, if we've loaded it).
90 Module *SourceModule = nullptr;
91
92 /// The allocator for all (sub)modules.
93 llvm::SpecificBumpPtrAllocator<Module> ModulesAlloc;
94
95 /// Submodules of the current module that have not yet been attached to it.
96 /// (Relationship is set up if/when we create an enclosing module.)
97 llvm::SmallVector<Module *, 8> PendingSubmodules;
98
99 /// The top-level modules that are known.
100 llvm::StringMap<Module *> Modules;
101
102 /// Module loading cache that includes submodules, indexed by IdentifierInfo.
103 /// nullptr is stored for modules that are known to fail to load.
104 llvm::DenseMap<const IdentifierInfo *, Module *> CachedModuleLoads;
105
106 /// Shadow modules created while building this module map.
107 llvm::SmallVector<Module*, 2> ShadowModules;
108
109 /// The number of modules we have created in total.
110 unsigned NumCreatedModules = 0;
111
112 /// In case a module has a export_as entry, it might have a pending link
113 /// name to be determined if that module is imported.
114 llvm::StringMap<llvm::StringSet<>> PendingLinkAsModule;
115
116public:
117 /// Use PendingLinkAsModule information to mark top level link names that
118 /// are going to be replaced by export_as aliases.
120
121 /// Make module to use export_as as the link dependency name if enough
122 /// information is available or add it to a pending list otherwise.
123 void addLinkAsDependency(Module *Mod);
124
125 /// Flags describing the role of a module header.
127 /// This header is normally included in the module.
129
130 /// This header is included but private.
132
133 /// This header is part of the module (for layering purposes) but
134 /// should be textually included.
136
137 /// This header is explicitly excluded from the module.
139
140 // Caution: Adding an enumerator needs other changes.
141 // Adjust the number of bits for KnownHeader::Storage.
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.
149
150 /// Convert a header role to a kind.
152
153 /// Check if the header with the given role is a modular one.
154 static bool isModular(ModuleHeaderRole Role);
155
156 /// A header that is known to reside within a given module,
157 /// whether it was included or excluded.
159 llvm::PointerIntPair<Module *, 3, ModuleHeaderRole> Storage;
160
161 public:
164
165 friend bool operator==(const KnownHeader &A, const KnownHeader &B) {
166 return A.Storage == B.Storage;
167 }
168 friend bool operator!=(const KnownHeader &A, const KnownHeader &B) {
169 return A.Storage != B.Storage;
170 }
171
172 /// Retrieve the module the header is stored in.
173 Module *getModule() const { return Storage.getPointer(); }
174
175 /// The role of this header within the module.
176 ModuleHeaderRole getRole() const { return Storage.getInt(); }
177
178 /// Whether this header is available in the module.
179 bool isAvailable() const {
180 return getRole() != ExcludedHeader && getModule()->isAvailable();
181 }
182
183 /// Whether this header is accessible from the specified module.
184 bool isAccessibleFrom(Module *M) const {
185 return !(getRole() & PrivateHeader) ||
186 (M && M->getTopLevelModule() == getModule()->getTopLevelModule());
187 }
188
189 // Whether this known header is valid (i.e., it has an
190 // associated module).
191 explicit operator bool() const {
192 return Storage.getPointer() != nullptr;
193 }
194 };
195
196 using AdditionalModMapsSet = llvm::DenseSet<FileEntryRef>;
197
198private:
199 friend class ModuleMapLoader;
200
201 using HeadersMap = llvm::DenseMap<FileEntryRef, SmallVector<KnownHeader, 1>>;
202
203 /// Mapping from each header to the module that owns the contents of
204 /// that header.
205 HeadersMap Headers;
206
207 /// Map from file sizes to modules with lazy header directives of that size.
208 mutable llvm::DenseMap<off_t, llvm::TinyPtrVector<Module*>> LazyHeadersBySize;
209
210 /// Map from mtimes to modules with lazy header directives with those mtimes.
211 mutable llvm::DenseMap<time_t, llvm::TinyPtrVector<Module*>>
212 LazyHeadersByModTime;
213
214 /// Mapping from directories with umbrella headers to the module
215 /// that is generated from the umbrella header.
216 ///
217 /// This mapping is used to map headers that haven't explicitly been named
218 /// in the module map over to the module that includes them via its umbrella
219 /// header.
220 llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs;
221
222 /// A generation counter that is used to test whether modules of the
223 /// same name may shadow or are illegal redefinitions.
224 ///
225 /// Modules from earlier scopes may shadow modules from later ones.
226 /// Modules from the same scope may not have the same name.
227 unsigned CurrentModuleScopeID = 0;
228
229 llvm::DenseMap<Module *, unsigned> ModuleScopeIDs;
230
231 using Attributes = ModuleAttributes;
232
233 /// A directory for which framework modules can be inferred.
234 struct InferredDirectory {
235 /// Whether to infer modules from this directory.
236 LLVM_PREFERRED_TYPE(bool)
237 unsigned InferModules : 1;
238
239 /// The attributes to use for inferred modules.
240 Attributes Attrs;
241
242 /// If \c InferModules is non-zero, the module map file that allowed
243 /// inferred modules. Otherwise, invalid.
244 FileID ModuleMapFID;
245
246 /// The names of modules that cannot be inferred within this
247 /// directory.
248 SmallVector<std::string, 2> ExcludedModules;
249
250 InferredDirectory() : InferModules(false) {}
251 };
252
253 /// A mapping from directories to information about inferring
254 /// framework modules from within those directories.
255 llvm::DenseMap<const DirectoryEntry *, InferredDirectory> InferredDirectories;
256
257 /// A mapping from an inferred module to the module map that allowed the
258 /// inference.
259 llvm::DenseMap<const Module *, FileID> InferredModuleAllowedBy;
260
261 llvm::DenseMap<const Module *, AdditionalModMapsSet> AdditionalModMaps;
262
263 /// Describes whether we haved loaded a particular file as a module
264 /// map.
265 llvm::DenseMap<const FileEntry *, bool> LoadedModuleMap;
266 llvm::DenseMap<const FileEntry *, const modulemap::ModuleMapFile *>
267 ParsedModuleMap;
268
269 /// Each CompilerInstance needs its own FileID for each module map, but there
270 /// should only ever be one for each.
271 llvm::DenseMap<const FileEntry *, FileID> ModuleMapLocalFileID;
272
273 std::vector<std::unique_ptr<modulemap::ModuleMapFile>> ParsedModuleMaps;
274
275 /// Map from top level module name to a list of ModuleDecls in the order they
276 /// were discovered. This allows handling shadowing correctly and diagnosing
277 /// redefinitions.
278 llvm::StringMap<SmallVector<std::pair<const modulemap::ModuleMapFile *,
279 const modulemap::ModuleDecl *>,
280 1>>
281 ParsedModules;
282
283 /// Resolve the given export declaration into an actual export
284 /// declaration.
285 ///
286 /// \param Mod The module in which we're resolving the export declaration.
287 ///
288 /// \param Unresolved The export declaration to resolve.
289 ///
290 /// \param Complain Whether this routine should complain about unresolvable
291 /// exports.
292 ///
293 /// \returns The resolved export declaration, which will have a NULL pointer
294 /// if the export could not be resolved.
296 resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved,
297 bool Complain) const;
298
299 /// Resolve the given module id to an actual module.
300 ///
301 /// \param Id The module-id to resolve.
302 ///
303 /// \param Mod The module in which we're resolving the module-id.
304 ///
305 /// \param Complain Whether this routine should complain about unresolvable
306 /// module-ids.
307 ///
308 /// \returns The resolved module, or null if the module-id could not be
309 /// resolved.
310 Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const;
311
312 /// Add an unresolved header to a module.
313 ///
314 /// \param Mod The module in which we're adding the unresolved header
315 /// directive.
316 /// \param Header The unresolved header directive.
317 /// \param NeedsFramework If Mod is not a framework but a missing header would
318 /// be found in case Mod was, set it to true. False otherwise.
319 void addUnresolvedHeader(Module *Mod,
320 Module::UnresolvedHeaderDirective Header,
321 bool &NeedsFramework);
322
323 /// Look up the given header directive to find an actual header file.
324 ///
325 /// \param M The module in which we're resolving the header directive.
326 /// \param Header The header directive to resolve.
327 /// \param RelativePathName Filled in with the relative path name from the
328 /// module to the resolved header.
329 /// \param NeedsFramework If M is not a framework but a missing header would
330 /// be found in case M was, set it to true. False otherwise.
331 /// \return The resolved file, if any.
333 findHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
334 SmallVectorImpl<char> &RelativePathName, 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(FileEntryRef 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(
365 FileEntryRef File, SmallVectorImpl<DirectoryEntryRef> &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(FileEntryRef File);
370
371 /// A convenience method to determine if \p File is (possibly nested)
372 /// in an umbrella directory.
373 bool isHeaderInUmbrellaDirs(FileEntryRef File) {
374 SmallVector<DirectoryEntryRef, 2> IntermediateDirs;
375 return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
376 }
377
378 Module *inferFrameworkModule(DirectoryEntryRef FrameworkDir, Attributes Attrs,
379 Module *Parent);
380
381public:
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.
399
400 /// Set the target information.
401 void setTarget(const TargetInfo &Target);
402
403 /// Set the directory that contains Clang-supplied include files, such as our
404 /// stdarg.h or tgmath.h.
405 void setBuiltinIncludeDir(DirectoryEntryRef Dir) { BuiltinIncludeDir = Dir; }
406
407 /// Get the directory that contains Clang-supplied include files.
408 OptionalDirectoryEntryRef getBuiltinDir() const { return BuiltinIncludeDir; }
409
410 /// Is this a compiler builtin header?
412
414 Module *Module) const;
415
416 /// Add a module map callback.
417 void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
418 Callbacks.push_back(std::move(Callback));
419 }
420
421 /// Retrieve the module that owns the given header file, if any. Note that
422 /// this does not implicitly load module maps, except for builtin headers,
423 /// and does not consult the external source. (Those checks are the
424 /// responsibility of \ref HeaderSearch.)
425 ///
426 /// \param File The header file that is likely to be included.
427 ///
428 /// \param AllowTextual If \c true and \p File is a textual header, return
429 /// its owning module. Otherwise, no KnownHeader will be returned if the
430 /// file is only known as a textual header.
431 ///
432 /// \returns The module KnownHeader, which provides the module that owns the
433 /// given header file. The KnownHeader is default constructed to indicate
434 /// that no module owns this header file.
435 KnownHeader findModuleForHeader(FileEntryRef File, bool AllowTextual = false,
436 bool AllowExcluded = false);
437
438 /// Retrieve all the modules that contain the given header file. Note that
439 /// this does not implicitly load module maps, except for builtin headers,
440 /// and does not consult the external source. (Those checks are the
441 /// responsibility of \ref HeaderSearch.)
442 ///
443 /// Typically, \ref findModuleForHeader should be used instead, as it picks
444 /// the preferred module for the header.
446
447 /// Like \ref findAllModulesForHeader, but do not attempt to infer module
448 /// ownership from umbrella headers if we've not already done so.
450
451 /// Resolve all lazy header directives for the specified file.
452 ///
453 /// This ensures that the HeaderFileInfo on HeaderSearch is up to date. This
454 /// is effectively internal, but is exposed so HeaderSearch can call it.
455 void resolveHeaderDirectives(const FileEntry *File) const;
456
457 /// Resolve lazy header directives for the specified module. If File is
458 /// provided, only headers with same size and modtime are resolved. If File
459 /// is not set, all headers are resolved.
461 std::optional<const FileEntry *> File) 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,
481
482 /// Determine whether the given header is part of a module
483 /// marked 'unavailable'.
484 bool isHeaderInUnavailableModule(FileEntryRef Header) const;
485
486 /// Determine whether the given header is unavailable as part
487 /// of the specified module.
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 Module *findOrLoadModule(StringRef Name);
499
500 Module *findOrInferSubmodule(Module *Parent, StringRef Name);
501
502 /// Retrieve a module with the given name using lexical name lookup,
503 /// starting at the given context.
504 ///
505 /// \param Name The name of the module to look up.
506 ///
507 /// \param Context The module context, from which we will perform lexical
508 /// name lookup.
509 ///
510 /// \returns The named module, if known; otherwise, returns null.
511 Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
512
513 /// Retrieve a module with the given name within the given context,
514 /// using direct (qualified) name lookup.
515 ///
516 /// \param Name The name of the module to look up.
517 ///
518 /// \param Context The module for which we will look for a submodule. If
519 /// null, we will look for a top-level module.
520 ///
521 /// \returns The named submodule, if known; otherwose, returns null.
522 Module *lookupModuleQualified(StringRef Name, Module *Context) const;
523
524 /// Find a new module or submodule, or create it if it does not already
525 /// exist.
526 ///
527 /// \param Name The name of the module to find or create.
528 ///
529 /// \param Parent The module that will act as the parent of this submodule,
530 /// or nullptr to indicate that this is a top-level module.
531 ///
532 /// \param IsFramework Whether this is a framework module.
533 ///
534 /// \param IsExplicit Whether this is an explicit submodule.
535 ///
536 /// \returns The found or newly-created module, along with a boolean value
537 /// that will be true if the module is newly-created.
538 std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
539 bool IsFramework,
540 bool IsExplicit);
541 /// Call \c ModuleMap::findOrCreateModule and throw away the information
542 /// whether the module was found or created.
543 Module *findOrCreateModuleFirst(StringRef Name, Module *Parent,
544 bool IsFramework, bool IsExplicit) {
545 return findOrCreateModule(Name, Parent, IsFramework, IsExplicit).first;
546 }
547 /// Create new submodule, assuming it does not exist. This function can only
548 /// be called when it is guaranteed that this submodule does not exist yet.
549 /// The parameters have same semantics as \c ModuleMap::findOrCreateModule.
550 Module *createModule(StringRef Name, Module *Parent, bool IsFramework,
551 bool IsExplicit);
552
553 /// Create a global module fragment for a C++ module unit.
554 ///
555 /// We model the global module fragment as a submodule of the module
556 /// interface unit. Unfortunately, we can't create the module interface
557 /// unit's Module until later, because we don't know what it will be called
558 /// usually. See C++20 [module.unit]/7.2 for the case we could know its
559 /// parent.
561 Module *Parent = nullptr);
563 Module *Parent);
564
565 /// Create a global module fragment for a C++ module interface unit.
567 SourceLocation Loc);
568
569 /// Create a new C++ module with the specified kind, and reparent any pending
570 /// global module fragment(s) to it.
572 Module::ModuleKind Kind);
573
574 /// Create a new module for a C++ module interface unit.
575 /// The module must not already exist, and will be configured for the current
576 /// compilation.
577 ///
578 /// Note that this also sets the current module to the newly-created module.
579 ///
580 /// \returns The newly-created module.
582
583 /// Create a new module for a C++ module implementation unit.
584 /// The interface module for this implementation (implicitly imported) must
585 /// exist and be loaded and present in the modules map.
586 ///
587 /// \returns The newly-created module.
589
590 /// Create a C++20 header unit.
591 Module *createHeaderUnit(SourceLocation Loc, StringRef Name,
593
594 /// Infer the contents of a framework module map from the given
595 /// framework directory.
596 Module *inferFrameworkModule(DirectoryEntryRef FrameworkDir, bool IsSystem,
597 Module *Parent);
598
599 /// Create a new top-level module that is shadowed by
600 /// \p ShadowingModule.
601 Module *createShadowedModule(StringRef Name, bool IsFramework,
602 Module *ShadowingModule);
603
604 /// Creates a new declaration scope for module names, allowing
605 /// previously defined modules to shadow definitions from the new scope.
606 ///
607 /// \note Module names from earlier scopes will shadow names from the new
608 /// scope, which is the opposite of how shadowing works for variables.
609 void finishModuleDeclarationScope() { CurrentModuleScopeID += 1; }
610
611 bool mayShadowNewModule(Module *ExistingModule) {
612 assert(!ExistingModule->Parent && "expected top-level module");
613 assert(ModuleScopeIDs.count(ExistingModule) && "unknown module");
614 return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
615 }
616
617 /// Check whether a framework module can be inferred in the given directory.
619 auto It = InferredDirectories.find(Dir);
620 return It != InferredDirectories.end() && It->getSecond().InferModules;
621 }
622
623 /// Retrieve the module map file containing the definition of the given
624 /// module.
625 ///
626 /// \param Module The module whose module map file will be returned, if known.
627 ///
628 /// \returns The FileID for the module map file containing the given module,
629 /// invalid if the module definition was inferred.
632
633 /// Get the module map file that (along with the module name) uniquely
634 /// identifies this module.
635 ///
636 /// The particular module that \c Name refers to may depend on how the module
637 /// was found in header search. However, the combination of \c Name and
638 /// this module map will be globally unique for top-level modules. In the case
639 /// of inferred modules, returns the module map that allowed the inference
640 /// (e.g. contained 'module *'). Otherwise, returns
641 /// getContainingModuleMapFile().
644
645 void setInferredModuleAllowedBy(Module *M, FileID ModMapFID);
646
647 /// Canonicalize \p Path in a manner suitable for a module map file. In
648 /// particular, this canonicalizes the parent directory separately from the
649 /// filename so that it does not affect header resolution relative to the
650 /// modulemap.
651 ///
652 /// \returns an error code if any filesystem operations failed. In this case
653 /// \p Path is not modified.
655
656 /// Get any module map files other than getModuleMapFileForUniquing(M)
657 /// that define submodules of a top-level module \p M. This is cheaper than
658 /// getting the module map file for each submodule individually, since the
659 /// expected number of results is very small.
661 auto I = AdditionalModMaps.find(M);
662 if (I == AdditionalModMaps.end())
663 return nullptr;
664 return &I->second;
665 }
666
668
669 /// Resolve all of the unresolved exports in the given module.
670 ///
671 /// \param Mod The module whose exports should be resolved.
672 ///
673 /// \param Complain Whether to emit diagnostics for failures.
674 ///
675 /// \returns true if any errors were encountered while resolving exports,
676 /// false otherwise.
677 bool resolveExports(Module *Mod, bool Complain);
678
679 /// Resolve all of the unresolved uses in the given module.
680 ///
681 /// \param Mod The module whose uses should be resolved.
682 ///
683 /// \param Complain Whether to emit diagnostics for failures.
684 ///
685 /// \returns true if any errors were encountered while resolving uses,
686 /// false otherwise.
687 bool resolveUses(Module *Mod, bool Complain);
688
689 /// Resolve all of the unresolved conflicts in the given module.
690 ///
691 /// \param Mod The module whose conflicts should be resolved.
692 ///
693 /// \param Complain Whether to emit diagnostics for failures.
694 ///
695 /// \returns true if any errors were encountered while resolving conflicts,
696 /// false otherwise.
697 bool resolveConflicts(Module *Mod, bool Complain);
698
699 /// Sets the umbrella header of the given module to the given header.
700 void
702 const Twine &NameAsWritten,
703 const Twine &PathRelativeToRootModuleDirectory);
704
705 /// Sets the umbrella directory of the given module to the given directory.
706 void setUmbrellaDirAsWritten(Module *Mod, DirectoryEntryRef UmbrellaDir,
707 const Twine &NameAsWritten,
708 const Twine &PathRelativeToRootModuleDirectory);
709
710 /// Adds this header to the given module.
711 /// \param Role The role of the header wrt the module.
712 void addHeader(Module *Mod, Module::Header Header,
713 ModuleHeaderRole Role, bool Imported = false);
714
715 /// Parse a module map without creating `clang::Module` instances.
716 bool parseModuleMapFile(FileEntryRef File, bool IsSystem,
717 DirectoryEntryRef Dir, FileID ID = FileID(),
718 SourceLocation ExternModuleLoc = SourceLocation());
719
720 /// Load the given module map file, and record any modules we
721 /// encounter.
722 ///
723 /// \param File The file to be loaded.
724 ///
725 /// \param IsSystem Whether this module map file is in a system header
726 /// directory, and therefore should be considered a system module.
727 ///
728 /// \param HomeDir The directory in which relative paths within this module
729 /// map file will be resolved.
730 ///
731 /// \param ID The FileID of the file to process, if we've already entered it.
732 ///
733 /// \param Offset [inout] On input the offset at which to start parsing. On
734 /// output, the offset at which the module map terminated.
735 ///
736 /// \param ExternModuleLoc The location of the "extern module" declaration
737 /// that caused us to load this module map file, if any.
738 ///
739 /// \returns true if an error occurred, false otherwise.
740 bool
742 DirectoryEntryRef HomeDir, FileID ID = FileID(),
743 unsigned *Offset = nullptr,
744 SourceLocation ExternModuleLoc = SourceLocation());
745
746 /// Dump the contents of the module map, for debugging purposes.
747 void dump();
748
749 using module_iterator = llvm::StringMap<Module *>::const_iterator;
750
751 module_iterator module_begin() const { return Modules.begin(); }
752 module_iterator module_end() const { return Modules.end(); }
753 llvm::iterator_range<module_iterator> modules() const {
754 return {module_begin(), module_end()};
755 }
756
757 /// Cache a module load. M might be nullptr.
759 CachedModuleLoads[&II] = M;
760 }
761
762 /// Return a cached module load.
763 std::optional<Module *> getCachedModuleLoad(const IdentifierInfo &II) {
764 auto I = CachedModuleLoads.find(&II);
765 if (I == CachedModuleLoads.end())
766 return std::nullopt;
767 return I->second;
768 }
769};
770
771} // namespace clang
772
773#endif // LLVM_CLANG_LEX_MODULEMAP_H
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Defines the clang::LangOptions interface.
Defines the clang::Module class, which describes a module in the source code.
Defines the clang::SourceLocation class and associated facilities.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
A reference to a DirectoryEntry that includes the name of the directory as it was accessed by the Fil...
Cached information about one directory (either on disk or in the virtual file system).
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
Cached information about one file (either on disk or in the virtual file system).
Definition FileEntry.h:302
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:53
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
One of these records is kept for each identifier that is lexed.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
A mechanism to observe the actions of the module map loader as it reads module map files.
Definition ModuleMap.h:49
virtual void moduleMapFileRead(SourceLocation FileStart, FileEntryRef File, bool IsSystem)
Called when a module map file has been read.
Definition ModuleMap.h:61
virtual ~ModuleMapCallbacks()=default
virtual void moduleMapAddHeader(StringRef Filename)
Called when a header is added during module map parsing.
Definition ModuleMap.h:67
virtual void moduleMapAddUmbrellaHeader(FileEntryRef Header)
Called when an umbrella header is added during module map parsing.
Definition ModuleMap.h:72
KnownHeader(Module *M, ModuleHeaderRole Role)
Definition ModuleMap.h:163
bool isAccessibleFrom(Module *M) const
Whether this header is accessible from the specified module.
Definition ModuleMap.h:184
ModuleHeaderRole getRole() const
The role of this header within the module.
Definition ModuleMap.h:176
friend bool operator!=(const KnownHeader &A, const KnownHeader &B)
Definition ModuleMap.h:168
friend bool operator==(const KnownHeader &A, const KnownHeader &B)
Definition ModuleMap.h:165
Module * getModule() const
Retrieve the module the header is stored in.
Definition ModuleMap.h:173
bool isAvailable() const
Whether this header is available in the module.
Definition ModuleMap.h:179
Module * createShadowedModule(StringRef Name, bool IsFramework, Module *ShadowingModule)
Create a new top-level module that is shadowed by ShadowingModule.
bool resolveExports(Module *Mod, bool Complain)
Resolve all of the unresolved exports in the given module.
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:62
friend class ModuleMapLoader
Definition ModuleMap.h:199
void dump()
Dump the contents of the module map, for debugging purposes.
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.
llvm::StringMap< Module * >::const_iterator module_iterator
Definition ModuleMap.h:749
void setUmbrellaDirAsWritten(Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory)
Sets the umbrella directory of the given module to the given directory.
void diagnoseHeaderInclusion(Module *RequestingModule, bool RequestingModuleIsModuleInterface, SourceLocation FilenameLoc, StringRef Filename, FileEntryRef File)
Reports errors if a module must not include a specific file.
void addAdditionalModuleMapFile(const Module *M, FileEntryRef ModuleMap)
OptionalFileEntryRef getContainingModuleMapFile(const Module *Module) const
static Module::HeaderKind headerRoleToKind(ModuleHeaderRole Role)
Convert a header role to a kind.
Definition ModuleMap.cpp:69
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
void finishModuleDeclarationScope()
Creates a new declaration scope for module names, allowing previously defined modules to shadow defin...
Definition ModuleMap.h:609
bool canInferFrameworkModule(const DirectoryEntry *Dir) const
Check whether a framework module can be inferred in the given directory.
Definition ModuleMap.h:618
bool mayShadowNewModule(Module *ExistingModule)
Definition ModuleMap.h:611
bool parseAndLoadModuleMapFile(FileEntryRef File, bool IsSystem, DirectoryEntryRef HomeDir, FileID ID=FileID(), unsigned *Offset=nullptr, SourceLocation ExternModuleLoc=SourceLocation())
Load the given module map file, and record any modules we encounter.
KnownHeader findModuleForHeader(FileEntryRef File, bool AllowTextual=false, bool AllowExcluded=false)
Retrieve the module that owns the given header file, if any.
Module * createHeaderUnit(SourceLocation Loc, StringRef Name, Module::Header H)
Create a C++20 header unit.
void addModuleMapCallbacks(std::unique_ptr< ModuleMapCallbacks > Callback)
Add a module map callback.
Definition ModuleMap.h:417
void setBuiltinIncludeDir(DirectoryEntryRef Dir)
Set the directory that contains Clang-supplied include files, such as our stdarg.h or tgmath....
Definition ModuleMap.h:405
static bool isModular(ModuleHeaderRole Role)
Check if the header with the given role is a modular one.
bool resolveConflicts(Module *Mod, bool Complain)
Resolve all of the unresolved conflicts in the given module.
bool isHeaderUnavailableInModule(FileEntryRef Header, const Module *RequestingModule) const
Determine whether the given header is unavailable as part of the specified module.
void resolveHeaderDirectives(const FileEntry *File) const
Resolve all lazy header directives for the specified file.
module_iterator module_begin() const
Definition ModuleMap.h:751
ArrayRef< KnownHeader > findResolvedModulesForHeader(FileEntryRef File) const
Like findAllModulesForHeader, but do not attempt to infer module ownership from umbrella headers if w...
OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const
bool shouldImportRelativeToBuiltinIncludeDir(StringRef FileName, Module *Module) const
Module * createModuleForImplementationUnit(SourceLocation Loc, StringRef Name)
Create a new module for a C++ module implementation unit.
ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags, const LangOptions &LangOpts, const TargetInfo *Target, HeaderSearch &HeaderInfo)
Construct a new module map.
std::optional< Module * > getCachedModuleLoad(const IdentifierInfo &II)
Return a cached module load.
Definition ModuleMap.h:763
std::error_code canonicalizeModuleMapPath(SmallVectorImpl< char > &Path)
Canonicalize Path in a manner suitable for a module map file.
FileID getModuleMapFileIDForUniquing(const Module *M) const
Get the module map file that (along with the module name) uniquely identifies this module.
void setInferredModuleAllowedBy(Module *M, FileID ModMapFID)
void setUmbrellaHeaderAsWritten(Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory)
Sets the umbrella header of the given module to the given header.
llvm::DenseSet< FileEntryRef > AdditionalModMapsSet
Definition ModuleMap.h:196
Module * findOrCreateModuleFirst(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Call ModuleMap::findOrCreateModule and throw away the information whether the module was found or cre...
Definition ModuleMap.h:543
Module * lookupModuleUnqualified(StringRef Name, Module *Context) const
Retrieve a module with the given name using lexical name lookup, starting at the given context.
bool isBuiltinHeader(FileEntryRef File)
Is this a compiler builtin header?
Module * createModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Create new submodule, assuming it does not exist.
module_iterator module_end() const
Definition ModuleMap.h:752
AdditionalModMapsSet * getAdditionalModuleMapFiles(const Module *M)
Get any module map files other than getModuleMapFileForUniquing(M) that define submodules of a top-le...
Definition ModuleMap.h:660
bool isHeaderInUnavailableModule(FileEntryRef Header) const
Determine whether the given header is part of a module marked 'unavailable'.
FileID getContainingModuleMapFileID(const Module *Module) const
Retrieve the module map file containing the definition of the given module.
OptionalDirectoryEntryRef getBuiltinDir() const
Get the directory that contains Clang-supplied include files.
Definition ModuleMap.h:408
~ModuleMap()
Destroy the module map.
bool parseModuleMapFile(FileEntryRef File, bool IsSystem, DirectoryEntryRef Dir, FileID ID=FileID(), SourceLocation ExternModuleLoc=SourceLocation())
Parse a module map without creating clang::Module instances.
Module * createGlobalModuleFragmentForModuleUnit(SourceLocation Loc, Module *Parent=nullptr)
Create a global module fragment for a C++ module unit.
void setTarget(const TargetInfo &Target)
Set the target information.
Module * lookupModuleQualified(StringRef Name, Module *Context) const
Retrieve a module with the given name within the given context, using direct (qualified) name lookup.
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
Definition ModuleMap.cpp:51
void cacheModuleLoad(const IdentifierInfo &II, Module *M)
Cache a module load. M might be nullptr.
Definition ModuleMap.h:758
ModuleHeaderRole
Flags describing the role of a module header.
Definition ModuleMap.h:126
@ PrivateHeader
This header is included but private.
Definition ModuleMap.h:131
@ ExcludedHeader
This header is explicitly excluded from the module.
Definition ModuleMap.h:138
@ NormalHeader
This header is normally included in the module.
Definition ModuleMap.h:128
@ TextualHeader
This header is part of the module (for layering purposes) but should be textually included.
Definition ModuleMap.h:135
Module * createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name)
Create a new module for a C++ module interface unit.
void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role, bool Imported=false)
Adds this header to the given module.
Module * createPrivateModuleFragmentForInterfaceUnit(Module *Parent, SourceLocation Loc)
Create a global module fragment for a C++ module interface unit.
Module * findOrInferSubmodule(Module *Parent, StringRef Name)
ArrayRef< KnownHeader > findAllModulesForHeader(FileEntryRef File)
Retrieve all the modules that contain the given header file.
Module * createImplicitGlobalModuleFragmentForModuleUnit(SourceLocation Loc, Module *Parent)
Module * createModuleUnitWithKind(SourceLocation Loc, StringRef Name, Module::ModuleKind Kind)
Create a new C++ module with the specified kind, and reparent any pending global module fragment(s) t...
Module * findOrLoadModule(StringRef Name)
static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind)
Convert a header kind to a role. Requires Kind to not be HK_Excluded.
Definition ModuleMap.cpp:86
llvm::iterator_range< module_iterator > modules() const
Definition ModuleMap.h:753
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Describes a module or submodule.
Definition Module.h:144
Module * Parent
The parent of this module.
Definition Module.h:193
bool isAvailable() const
Determine whether this module is available for use within the current translation unit.
Definition Module.h:586
llvm::PointerIntPair< Module *, 1, bool > ExportDecl
Describes an exported module.
Definition Module.h:468
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:722
Encodes a location in the source.
This class handles loading and caching of source files into memory.
Exposes information about the current target.
Definition TargetInfo.h:226
#define bool
Definition gpuintrin.h:32
The JSON file list parser is used to communicate input to InstallAPI.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:208
SmallVector< std::pair< std::string, SourceLocation >, 2 > ModuleId
Describes the name of a module.
Definition Module.h:55
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
CustomizableOptional< DirectoryEntryRef > OptionalDirectoryEntryRef
#define false
Definition stdbool.h:26
The set of attributes that can be attached to a module.
Definition Module.h:109
Information about a header directive as found in the module map file.
Definition Module.h:287