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