1 //===--- SemaModule.cpp - Semantic Analysis for Modules -------------------===//
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 implements semantic analysis for modules (C++ modules syntax,
10 //  Objective-C modules syntax, and Clang header modules).
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/Lex/HeaderSearch.h"
16 #include "clang/Lex/Preprocessor.h"
17 #include "clang/Sema/SemaInternal.h"
18 
19 using namespace clang;
20 using namespace sema;
21 
22 static void checkModuleImportContext(Sema &S, Module *M,
23                                      SourceLocation ImportLoc, DeclContext *DC,
24                                      bool FromInclude = false) {
25   SourceLocation ExternCLoc;
26 
27   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
28     switch (LSD->getLanguage()) {
29     case LinkageSpecDecl::lang_c:
30       if (ExternCLoc.isInvalid())
31         ExternCLoc = LSD->getBeginLoc();
32       break;
33     case LinkageSpecDecl::lang_cxx:
34       break;
35     }
36     DC = LSD->getParent();
37   }
38 
39   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
40     DC = DC->getParent();
41 
42   if (!isa<TranslationUnitDecl>(DC)) {
43     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
44                           ? diag::ext_module_import_not_at_top_level_noop
45                           : diag::err_module_import_not_at_top_level_fatal)
46         << M->getFullModuleName() << DC;
47     S.Diag(cast<Decl>(DC)->getBeginLoc(),
48            diag::note_module_import_not_at_top_level)
49         << DC;
50   } else if (!M->IsExternC && ExternCLoc.isValid()) {
51     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
52       << M->getFullModuleName();
53     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
54   }
55 }
56 
57 // We represent the primary and partition names as 'Paths' which are sections
58 // of the hierarchical access path for a clang module.  However for C++20
59 // the periods in a name are just another character, and we will need to
60 // flatten them into a string.
61 static std::string stringFromPath(ModuleIdPath Path) {
62   std::string Name;
63   if (Path.empty())
64     return Name;
65 
66   for (auto &Piece : Path) {
67     if (!Name.empty())
68       Name += ".";
69     Name += Piece.first->getName();
70   }
71   return Name;
72 }
73 
74 Sema::DeclGroupPtrTy
75 Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc) {
76   if (!ModuleScopes.empty() &&
77       ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment) {
78     // Under -std=c++2a -fmodules-ts, we can find an explicit 'module;' after
79     // already implicitly entering the global module fragment. That's OK.
80     assert(getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS &&
81            "unexpectedly encountered multiple global module fragment decls");
82     ModuleScopes.back().BeginLoc = ModuleLoc;
83     return nullptr;
84   }
85 
86   // We start in the global module; all those declarations are implicitly
87   // module-private (though they do not have module linkage).
88   Module *GlobalModule =
89       PushGlobalModuleFragment(ModuleLoc, /*IsImplicit=*/false);
90 
91   // All declarations created from now on are owned by the global module.
92   auto *TU = Context.getTranslationUnitDecl();
93   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
94   TU->setLocalOwningModule(GlobalModule);
95 
96   // FIXME: Consider creating an explicit representation of this declaration.
97   return nullptr;
98 }
99 
100 Sema::DeclGroupPtrTy
101 Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc,
102                       ModuleDeclKind MDK, ModuleIdPath Path,
103                       ModuleIdPath Partition, ModuleImportState &ImportState) {
104   assert((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) &&
105          "should only have module decl in Modules TS or C++20");
106 
107   bool IsFirstDecl = ImportState == ModuleImportState::FirstDecl;
108   bool SeenGMF = ImportState == ModuleImportState::GlobalFragment;
109   // If any of the steps here fail, we count that as invalidating C++20
110   // module state;
111   ImportState = ModuleImportState::NotACXX20Module;
112 
113   // A module implementation unit requires that we are not compiling a module
114   // of any kind. A module interface unit requires that we are not compiling a
115   // module map.
116   switch (getLangOpts().getCompilingModule()) {
117   case LangOptions::CMK_None:
118     // It's OK to compile a module interface as a normal translation unit.
119     break;
120 
121   case LangOptions::CMK_ModuleInterface:
122     if (MDK != ModuleDeclKind::Implementation)
123       break;
124 
125     // We were asked to compile a module interface unit but this is a module
126     // implementation unit. That indicates the 'export' is missing.
127     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
128       << FixItHint::CreateInsertion(ModuleLoc, "export ");
129     MDK = ModuleDeclKind::Interface;
130     break;
131 
132   case LangOptions::CMK_ModuleMap:
133     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
134     return nullptr;
135 
136   case LangOptions::CMK_HeaderModule:
137     Diag(ModuleLoc, diag::err_module_decl_in_header_module);
138     return nullptr;
139   }
140 
141   assert(ModuleScopes.size() <= 1 && "expected to be at global module scope");
142 
143   // FIXME: Most of this work should be done by the preprocessor rather than
144   // here, in order to support macro import.
145 
146   // Only one module-declaration is permitted per source file.
147   if (!ModuleScopes.empty() &&
148       ModuleScopes.back().Module->isModulePurview()) {
149     Diag(ModuleLoc, diag::err_module_redeclaration);
150     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
151          diag::note_prev_module_declaration);
152     return nullptr;
153   }
154 
155   // Find the global module fragment we're adopting into this module, if any.
156   Module *GlobalModuleFragment = nullptr;
157   if (!ModuleScopes.empty() &&
158       ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment)
159     GlobalModuleFragment = ModuleScopes.back().Module;
160 
161   assert((!getLangOpts().CPlusPlusModules ||
162           SeenGMF == (bool)GlobalModuleFragment) &&
163          "mismatched global module state");
164 
165   // In C++20, the module-declaration must be the first declaration if there
166   // is no global module fragment.
167   if (getLangOpts().CPlusPlusModules && !IsFirstDecl && !SeenGMF) {
168     Diag(ModuleLoc, diag::err_module_decl_not_at_start);
169     SourceLocation BeginLoc =
170         ModuleScopes.empty()
171             ? SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID())
172             : ModuleScopes.back().BeginLoc;
173     if (BeginLoc.isValid()) {
174       Diag(BeginLoc, diag::note_global_module_introducer_missing)
175           << FixItHint::CreateInsertion(BeginLoc, "module;\n");
176     }
177   }
178 
179   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
180   // modules, the dots here are just another character that can appear in a
181   // module name.
182   std::string ModuleName = stringFromPath(Path);
183   bool IsPartition = !Partition.empty();
184   if (IsPartition) {
185     ModuleName += ":";
186     ModuleName += stringFromPath(Partition);
187   }
188   // If a module name was explicitly specified on the command line, it must be
189   // correct.
190   if (!getLangOpts().CurrentModule.empty() &&
191       getLangOpts().CurrentModule != ModuleName) {
192     Diag(Path.front().second, diag::err_current_module_name_mismatch)
193         << SourceRange(Path.front().second, IsPartition
194                                                 ? Partition.back().second
195                                                 : Path.back().second)
196         << getLangOpts().CurrentModule;
197     return nullptr;
198   }
199   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
200 
201   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
202   Module *Mod;
203 
204   switch (MDK) {
205   case ModuleDeclKind::Interface: {
206     // We can't have parsed or imported a definition of this module or parsed a
207     // module map defining it already.
208     if (auto *M = Map.findModule(ModuleName)) {
209       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
210       if (M->DefinitionLoc.isValid())
211         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
212       else if (Optional<FileEntryRef> FE = M->getASTFile())
213         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
214             << FE->getName();
215       Mod = M;
216       break;
217     }
218 
219     // Create a Module for the module that we're defining.
220     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
221                                            GlobalModuleFragment);
222     if (IsPartition)
223       Mod->Kind = Module::ModulePartitionInterface;
224     assert(Mod && "module creation should not fail");
225     break;
226   }
227 
228   case ModuleDeclKind::Implementation:
229     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
230         PP.getIdentifierInfo(ModuleName), Path[0].second);
231     if (IsPartition) {
232       // Create an interface, but note that it is an implementation
233       // unit.
234       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
235                                              GlobalModuleFragment);
236       Mod->Kind = Module::ModulePartitionImplementation;
237     } else {
238       // C++20 A module-declaration that contains neither an export-
239       // keyword nor a module-partition implicitly imports the primary
240       // module interface unit of the module as if by a module-import-
241       // declaration.
242       Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
243                                          Module::AllVisible,
244                                          /*IsInclusionDirective=*/false);
245       if (!Mod) {
246         Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
247         // Create an empty module interface unit for error recovery.
248         Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
249                                                GlobalModuleFragment);
250       }
251     }
252     break;
253   }
254 
255   if (!GlobalModuleFragment) {
256     ModuleScopes.push_back({});
257     if (getLangOpts().ModulesLocalVisibility)
258       ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
259   } else {
260     // We're done with the global module fragment now.
261     ActOnEndOfTranslationUnitFragment(TUFragmentKind::Global);
262   }
263 
264   // Switch from the global module fragment (if any) to the named module.
265   ModuleScopes.back().BeginLoc = StartLoc;
266   ModuleScopes.back().Module = Mod;
267   ModuleScopes.back().ModuleInterface =
268       (MDK != ModuleDeclKind::Implementation || IsPartition);
269   ModuleScopes.back().IsPartition = IsPartition;
270   VisibleModules.setVisible(Mod, ModuleLoc);
271 
272   // From now on, we have an owning module for all declarations we see.
273   // However, those declarations are module-private unless explicitly
274   // exported.
275   auto *TU = Context.getTranslationUnitDecl();
276   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
277   TU->setLocalOwningModule(Mod);
278 
279   // We are in the module purview, but before any other (non import)
280   // statements, so imports are allowed.
281   ImportState = ModuleImportState::ImportAllowed;
282 
283   // FIXME: Create a ModuleDecl.
284   return nullptr;
285 }
286 
287 Sema::DeclGroupPtrTy
288 Sema::ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
289                                      SourceLocation PrivateLoc) {
290   // C++20 [basic.link]/2:
291   //   A private-module-fragment shall appear only in a primary module
292   //   interface unit.
293   switch (ModuleScopes.empty() ? Module::GlobalModuleFragment
294                                : ModuleScopes.back().Module->Kind) {
295   case Module::ModuleMapModule:
296   case Module::GlobalModuleFragment:
297   case Module::ModulePartitionImplementation:
298   case Module::ModulePartitionInterface:
299     Diag(PrivateLoc, diag::err_private_module_fragment_not_module);
300     return nullptr;
301 
302   case Module::PrivateModuleFragment:
303     Diag(PrivateLoc, diag::err_private_module_fragment_redefined);
304     Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition);
305     return nullptr;
306 
307   case Module::ModuleInterfaceUnit:
308     break;
309   }
310 
311   if (!ModuleScopes.back().ModuleInterface) {
312     Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface);
313     Diag(ModuleScopes.back().BeginLoc,
314          diag::note_not_module_interface_add_export)
315         << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
316     return nullptr;
317   }
318 
319   // FIXME: Check this isn't a module interface partition.
320   // FIXME: Check that this translation unit does not import any partitions;
321   // such imports would violate [basic.link]/2's "shall be the only module unit"
322   // restriction.
323 
324   // We've finished the public fragment of the translation unit.
325   ActOnEndOfTranslationUnitFragment(TUFragmentKind::Normal);
326 
327   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
328   Module *PrivateModuleFragment =
329       Map.createPrivateModuleFragmentForInterfaceUnit(
330           ModuleScopes.back().Module, PrivateLoc);
331   assert(PrivateModuleFragment && "module creation should not fail");
332 
333   // Enter the scope of the private module fragment.
334   ModuleScopes.push_back({});
335   ModuleScopes.back().BeginLoc = ModuleLoc;
336   ModuleScopes.back().Module = PrivateModuleFragment;
337   ModuleScopes.back().ModuleInterface = true;
338   VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
339 
340   // All declarations created from now on are scoped to the private module
341   // fragment (and are neither visible nor reachable in importers of the module
342   // interface).
343   auto *TU = Context.getTranslationUnitDecl();
344   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
345   TU->setLocalOwningModule(PrivateModuleFragment);
346 
347   // FIXME: Consider creating an explicit representation of this declaration.
348   return nullptr;
349 }
350 
351 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
352                                    SourceLocation ExportLoc,
353                                    SourceLocation ImportLoc, ModuleIdPath Path,
354                                    ModuleIdPath Partition) {
355 
356   bool IsPartition = !Partition.empty();
357   bool Cxx20Mode = getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS;
358   assert((!IsPartition || Cxx20Mode) && "partition seen in non-C++20 code?");
359   assert((!IsPartition || Path.empty()) &&
360          "trying to import a partition with its named module specified?");
361 
362   // For a C++20 module name, flatten into a single identifier with the source
363   // location of the first component.
364   std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
365 
366   std::string ModuleName;
367   if (IsPartition) {
368     // We already checked that we are in a module purview in the parser.
369     assert(!ModuleScopes.empty() && "in a module purview, but no module?");
370     Module *NamedMod = ModuleScopes.back().Module;
371     if (ModuleScopes.back().IsPartition) {
372       // We're importing a partition into a partition, find the name of the
373       // owning named module.
374       size_t P = NamedMod->Name.find_first_of(":");
375       ModuleName = NamedMod->Name.substr(0, P + 1);
376     } else {
377       // We're importing a partition into the named module itself (either the
378       // interface or an implementation TU).
379       ModuleName = NamedMod->Name;
380       ModuleName += ":";
381     }
382     ModuleName += stringFromPath(Partition);
383     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Partition[0].second};
384     Partition = ModuleIdPath(ModuleNameLoc);
385   } else if (Cxx20Mode) {
386     ModuleName = stringFromPath(Path);
387     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
388     Path = ModuleIdPath(ModuleNameLoc);
389   }
390 
391   // Diagnose self-import before attempting a load.
392   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview() &&
393       getCurrentModule()->Name == ModuleName) {
394     Diag(ImportLoc, diag::err_module_self_import)
395         << ModuleName << getLangOpts().CurrentModule;
396     return true;
397   }
398 
399   Module *Mod = getModuleLoader().loadModule(
400       ImportLoc, IsPartition ? Partition : Path, Module::AllVisible,
401       /*IsInclusionDirective=*/false);
402   if (!Mod)
403     return true;
404 
405   return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod,
406                            IsPartition ? Partition : Path);
407 }
408 
409 /// Determine whether \p D is lexically within an export-declaration.
410 static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
411   for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
412     if (auto *ED = dyn_cast<ExportDecl>(DC))
413       return ED;
414   return nullptr;
415 }
416 
417 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
418                                    SourceLocation ExportLoc,
419                                    SourceLocation ImportLoc, Module *Mod,
420                                    ModuleIdPath Path) {
421   VisibleModules.setVisible(Mod, ImportLoc);
422 
423   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
424 
425   // FIXME: we should support importing a submodule within a different submodule
426   // of the same top-level module. Until we do, make it an error rather than
427   // silently ignoring the import.
428   // FIXME: Should we warn on a redundant import of the current module?
429   if (!getLangOpts().CPlusPlusModules &&
430       Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
431       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) {
432     Diag(ImportLoc, getLangOpts().isCompilingModule()
433                         ? diag::err_module_self_import
434                         : diag::err_module_import_in_implementation)
435         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
436   }
437 
438   SmallVector<SourceLocation, 2> IdentifierLocs;
439 
440   if (Path.empty()) {
441     // If this was a header import, pad out with dummy locations.
442     // FIXME: Pass in and use the location of the header-name token in this
443     // case.
444     for (Module *ModCheck = Mod; ModCheck; ModCheck = ModCheck->Parent)
445       IdentifierLocs.push_back(SourceLocation());
446   } else if (getLangOpts().CPlusPlusModules && !Mod->Parent) {
447     // A single identifier for the whole name.
448     IdentifierLocs.push_back(Path[0].second);
449   } else {
450     Module *ModCheck = Mod;
451     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
452       // If we've run out of module parents, just drop the remaining
453       // identifiers.  We need the length to be consistent.
454       if (!ModCheck)
455         break;
456       ModCheck = ModCheck->Parent;
457 
458       IdentifierLocs.push_back(Path[I].second);
459     }
460   }
461 
462   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
463                                           Mod, IdentifierLocs);
464   CurContext->addDecl(Import);
465 
466   // Sequence initialization of the imported module before that of the current
467   // module, if any.
468   if (!ModuleScopes.empty())
469     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
470 
471   if (!ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) {
472     // Re-export the module if the imported module is exported.
473     // Note that we don't need to add re-exported module to Imports field
474     // since `Exports` implies the module is imported already.
475     if (ExportLoc.isValid() || getEnclosingExportDecl(Import))
476       getCurrentModule()->Exports.emplace_back(Mod, false);
477     else
478       getCurrentModule()->Imports.insert(Mod);
479   } else if (ExportLoc.isValid()) {
480     // [module.interface]p1:
481     // An export-declaration shall inhabit a namespace scope and appear in the
482     // purview of a module interface unit.
483     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
484   } else if (getLangOpts().isCompilingModule()) {
485     Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
486         getLangOpts().CurrentModule, ExportLoc, false, false);
487     assert(ThisModule && "was expecting a module if building one");
488   }
489 
490   return Import;
491 }
492 
493 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
494   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
495   BuildModuleInclude(DirectiveLoc, Mod);
496 }
497 
498 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
499   // Determine whether we're in the #include buffer for a module. The #includes
500   // in that buffer do not qualify as module imports; they're just an
501   // implementation detail of us building the module.
502   //
503   // FIXME: Should we even get ActOnModuleInclude calls for those?
504   bool IsInModuleIncludes =
505       TUKind == TU_Module &&
506       getSourceManager().isWrittenInMainFile(DirectiveLoc);
507 
508   bool ShouldAddImport = !IsInModuleIncludes;
509 
510   // If this module import was due to an inclusion directive, create an
511   // implicit import declaration to capture it in the AST.
512   if (ShouldAddImport) {
513     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
514     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
515                                                      DirectiveLoc, Mod,
516                                                      DirectiveLoc);
517     if (!ModuleScopes.empty())
518       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
519     TU->addDecl(ImportD);
520     Consumer.HandleImplicitImportDecl(ImportD);
521   }
522 
523   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
524   VisibleModules.setVisible(Mod, DirectiveLoc);
525 
526   if (getLangOpts().isCompilingModule()) {
527     Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
528         getLangOpts().CurrentModule, DirectiveLoc, false, false);
529     assert(ThisModule && "was expecting a module if building one");
530   }
531 }
532 
533 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
534   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
535 
536   ModuleScopes.push_back({});
537   ModuleScopes.back().Module = Mod;
538   if (getLangOpts().ModulesLocalVisibility)
539     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
540 
541   VisibleModules.setVisible(Mod, DirectiveLoc);
542 
543   // The enclosing context is now part of this module.
544   // FIXME: Consider creating a child DeclContext to hold the entities
545   // lexically within the module.
546   if (getLangOpts().trackLocalOwningModule()) {
547     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
548       cast<Decl>(DC)->setModuleOwnershipKind(
549           getLangOpts().ModulesLocalVisibility
550               ? Decl::ModuleOwnershipKind::VisibleWhenImported
551               : Decl::ModuleOwnershipKind::Visible);
552       cast<Decl>(DC)->setLocalOwningModule(Mod);
553     }
554   }
555 }
556 
557 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
558   if (getLangOpts().ModulesLocalVisibility) {
559     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
560     // Leaving a module hides namespace names, so our visible namespace cache
561     // is now out of date.
562     VisibleNamespaceCache.clear();
563   }
564 
565   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
566          "left the wrong module scope");
567   ModuleScopes.pop_back();
568 
569   // We got to the end of processing a local module. Create an
570   // ImportDecl as we would for an imported module.
571   FileID File = getSourceManager().getFileID(EomLoc);
572   SourceLocation DirectiveLoc;
573   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
574     // We reached the end of a #included module header. Use the #include loc.
575     assert(File != getSourceManager().getMainFileID() &&
576            "end of submodule in main source file");
577     DirectiveLoc = getSourceManager().getIncludeLoc(File);
578   } else {
579     // We reached an EOM pragma. Use the pragma location.
580     DirectiveLoc = EomLoc;
581   }
582   BuildModuleInclude(DirectiveLoc, Mod);
583 
584   // Any further declarations are in whatever module we returned to.
585   if (getLangOpts().trackLocalOwningModule()) {
586     // The parser guarantees that this is the same context that we entered
587     // the module within.
588     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
589       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
590       if (!getCurrentModule())
591         cast<Decl>(DC)->setModuleOwnershipKind(
592             Decl::ModuleOwnershipKind::Unowned);
593     }
594   }
595 }
596 
597 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
598                                                       Module *Mod) {
599   // Bail if we're not allowed to implicitly import a module here.
600   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
601       VisibleModules.isVisible(Mod))
602     return;
603 
604   // Create the implicit import declaration.
605   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
606   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
607                                                    Loc, Mod, Loc);
608   TU->addDecl(ImportD);
609   Consumer.HandleImplicitImportDecl(ImportD);
610 
611   // Make the module visible.
612   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
613   VisibleModules.setVisible(Mod, Loc);
614 }
615 
616 /// We have parsed the start of an export declaration, including the '{'
617 /// (if present).
618 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
619                                  SourceLocation LBraceLoc) {
620   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
621 
622   // Set this temporarily so we know the export-declaration was braced.
623   D->setRBraceLoc(LBraceLoc);
624 
625   CurContext->addDecl(D);
626   PushDeclContext(S, D);
627 
628   // C++2a [module.interface]p1:
629   //   An export-declaration shall appear only [...] in the purview of a module
630   //   interface unit. An export-declaration shall not appear directly or
631   //   indirectly within [...] a private-module-fragment.
632   if (ModuleScopes.empty() || !ModuleScopes.back().Module->isModulePurview()) {
633     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
634     D->setInvalidDecl();
635     return D;
636   } else if (!ModuleScopes.back().ModuleInterface) {
637     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
638     Diag(ModuleScopes.back().BeginLoc,
639          diag::note_not_module_interface_add_export)
640         << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
641     D->setInvalidDecl();
642     return D;
643   } else if (ModuleScopes.back().Module->Kind ==
644              Module::PrivateModuleFragment) {
645     Diag(ExportLoc, diag::err_export_in_private_module_fragment);
646     Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
647     D->setInvalidDecl();
648     return D;
649   }
650 
651   for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
652     if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
653       //   An export-declaration shall not appear directly or indirectly within
654       //   an unnamed namespace [...]
655       if (ND->isAnonymousNamespace()) {
656         Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
657         Diag(ND->getLocation(), diag::note_anonymous_namespace);
658         // Don't diagnose internal-linkage declarations in this region.
659         D->setInvalidDecl();
660         return D;
661       }
662 
663       //   A declaration is exported if it is [...] a namespace-definition
664       //   that contains an exported declaration.
665       //
666       // Defer exporting the namespace until after we leave it, in order to
667       // avoid marking all subsequent declarations in the namespace as exported.
668       if (!DeferredExportedNamespaces.insert(ND).second)
669         break;
670     }
671   }
672 
673   //   [...] its declaration or declaration-seq shall not contain an
674   //   export-declaration.
675   if (auto *ED = getEnclosingExportDecl(D)) {
676     Diag(ExportLoc, diag::err_export_within_export);
677     if (ED->hasBraces())
678       Diag(ED->getLocation(), diag::note_export);
679     D->setInvalidDecl();
680     return D;
681   }
682 
683   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
684   return D;
685 }
686 
687 static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
688                                      SourceLocation BlockStart);
689 
690 namespace {
691 enum class UnnamedDeclKind {
692   Empty,
693   StaticAssert,
694   Asm,
695   UsingDirective,
696   Context
697 };
698 }
699 
700 static llvm::Optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) {
701   if (isa<EmptyDecl>(D))
702     return UnnamedDeclKind::Empty;
703   if (isa<StaticAssertDecl>(D))
704     return UnnamedDeclKind::StaticAssert;
705   if (isa<FileScopeAsmDecl>(D))
706     return UnnamedDeclKind::Asm;
707   if (isa<UsingDirectiveDecl>(D))
708     return UnnamedDeclKind::UsingDirective;
709   // Everything else either introduces one or more names or is ill-formed.
710   return llvm::None;
711 }
712 
713 unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) {
714   switch (UDK) {
715   case UnnamedDeclKind::Empty:
716   case UnnamedDeclKind::StaticAssert:
717     // Allow empty-declarations and static_asserts in an export block as an
718     // extension.
719     return InBlock ? diag::ext_export_no_name_block : diag::err_export_no_name;
720 
721   case UnnamedDeclKind::UsingDirective:
722     // Allow exporting using-directives as an extension.
723     return diag::ext_export_using_directive;
724 
725   case UnnamedDeclKind::Context:
726     // Allow exporting DeclContexts that transitively contain no declarations
727     // as an extension.
728     return diag::ext_export_no_names;
729 
730   case UnnamedDeclKind::Asm:
731     return diag::err_export_no_name;
732   }
733   llvm_unreachable("unknown kind");
734 }
735 
736 static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D,
737                                     SourceLocation BlockStart) {
738   S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid()))
739       << (unsigned)UDK;
740   if (BlockStart.isValid())
741     S.Diag(BlockStart, diag::note_export);
742 }
743 
744 /// Check that it's valid to export \p D.
745 static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
746   // C++2a [module.interface]p3:
747   //   An exported declaration shall declare at least one name
748   if (auto UDK = getUnnamedDeclKind(D))
749     diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
750 
751   //   [...] shall not declare a name with internal linkage.
752   if (auto *ND = dyn_cast<NamedDecl>(D)) {
753     // Don't diagnose anonymous union objects; we'll diagnose their members
754     // instead.
755     if (ND->getDeclName() && ND->getFormalLinkage() == InternalLinkage) {
756       S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
757       if (BlockStart.isValid())
758         S.Diag(BlockStart, diag::note_export);
759     }
760   }
761 
762   // C++2a [module.interface]p5:
763   //   all entities to which all of the using-declarators ultimately refer
764   //   shall have been introduced with a name having external linkage
765   if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
766     NamedDecl *Target = USD->getUnderlyingDecl();
767     if (Target->getFormalLinkage() == InternalLinkage) {
768       S.Diag(USD->getLocation(), diag::err_export_using_internal) << Target;
769       S.Diag(Target->getLocation(), diag::note_using_decl_target);
770       if (BlockStart.isValid())
771         S.Diag(BlockStart, diag::note_export);
772     }
773   }
774 
775   // Recurse into namespace-scope DeclContexts. (Only namespace-scope
776   // declarations are exported.)
777   if (auto *DC = dyn_cast<DeclContext>(D))
778     if (DC->getRedeclContext()->isFileContext() && !isa<EnumDecl>(D))
779       return checkExportedDeclContext(S, DC, BlockStart);
780   return false;
781 }
782 
783 /// Check that it's valid to export all the declarations in \p DC.
784 static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
785                                      SourceLocation BlockStart) {
786   bool AllUnnamed = true;
787   for (auto *D : DC->decls())
788     AllUnnamed &= checkExportedDecl(S, D, BlockStart);
789   return AllUnnamed;
790 }
791 
792 /// Complete the definition of an export declaration.
793 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
794   auto *ED = cast<ExportDecl>(D);
795   if (RBraceLoc.isValid())
796     ED->setRBraceLoc(RBraceLoc);
797 
798   PopDeclContext();
799 
800   if (!D->isInvalidDecl()) {
801     SourceLocation BlockStart =
802         ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
803     for (auto *Child : ED->decls()) {
804       if (checkExportedDecl(*this, Child, BlockStart)) {
805         // If a top-level child is a linkage-spec declaration, it might contain
806         // no declarations (transitively), in which case it's ill-formed.
807         diagExportedUnnamedDecl(*this, UnnamedDeclKind::Context, Child,
808                                 BlockStart);
809       }
810     }
811   }
812 
813   return D;
814 }
815 
816 Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc,
817                                        bool IsImplicit) {
818   // We shouldn't create new global module fragment if there is already
819   // one.
820   if (!GlobalModuleFragment) {
821     ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
822     GlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
823         BeginLoc, getCurrentModule());
824   }
825 
826   assert(GlobalModuleFragment && "module creation should not fail");
827 
828   // Enter the scope of the global module.
829   ModuleScopes.push_back({BeginLoc, GlobalModuleFragment,
830                           /*ModuleInterface=*/false,
831                           /*IsPartition=*/false,
832                           /*ImplicitGlobalModuleFragment=*/IsImplicit,
833                           /*OuterVisibleModules=*/{}});
834   VisibleModules.setVisible(GlobalModuleFragment, BeginLoc);
835 
836   return GlobalModuleFragment;
837 }
838 
839 void Sema::PopGlobalModuleFragment() {
840   assert(!ModuleScopes.empty() && getCurrentModule()->isGlobalModule() &&
841          "left the wrong module scope, which is not global module fragment");
842   ModuleScopes.pop_back();
843 }
844