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