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 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_BASIC_MODULE_H
16 #define LLVM_CLANG_BASIC_MODULE_H
18 #include "clang/Basic/FileManager.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/PointerIntPair.h"
23 #include "llvm/ADT/PointerUnion.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/StringRef.h"
43 /// \brief Describes the name of a module.
44 typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
46 /// The signature of a module, which is a hash of the AST content.
47 struct ASTFileSignature : std::array<uint32_t, 5> {
48 ASTFileSignature(std::array<uint32_t, 5> S = {{0}})
49 : std::array<uint32_t, 5>(std::move(S)) {}
51 explicit operator bool() const {
52 return *this != std::array<uint32_t, 5>({{0}});
56 /// \brief Describes a module or submodule.
59 /// \brief The name of this module.
62 /// \brief The location of the module definition.
63 SourceLocation DefinitionLoc;
66 /// \brief This is a module that was defined by a module map and built out
70 /// \brief This is a C++ Modules TS module interface unit.
74 /// \brief The kind of this module.
75 ModuleKind Kind = ModuleMapModule;
77 /// \brief The parent of this module. This will be NULL for the top-level
81 /// \brief The build directory of this module. This is the directory in
82 /// which the module is notionally built, and relative to which its headers
84 const DirectoryEntry *Directory;
86 /// \brief The presumed file name for the module map defining this module.
87 /// Only non-empty when building from preprocessed source.
88 std::string PresumedModuleMapFile;
90 /// \brief The umbrella header or directory.
91 llvm::PointerUnion<const DirectoryEntry *, const FileEntry *> Umbrella;
93 /// \brief The module signature.
94 ASTFileSignature Signature;
96 /// \brief The name of the umbrella entry, as written in the module map.
97 std::string UmbrellaAsWritten;
100 /// \brief The submodules of this module, indexed by name.
101 std::vector<Module *> SubModules;
103 /// \brief A mapping from the submodule name to the index into the
104 /// \c SubModules vector at which that submodule resides.
105 llvm::StringMap<unsigned> SubModuleIndex;
107 /// \brief The AST file if this is a top-level module which has a
108 /// corresponding serialized AST file, or null otherwise.
109 const FileEntry *ASTFile;
111 /// \brief The top-level headers associated with this module.
112 llvm::SmallSetVector<const FileEntry *, 2> TopHeaders;
114 /// \brief top-level header filenames that aren't resolved to FileEntries yet.
115 std::vector<std::string> TopHeaderNames;
117 /// \brief Cache of modules visible to lookup in this module.
118 mutable llvm::DenseSet<const Module*> VisibleModulesCache;
120 /// The ID used when referencing this module within a VisibleModuleSet.
121 unsigned VisibilityID;
131 static const int NumHeaderKinds = HK_Excluded + 1;
133 /// \brief Information about a header directive as found in the module map
136 std::string NameAsWritten;
137 const FileEntry *Entry;
139 explicit operator bool() { return Entry; }
142 /// \brief Information about a directory name as found in the module map
144 struct DirectoryName {
145 std::string NameAsWritten;
146 const DirectoryEntry *Entry;
148 explicit operator bool() { return Entry; }
151 /// \brief The headers that are part of this module.
152 SmallVector<Header, 2> Headers[5];
154 /// \brief Stored information about a header directive that was found in the
155 /// module map file but has not been resolved to a file.
156 struct UnresolvedHeaderDirective {
157 HeaderKind Kind = HK_Normal;
158 SourceLocation FileNameLoc;
159 std::string FileName;
160 bool IsUmbrella = false;
161 bool HasBuiltinHeader = false;
162 Optional<off_t> Size;
163 Optional<time_t> ModTime;
166 /// Headers that are mentioned in the module map file but that we have not
167 /// yet attempted to resolve to a file on the file system.
168 SmallVector<UnresolvedHeaderDirective, 1> UnresolvedHeaders;
170 /// \brief Headers that are mentioned in the module map file but could not be
171 /// found on the file system.
172 SmallVector<UnresolvedHeaderDirective, 1> MissingHeaders;
174 /// \brief An individual requirement: a feature name and a flag indicating
175 /// the required state of that feature.
176 typedef std::pair<std::string, bool> Requirement;
178 /// \brief The set of language features required to use this module.
180 /// If any of these requirements are not available, the \c IsAvailable bit
181 /// will be false to indicate that this (sub)module is not available.
182 SmallVector<Requirement, 2> Requirements;
184 /// \brief Whether this module is missing a feature from \c Requirements.
185 unsigned IsMissingRequirement : 1;
187 /// \brief Whether we tried and failed to load a module file for this module.
188 unsigned HasIncompatibleModuleFile : 1;
190 /// \brief Whether this module is available in the current translation unit.
192 /// If the module is missing headers or does not meet all requirements then
193 /// this bit will be 0.
194 unsigned IsAvailable : 1;
196 /// \brief Whether this module was loaded from a module file.
197 unsigned IsFromModuleFile : 1;
199 /// \brief Whether this is a framework module.
200 unsigned IsFramework : 1;
202 /// \brief Whether this is an explicit submodule.
203 unsigned IsExplicit : 1;
205 /// \brief Whether this is a "system" module (which assumes that all
206 /// headers in it are system headers).
207 unsigned IsSystem : 1;
209 /// \brief Whether this is an 'extern "C"' module (which implicitly puts all
210 /// headers in it within an 'extern "C"' block, and allows the module to be
211 /// imported within such a block).
212 unsigned IsExternC : 1;
214 /// \brief Whether this is an inferred submodule (module * { ... }).
215 unsigned IsInferred : 1;
217 /// \brief Whether we should infer submodules for this module based on
220 /// Submodules can only be inferred for modules with an umbrella header.
221 unsigned InferSubmodules : 1;
223 /// \brief Whether, when inferring submodules, the inferred submodules
224 /// should be explicit.
225 unsigned InferExplicitSubmodules : 1;
227 /// \brief Whether, when inferring submodules, the inferr submodules should
228 /// export all modules they import (e.g., the equivalent of "export *").
229 unsigned InferExportWildcard : 1;
231 /// \brief Whether the set of configuration macros is exhaustive.
233 /// When the set of configuration macros is exhaustive, meaning
234 /// that no identifier not in this list should affect how the module is
236 unsigned ConfigMacrosExhaustive : 1;
238 /// \brief Whether files in this module can only include non-modular headers
239 /// and headers from used modules.
240 unsigned NoUndeclaredIncludes : 1;
242 /// \brief Describes the visibility of the various names within a
243 /// particular module.
244 enum NameVisibilityKind {
245 /// \brief All of the names in this module are hidden.
247 /// \brief All of the names in this module are visible.
251 /// \brief The visibility of names within this particular module.
252 NameVisibilityKind NameVisibility;
254 /// \brief The location of the inferred submodule.
255 SourceLocation InferredSubmoduleLoc;
257 /// \brief The set of modules imported by this module, and on which this
259 llvm::SmallSetVector<Module *, 2> Imports;
261 /// \brief Describes an exported module.
263 /// The pointer is the module being re-exported, while the bit will be true
264 /// to indicate that this is a wildcard export.
265 typedef llvm::PointerIntPair<Module *, 1, bool> ExportDecl;
267 /// \brief The set of export declarations.
268 SmallVector<ExportDecl, 2> Exports;
270 /// \brief Describes an exported module that has not yet been resolved
271 /// (perhaps because the module it refers to has not yet been loaded).
272 struct UnresolvedExportDecl {
273 /// \brief The location of the 'export' keyword in the module map file.
274 SourceLocation ExportLoc;
276 /// \brief The name of the module.
279 /// \brief Whether this export declaration ends in a wildcard, indicating
280 /// that all of its submodules should be exported (rather than the named
285 /// \brief The set of export declarations that have yet to be resolved.
286 SmallVector<UnresolvedExportDecl, 2> UnresolvedExports;
288 /// \brief The directly used modules.
289 SmallVector<Module *, 2> DirectUses;
291 /// \brief The set of use declarations that have yet to be resolved.
292 SmallVector<ModuleId, 2> UnresolvedDirectUses;
294 /// \brief A library or framework to link against when an entity from this
297 LinkLibrary() : IsFramework(false) { }
298 LinkLibrary(const std::string &Library, bool IsFramework)
299 : Library(Library), IsFramework(IsFramework) { }
301 /// \brief The library to link against.
303 /// This will typically be a library or framework name, but can also
304 /// be an absolute path to the library or framework.
307 /// \brief Whether this is a framework rather than a library.
311 /// \brief The set of libraries or frameworks to link against when
312 /// an entity from this module is used.
313 llvm::SmallVector<LinkLibrary, 2> LinkLibraries;
315 /// \brief The set of "configuration macros", which are macros that
316 /// (intentionally) change how this module is built.
317 std::vector<std::string> ConfigMacros;
319 /// \brief An unresolved conflict with another module.
320 struct UnresolvedConflict {
321 /// \brief The (unresolved) module id.
324 /// \brief The message provided to the user when there is a conflict.
328 /// \brief The list of conflicts for which the module-id has not yet been
330 std::vector<UnresolvedConflict> UnresolvedConflicts;
332 /// \brief A conflict between two modules.
334 /// \brief The module that this module conflicts with.
337 /// \brief The message provided to the user when there is a conflict.
341 /// \brief The list of conflicts.
342 std::vector<Conflict> Conflicts;
344 /// \brief Construct a new module or submodule.
345 Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
346 bool IsFramework, bool IsExplicit, unsigned VisibilityID);
350 /// \brief Determine whether this module is available for use within the
351 /// current translation unit.
352 bool isAvailable() const { return IsAvailable; }
354 /// \brief Determine whether this module is available for use within the
355 /// current translation unit.
357 /// \param LangOpts The language options used for the current
358 /// translation unit.
360 /// \param Target The target options used for the current translation unit.
362 /// \param Req If this module is unavailable, this parameter
363 /// will be set to one of the requirements that is not met for use of
365 bool isAvailable(const LangOptions &LangOpts,
366 const TargetInfo &Target,
368 UnresolvedHeaderDirective &MissingHeader) const;
370 /// \brief Determine whether this module is a submodule.
371 bool isSubModule() const { return Parent != nullptr; }
373 /// \brief Determine whether this module is a submodule of the given other
375 bool isSubModuleOf(const Module *Other) const;
377 /// \brief Determine whether this module is a part of a framework,
378 /// either because it is a framework module or because it is a submodule
379 /// of a framework module.
380 bool isPartOfFramework() const {
381 for (const Module *Mod = this; Mod; Mod = Mod->Parent)
382 if (Mod->IsFramework)
388 /// \brief Determine whether this module is a subframework of another
390 bool isSubFramework() const {
391 return IsFramework && Parent && Parent->isPartOfFramework();
394 /// \brief Retrieve the full name of this module, including the path from
395 /// its top-level module.
396 /// \param AllowStringLiterals If \c true, components that might not be
397 /// lexically valid as identifiers will be emitted as string literals.
398 std::string getFullModuleName(bool AllowStringLiterals = false) const;
400 /// \brief Whether the full name of this module is equal to joining
401 /// \p nameParts with "."s.
403 /// This is more efficient than getFullModuleName().
404 bool fullModuleNameIs(ArrayRef<StringRef> nameParts) const;
406 /// \brief Retrieve the top-level module for this (sub)module, which may
408 Module *getTopLevelModule() {
409 return const_cast<Module *>(
410 const_cast<const Module *>(this)->getTopLevelModule());
413 /// \brief Retrieve the top-level module for this (sub)module, which may
415 const Module *getTopLevelModule() const;
417 /// \brief Retrieve the name of the top-level module.
419 StringRef getTopLevelModuleName() const {
420 return getTopLevelModule()->Name;
423 /// \brief The serialized AST file for this module, if one was created.
424 const FileEntry *getASTFile() const {
425 return getTopLevelModule()->ASTFile;
428 /// \brief Set the serialized AST file for the top-level module of this module.
429 void setASTFile(const FileEntry *File) {
430 assert((File == nullptr || getASTFile() == nullptr ||
431 getASTFile() == File) && "file path changed");
432 getTopLevelModule()->ASTFile = File;
435 /// \brief Retrieve the directory for which this module serves as the
437 DirectoryName getUmbrellaDir() const;
439 /// \brief Retrieve the header that serves as the umbrella header for this
441 Header getUmbrellaHeader() const {
442 if (auto *E = Umbrella.dyn_cast<const FileEntry *>())
443 return Header{UmbrellaAsWritten, E};
447 /// \brief Determine whether this module has an umbrella directory that is
448 /// not based on an umbrella header.
449 bool hasUmbrellaDir() const {
450 return Umbrella && Umbrella.is<const DirectoryEntry *>();
453 /// \brief Add a top-level header associated with this module.
454 void addTopHeader(const FileEntry *File) {
456 TopHeaders.insert(File);
459 /// \brief Add a top-level header filename associated with this module.
460 void addTopHeaderFilename(StringRef Filename) {
461 TopHeaderNames.push_back(Filename);
464 /// \brief The top-level headers associated with this module.
465 ArrayRef<const FileEntry *> getTopHeaders(FileManager &FileMgr);
467 /// \brief Determine whether this module has declared its intention to
468 /// directly use another module.
469 bool directlyUses(const Module *Requested) const;
471 /// \brief Add the given feature requirement to the list of features
472 /// required by this module.
474 /// \param Feature The feature that is required by this module (and
477 /// \param RequiredState The required state of this feature: \c true
478 /// if it must be present, \c false if it must be absent.
480 /// \param LangOpts The set of language options that will be used to
481 /// evaluate the availability of this feature.
483 /// \param Target The target options that will be used to evaluate the
484 /// availability of this feature.
485 void addRequirement(StringRef Feature, bool RequiredState,
486 const LangOptions &LangOpts,
487 const TargetInfo &Target);
489 /// \brief Mark this module and all of its submodules as unavailable.
490 void markUnavailable(bool MissingRequirement = false);
492 /// \brief Find the submodule with the given name.
494 /// \returns The submodule if found, or NULL otherwise.
495 Module *findSubmodule(StringRef Name) const;
497 /// \brief Determine whether the specified module would be visible to
498 /// a lookup at the end of this module.
500 /// FIXME: This may return incorrect results for (submodules of) the
501 /// module currently being built, if it's queried before we see all
503 bool isModuleVisible(const Module *M) const {
504 if (VisibleModulesCache.empty())
505 buildVisibleModulesCache();
506 return VisibleModulesCache.count(M);
509 unsigned getVisibilityID() const { return VisibilityID; }
511 typedef std::vector<Module *>::iterator submodule_iterator;
512 typedef std::vector<Module *>::const_iterator submodule_const_iterator;
514 submodule_iterator submodule_begin() { return SubModules.begin(); }
515 submodule_const_iterator submodule_begin() const {return SubModules.begin();}
516 submodule_iterator submodule_end() { return SubModules.end(); }
517 submodule_const_iterator submodule_end() const { return SubModules.end(); }
519 llvm::iterator_range<submodule_iterator> submodules() {
520 return llvm::make_range(submodule_begin(), submodule_end());
522 llvm::iterator_range<submodule_const_iterator> submodules() const {
523 return llvm::make_range(submodule_begin(), submodule_end());
526 /// \brief Appends this module's list of exported modules to \p Exported.
528 /// This provides a subset of immediately imported modules (the ones that are
529 /// directly exported), not the complete set of exported modules.
530 void getExportedModules(SmallVectorImpl<Module *> &Exported) const;
532 static StringRef getModuleInputBufferName() {
533 return "<module-includes>";
536 /// \brief Print the module map for this module to the given stream.
538 void print(raw_ostream &OS, unsigned Indent = 0) const;
540 /// \brief Dump the contents of this module to the given output stream.
544 void buildVisibleModulesCache() const;
547 /// \brief A set of visible modules.
548 class VisibleModuleSet {
550 VisibleModuleSet() : Generation(0) {}
551 VisibleModuleSet(VisibleModuleSet &&O)
552 : ImportLocs(std::move(O.ImportLocs)), Generation(O.Generation ? 1 : 0) {
553 O.ImportLocs.clear();
557 /// Move from another visible modules set. Guaranteed to leave the source
558 /// empty and bump the generation on both.
559 VisibleModuleSet &operator=(VisibleModuleSet &&O) {
560 ImportLocs = std::move(O.ImportLocs);
561 O.ImportLocs.clear();
567 /// \brief Get the current visibility generation. Incremented each time the
568 /// set of visible modules changes in any way.
569 unsigned getGeneration() const { return Generation; }
571 /// \brief Determine whether a module is visible.
572 bool isVisible(const Module *M) const {
573 return getImportLoc(M).isValid();
576 /// \brief Get the location at which the import of a module was triggered.
577 SourceLocation getImportLoc(const Module *M) const {
578 return M->getVisibilityID() < ImportLocs.size()
579 ? ImportLocs[M->getVisibilityID()]
583 /// \brief A callback to call when a module is made visible (directly or
584 /// indirectly) by a call to \ref setVisible.
585 typedef llvm::function_ref<void(Module *M)> VisibleCallback;
586 /// \brief A callback to call when a module conflict is found. \p Path
587 /// consists of a sequence of modules from the conflicting module to the one
588 /// made visible, where each was exported by the next.
589 typedef llvm::function_ref<void(ArrayRef<Module *> Path,
590 Module *Conflict, StringRef Message)>
592 /// \brief Make a specific module visible.
593 void setVisible(Module *M, SourceLocation Loc,
594 VisibleCallback Vis = [](Module *) {},
595 ConflictCallback Cb = [](ArrayRef<Module *>, Module *,
599 /// Import locations for each visible module. Indexed by the module's
601 std::vector<SourceLocation> ImportLocs;
602 /// Visibility generation, bumped every time the visibility state changes.
606 } // end namespace clang
609 #endif // LLVM_CLANG_BASIC_MODULE_H