1 //===- Module.h - Describe a module -----------------------------*- 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 /// \file
10 /// Defines the clang::Module class, which describes a module in the
11 /// source code.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CLANG_BASIC_MODULE_H
16 #define LLVM_CLANG_BASIC_MODULE_H
17 
18 #include "clang/Basic/DirectoryEntry.h"
19 #include "clang/Basic/FileEntry.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/STLExtras.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/iterator_range.h"
31 #include <array>
32 #include <cassert>
33 #include <cstdint>
34 #include <ctime>
35 #include <iterator>
36 #include <string>
37 #include <utility>
38 #include <vector>
39 
40 namespace llvm {
41 
42 class raw_ostream;
43 
44 } // namespace llvm
45 
46 namespace clang {
47 
48 class FileManager;
49 class LangOptions;
50 class TargetInfo;
51 
52 /// Describes the name of a module.
53 using ModuleId = SmallVector<std::pair<std::string, SourceLocation>, 2>;
54 
55 /// The signature of a module, which is a hash of the AST content.
56 struct ASTFileSignature : std::array<uint8_t, 20> {
57   using BaseT = std::array<uint8_t, 20>;
58 
59   static constexpr size_t size = std::tuple_size<BaseT>::value;
60 
61   ASTFileSignature(BaseT S = {{0}}) : BaseT(std::move(S)) {}
62 
63   explicit operator bool() const { return *this != BaseT({{0}}); }
64 
65   /// Returns the value truncated to the size of an uint64_t.
66   uint64_t truncatedValue() const {
67     uint64_t Value = 0;
68     static_assert(sizeof(*this) >= sizeof(uint64_t), "No need to truncate.");
69     for (unsigned I = 0; I < sizeof(uint64_t); ++I)
70       Value |= static_cast<uint64_t>((*this)[I]) << (I * 8);
71     return Value;
72   }
73 
74   static ASTFileSignature create(std::array<uint8_t, 20> Bytes) {
75     return ASTFileSignature(std::move(Bytes));
76   }
77 
78   static ASTFileSignature createDISentinel() {
79     ASTFileSignature Sentinel;
80     Sentinel.fill(0xFF);
81     return Sentinel;
82   }
83 
84   template <typename InputIt>
85   static ASTFileSignature create(InputIt First, InputIt Last) {
86     assert(std::distance(First, Last) == size &&
87            "Wrong amount of bytes to create an ASTFileSignature");
88 
89     ASTFileSignature Signature;
90     std::copy(First, Last, Signature.begin());
91     return Signature;
92   }
93 };
94 
95 /// Describes a module or submodule.
96 class Module {
97 public:
98   /// The name of this module.
99   std::string Name;
100 
101   /// The location of the module definition.
102   SourceLocation DefinitionLoc;
103 
104   enum ModuleKind {
105     /// This is a module that was defined by a module map and built out
106     /// of header files.
107     ModuleMapModule,
108 
109     /// This is a C++20 module interface unit.
110     ModuleInterfaceUnit,
111 
112     /// This is a C++ 20 header unit.
113     ModuleHeaderUnit,
114 
115     /// This is a C++ 20 module partition interface.
116     ModulePartitionInterface,
117 
118     /// This is a C++ 20 module partition implementation.
119     ModulePartitionImplementation,
120 
121     /// This is a fragment of the global module within some C++ module.
122     GlobalModuleFragment,
123 
124     /// This is the private module fragment within some C++ module.
125     PrivateModuleFragment,
126   };
127 
128   /// The kind of this module.
129   ModuleKind Kind = ModuleMapModule;
130 
131   /// The parent of this module. This will be NULL for the top-level
132   /// module.
133   Module *Parent;
134 
135   /// The build directory of this module. This is the directory in
136   /// which the module is notionally built, and relative to which its headers
137   /// are found.
138   const DirectoryEntry *Directory = nullptr;
139 
140   /// The presumed file name for the module map defining this module.
141   /// Only non-empty when building from preprocessed source.
142   std::string PresumedModuleMapFile;
143 
144   /// The umbrella header or directory.
145   llvm::PointerUnion<const FileEntry *, const DirectoryEntry *> Umbrella;
146 
147   /// The module signature.
148   ASTFileSignature Signature;
149 
150   /// The name of the umbrella entry, as written in the module map.
151   std::string UmbrellaAsWritten;
152 
153   // The path to the umbrella entry relative to the root module's \c Directory.
154   std::string UmbrellaRelativeToRootModuleDirectory;
155 
156   /// The module through which entities defined in this module will
157   /// eventually be exposed, for use in "private" modules.
158   std::string ExportAsModule;
159 
160   /// Does this Module scope describe part of the purview of a named C++ module?
161   bool isModulePurview() const {
162     return Kind == ModuleInterfaceUnit || Kind == ModulePartitionInterface ||
163            Kind == ModulePartitionImplementation ||
164            Kind == PrivateModuleFragment;
165   }
166 
167   /// Does this Module scope describe a fragment of the global module within
168   /// some C++ module.
169   bool isGlobalModule() const { return Kind == GlobalModuleFragment; }
170 
171   bool isPrivateModule() const { return Kind == PrivateModuleFragment; }
172 
173   bool isModuleMapModule() const { return Kind == ModuleMapModule; }
174 
175 private:
176   /// The submodules of this module, indexed by name.
177   std::vector<Module *> SubModules;
178 
179   /// A mapping from the submodule name to the index into the
180   /// \c SubModules vector at which that submodule resides.
181   llvm::StringMap<unsigned> SubModuleIndex;
182 
183   /// The AST file if this is a top-level module which has a
184   /// corresponding serialized AST file, or null otherwise.
185   Optional<FileEntryRef> ASTFile;
186 
187   /// The top-level headers associated with this module.
188   llvm::SmallSetVector<const FileEntry *, 2> TopHeaders;
189 
190   /// top-level header filenames that aren't resolved to FileEntries yet.
191   std::vector<std::string> TopHeaderNames;
192 
193   /// Cache of modules visible to lookup in this module.
194   mutable llvm::DenseSet<const Module*> VisibleModulesCache;
195 
196   /// The ID used when referencing this module within a VisibleModuleSet.
197   unsigned VisibilityID;
198 
199 public:
200   enum HeaderKind {
201     HK_Normal,
202     HK_Textual,
203     HK_Private,
204     HK_PrivateTextual,
205     HK_Excluded
206   };
207   static const int NumHeaderKinds = HK_Excluded + 1;
208 
209   /// Information about a header directive as found in the module map
210   /// file.
211   struct Header {
212     std::string NameAsWritten;
213     std::string PathRelativeToRootModuleDirectory;
214     const FileEntry *Entry;
215 
216     explicit operator bool() { return Entry; }
217   };
218 
219   /// Information about a directory name as found in the module map
220   /// file.
221   struct DirectoryName {
222     std::string NameAsWritten;
223     std::string PathRelativeToRootModuleDirectory;
224     const DirectoryEntry *Entry;
225 
226     explicit operator bool() { return Entry; }
227   };
228 
229   /// The headers that are part of this module.
230   SmallVector<Header, 2> Headers[5];
231 
232   /// Stored information about a header directive that was found in the
233   /// module map file but has not been resolved to a file.
234   struct UnresolvedHeaderDirective {
235     HeaderKind Kind = HK_Normal;
236     SourceLocation FileNameLoc;
237     std::string FileName;
238     bool IsUmbrella = false;
239     bool HasBuiltinHeader = false;
240     Optional<off_t> Size;
241     Optional<time_t> ModTime;
242   };
243 
244   /// Headers that are mentioned in the module map file but that we have not
245   /// yet attempted to resolve to a file on the file system.
246   SmallVector<UnresolvedHeaderDirective, 1> UnresolvedHeaders;
247 
248   /// Headers that are mentioned in the module map file but could not be
249   /// found on the file system.
250   SmallVector<UnresolvedHeaderDirective, 1> MissingHeaders;
251 
252   /// An individual requirement: a feature name and a flag indicating
253   /// the required state of that feature.
254   using Requirement = std::pair<std::string, bool>;
255 
256   /// The set of language features required to use this module.
257   ///
258   /// If any of these requirements are not available, the \c IsAvailable bit
259   /// will be false to indicate that this (sub)module is not available.
260   SmallVector<Requirement, 2> Requirements;
261 
262   /// A module with the same name that shadows this module.
263   Module *ShadowingModule = nullptr;
264 
265   /// Whether this module has declared itself unimportable, either because
266   /// it's missing a requirement from \p Requirements or because it's been
267   /// shadowed by another module.
268   unsigned IsUnimportable : 1;
269 
270   /// Whether we tried and failed to load a module file for this module.
271   unsigned HasIncompatibleModuleFile : 1;
272 
273   /// Whether this module is available in the current translation unit.
274   ///
275   /// If the module is missing headers or does not meet all requirements then
276   /// this bit will be 0.
277   unsigned IsAvailable : 1;
278 
279   /// Whether this module was loaded from a module file.
280   unsigned IsFromModuleFile : 1;
281 
282   /// Whether this is a framework module.
283   unsigned IsFramework : 1;
284 
285   /// Whether this is an explicit submodule.
286   unsigned IsExplicit : 1;
287 
288   /// Whether this is a "system" module (which assumes that all
289   /// headers in it are system headers).
290   unsigned IsSystem : 1;
291 
292   /// Whether this is an 'extern "C"' module (which implicitly puts all
293   /// headers in it within an 'extern "C"' block, and allows the module to be
294   /// imported within such a block).
295   unsigned IsExternC : 1;
296 
297   /// Whether this is an inferred submodule (module * { ... }).
298   unsigned IsInferred : 1;
299 
300   /// Whether we should infer submodules for this module based on
301   /// the headers.
302   ///
303   /// Submodules can only be inferred for modules with an umbrella header.
304   unsigned InferSubmodules : 1;
305 
306   /// Whether, when inferring submodules, the inferred submodules
307   /// should be explicit.
308   unsigned InferExplicitSubmodules : 1;
309 
310   /// Whether, when inferring submodules, the inferr submodules should
311   /// export all modules they import (e.g., the equivalent of "export *").
312   unsigned InferExportWildcard : 1;
313 
314   /// Whether the set of configuration macros is exhaustive.
315   ///
316   /// When the set of configuration macros is exhaustive, meaning
317   /// that no identifier not in this list should affect how the module is
318   /// built.
319   unsigned ConfigMacrosExhaustive : 1;
320 
321   /// Whether files in this module can only include non-modular headers
322   /// and headers from used modules.
323   unsigned NoUndeclaredIncludes : 1;
324 
325   /// Whether this module came from a "private" module map, found next
326   /// to a regular (public) module map.
327   unsigned ModuleMapIsPrivate : 1;
328 
329   /// Describes the visibility of the various names within a
330   /// particular module.
331   enum NameVisibilityKind {
332     /// All of the names in this module are hidden.
333     Hidden,
334     /// All of the names in this module are visible.
335     AllVisible
336   };
337 
338   /// The visibility of names within this particular module.
339   NameVisibilityKind NameVisibility;
340 
341   /// The location of the inferred submodule.
342   SourceLocation InferredSubmoduleLoc;
343 
344   /// The set of modules imported by this module, and on which this
345   /// module depends.
346   llvm::SmallSetVector<Module *, 2> Imports;
347 
348   /// Describes an exported module.
349   ///
350   /// The pointer is the module being re-exported, while the bit will be true
351   /// to indicate that this is a wildcard export.
352   using ExportDecl = llvm::PointerIntPair<Module *, 1, bool>;
353 
354   /// The set of export declarations.
355   SmallVector<ExportDecl, 2> Exports;
356 
357   /// Describes an exported module that has not yet been resolved
358   /// (perhaps because the module it refers to has not yet been loaded).
359   struct UnresolvedExportDecl {
360     /// The location of the 'export' keyword in the module map file.
361     SourceLocation ExportLoc;
362 
363     /// The name of the module.
364     ModuleId Id;
365 
366     /// Whether this export declaration ends in a wildcard, indicating
367     /// that all of its submodules should be exported (rather than the named
368     /// module itself).
369     bool Wildcard;
370   };
371 
372   /// The set of export declarations that have yet to be resolved.
373   SmallVector<UnresolvedExportDecl, 2> UnresolvedExports;
374 
375   /// The directly used modules.
376   SmallVector<Module *, 2> DirectUses;
377 
378   /// The set of use declarations that have yet to be resolved.
379   SmallVector<ModuleId, 2> UnresolvedDirectUses;
380 
381   /// When \c NoUndeclaredIncludes is true, the set of modules this module tried
382   /// to import but didn't because they are not direct uses.
383   llvm::SmallSetVector<const Module *, 2> UndeclaredUses;
384 
385   /// A library or framework to link against when an entity from this
386   /// module is used.
387   struct LinkLibrary {
388     LinkLibrary() = default;
389     LinkLibrary(const std::string &Library, bool IsFramework)
390         : Library(Library), IsFramework(IsFramework) {}
391 
392     /// The library to link against.
393     ///
394     /// This will typically be a library or framework name, but can also
395     /// be an absolute path to the library or framework.
396     std::string Library;
397 
398     /// Whether this is a framework rather than a library.
399     bool IsFramework = false;
400   };
401 
402   /// The set of libraries or frameworks to link against when
403   /// an entity from this module is used.
404   llvm::SmallVector<LinkLibrary, 2> LinkLibraries;
405 
406   /// Autolinking uses the framework name for linking purposes
407   /// when this is false and the export_as name otherwise.
408   bool UseExportAsModuleLinkName = false;
409 
410   /// The set of "configuration macros", which are macros that
411   /// (intentionally) change how this module is built.
412   std::vector<std::string> ConfigMacros;
413 
414   /// An unresolved conflict with another module.
415   struct UnresolvedConflict {
416     /// The (unresolved) module id.
417     ModuleId Id;
418 
419     /// The message provided to the user when there is a conflict.
420     std::string Message;
421   };
422 
423   /// The list of conflicts for which the module-id has not yet been
424   /// resolved.
425   std::vector<UnresolvedConflict> UnresolvedConflicts;
426 
427   /// A conflict between two modules.
428   struct Conflict {
429     /// The module that this module conflicts with.
430     Module *Other;
431 
432     /// The message provided to the user when there is a conflict.
433     std::string Message;
434   };
435 
436   /// The list of conflicts.
437   std::vector<Conflict> Conflicts;
438 
439   /// Construct a new module or submodule.
440   Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
441          bool IsFramework, bool IsExplicit, unsigned VisibilityID);
442 
443   ~Module();
444 
445   /// Determine whether this module has been declared unimportable.
446   bool isUnimportable() const { return IsUnimportable; }
447 
448   /// Determine whether this module has been declared unimportable.
449   ///
450   /// \param LangOpts The language options used for the current
451   /// translation unit.
452   ///
453   /// \param Target The target options used for the current translation unit.
454   ///
455   /// \param Req If this module is unimportable because of a missing
456   /// requirement, this parameter will be set to one of the requirements that
457   /// is not met for use of this module.
458   ///
459   /// \param ShadowingModule If this module is unimportable because it is
460   /// shadowed, this parameter will be set to the shadowing module.
461   bool isUnimportable(const LangOptions &LangOpts, const TargetInfo &Target,
462                       Requirement &Req, Module *&ShadowingModule) const;
463 
464   /// Determine whether this module is available for use within the
465   /// current translation unit.
466   bool isAvailable() const { return IsAvailable; }
467 
468   /// Determine whether this module is available for use within the
469   /// current translation unit.
470   ///
471   /// \param LangOpts The language options used for the current
472   /// translation unit.
473   ///
474   /// \param Target The target options used for the current translation unit.
475   ///
476   /// \param Req If this module is unavailable because of a missing requirement,
477   /// this parameter will be set to one of the requirements that is not met for
478   /// use of this module.
479   ///
480   /// \param MissingHeader If this module is unavailable because of a missing
481   /// header, this parameter will be set to one of the missing headers.
482   ///
483   /// \param ShadowingModule If this module is unavailable because it is
484   /// shadowed, this parameter will be set to the shadowing module.
485   bool isAvailable(const LangOptions &LangOpts,
486                    const TargetInfo &Target,
487                    Requirement &Req,
488                    UnresolvedHeaderDirective &MissingHeader,
489                    Module *&ShadowingModule) const;
490 
491   /// Determine whether this module is a submodule.
492   bool isSubModule() const { return Parent != nullptr; }
493 
494   /// Check if this module is a (possibly transitive) submodule of \p Other.
495   ///
496   /// The 'A is a submodule of B' relation is a partial order based on the
497   /// the parent-child relationship between individual modules.
498   ///
499   /// Returns \c false if \p Other is \c nullptr.
500   bool isSubModuleOf(const Module *Other) const;
501 
502   /// Determine whether this module is a part of a framework,
503   /// either because it is a framework module or because it is a submodule
504   /// of a framework module.
505   bool isPartOfFramework() const {
506     for (const Module *Mod = this; Mod; Mod = Mod->Parent)
507       if (Mod->IsFramework)
508         return true;
509 
510     return false;
511   }
512 
513   /// Determine whether this module is a subframework of another
514   /// framework.
515   bool isSubFramework() const {
516     return IsFramework && Parent && Parent->isPartOfFramework();
517   }
518 
519   /// Set the parent of this module. This should only be used if the parent
520   /// could not be set during module creation.
521   void setParent(Module *M) {
522     assert(!Parent);
523     Parent = M;
524     Parent->SubModuleIndex[Name] = Parent->SubModules.size();
525     Parent->SubModules.push_back(this);
526   }
527 
528   /// Is this a module partition.
529   bool isModulePartition() const {
530     return Kind == ModulePartitionInterface ||
531            Kind == ModulePartitionImplementation;
532   }
533 
534   /// Is this module a header unit.
535   bool isHeaderUnit() const { return Kind == ModuleHeaderUnit; }
536   // Is this a C++20 module interface or a partition.
537   bool isInterfaceOrPartition() const {
538     return Kind == ModuleInterfaceUnit || isModulePartition();
539   }
540 
541   bool isModuleInterfaceUnit() const {
542     return Kind == ModuleInterfaceUnit || Kind == ModulePartitionInterface;
543   }
544 
545   /// Get the primary module interface name from a partition.
546   StringRef getPrimaryModuleInterfaceName() const {
547     // Technically, global module fragment belongs to global module. And global
548     // module has no name: [module.unit]p6:
549     //   The global module has no name, no module interface unit, and is not
550     //   introduced by any module-declaration.
551     //
552     // <global> is the default name showed in module map.
553     if (isGlobalModule())
554       return "<global>";
555 
556     if (isModulePartition()) {
557       auto pos = Name.find(':');
558       return StringRef(Name.data(), pos);
559     }
560 
561     if (isPrivateModule())
562       return getTopLevelModuleName();
563 
564     return Name;
565   }
566 
567   /// Retrieve the full name of this module, including the path from
568   /// its top-level module.
569   /// \param AllowStringLiterals If \c true, components that might not be
570   ///        lexically valid as identifiers will be emitted as string literals.
571   std::string getFullModuleName(bool AllowStringLiterals = false) const;
572 
573   /// Whether the full name of this module is equal to joining
574   /// \p nameParts with "."s.
575   ///
576   /// This is more efficient than getFullModuleName().
577   bool fullModuleNameIs(ArrayRef<StringRef> nameParts) const;
578 
579   /// Retrieve the top-level module for this (sub)module, which may
580   /// be this module.
581   Module *getTopLevelModule() {
582     return const_cast<Module *>(
583              const_cast<const Module *>(this)->getTopLevelModule());
584   }
585 
586   /// Retrieve the top-level module for this (sub)module, which may
587   /// be this module.
588   const Module *getTopLevelModule() const;
589 
590   /// Retrieve the name of the top-level module.
591   StringRef getTopLevelModuleName() const {
592     return getTopLevelModule()->Name;
593   }
594 
595   /// The serialized AST file for this module, if one was created.
596   OptionalFileEntryRefDegradesToFileEntryPtr getASTFile() const {
597     return getTopLevelModule()->ASTFile;
598   }
599 
600   /// Set the serialized AST file for the top-level module of this module.
601   void setASTFile(Optional<FileEntryRef> File) {
602     assert((!File || !getASTFile() || getASTFile() == File) &&
603            "file path changed");
604     getTopLevelModule()->ASTFile = File;
605   }
606 
607   /// Retrieve the directory for which this module serves as the
608   /// umbrella.
609   DirectoryName getUmbrellaDir() const;
610 
611   /// Retrieve the header that serves as the umbrella header for this
612   /// module.
613   Header getUmbrellaHeader() const {
614     if (auto *FE = Umbrella.dyn_cast<const FileEntry *>())
615       return Header{UmbrellaAsWritten, UmbrellaRelativeToRootModuleDirectory,
616                     FE};
617     return Header{};
618   }
619 
620   /// Determine whether this module has an umbrella directory that is
621   /// not based on an umbrella header.
622   bool hasUmbrellaDir() const {
623     return Umbrella && Umbrella.is<const DirectoryEntry *>();
624   }
625 
626   /// Add a top-level header associated with this module.
627   void addTopHeader(const FileEntry *File);
628 
629   /// Add a top-level header filename associated with this module.
630   void addTopHeaderFilename(StringRef Filename) {
631     TopHeaderNames.push_back(std::string(Filename));
632   }
633 
634   /// The top-level headers associated with this module.
635   ArrayRef<const FileEntry *> getTopHeaders(FileManager &FileMgr);
636 
637   /// Determine whether this module has declared its intention to
638   /// directly use another module.
639   bool directlyUses(const Module *Requested);
640 
641   /// Add the given feature requirement to the list of features
642   /// required by this module.
643   ///
644   /// \param Feature The feature that is required by this module (and
645   /// its submodules).
646   ///
647   /// \param RequiredState The required state of this feature: \c true
648   /// if it must be present, \c false if it must be absent.
649   ///
650   /// \param LangOpts The set of language options that will be used to
651   /// evaluate the availability of this feature.
652   ///
653   /// \param Target The target options that will be used to evaluate the
654   /// availability of this feature.
655   void addRequirement(StringRef Feature, bool RequiredState,
656                       const LangOptions &LangOpts,
657                       const TargetInfo &Target);
658 
659   /// Mark this module and all of its submodules as unavailable.
660   void markUnavailable(bool Unimportable);
661 
662   /// Find the submodule with the given name.
663   ///
664   /// \returns The submodule if found, or NULL otherwise.
665   Module *findSubmodule(StringRef Name) const;
666   Module *findOrInferSubmodule(StringRef Name);
667 
668   /// Get the Global Module Fragment (sub-module) for this module, it there is
669   /// one.
670   ///
671   /// \returns The GMF sub-module if found, or NULL otherwise.
672   Module *getGlobalModuleFragment() { return findSubmodule("<global>"); }
673 
674   /// Get the Private Module Fragment (sub-module) for this module, it there is
675   /// one.
676   ///
677   /// \returns The PMF sub-module if found, or NULL otherwise.
678   Module *getPrivateModuleFragment() { return findSubmodule("<private>"); }
679 
680   /// Determine whether the specified module would be visible to
681   /// a lookup at the end of this module.
682   ///
683   /// FIXME: This may return incorrect results for (submodules of) the
684   /// module currently being built, if it's queried before we see all
685   /// of its imports.
686   bool isModuleVisible(const Module *M) const {
687     if (VisibleModulesCache.empty())
688       buildVisibleModulesCache();
689     return VisibleModulesCache.count(M);
690   }
691 
692   unsigned getVisibilityID() const { return VisibilityID; }
693 
694   using submodule_iterator = std::vector<Module *>::iterator;
695   using submodule_const_iterator = std::vector<Module *>::const_iterator;
696 
697   submodule_iterator submodule_begin() { return SubModules.begin(); }
698   submodule_const_iterator submodule_begin() const {return SubModules.begin();}
699   submodule_iterator submodule_end()   { return SubModules.end(); }
700   submodule_const_iterator submodule_end() const { return SubModules.end(); }
701 
702   llvm::iterator_range<submodule_iterator> submodules() {
703     return llvm::make_range(submodule_begin(), submodule_end());
704   }
705   llvm::iterator_range<submodule_const_iterator> submodules() const {
706     return llvm::make_range(submodule_begin(), submodule_end());
707   }
708 
709   /// Appends this module's list of exported modules to \p Exported.
710   ///
711   /// This provides a subset of immediately imported modules (the ones that are
712   /// directly exported), not the complete set of exported modules.
713   void getExportedModules(SmallVectorImpl<Module *> &Exported) const;
714 
715   static StringRef getModuleInputBufferName() {
716     return "<module-includes>";
717   }
718 
719   /// Print the module map for this module to the given stream.
720   void print(raw_ostream &OS, unsigned Indent = 0, bool Dump = false) const;
721 
722   /// Dump the contents of this module to the given output stream.
723   void dump() const;
724 
725 private:
726   void buildVisibleModulesCache() const;
727 };
728 
729 /// A set of visible modules.
730 class VisibleModuleSet {
731 public:
732   VisibleModuleSet() = default;
733   VisibleModuleSet(VisibleModuleSet &&O)
734       : ImportLocs(std::move(O.ImportLocs)), Generation(O.Generation ? 1 : 0) {
735     O.ImportLocs.clear();
736     ++O.Generation;
737   }
738 
739   /// Move from another visible modules set. Guaranteed to leave the source
740   /// empty and bump the generation on both.
741   VisibleModuleSet &operator=(VisibleModuleSet &&O) {
742     ImportLocs = std::move(O.ImportLocs);
743     O.ImportLocs.clear();
744     ++O.Generation;
745     ++Generation;
746     return *this;
747   }
748 
749   /// Get the current visibility generation. Incremented each time the
750   /// set of visible modules changes in any way.
751   unsigned getGeneration() const { return Generation; }
752 
753   /// Determine whether a module is visible.
754   bool isVisible(const Module *M) const {
755     return getImportLoc(M).isValid();
756   }
757 
758   /// Get the location at which the import of a module was triggered.
759   SourceLocation getImportLoc(const Module *M) const {
760     return M->getVisibilityID() < ImportLocs.size()
761                ? ImportLocs[M->getVisibilityID()]
762                : SourceLocation();
763   }
764 
765   /// A callback to call when a module is made visible (directly or
766   /// indirectly) by a call to \ref setVisible.
767   using VisibleCallback = llvm::function_ref<void(Module *M)>;
768 
769   /// A callback to call when a module conflict is found. \p Path
770   /// consists of a sequence of modules from the conflicting module to the one
771   /// made visible, where each was exported by the next.
772   using ConflictCallback =
773       llvm::function_ref<void(ArrayRef<Module *> Path, Module *Conflict,
774                          StringRef Message)>;
775 
776   /// Make a specific module visible.
777   void setVisible(Module *M, SourceLocation Loc,
778                   VisibleCallback Vis = [](Module *) {},
779                   ConflictCallback Cb = [](ArrayRef<Module *>, Module *,
780                                            StringRef) {});
781 
782 private:
783   /// Import locations for each visible module. Indexed by the module's
784   /// VisibilityID.
785   std::vector<SourceLocation> ImportLocs;
786 
787   /// Visibility generation, bumped every time the visibility state changes.
788   unsigned Generation = 0;
789 };
790 
791 /// Abstracts clang modules and precompiled header files and holds
792 /// everything needed to generate debug info for an imported module
793 /// or PCH.
794 class ASTSourceDescriptor {
795   StringRef PCHModuleName;
796   StringRef Path;
797   StringRef ASTFile;
798   ASTFileSignature Signature;
799   Module *ClangModule = nullptr;
800 
801 public:
802   ASTSourceDescriptor() = default;
803   ASTSourceDescriptor(StringRef Name, StringRef Path, StringRef ASTFile,
804                       ASTFileSignature Signature)
805       : PCHModuleName(std::move(Name)), Path(std::move(Path)),
806         ASTFile(std::move(ASTFile)), Signature(Signature) {}
807   ASTSourceDescriptor(Module &M);
808 
809   std::string getModuleName() const;
810   StringRef getPath() const { return Path; }
811   StringRef getASTFile() const { return ASTFile; }
812   ASTFileSignature getSignature() const { return Signature; }
813   Module *getModuleOrNull() const { return ClangModule; }
814 };
815 
816 
817 } // namespace clang
818 
819 #endif // LLVM_CLANG_BASIC_MODULE_H
820