xref: /llvm-project/clang/lib/Basic/Module.cpp (revision 989173c09c2930a9f523ccb455111ef446e9f96d)
1 //===- Module.cpp - Describe a module -------------------------------------===//
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 // This file defines the Module class, which describes a module in the source
10 // code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/Module.h"
15 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/LangOptions.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <algorithm>
29 #include <cassert>
30 #include <functional>
31 #include <string>
32 #include <utility>
33 #include <vector>
34 
35 using namespace clang;
36 
37 Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
38                bool IsFramework, bool IsExplicit, unsigned VisibilityID)
39     : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent),
40       VisibilityID(VisibilityID), IsUnimportable(false),
41       HasIncompatibleModuleFile(false), IsAvailable(true),
42       IsFromModuleFile(false), IsFramework(IsFramework), IsExplicit(IsExplicit),
43       IsSystem(false), IsExternC(false), IsInferred(false),
44       InferSubmodules(false), InferExplicitSubmodules(false),
45       InferExportWildcard(false), ConfigMacrosExhaustive(false),
46       NoUndeclaredIncludes(false), ModuleMapIsPrivate(false),
47       NamedModuleHasNoInit(false), NameVisibility(Hidden) {
48   if (Parent) {
49     IsAvailable = Parent->isAvailable();
50     IsUnimportable = Parent->isUnimportable();
51     IsSystem = Parent->IsSystem;
52     IsExternC = Parent->IsExternC;
53     NoUndeclaredIncludes = Parent->NoUndeclaredIncludes;
54     ModuleMapIsPrivate = Parent->ModuleMapIsPrivate;
55 
56     Parent->SubModuleIndex[Name] = Parent->SubModules.size();
57     Parent->SubModules.push_back(this);
58   }
59 }
60 
61 Module::~Module() {
62   for (auto *Submodule : SubModules) {
63     delete Submodule;
64   }
65 }
66 
67 static bool isPlatformEnvironment(const TargetInfo &Target, StringRef Feature) {
68   StringRef Platform = Target.getPlatformName();
69   StringRef Env = Target.getTriple().getEnvironmentName();
70 
71   // Attempt to match platform and environment.
72   if (Platform == Feature || Target.getTriple().getOSName() == Feature ||
73       Env == Feature)
74     return true;
75 
76   auto CmpPlatformEnv = [](StringRef LHS, StringRef RHS) {
77     auto Pos = LHS.find('-');
78     if (Pos == StringRef::npos)
79       return false;
80     SmallString<128> NewLHS = LHS.slice(0, Pos);
81     NewLHS += LHS.slice(Pos+1, LHS.size());
82     return NewLHS == RHS;
83   };
84 
85   SmallString<128> PlatformEnv = Target.getTriple().getOSAndEnvironmentName();
86   // Darwin has different but equivalent variants for simulators, example:
87   //   1. x86_64-apple-ios-simulator
88   //   2. x86_64-apple-iossimulator
89   // where both are valid examples of the same platform+environment but in the
90   // variant (2) the simulator is hardcoded as part of the platform name. Both
91   // forms above should match for "iossimulator" requirement.
92   if (Target.getTriple().isOSDarwin() && PlatformEnv.endswith("simulator"))
93     return PlatformEnv == Feature || CmpPlatformEnv(PlatformEnv, Feature);
94 
95   return PlatformEnv == Feature;
96 }
97 
98 /// Determine whether a translation unit built using the current
99 /// language options has the given feature.
100 static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
101                        const TargetInfo &Target) {
102   bool HasFeature = llvm::StringSwitch<bool>(Feature)
103                         .Case("altivec", LangOpts.AltiVec)
104                         .Case("blocks", LangOpts.Blocks)
105                         .Case("coroutines", LangOpts.Coroutines)
106                         .Case("cplusplus", LangOpts.CPlusPlus)
107                         .Case("cplusplus11", LangOpts.CPlusPlus11)
108                         .Case("cplusplus14", LangOpts.CPlusPlus14)
109                         .Case("cplusplus17", LangOpts.CPlusPlus17)
110                         .Case("cplusplus20", LangOpts.CPlusPlus20)
111                         .Case("cplusplus23", LangOpts.CPlusPlus23)
112                         .Case("cplusplus26", LangOpts.CPlusPlus26)
113                         .Case("c99", LangOpts.C99)
114                         .Case("c11", LangOpts.C11)
115                         .Case("c17", LangOpts.C17)
116                         .Case("c23", LangOpts.C23)
117                         .Case("freestanding", LangOpts.Freestanding)
118                         .Case("gnuinlineasm", LangOpts.GNUAsm)
119                         .Case("objc", LangOpts.ObjC)
120                         .Case("objc_arc", LangOpts.ObjCAutoRefCount)
121                         .Case("opencl", LangOpts.OpenCL)
122                         .Case("tls", Target.isTLSSupported())
123                         .Case("zvector", LangOpts.ZVector)
124                         .Default(Target.hasFeature(Feature) ||
125                                  isPlatformEnvironment(Target, Feature));
126   if (!HasFeature)
127     HasFeature = llvm::is_contained(LangOpts.ModuleFeatures, Feature);
128   return HasFeature;
129 }
130 
131 bool Module::isUnimportable(const LangOptions &LangOpts,
132                             const TargetInfo &Target, Requirement &Req,
133                             Module *&ShadowingModule) const {
134   if (!IsUnimportable)
135     return false;
136 
137   for (const Module *Current = this; Current; Current = Current->Parent) {
138     if (Current->ShadowingModule) {
139       ShadowingModule = Current->ShadowingModule;
140       return true;
141     }
142     for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
143       if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
144               Current->Requirements[I].second) {
145         Req = Current->Requirements[I];
146         return true;
147       }
148     }
149   }
150 
151   llvm_unreachable("could not find a reason why module is unimportable");
152 }
153 
154 // The -fmodule-name option tells the compiler to textually include headers in
155 // the specified module, meaning Clang won't build the specified module. This
156 // is useful in a number of situations, for instance, when building a library
157 // that vends a module map, one might want to avoid hitting intermediate build
158 // products containing the module map or avoid finding the system installed
159 // modulemap for that library.
160 bool Module::isForBuilding(const LangOptions &LangOpts) const {
161   StringRef TopLevelName = getTopLevelModuleName();
162   StringRef CurrentModule = LangOpts.CurrentModule;
163 
164   // When building framework Foo, we want to make sure that Foo *and*
165   // Foo_Private are textually included and no modules are built for both.
166   if (getTopLevelModule()->IsFramework &&
167       CurrentModule == LangOpts.ModuleName &&
168       !CurrentModule.endswith("_Private") && TopLevelName.endswith("_Private"))
169     TopLevelName = TopLevelName.drop_back(8);
170 
171   return TopLevelName == CurrentModule;
172 }
173 
174 bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
175                          Requirement &Req,
176                          UnresolvedHeaderDirective &MissingHeader,
177                          Module *&ShadowingModule) const {
178   if (IsAvailable)
179     return true;
180 
181   if (isUnimportable(LangOpts, Target, Req, ShadowingModule))
182     return false;
183 
184   // FIXME: All missing headers are listed on the top-level module. Should we
185   // just look there?
186   for (const Module *Current = this; Current; Current = Current->Parent) {
187     if (!Current->MissingHeaders.empty()) {
188       MissingHeader = Current->MissingHeaders.front();
189       return false;
190     }
191   }
192 
193   llvm_unreachable("could not find a reason why module is unavailable");
194 }
195 
196 bool Module::isSubModuleOf(const Module *Other) const {
197   for (auto *Parent = this; Parent; Parent = Parent->Parent) {
198     if (Parent == Other)
199       return true;
200   }
201   return false;
202 }
203 
204 const Module *Module::getTopLevelModule() const {
205   const Module *Result = this;
206   while (Result->Parent)
207     Result = Result->Parent;
208 
209   return Result;
210 }
211 
212 static StringRef getModuleNameFromComponent(
213     const std::pair<std::string, SourceLocation> &IdComponent) {
214   return IdComponent.first;
215 }
216 
217 static StringRef getModuleNameFromComponent(StringRef R) { return R; }
218 
219 template<typename InputIter>
220 static void printModuleId(raw_ostream &OS, InputIter Begin, InputIter End,
221                           bool AllowStringLiterals = true) {
222   for (InputIter It = Begin; It != End; ++It) {
223     if (It != Begin)
224       OS << ".";
225 
226     StringRef Name = getModuleNameFromComponent(*It);
227     if (!AllowStringLiterals || isValidAsciiIdentifier(Name))
228       OS << Name;
229     else {
230       OS << '"';
231       OS.write_escaped(Name);
232       OS << '"';
233     }
234   }
235 }
236 
237 template<typename Container>
238 static void printModuleId(raw_ostream &OS, const Container &C) {
239   return printModuleId(OS, C.begin(), C.end());
240 }
241 
242 std::string Module::getFullModuleName(bool AllowStringLiterals) const {
243   SmallVector<StringRef, 2> Names;
244 
245   // Build up the set of module names (from innermost to outermost).
246   for (const Module *M = this; M; M = M->Parent)
247     Names.push_back(M->Name);
248 
249   std::string Result;
250 
251   llvm::raw_string_ostream Out(Result);
252   printModuleId(Out, Names.rbegin(), Names.rend(), AllowStringLiterals);
253   Out.flush();
254 
255   return Result;
256 }
257 
258 bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const {
259   for (const Module *M = this; M; M = M->Parent) {
260     if (nameParts.empty() || M->Name != nameParts.back())
261       return false;
262     nameParts = nameParts.drop_back();
263   }
264   return nameParts.empty();
265 }
266 
267 OptionalDirectoryEntryRef Module::getEffectiveUmbrellaDir() const {
268   if (Umbrella && Umbrella.is<FileEntryRef>())
269     return Umbrella.get<FileEntryRef>().getDir();
270   if (Umbrella && Umbrella.is<DirectoryEntryRef>())
271     return Umbrella.get<DirectoryEntryRef>();
272   return std::nullopt;
273 }
274 
275 void Module::addTopHeader(FileEntryRef File) {
276   assert(File);
277   TopHeaders.insert(File);
278 }
279 
280 ArrayRef<FileEntryRef> Module::getTopHeaders(FileManager &FileMgr) {
281   if (!TopHeaderNames.empty()) {
282     for (StringRef TopHeaderName : TopHeaderNames)
283       if (auto FE = FileMgr.getOptionalFileRef(TopHeaderName))
284         TopHeaders.insert(*FE);
285     TopHeaderNames.clear();
286   }
287 
288   return llvm::ArrayRef(TopHeaders.begin(), TopHeaders.end());
289 }
290 
291 bool Module::directlyUses(const Module *Requested) {
292   auto *Top = getTopLevelModule();
293 
294   // A top-level module implicitly uses itself.
295   if (Requested->isSubModuleOf(Top))
296     return true;
297 
298   for (auto *Use : Top->DirectUses)
299     if (Requested->isSubModuleOf(Use))
300       return true;
301 
302   // Anyone is allowed to use our builtin stddef.h and its accompanying module.
303   if (!Requested->Parent && Requested->Name == "_Builtin_stddef_max_align_t")
304     return true;
305 
306   if (NoUndeclaredIncludes)
307     UndeclaredUses.insert(Requested);
308 
309   return false;
310 }
311 
312 void Module::addRequirement(StringRef Feature, bool RequiredState,
313                             const LangOptions &LangOpts,
314                             const TargetInfo &Target) {
315   Requirements.push_back(Requirement(std::string(Feature), RequiredState));
316 
317   // If this feature is currently available, we're done.
318   if (hasFeature(Feature, LangOpts, Target) == RequiredState)
319     return;
320 
321   markUnavailable(/*Unimportable*/true);
322 }
323 
324 void Module::markUnavailable(bool Unimportable) {
325   auto needUpdate = [Unimportable](Module *M) {
326     return M->IsAvailable || (!M->IsUnimportable && Unimportable);
327   };
328 
329   if (!needUpdate(this))
330     return;
331 
332   SmallVector<Module *, 2> Stack;
333   Stack.push_back(this);
334   while (!Stack.empty()) {
335     Module *Current = Stack.back();
336     Stack.pop_back();
337 
338     if (!needUpdate(Current))
339       continue;
340 
341     Current->IsAvailable = false;
342     Current->IsUnimportable |= Unimportable;
343     for (auto *Submodule : Current->submodules()) {
344       if (needUpdate(Submodule))
345         Stack.push_back(Submodule);
346     }
347   }
348 }
349 
350 Module *Module::findSubmodule(StringRef Name) const {
351   llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
352   if (Pos == SubModuleIndex.end())
353     return nullptr;
354 
355   return SubModules[Pos->getValue()];
356 }
357 
358 Module *Module::findOrInferSubmodule(StringRef Name) {
359   llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
360   if (Pos != SubModuleIndex.end())
361     return SubModules[Pos->getValue()];
362   if (!InferSubmodules)
363     return nullptr;
364   Module *Result = new Module(Name, SourceLocation(), this, false, InferExplicitSubmodules, 0);
365   Result->InferExplicitSubmodules = InferExplicitSubmodules;
366   Result->InferSubmodules = InferSubmodules;
367   Result->InferExportWildcard = InferExportWildcard;
368   if (Result->InferExportWildcard)
369     Result->Exports.push_back(Module::ExportDecl(nullptr, true));
370   return Result;
371 }
372 
373 Module *Module::getGlobalModuleFragment() const {
374   assert(isNamedModuleUnit() && "We should only query the global module "
375                                 "fragment from the C++ 20 Named modules");
376 
377   for (auto *SubModule : SubModules)
378     if (SubModule->isExplicitGlobalModule())
379       return SubModule;
380 
381   return nullptr;
382 }
383 
384 Module *Module::getPrivateModuleFragment() const {
385   assert(isNamedModuleUnit() && "We should only query the private module "
386                                 "fragment from the C++ 20 Named modules");
387 
388   for (auto *SubModule : SubModules)
389     if (SubModule->isPrivateModule())
390       return SubModule;
391 
392   return nullptr;
393 }
394 
395 void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
396   // All non-explicit submodules are exported.
397   for (std::vector<Module *>::const_iterator I = SubModules.begin(),
398                                              E = SubModules.end();
399        I != E; ++I) {
400     Module *Mod = *I;
401     if (!Mod->IsExplicit)
402       Exported.push_back(Mod);
403   }
404 
405   // Find re-exported modules by filtering the list of imported modules.
406   bool AnyWildcard = false;
407   bool UnrestrictedWildcard = false;
408   SmallVector<Module *, 4> WildcardRestrictions;
409   for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
410     Module *Mod = Exports[I].getPointer();
411     if (!Exports[I].getInt()) {
412       // Export a named module directly; no wildcards involved.
413       Exported.push_back(Mod);
414 
415       continue;
416     }
417 
418     // Wildcard export: export all of the imported modules that match
419     // the given pattern.
420     AnyWildcard = true;
421     if (UnrestrictedWildcard)
422       continue;
423 
424     if (Module *Restriction = Exports[I].getPointer())
425       WildcardRestrictions.push_back(Restriction);
426     else {
427       WildcardRestrictions.clear();
428       UnrestrictedWildcard = true;
429     }
430   }
431 
432   // If there were any wildcards, push any imported modules that were
433   // re-exported by the wildcard restriction.
434   if (!AnyWildcard)
435     return;
436 
437   for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
438     Module *Mod = Imports[I];
439     bool Acceptable = UnrestrictedWildcard;
440     if (!Acceptable) {
441       // Check whether this module meets one of the restrictions.
442       for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
443         Module *Restriction = WildcardRestrictions[R];
444         if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
445           Acceptable = true;
446           break;
447         }
448       }
449     }
450 
451     if (!Acceptable)
452       continue;
453 
454     Exported.push_back(Mod);
455   }
456 }
457 
458 void Module::buildVisibleModulesCache() const {
459   assert(VisibleModulesCache.empty() && "cache does not need building");
460 
461   // This module is visible to itself.
462   VisibleModulesCache.insert(this);
463 
464   // Every imported module is visible.
465   SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
466   while (!Stack.empty()) {
467     Module *CurrModule = Stack.pop_back_val();
468 
469     // Every module transitively exported by an imported module is visible.
470     if (VisibleModulesCache.insert(CurrModule).second)
471       CurrModule->getExportedModules(Stack);
472   }
473 }
474 
475 void Module::print(raw_ostream &OS, unsigned Indent, bool Dump) const {
476   OS.indent(Indent);
477   if (IsFramework)
478     OS << "framework ";
479   if (IsExplicit)
480     OS << "explicit ";
481   OS << "module ";
482   printModuleId(OS, &Name, &Name + 1);
483 
484   if (IsSystem || IsExternC) {
485     OS.indent(Indent + 2);
486     if (IsSystem)
487       OS << " [system]";
488     if (IsExternC)
489       OS << " [extern_c]";
490   }
491 
492   OS << " {\n";
493 
494   if (!Requirements.empty()) {
495     OS.indent(Indent + 2);
496     OS << "requires ";
497     for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
498       if (I)
499         OS << ", ";
500       if (!Requirements[I].second)
501         OS << "!";
502       OS << Requirements[I].first;
503     }
504     OS << "\n";
505   }
506 
507   if (std::optional<Header> H = getUmbrellaHeaderAsWritten()) {
508     OS.indent(Indent + 2);
509     OS << "umbrella header \"";
510     OS.write_escaped(H->NameAsWritten);
511     OS << "\"\n";
512   } else if (std::optional<DirectoryName> D = getUmbrellaDirAsWritten()) {
513     OS.indent(Indent + 2);
514     OS << "umbrella \"";
515     OS.write_escaped(D->NameAsWritten);
516     OS << "\"\n";
517   }
518 
519   if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
520     OS.indent(Indent + 2);
521     OS << "config_macros ";
522     if (ConfigMacrosExhaustive)
523       OS << "[exhaustive]";
524     for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
525       if (I)
526         OS << ", ";
527       OS << ConfigMacros[I];
528     }
529     OS << "\n";
530   }
531 
532   struct {
533     StringRef Prefix;
534     HeaderKind Kind;
535   } Kinds[] = {{"", HK_Normal},
536                {"textual ", HK_Textual},
537                {"private ", HK_Private},
538                {"private textual ", HK_PrivateTextual},
539                {"exclude ", HK_Excluded}};
540 
541   for (auto &K : Kinds) {
542     assert(&K == &Kinds[K.Kind] && "kinds in wrong order");
543     for (auto &H : Headers[K.Kind]) {
544       OS.indent(Indent + 2);
545       OS << K.Prefix << "header \"";
546       OS.write_escaped(H.NameAsWritten);
547       OS << "\" { size " << H.Entry.getSize()
548          << " mtime " << H.Entry.getModificationTime() << " }\n";
549     }
550   }
551   for (auto *Unresolved : {&UnresolvedHeaders, &MissingHeaders}) {
552     for (auto &U : *Unresolved) {
553       OS.indent(Indent + 2);
554       OS << Kinds[U.Kind].Prefix << "header \"";
555       OS.write_escaped(U.FileName);
556       OS << "\"";
557       if (U.Size || U.ModTime) {
558         OS << " {";
559         if (U.Size)
560           OS << " size " << *U.Size;
561         if (U.ModTime)
562           OS << " mtime " << *U.ModTime;
563         OS << " }";
564       }
565       OS << "\n";
566     }
567   }
568 
569   if (!ExportAsModule.empty()) {
570     OS.indent(Indent + 2);
571     OS << "export_as" << ExportAsModule << "\n";
572   }
573 
574   for (auto *Submodule : submodules())
575     // Print inferred subframework modules so that we don't need to re-infer
576     // them (requires expensive directory iteration + stat calls) when we build
577     // the module. Regular inferred submodules are OK, as we need to look at all
578     // those header files anyway.
579     if (!Submodule->IsInferred || Submodule->IsFramework)
580       Submodule->print(OS, Indent + 2, Dump);
581 
582   for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
583     OS.indent(Indent + 2);
584     OS << "export ";
585     if (Module *Restriction = Exports[I].getPointer()) {
586       OS << Restriction->getFullModuleName(true);
587       if (Exports[I].getInt())
588         OS << ".*";
589     } else {
590       OS << "*";
591     }
592     OS << "\n";
593   }
594 
595   for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
596     OS.indent(Indent + 2);
597     OS << "export ";
598     printModuleId(OS, UnresolvedExports[I].Id);
599     if (UnresolvedExports[I].Wildcard)
600       OS << (UnresolvedExports[I].Id.empty() ? "*" : ".*");
601     OS << "\n";
602   }
603 
604   if (Dump) {
605     for (Module *M : Imports) {
606       OS.indent(Indent + 2);
607       llvm::errs() << "import " << M->getFullModuleName() << "\n";
608     }
609   }
610 
611   for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
612     OS.indent(Indent + 2);
613     OS << "use ";
614     OS << DirectUses[I]->getFullModuleName(true);
615     OS << "\n";
616   }
617 
618   for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
619     OS.indent(Indent + 2);
620     OS << "use ";
621     printModuleId(OS, UnresolvedDirectUses[I]);
622     OS << "\n";
623   }
624 
625   for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
626     OS.indent(Indent + 2);
627     OS << "link ";
628     if (LinkLibraries[I].IsFramework)
629       OS << "framework ";
630     OS << "\"";
631     OS.write_escaped(LinkLibraries[I].Library);
632     OS << "\"";
633   }
634 
635   for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
636     OS.indent(Indent + 2);
637     OS << "conflict ";
638     printModuleId(OS, UnresolvedConflicts[I].Id);
639     OS << ", \"";
640     OS.write_escaped(UnresolvedConflicts[I].Message);
641     OS << "\"\n";
642   }
643 
644   for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
645     OS.indent(Indent + 2);
646     OS << "conflict ";
647     OS << Conflicts[I].Other->getFullModuleName(true);
648     OS << ", \"";
649     OS.write_escaped(Conflicts[I].Message);
650     OS << "\"\n";
651   }
652 
653   if (InferSubmodules) {
654     OS.indent(Indent + 2);
655     if (InferExplicitSubmodules)
656       OS << "explicit ";
657     OS << "module * {\n";
658     if (InferExportWildcard) {
659       OS.indent(Indent + 4);
660       OS << "export *\n";
661     }
662     OS.indent(Indent + 2);
663     OS << "}\n";
664   }
665 
666   OS.indent(Indent);
667   OS << "}\n";
668 }
669 
670 LLVM_DUMP_METHOD void Module::dump() const {
671   print(llvm::errs(), 0, true);
672 }
673 
674 void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
675                                   VisibleCallback Vis, ConflictCallback Cb) {
676   // We can't import a global module fragment so the location can be invalid.
677   assert((M->isGlobalModule() || Loc.isValid()) &&
678          "setVisible expects a valid import location");
679   if (isVisible(M))
680     return;
681 
682   ++Generation;
683 
684   struct Visiting {
685     Module *M;
686     Visiting *ExportedBy;
687   };
688 
689   std::function<void(Visiting)> VisitModule = [&](Visiting V) {
690     // Nothing to do for a module that's already visible.
691     unsigned ID = V.M->getVisibilityID();
692     if (ImportLocs.size() <= ID)
693       ImportLocs.resize(ID + 1);
694     else if (ImportLocs[ID].isValid())
695       return;
696 
697     ImportLocs[ID] = Loc;
698     Vis(V.M);
699 
700     // Make any exported modules visible.
701     SmallVector<Module *, 16> Exports;
702     V.M->getExportedModules(Exports);
703     for (Module *E : Exports) {
704       // Don't import non-importable modules.
705       if (!E->isUnimportable())
706         VisitModule({E, &V});
707     }
708 
709     for (auto &C : V.M->Conflicts) {
710       if (isVisible(C.Other)) {
711         llvm::SmallVector<Module*, 8> Path;
712         for (Visiting *I = &V; I; I = I->ExportedBy)
713           Path.push_back(I->M);
714         Cb(Path, C.Other, C.Message);
715       }
716     }
717   };
718   VisitModule({M, nullptr});
719 }
720 
721 void VisibleModuleSet::makeTransitiveImportsVisible(Module *M,
722                                                     SourceLocation Loc,
723                                                     VisibleCallback Vis,
724                                                     ConflictCallback Cb) {
725   for (auto *I : M->Imports)
726     setVisible(I, Loc, Vis, Cb);
727 }
728 
729 ASTSourceDescriptor::ASTSourceDescriptor(Module &M)
730     : Signature(M.Signature), ClangModule(&M) {
731   if (M.Directory)
732     Path = M.Directory->getName();
733   if (auto File = M.getASTFile())
734     ASTFile = File->getName();
735 }
736 
737 std::string ASTSourceDescriptor::getModuleName() const {
738   if (ClangModule)
739     return ClangModule->Name;
740   else
741     return std::string(PCHModuleName);
742 }
743