1 //===- Module.h - Describe a module -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Defines the clang::Module class, which describes a module in the
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CLANG_BASIC_MODULE_H
17 #define LLVM_CLANG_BASIC_MODULE_H
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/PointerIntPair.h"
25 #include "llvm/ADT/PointerUnion.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/iterator_range.h"
51 /// \brief Describes the name of a module.
52 using ModuleId = SmallVector<std::pair<std::string, SourceLocation>, 2>;
54 /// The signature of a module, which is a hash of the AST content.
55 struct ASTFileSignature : std::array<uint32_t, 5> {
56 ASTFileSignature(std::array<uint32_t, 5> S = {{0}})
57 : std::array<uint32_t, 5>(std::move(S)) {}
59 explicit operator bool() const {
60 return *this != std::array<uint32_t, 5>({{0}});
64 /// \brief Describes a module or submodule.
67 /// \brief The name of this module.
70 /// \brief The location of the module definition.
71 SourceLocation DefinitionLoc;
74 /// \brief This is a module that was defined by a module map and built out
78 /// \brief This is a C++ Modules TS module interface unit.
81 /// \brief This is a fragment of the global module within some C++ Modules
86 /// \brief The kind of this module.
87 ModuleKind Kind = ModuleMapModule;
89 /// \brief The parent of this module. This will be NULL for the top-level
93 /// \brief The build directory of this module. This is the directory in
94 /// which the module is notionally built, and relative to which its headers
96 const DirectoryEntry *Directory = nullptr;
98 /// \brief The presumed file name for the module map defining this module.
99 /// Only non-empty when building from preprocessed source.
100 std::string PresumedModuleMapFile;
102 /// \brief The umbrella header or directory.
103 llvm::PointerUnion<const DirectoryEntry *, const FileEntry *> Umbrella;
105 /// \brief The module signature.
106 ASTFileSignature Signature;
108 /// \brief The name of the umbrella entry, as written in the module map.
109 std::string UmbrellaAsWritten;
111 /// \brief The module through which entities defined in this module will
112 /// eventually be exposed, for use in "private" modules.
113 std::string ExportAsModule;
116 /// \brief The submodules of this module, indexed by name.
117 std::vector<Module *> SubModules;
119 /// \brief A mapping from the submodule name to the index into the
120 /// \c SubModules vector at which that submodule resides.
121 llvm::StringMap<unsigned> SubModuleIndex;
123 /// \brief The AST file if this is a top-level module which has a
124 /// corresponding serialized AST file, or null otherwise.
125 const FileEntry *ASTFile = nullptr;
127 /// \brief The top-level headers associated with this module.
128 llvm::SmallSetVector<const FileEntry *, 2> TopHeaders;
130 /// \brief top-level header filenames that aren't resolved to FileEntries yet.
131 std::vector<std::string> TopHeaderNames;
133 /// \brief Cache of modules visible to lookup in this module.
134 mutable llvm::DenseSet<const Module*> VisibleModulesCache;
136 /// The ID used when referencing this module within a VisibleModuleSet.
137 unsigned VisibilityID;
147 static const int NumHeaderKinds = HK_Excluded + 1;
149 /// \brief Information about a header directive as found in the module map
152 std::string NameAsWritten;
153 const FileEntry *Entry;
155 explicit operator bool() { return Entry; }
158 /// \brief Information about a directory name as found in the module map
160 struct DirectoryName {
161 std::string NameAsWritten;
162 const DirectoryEntry *Entry;
164 explicit operator bool() { return Entry; }
167 /// \brief The headers that are part of this module.
168 SmallVector<Header, 2> Headers[5];
170 /// \brief Stored information about a header directive that was found in the
171 /// module map file but has not been resolved to a file.
172 struct UnresolvedHeaderDirective {
173 HeaderKind Kind = HK_Normal;
174 SourceLocation FileNameLoc;
175 std::string FileName;
176 bool IsUmbrella = false;
177 bool HasBuiltinHeader = false;
178 Optional<off_t> Size;
179 Optional<time_t> ModTime;
182 /// Headers that are mentioned in the module map file but that we have not
183 /// yet attempted to resolve to a file on the file system.
184 SmallVector<UnresolvedHeaderDirective, 1> UnresolvedHeaders;
186 /// \brief Headers that are mentioned in the module map file but could not be
187 /// found on the file system.
188 SmallVector<UnresolvedHeaderDirective, 1> MissingHeaders;
190 /// \brief An individual requirement: a feature name and a flag indicating
191 /// the required state of that feature.
192 using Requirement = std::pair<std::string, bool>;
194 /// \brief The set of language features required to use this module.
196 /// If any of these requirements are not available, the \c IsAvailable bit
197 /// will be false to indicate that this (sub)module is not available.
198 SmallVector<Requirement, 2> Requirements;
200 /// \brief Whether this module is missing a feature from \c Requirements.
201 unsigned IsMissingRequirement : 1;
203 /// \brief Whether we tried and failed to load a module file for this module.
204 unsigned HasIncompatibleModuleFile : 1;
206 /// \brief Whether this module is available in the current translation unit.
208 /// If the module is missing headers or does not meet all requirements then
209 /// this bit will be 0.
210 unsigned IsAvailable : 1;
212 /// \brief Whether this module was loaded from a module file.
213 unsigned IsFromModuleFile : 1;
215 /// \brief Whether this is a framework module.
216 unsigned IsFramework : 1;
218 /// \brief Whether this is an explicit submodule.
219 unsigned IsExplicit : 1;
221 /// \brief Whether this is a "system" module (which assumes that all
222 /// headers in it are system headers).
223 unsigned IsSystem : 1;
225 /// \brief Whether this is an 'extern "C"' module (which implicitly puts all
226 /// headers in it within an 'extern "C"' block, and allows the module to be
227 /// imported within such a block).
228 unsigned IsExternC : 1;
230 /// \brief Whether this is an inferred submodule (module * { ... }).
231 unsigned IsInferred : 1;
233 /// \brief Whether we should infer submodules for this module based on
236 /// Submodules can only be inferred for modules with an umbrella header.
237 unsigned InferSubmodules : 1;
239 /// \brief Whether, when inferring submodules, the inferred submodules
240 /// should be explicit.
241 unsigned InferExplicitSubmodules : 1;
243 /// \brief Whether, when inferring submodules, the inferr submodules should
244 /// export all modules they import (e.g., the equivalent of "export *").
245 unsigned InferExportWildcard : 1;
247 /// \brief Whether the set of configuration macros is exhaustive.
249 /// When the set of configuration macros is exhaustive, meaning
250 /// that no identifier not in this list should affect how the module is
252 unsigned ConfigMacrosExhaustive : 1;
254 /// \brief Whether files in this module can only include non-modular headers
255 /// and headers from used modules.
256 unsigned NoUndeclaredIncludes : 1;
258 /// \brief Describes the visibility of the various names within a
259 /// particular module.
260 enum NameVisibilityKind {
261 /// \brief All of the names in this module are hidden.
263 /// \brief All of the names in this module are visible.
267 /// \brief The visibility of names within this particular module.
268 NameVisibilityKind NameVisibility;
270 /// \brief The location of the inferred submodule.
271 SourceLocation InferredSubmoduleLoc;
273 /// \brief The set of modules imported by this module, and on which this
275 llvm::SmallSetVector<Module *, 2> Imports;
277 /// \brief Describes an exported module.
279 /// The pointer is the module being re-exported, while the bit will be true
280 /// to indicate that this is a wildcard export.
281 using ExportDecl = llvm::PointerIntPair<Module *, 1, bool>;
283 /// \brief The set of export declarations.
284 SmallVector<ExportDecl, 2> Exports;
286 /// \brief Describes an exported module that has not yet been resolved
287 /// (perhaps because the module it refers to has not yet been loaded).
288 struct UnresolvedExportDecl {
289 /// \brief The location of the 'export' keyword in the module map file.
290 SourceLocation ExportLoc;
292 /// \brief The name of the module.
295 /// \brief Whether this export declaration ends in a wildcard, indicating
296 /// that all of its submodules should be exported (rather than the named
301 /// \brief The set of export declarations that have yet to be resolved.
302 SmallVector<UnresolvedExportDecl, 2> UnresolvedExports;
304 /// \brief The directly used modules.
305 SmallVector<Module *, 2> DirectUses;
307 /// \brief The set of use declarations that have yet to be resolved.
308 SmallVector<ModuleId, 2> UnresolvedDirectUses;
310 /// \brief A library or framework to link against when an entity from this
313 LinkLibrary() = default;
314 LinkLibrary(const std::string &Library, bool IsFramework)
315 : Library(Library), IsFramework(IsFramework) {}
317 /// \brief The library to link against.
319 /// This will typically be a library or framework name, but can also
320 /// be an absolute path to the library or framework.
323 /// \brief Whether this is a framework rather than a library.
324 bool IsFramework = false;
327 /// \brief The set of libraries or frameworks to link against when
328 /// an entity from this module is used.
329 llvm::SmallVector<LinkLibrary, 2> LinkLibraries;
331 /// \brief The set of "configuration macros", which are macros that
332 /// (intentionally) change how this module is built.
333 std::vector<std::string> ConfigMacros;
335 /// \brief An unresolved conflict with another module.
336 struct UnresolvedConflict {
337 /// \brief The (unresolved) module id.
340 /// \brief The message provided to the user when there is a conflict.
344 /// \brief The list of conflicts for which the module-id has not yet been
346 std::vector<UnresolvedConflict> UnresolvedConflicts;
348 /// \brief A conflict between two modules.
350 /// \brief The module that this module conflicts with.
353 /// \brief The message provided to the user when there is a conflict.
357 /// \brief The list of conflicts.
358 std::vector<Conflict> Conflicts;
360 /// \brief Construct a new module or submodule.
361 Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
362 bool IsFramework, bool IsExplicit, unsigned VisibilityID);
366 /// \brief Determine whether this module is available for use within the
367 /// current translation unit.
368 bool isAvailable() const { return IsAvailable; }
370 /// \brief Determine whether this module is available for use within the
371 /// current translation unit.
373 /// \param LangOpts The language options used for the current
374 /// translation unit.
376 /// \param Target The target options used for the current translation unit.
378 /// \param Req If this module is unavailable, this parameter
379 /// will be set to one of the requirements that is not met for use of
381 bool isAvailable(const LangOptions &LangOpts,
382 const TargetInfo &Target,
384 UnresolvedHeaderDirective &MissingHeader) const;
386 /// \brief Determine whether this module is a submodule.
387 bool isSubModule() const { return Parent != nullptr; }
389 /// \brief Determine whether this module is a submodule of the given other
391 bool isSubModuleOf(const Module *Other) const;
393 /// \brief Determine whether this module is a part of a framework,
394 /// either because it is a framework module or because it is a submodule
395 /// of a framework module.
396 bool isPartOfFramework() const {
397 for (const Module *Mod = this; Mod; Mod = Mod->Parent)
398 if (Mod->IsFramework)
404 /// \brief Determine whether this module is a subframework of another
406 bool isSubFramework() const {
407 return IsFramework && Parent && Parent->isPartOfFramework();
410 /// Set the parent of this module. This should only be used if the parent
411 /// could not be set during module creation.
412 void setParent(Module *M) {
415 Parent->SubModuleIndex[Name] = Parent->SubModules.size();
416 Parent->SubModules.push_back(this);
419 /// \brief Retrieve the full name of this module, including the path from
420 /// its top-level module.
421 /// \param AllowStringLiterals If \c true, components that might not be
422 /// lexically valid as identifiers will be emitted as string literals.
423 std::string getFullModuleName(bool AllowStringLiterals = false) const;
425 /// \brief Whether the full name of this module is equal to joining
426 /// \p nameParts with "."s.
428 /// This is more efficient than getFullModuleName().
429 bool fullModuleNameIs(ArrayRef<StringRef> nameParts) const;
431 /// \brief Retrieve the top-level module for this (sub)module, which may
433 Module *getTopLevelModule() {
434 return const_cast<Module *>(
435 const_cast<const Module *>(this)->getTopLevelModule());
438 /// \brief Retrieve the top-level module for this (sub)module, which may
440 const Module *getTopLevelModule() const;
442 /// \brief Retrieve the name of the top-level module.
443 StringRef getTopLevelModuleName() const {
444 return getTopLevelModule()->Name;
447 /// \brief The serialized AST file for this module, if one was created.
448 const FileEntry *getASTFile() const {
449 return getTopLevelModule()->ASTFile;
452 /// \brief Set the serialized AST file for the top-level module of this module.
453 void setASTFile(const FileEntry *File) {
454 assert((File == nullptr || getASTFile() == nullptr ||
455 getASTFile() == File) && "file path changed");
456 getTopLevelModule()->ASTFile = File;
459 /// \brief Retrieve the directory for which this module serves as the
461 DirectoryName getUmbrellaDir() const;
463 /// \brief Retrieve the header that serves as the umbrella header for this
465 Header getUmbrellaHeader() const {
466 if (auto *E = Umbrella.dyn_cast<const FileEntry *>())
467 return Header{UmbrellaAsWritten, E};
471 /// \brief Determine whether this module has an umbrella directory that is
472 /// not based on an umbrella header.
473 bool hasUmbrellaDir() const {
474 return Umbrella && Umbrella.is<const DirectoryEntry *>();
477 /// \brief Add a top-level header associated with this module.
478 void addTopHeader(const FileEntry *File) {
480 TopHeaders.insert(File);
483 /// \brief Add a top-level header filename associated with this module.
484 void addTopHeaderFilename(StringRef Filename) {
485 TopHeaderNames.push_back(Filename);
488 /// \brief The top-level headers associated with this module.
489 ArrayRef<const FileEntry *> getTopHeaders(FileManager &FileMgr);
491 /// \brief Determine whether this module has declared its intention to
492 /// directly use another module.
493 bool directlyUses(const Module *Requested) const;
495 /// \brief Add the given feature requirement to the list of features
496 /// required by this module.
498 /// \param Feature The feature that is required by this module (and
501 /// \param RequiredState The required state of this feature: \c true
502 /// if it must be present, \c false if it must be absent.
504 /// \param LangOpts The set of language options that will be used to
505 /// evaluate the availability of this feature.
507 /// \param Target The target options that will be used to evaluate the
508 /// availability of this feature.
509 void addRequirement(StringRef Feature, bool RequiredState,
510 const LangOptions &LangOpts,
511 const TargetInfo &Target);
513 /// \brief Mark this module and all of its submodules as unavailable.
514 void markUnavailable(bool MissingRequirement = false);
516 /// \brief Find the submodule with the given name.
518 /// \returns The submodule if found, or NULL otherwise.
519 Module *findSubmodule(StringRef Name) const;
521 /// \brief Determine whether the specified module would be visible to
522 /// a lookup at the end of this module.
524 /// FIXME: This may return incorrect results for (submodules of) the
525 /// module currently being built, if it's queried before we see all
527 bool isModuleVisible(const Module *M) const {
528 if (VisibleModulesCache.empty())
529 buildVisibleModulesCache();
530 return VisibleModulesCache.count(M);
533 unsigned getVisibilityID() const { return VisibilityID; }
535 using submodule_iterator = std::vector<Module *>::iterator;
536 using submodule_const_iterator = std::vector<Module *>::const_iterator;
538 submodule_iterator submodule_begin() { return SubModules.begin(); }
539 submodule_const_iterator submodule_begin() const {return SubModules.begin();}
540 submodule_iterator submodule_end() { return SubModules.end(); }
541 submodule_const_iterator submodule_end() const { return SubModules.end(); }
543 llvm::iterator_range<submodule_iterator> submodules() {
544 return llvm::make_range(submodule_begin(), submodule_end());
546 llvm::iterator_range<submodule_const_iterator> submodules() const {
547 return llvm::make_range(submodule_begin(), submodule_end());
550 /// \brief Appends this module's list of exported modules to \p Exported.
552 /// This provides a subset of immediately imported modules (the ones that are
553 /// directly exported), not the complete set of exported modules.
554 void getExportedModules(SmallVectorImpl<Module *> &Exported) const;
556 static StringRef getModuleInputBufferName() {
557 return "<module-includes>";
560 /// \brief Print the module map for this module to the given stream.
561 void print(raw_ostream &OS, unsigned Indent = 0) const;
563 /// \brief Dump the contents of this module to the given output stream.
567 void buildVisibleModulesCache() const;
570 /// \brief A set of visible modules.
571 class VisibleModuleSet {
573 VisibleModuleSet() = default;
574 VisibleModuleSet(VisibleModuleSet &&O)
575 : ImportLocs(std::move(O.ImportLocs)), Generation(O.Generation ? 1 : 0) {
576 O.ImportLocs.clear();
580 /// Move from another visible modules set. Guaranteed to leave the source
581 /// empty and bump the generation on both.
582 VisibleModuleSet &operator=(VisibleModuleSet &&O) {
583 ImportLocs = std::move(O.ImportLocs);
584 O.ImportLocs.clear();
590 /// \brief Get the current visibility generation. Incremented each time the
591 /// set of visible modules changes in any way.
592 unsigned getGeneration() const { return Generation; }
594 /// \brief Determine whether a module is visible.
595 bool isVisible(const Module *M) const {
596 return getImportLoc(M).isValid();
599 /// \brief Get the location at which the import of a module was triggered.
600 SourceLocation getImportLoc(const Module *M) const {
601 return M->getVisibilityID() < ImportLocs.size()
602 ? ImportLocs[M->getVisibilityID()]
606 /// \brief A callback to call when a module is made visible (directly or
607 /// indirectly) by a call to \ref setVisible.
608 using VisibleCallback = llvm::function_ref<void(Module *M)>;
610 /// \brief A callback to call when a module conflict is found. \p Path
611 /// consists of a sequence of modules from the conflicting module to the one
612 /// made visible, where each was exported by the next.
613 using ConflictCallback =
614 llvm::function_ref<void(ArrayRef<Module *> Path, Module *Conflict,
617 /// \brief Make a specific module visible.
618 void setVisible(Module *M, SourceLocation Loc,
619 VisibleCallback Vis = [](Module *) {},
620 ConflictCallback Cb = [](ArrayRef<Module *>, Module *,
624 /// Import locations for each visible module. Indexed by the module's
626 std::vector<SourceLocation> ImportLocs;
628 /// Visibility generation, bumped every time the visibility state changes.
629 unsigned Generation = 0;
634 #endif // LLVM_CLANG_BASIC_MODULE_H