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/AST/ASTMutationListener.h"
16#include "clang/AST/DynamicRecursiveASTVisitor.h"
17#include "clang/Lex/HeaderSearch.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Sema/ParsedAttr.h"
20#include "clang/Sema/SemaInternal.h"
21#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/StringExtras.h"
23
24using namespace clang;
25using namespace sema;
26
27static void checkModuleImportContext(Sema &S, Module *M,
28 SourceLocation ImportLoc, DeclContext *DC,
29 bool FromInclude = false) {
30 SourceLocation ExternCLoc;
31
32 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Val: DC)) {
33 switch (LSD->getLanguage()) {
34 case LinkageSpecLanguageIDs::C:
35 if (ExternCLoc.isInvalid())
36 ExternCLoc = LSD->getBeginLoc();
37 break;
38 case LinkageSpecLanguageIDs::CXX:
39 break;
40 }
41 DC = LSD->getParent();
42 }
43
44 while (isa<LinkageSpecDecl>(Val: DC) || isa<ExportDecl>(Val: DC))
45 DC = DC->getParent();
46
47 if (!isa<TranslationUnitDecl>(Val: DC)) {
48 S.Diag(Loc: ImportLoc, DiagID: (FromInclude && S.isModuleVisible(M))
49 ? diag::ext_module_import_not_at_top_level_noop
50 : diag::err_module_import_not_at_top_level_fatal)
51 << M->getFullModuleName() << DC;
52 S.Diag(Loc: cast<Decl>(Val: DC)->getBeginLoc(),
53 DiagID: diag::note_module_import_not_at_top_level)
54 << DC;
55 } else if (!M->IsExternC && ExternCLoc.isValid()) {
56 S.Diag(Loc: ImportLoc, DiagID: diag::ext_module_import_in_extern_c)
57 << M->getFullModuleName();
58 S.Diag(Loc: ExternCLoc, DiagID: diag::note_extern_c_begins_here);
59 }
60}
61
62/// Helper function for makeTransitiveImportsVisible to decide whether
63/// the \param Imported module unit is in the same module with the \param
64/// CurrentModule.
65/// \param FoundPrimaryModuleInterface is a helper parameter to record the
66/// primary module interface unit corresponding to the module \param
67/// CurrentModule. Since currently it is expensive to decide whether two module
68/// units come from the same module by comparing the module name.
69static bool
70isImportingModuleUnitFromSameModule(ASTContext &Ctx, Module *Imported,
71 Module *CurrentModule,
72 Module *&FoundPrimaryModuleInterface) {
73 if (!Imported->isNamedModule())
74 return false;
75
76 // The a partition unit we're importing must be in the same module of the
77 // current module.
78 if (Imported->isModulePartition())
79 return true;
80
81 // If we found the primary module interface during the search process, we can
82 // return quickly to avoid expensive string comparison.
83 if (FoundPrimaryModuleInterface)
84 return Imported == FoundPrimaryModuleInterface;
85
86 if (!CurrentModule)
87 return false;
88
89 // Then the imported module must be a primary module interface unit. It
90 // is only allowed to import the primary module interface unit from the same
91 // module in the implementation unit and the implementation partition unit.
92
93 // Since we'll handle implementation unit above. We can only care
94 // about the implementation partition unit here.
95 if (!CurrentModule->isModulePartitionImplementation())
96 return false;
97
98 if (Ctx.isInSameModule(M1: Imported, M2: CurrentModule)) {
99 assert(!FoundPrimaryModuleInterface ||
100 FoundPrimaryModuleInterface == Imported);
101 FoundPrimaryModuleInterface = Imported;
102 return true;
103 }
104
105 return false;
106}
107
108/// [module.import]p7:
109/// Additionally, when a module-import-declaration in a module unit of some
110/// module M imports another module unit U of M, it also imports all
111/// translation units imported by non-exported module-import-declarations in
112/// the module unit purview of U. These rules can in turn lead to the
113/// importation of yet more translation units.
114static void
115makeTransitiveImportsVisible(ASTContext &Ctx, VisibleModuleSet &VisibleModules,
116 Module *Imported, Module *CurrentModule,
117 SourceLocation ImportLoc,
118 bool IsImportingPrimaryModuleInterface = false) {
119 assert(Imported->isNamedModule() &&
120 "'makeTransitiveImportsVisible()' is intended for standard C++ named "
121 "modules only.");
122
123 llvm::SmallVector<Module *, 4> Worklist;
124 llvm::SmallPtrSet<Module *, 16> Visited;
125 Worklist.push_back(Elt: Imported);
126
127 Module *FoundPrimaryModuleInterface =
128 IsImportingPrimaryModuleInterface ? Imported : nullptr;
129
130 while (!Worklist.empty()) {
131 Module *Importing = Worklist.pop_back_val();
132
133 if (Visited.count(Ptr: Importing))
134 continue;
135 Visited.insert(Ptr: Importing);
136
137 // FIXME: The ImportLoc here is not meaningful. It may be problematic if we
138 // use the sourcelocation loaded from the visible modules.
139 VisibleModules.setVisible(M: Importing, Loc: ImportLoc);
140
141 if (isImportingModuleUnitFromSameModule(Ctx, Imported: Importing, CurrentModule,
142 FoundPrimaryModuleInterface)) {
143 for (Module *TransImported : Importing->Imports)
144 Worklist.push_back(Elt: TransImported);
145
146 for (auto [Exports, _] : Importing->Exports)
147 Worklist.push_back(Elt: Exports);
148 }
149 }
150}
151
152Sema::DeclGroupPtrTy
153Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc) {
154 // We start in the global module;
155 Module *GlobalModule =
156 PushGlobalModuleFragment(BeginLoc: ModuleLoc);
157
158 // All declarations created from now on are owned by the global module.
159 auto *TU = Context.getTranslationUnitDecl();
160 // [module.global.frag]p2
161 // A global-module-fragment specifies the contents of the global module
162 // fragment for a module unit. The global module fragment can be used to
163 // provide declarations that are attached to the global module and usable
164 // within the module unit.
165 //
166 // So the declations in the global module shouldn't be visible by default.
167 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
168 TU->setLocalOwningModule(GlobalModule);
169
170 // FIXME: Consider creating an explicit representation of this declaration.
171 return nullptr;
172}
173
174void Sema::HandleStartOfHeaderUnit() {
175 assert(getLangOpts().CPlusPlusModules &&
176 "Header units are only valid for C++20 modules");
177 SourceLocation StartOfTU =
178 SourceMgr.getLocForStartOfFile(FID: SourceMgr.getMainFileID());
179
180 StringRef HUName = getLangOpts().CurrentModule;
181 if (HUName.empty()) {
182 HUName =
183 SourceMgr.getFileEntryRefForID(FID: SourceMgr.getMainFileID())->getName();
184 const_cast<LangOptions &>(getLangOpts()).CurrentModule = HUName.str();
185 }
186
187 // TODO: Make the C++20 header lookup independent.
188 // When the input is pre-processed source, we need a file ref to the original
189 // file for the header map.
190 auto F = SourceMgr.getFileManager().getOptionalFileRef(Filename: HUName);
191 // For the sake of error recovery (if someone has moved the original header
192 // after creating the pre-processed output) fall back to obtaining the file
193 // ref for the input file, which must be present.
194 if (!F)
195 F = SourceMgr.getFileEntryRefForID(FID: SourceMgr.getMainFileID());
196 assert(F && "failed to find the header unit source?");
197 Module::Header H{.NameAsWritten: HUName.str(), .PathRelativeToRootModuleDirectory: HUName.str(), .Entry: *F};
198 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
199 Module *Mod = Map.createHeaderUnit(Loc: StartOfTU, Name: HUName, H);
200 assert(Mod && "module creation should not fail");
201 ModuleScopes.push_back(Elt: {}); // No GMF
202 ModuleScopes.back().BeginLoc = StartOfTU;
203 ModuleScopes.back().Module = Mod;
204 VisibleModules.setVisible(M: Mod, Loc: StartOfTU);
205
206 // From now on, we have an owning module for all declarations we see.
207 // All of these are implicitly exported.
208 auto *TU = Context.getTranslationUnitDecl();
209 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
210 TU->setLocalOwningModule(Mod);
211}
212
213/// Tests whether the given identifier is reserved as a module name and
214/// diagnoses if it is. Returns true if a diagnostic is emitted and false
215/// otherwise.
216static bool DiagReservedModuleName(Sema &S, const IdentifierInfo *II,
217 SourceLocation Loc) {
218 enum {
219 Valid = -1,
220 Invalid = 0,
221 Reserved = 1,
222 } Reason = Valid;
223
224 if (II->isStr(Str: "module") || II->isStr(Str: "import"))
225 Reason = Invalid;
226 else if (II->isReserved(LangOpts: S.getLangOpts()) !=
227 ReservedIdentifierStatus::NotReserved)
228 Reason = Reserved;
229
230 // If the identifier is reserved (not invalid) but is in a system header,
231 // we do not diagnose (because we expect system headers to use reserved
232 // identifiers).
233 if (Reason == Reserved && S.getSourceManager().isInSystemHeader(Loc))
234 Reason = Valid;
235
236 switch (Reason) {
237 case Valid:
238 return false;
239 case Invalid:
240 return S.Diag(Loc, DiagID: diag::err_invalid_module_name) << II;
241 case Reserved:
242 S.Diag(Loc, DiagID: diag::warn_reserved_module_name) << II;
243 return false;
244 }
245 llvm_unreachable("fell off a fully covered switch");
246}
247
248Sema::DeclGroupPtrTy
249Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc,
250 ModuleDeclKind MDK, ModuleIdPath Path,
251 ModuleIdPath Partition, ModuleImportState &ImportState,
252 bool SeenNoTrivialPPDirective) {
253 assert(getLangOpts().CPlusPlusModules &&
254 "should only have module decl in standard C++ modules");
255
256 bool IsFirstDecl = ImportState == ModuleImportState::FirstDecl;
257 bool SeenGMF = ImportState == ModuleImportState::GlobalFragment;
258 // If any of the steps here fail, we count that as invalidating C++20
259 // module state;
260 ImportState = ModuleImportState::NotACXX20Module;
261
262 bool IsPartition = !Partition.empty();
263 if (IsPartition)
264 switch (MDK) {
265 case ModuleDeclKind::Implementation:
266 MDK = ModuleDeclKind::PartitionImplementation;
267 break;
268 case ModuleDeclKind::Interface:
269 MDK = ModuleDeclKind::PartitionInterface;
270 break;
271 default:
272 llvm_unreachable("how did we get a partition type set?");
273 }
274
275 // A (non-partition) module implementation unit requires that we are not
276 // compiling a module of any kind. A partition implementation emits an
277 // interface (and the AST for the implementation), which will subsequently
278 // be consumed to emit a binary.
279 // A module interface unit requires that we are not compiling a module map.
280 switch (getLangOpts().getCompilingModule()) {
281 case LangOptions::CMK_None:
282 // It's OK to compile a module interface as a normal translation unit.
283 break;
284
285 case LangOptions::CMK_ModuleInterface:
286 if (MDK != ModuleDeclKind::Implementation)
287 break;
288
289 // We were asked to compile a module interface unit but this is a module
290 // implementation unit.
291 Diag(Loc: ModuleLoc, DiagID: diag::err_module_interface_implementation_mismatch)
292 << FixItHint::CreateInsertion(InsertionLoc: ModuleLoc, Code: "export ");
293 MDK = ModuleDeclKind::Interface;
294 break;
295
296 case LangOptions::CMK_ModuleMap:
297 Diag(Loc: ModuleLoc, DiagID: diag::err_module_decl_in_module_map_module);
298 return nullptr;
299
300 case LangOptions::CMK_HeaderUnit:
301 Diag(Loc: ModuleLoc, DiagID: diag::err_module_decl_in_header_unit);
302 return nullptr;
303 }
304
305 assert(ModuleScopes.size() <= 1 && "expected to be at global module scope");
306
307 // FIXME: Most of this work should be done by the preprocessor rather than
308 // here, in order to support macro import.
309
310 // Only one module-declaration is permitted per source file.
311 if (isCurrentModulePurview()) {
312 Diag(Loc: ModuleLoc, DiagID: diag::err_module_redeclaration);
313 Diag(Loc: VisibleModules.getImportLoc(M: ModuleScopes.back().Module),
314 DiagID: diag::note_prev_module_declaration);
315 return nullptr;
316 }
317
318 assert((!getLangOpts().CPlusPlusModules ||
319 SeenGMF == (bool)this->TheGlobalModuleFragment) &&
320 "mismatched global module state");
321
322 // In C++20, A module directive may only appear as the first preprocessing
323 // tokens in a file (excluding the global module fragment.).
324 if (getLangOpts().CPlusPlusModules &&
325 (!IsFirstDecl || SeenNoTrivialPPDirective) && !SeenGMF) {
326 Diag(Loc: ModuleLoc, DiagID: diag::err_module_decl_not_at_start);
327 SourceLocation BeginLoc = PP.getMainFileFirstPPTokenLoc();
328 Diag(Loc: BeginLoc, DiagID: diag::note_global_module_introducer_missing)
329 << FixItHint::CreateInsertion(InsertionLoc: BeginLoc, Code: "module;\n");
330 }
331
332 // C++23 [module.unit]p1: ... The identifiers module and import shall not
333 // appear as identifiers in a module-name or module-partition. All
334 // module-names either beginning with an identifier consisting of std
335 // followed by zero or more digits or containing a reserved identifier
336 // ([lex.name]) are reserved and shall not be specified in a
337 // module-declaration; no diagnostic is required.
338
339 // Test the first part of the path to see if it's std[0-9]+ but allow the
340 // name in a system header.
341 StringRef FirstComponentName = Path[0].getIdentifierInfo()->getName();
342 if (!getSourceManager().isInSystemHeader(Loc: Path[0].getLoc()) &&
343 (FirstComponentName == "std" ||
344 (FirstComponentName.starts_with(Prefix: "std") &&
345 llvm::all_of(Range: FirstComponentName.drop_front(N: 3), P: &llvm::isDigit))))
346 Diag(Loc: Path[0].getLoc(), DiagID: diag::warn_reserved_module_name)
347 << Path[0].getIdentifierInfo();
348
349 // Then test all of the components in the path to see if any of them are
350 // using another kind of reserved or invalid identifier.
351 for (auto Part : Path) {
352 if (DiagReservedModuleName(S&: *this, II: Part.getIdentifierInfo(), Loc: Part.getLoc()))
353 return nullptr;
354 }
355
356 // Flatten the dots in a module name. Unlike Clang's hierarchical module map
357 // modules, the dots here are just another character that can appear in a
358 // module name.
359 std::string ModuleName = ModuleLoader::getFlatNameFromPath(Path);
360 if (IsPartition) {
361 ModuleName += ":";
362 ModuleName += ModuleLoader::getFlatNameFromPath(Path: Partition);
363 }
364 // If a module name was explicitly specified on the command line, it must be
365 // correct.
366 if (!getLangOpts().CurrentModule.empty() &&
367 getLangOpts().CurrentModule != ModuleName) {
368 Diag(Loc: Path.front().getLoc(), DiagID: diag::err_current_module_name_mismatch)
369 << SourceRange(Path.front().getLoc(), IsPartition
370 ? Partition.back().getLoc()
371 : Path.back().getLoc())
372 << getLangOpts().CurrentModule;
373 return nullptr;
374 }
375 const_cast<LangOptions &>(getLangOpts()).CurrentModule = ModuleName;
376
377 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
378 Module *Mod; // The module we are creating.
379 Module *Interface = nullptr; // The interface for an implementation.
380 switch (MDK) {
381 case ModuleDeclKind::Interface:
382 case ModuleDeclKind::PartitionInterface: {
383 // We can't have parsed or imported a definition of this module or parsed a
384 // module map defining it already.
385 if (auto *M = Map.findOrLoadModule(Name: ModuleName)) {
386 Diag(Loc: Path[0].getLoc(), DiagID: diag::err_module_redefinition) << ModuleName;
387 if (M->DefinitionLoc.isValid())
388 Diag(Loc: M->DefinitionLoc, DiagID: diag::note_prev_module_definition);
389 else if (OptionalFileEntryRef FE = M->getASTFile())
390 Diag(Loc: M->DefinitionLoc, DiagID: diag::note_prev_module_definition_from_ast_file)
391 << FE->getName();
392 Mod = M;
393 break;
394 }
395
396 // Create a Module for the module that we're defining.
397 Mod = Map.createModuleForInterfaceUnit(Loc: ModuleLoc, Name: ModuleName);
398 if (MDK == ModuleDeclKind::PartitionInterface)
399 Mod->Kind = Module::ModulePartitionInterface;
400 assert(Mod && "module creation should not fail");
401 break;
402 }
403
404 case ModuleDeclKind::Implementation: {
405 // C++20 A module-declaration that contains neither an export-
406 // keyword nor a module-partition implicitly imports the primary
407 // module interface unit of the module as if by a module-import-
408 // declaration.
409 IdentifierLoc ModuleNameLoc(Path[0].getLoc(),
410 PP.getIdentifierInfo(Name: ModuleName));
411
412 // The module loader will assume we're trying to import the module that
413 // we're building if `LangOpts.CurrentModule` equals to 'ModuleName'.
414 // Change the value for `LangOpts.CurrentModule` temporarily to make the
415 // module loader work properly.
416 const_cast<LangOptions &>(getLangOpts()).CurrentModule = "";
417 Interface = getModuleLoader().loadModule(ImportLoc: ModuleLoc, Path: {ModuleNameLoc},
418 Visibility: Module::AllVisible,
419 /*IsInclusionDirective=*/false);
420 const_cast<LangOptions &>(getLangOpts()).CurrentModule = ModuleName;
421
422 if (!Interface) {
423 Diag(Loc: ModuleLoc, DiagID: diag::err_module_not_defined) << ModuleName;
424 // Create an empty module interface unit for error recovery.
425 Mod = Map.createModuleForInterfaceUnit(Loc: ModuleLoc, Name: ModuleName);
426 } else {
427 Mod = Map.createModuleForImplementationUnit(Loc: ModuleLoc, Name: ModuleName);
428 }
429 } break;
430
431 case ModuleDeclKind::PartitionImplementation:
432 // Create an interface, but note that it is an implementation
433 // unit.
434 Mod = Map.createModuleForInterfaceUnit(Loc: ModuleLoc, Name: ModuleName);
435 Mod->Kind = Module::ModulePartitionImplementation;
436 break;
437 }
438
439 if (!this->TheGlobalModuleFragment) {
440 ModuleScopes.push_back(Elt: {});
441 if (getLangOpts().ModulesLocalVisibility)
442 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
443 } else {
444 // We're done with the global module fragment now.
445 ActOnEndOfTranslationUnitFragment(Kind: TUFragmentKind::Global);
446 }
447
448 // Switch from the global module fragment (if any) to the named module.
449 ModuleScopes.back().BeginLoc = StartLoc;
450 ModuleScopes.back().Module = Mod;
451 VisibleModules.setVisible(M: Mod, Loc: ModuleLoc);
452
453 // From now on, we have an owning module for all declarations we see.
454 // In C++20 modules, those declaration would be reachable when imported
455 // unless explicitily exported.
456 // Otherwise, those declarations are module-private unless explicitly
457 // exported.
458 auto *TU = Context.getTranslationUnitDecl();
459 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
460 TU->setLocalOwningModule(Mod);
461
462 // We are in the module purview, but before any other (non import)
463 // statements, so imports are allowed.
464 ImportState = ModuleImportState::ImportAllowed;
465
466 getASTContext().setCurrentNamedModule(Mod);
467
468 if (auto *Listener = getASTMutationListener())
469 Listener->EnteringModulePurview();
470
471 // We already potentially made an implicit import (in the case of a module
472 // implementation unit importing its interface). Make this module visible
473 // and return the import decl to be added to the current TU.
474 if (Interface) {
475 HadImportedNamedModules = true;
476
477 makeTransitiveImportsVisible(Ctx&: getASTContext(), VisibleModules, Imported: Interface,
478 CurrentModule: Mod, ImportLoc: ModuleLoc,
479 /*IsImportingPrimaryModuleInterface=*/true);
480
481 // Make the import decl for the interface in the impl module.
482 ImportDecl *Import = ImportDecl::Create(C&: Context, DC: CurContext, StartLoc: ModuleLoc,
483 Imported: Interface, IdentifierLocs: Path[0].getLoc());
484 CurContext->addDecl(D: Import);
485
486 // Sequence initialization of the imported module before that of the current
487 // module, if any.
488 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: Import);
489 Mod->Imports.insert(X: Interface); // As if we imported it.
490 // Also save this as a shortcut to checking for decls in the interface
491 ThePrimaryInterface = Interface;
492 // If we made an implicit import of the module interface, then return the
493 // imported module decl.
494 return ConvertDeclToDeclGroup(Ptr: Import);
495 }
496
497 return nullptr;
498}
499
500Sema::DeclGroupPtrTy
501Sema::ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
502 SourceLocation PrivateLoc) {
503 // C++20 [basic.link]/2:
504 // A private-module-fragment shall appear only in a primary module
505 // interface unit.
506 switch (ModuleScopes.empty() ? Module::ExplicitGlobalModuleFragment
507 : ModuleScopes.back().Module->Kind) {
508 case Module::ModuleMapModule:
509 case Module::ExplicitGlobalModuleFragment:
510 case Module::ImplicitGlobalModuleFragment:
511 case Module::ModulePartitionImplementation:
512 case Module::ModulePartitionInterface:
513 case Module::ModuleHeaderUnit:
514 Diag(Loc: PrivateLoc, DiagID: diag::err_private_module_fragment_not_module);
515 return nullptr;
516
517 case Module::PrivateModuleFragment:
518 Diag(Loc: PrivateLoc, DiagID: diag::err_private_module_fragment_redefined);
519 Diag(Loc: ModuleScopes.back().BeginLoc, DiagID: diag::note_previous_definition);
520 return nullptr;
521
522 case Module::ModuleImplementationUnit:
523 Diag(Loc: PrivateLoc, DiagID: diag::err_private_module_fragment_not_module_interface);
524 Diag(Loc: ModuleScopes.back().BeginLoc,
525 DiagID: diag::note_not_module_interface_add_export)
526 << FixItHint::CreateInsertion(InsertionLoc: ModuleScopes.back().BeginLoc, Code: "export ");
527 return nullptr;
528
529 case Module::ModuleInterfaceUnit:
530 break;
531 }
532
533 // FIXME: Check that this translation unit does not import any partitions;
534 // such imports would violate [basic.link]/2's "shall be the only module unit"
535 // restriction.
536
537 // We've finished the public fragment of the translation unit.
538 ActOnEndOfTranslationUnitFragment(Kind: TUFragmentKind::Normal);
539
540 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
541 Module *PrivateModuleFragment =
542 Map.createPrivateModuleFragmentForInterfaceUnit(
543 Parent: ModuleScopes.back().Module, Loc: PrivateLoc);
544 assert(PrivateModuleFragment && "module creation should not fail");
545
546 // Enter the scope of the private module fragment.
547 ModuleScopes.push_back(Elt: {});
548 ModuleScopes.back().BeginLoc = ModuleLoc;
549 ModuleScopes.back().Module = PrivateModuleFragment;
550 VisibleModules.setVisible(M: PrivateModuleFragment, Loc: ModuleLoc);
551
552 // All declarations created from now on are scoped to the private module
553 // fragment (and are neither visible nor reachable in importers of the module
554 // interface).
555 auto *TU = Context.getTranslationUnitDecl();
556 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
557 TU->setLocalOwningModule(PrivateModuleFragment);
558
559 // FIXME: Consider creating an explicit representation of this declaration.
560 return nullptr;
561}
562
563DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
564 SourceLocation ExportLoc,
565 SourceLocation ImportLoc, ModuleIdPath Path,
566 bool IsPartition) {
567 assert((!IsPartition || getLangOpts().CPlusPlusModules) &&
568 "partition seen in non-C++20 code?");
569
570 // For a C++20 module name, flatten into a single identifier with the source
571 // location of the first component.
572 IdentifierLoc ModuleNameLoc;
573
574 std::string ModuleName;
575 if (IsPartition) {
576 // We already checked that we are in a module purview in the parser.
577 assert(!ModuleScopes.empty() && "in a module purview, but no module?");
578 Module *NamedMod = ModuleScopes.back().Module;
579 // If we are importing into a partition, find the owning named module,
580 // otherwise, the name of the importing named module.
581 ModuleName = NamedMod->getPrimaryModuleInterfaceName().str();
582 ModuleName += ":";
583 ModuleName += ModuleLoader::getFlatNameFromPath(Path);
584 ModuleNameLoc =
585 IdentifierLoc(Path[0].getLoc(), PP.getIdentifierInfo(Name: ModuleName));
586 Path = ModuleIdPath(ModuleNameLoc);
587 } else if (getLangOpts().CPlusPlusModules) {
588 ModuleName = ModuleLoader::getFlatNameFromPath(Path);
589 ModuleNameLoc =
590 IdentifierLoc(Path[0].getLoc(), PP.getIdentifierInfo(Name: ModuleName));
591 Path = ModuleIdPath(ModuleNameLoc);
592 }
593
594 // Diagnose self-import before attempting a load.
595 // [module.import]/9
596 // A module implementation unit of a module M that is not a module partition
597 // shall not contain a module-import-declaration nominating M.
598 // (for an implementation, the module interface is imported implicitly,
599 // but that's handled in the module decl code).
600
601 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview() &&
602 getCurrentModule()->Name == ModuleName) {
603 Diag(Loc: ImportLoc, DiagID: diag::err_module_self_import_cxx20)
604 << ModuleName << currentModuleIsImplementation();
605 return true;
606 }
607
608 Module *Mod = getModuleLoader().loadModule(
609 ImportLoc, Path, Visibility: Module::AllVisible, /*IsInclusionDirective=*/false);
610 if (!Mod)
611 return true;
612
613 if (!Mod->isInterfaceOrPartition() && !ModuleName.empty() &&
614 !getLangOpts().ObjC) {
615 Diag(Loc: ImportLoc, DiagID: diag::err_module_import_non_interface_nor_parition)
616 << ModuleName;
617 return true;
618 }
619
620 return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, M: Mod, Path);
621}
622
623/// Determine whether \p D is lexically within an export-declaration.
624static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
625 for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
626 if (auto *ED = dyn_cast<ExportDecl>(Val: DC))
627 return ED;
628 return nullptr;
629}
630
631DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
632 SourceLocation ExportLoc,
633 SourceLocation ImportLoc, Module *Mod,
634 ModuleIdPath Path) {
635 if (Mod->isHeaderUnit())
636 Diag(Loc: ImportLoc, DiagID: diag::warn_experimental_header_unit);
637
638 if (Mod->isNamedModule())
639 makeTransitiveImportsVisible(Ctx&: getASTContext(), VisibleModules, Imported: Mod,
640 CurrentModule: getCurrentModule(), ImportLoc);
641 else
642 VisibleModules.setVisible(M: Mod, Loc: ImportLoc);
643
644 assert((!Mod->isModulePartitionImplementation() || getCurrentModule()) &&
645 "We can only import a partition unit in a named module.");
646 if (Mod->isModulePartitionImplementation() &&
647 getCurrentModule()->isModuleInterfaceUnit())
648 Diag(Loc: ImportLoc,
649 DiagID: diag::warn_import_implementation_partition_unit_in_interface_unit)
650 << Mod->Name;
651
652 checkModuleImportContext(S&: *this, M: Mod, ImportLoc, DC: CurContext);
653
654 // FIXME: we should support importing a submodule within a different submodule
655 // of the same top-level module. Until we do, make it an error rather than
656 // silently ignoring the import.
657 // FIXME: Should we warn on a redundant import of the current module?
658 if (Mod->isForBuilding(LangOpts: getLangOpts())) {
659 Diag(Loc: ImportLoc, DiagID: getLangOpts().isCompilingModule()
660 ? diag::err_module_self_import
661 : diag::err_module_import_in_implementation)
662 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
663 }
664
665 SmallVector<SourceLocation, 2> IdentifierLocs;
666
667 if (Path.empty()) {
668 // If this was a header import, pad out with dummy locations.
669 // FIXME: Pass in and use the location of the header-name token in this
670 // case.
671 for (Module *ModCheck = Mod; ModCheck; ModCheck = ModCheck->Parent)
672 IdentifierLocs.push_back(Elt: SourceLocation());
673 } else if (getLangOpts().CPlusPlusModules && !Mod->Parent) {
674 // A single identifier for the whole name.
675 IdentifierLocs.push_back(Elt: Path[0].getLoc());
676 } else {
677 Module *ModCheck = Mod;
678 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
679 // If we've run out of module parents, just drop the remaining
680 // identifiers. We need the length to be consistent.
681 if (!ModCheck)
682 break;
683 ModCheck = ModCheck->Parent;
684
685 IdentifierLocs.push_back(Elt: Path[I].getLoc());
686 }
687 }
688
689 ImportDecl *Import = ImportDecl::Create(C&: Context, DC: CurContext, StartLoc,
690 Imported: Mod, IdentifierLocs);
691 CurContext->addDecl(D: Import);
692
693 // Sequence initialization of the imported module before that of the current
694 // module, if any.
695 if (!ModuleScopes.empty())
696 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: Import);
697
698 // A module (partition) implementation unit shall not be exported.
699 if (getLangOpts().CPlusPlusModules && ExportLoc.isValid() &&
700 Mod->Kind == Module::ModuleKind::ModulePartitionImplementation) {
701 Diag(Loc: ExportLoc, DiagID: diag::err_export_partition_impl)
702 << SourceRange(ExportLoc, Path.back().getLoc());
703 } else if (ExportLoc.isValid() &&
704 (ModuleScopes.empty() || currentModuleIsImplementation())) {
705 // [module.interface]p1:
706 // An export-declaration shall inhabit a namespace scope and appear in the
707 // purview of a module interface unit.
708 Diag(Loc: ExportLoc, DiagID: diag::err_export_not_in_module_interface);
709 } else if (!ModuleScopes.empty()) {
710 // Re-export the module if the imported module is exported.
711 // Note that we don't need to add re-exported module to Imports field
712 // since `Exports` implies the module is imported already.
713 if (ExportLoc.isValid() || getEnclosingExportDecl(D: Import))
714 getCurrentModule()->Exports.emplace_back(Args&: Mod, Args: false);
715 else
716 getCurrentModule()->Imports.insert(X: Mod);
717 }
718
719 HadImportedNamedModules = true;
720
721 return Import;
722}
723
724void Sema::ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
725 checkModuleImportContext(S&: *this, M: Mod, ImportLoc: DirectiveLoc, DC: CurContext, FromInclude: true);
726 BuildModuleInclude(DirectiveLoc, Mod);
727}
728
729void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
730 // Determine whether we're in the #include buffer for a module. The #includes
731 // in that buffer do not qualify as module imports; they're just an
732 // implementation detail of us building the module.
733 //
734 // FIXME: Should we even get ActOnAnnotModuleInclude calls for those?
735 bool IsInModuleIncludes =
736 TUKind == TU_ClangModule &&
737 getSourceManager().isWrittenInMainFile(Loc: DirectiveLoc);
738
739 // If we are really importing a module (not just checking layering) due to an
740 // #include in the main file, synthesize an ImportDecl.
741 if (getLangOpts().Modules && !IsInModuleIncludes) {
742 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
743 ImportDecl *ImportD = ImportDecl::CreateImplicit(C&: getASTContext(), DC: TU,
744 StartLoc: DirectiveLoc, Imported: Mod,
745 EndLoc: DirectiveLoc);
746 if (!ModuleScopes.empty())
747 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: ImportD);
748 TU->addDecl(D: ImportD);
749 Consumer.HandleImplicitImportDecl(D: ImportD);
750 }
751
752 getModuleLoader().makeModuleVisible(Mod, Visibility: Module::AllVisible, ImportLoc: DirectiveLoc);
753 VisibleModules.setVisible(M: Mod, Loc: DirectiveLoc);
754
755 if (getLangOpts().isCompilingModule()) {
756 Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
757 ModuleName: getLangOpts().CurrentModule, ImportLoc: DirectiveLoc, AllowSearch: false, AllowExtraModuleMapSearch: false);
758 (void)ThisModule;
759 // For named modules, the current module name is not known while parsing the
760 // global module fragment and lookupModule may return null.
761 assert((getLangOpts().getCompilingModule() ==
762 LangOptionsBase::CMK_ModuleInterface ||
763 ThisModule) &&
764 "was expecting a module if building a Clang module");
765 }
766}
767
768void Sema::ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
769 checkModuleImportContext(S&: *this, M: Mod, ImportLoc: DirectiveLoc, DC: CurContext, FromInclude: true);
770
771 ModuleScopes.push_back(Elt: {});
772 ModuleScopes.back().Module = Mod;
773 if (getLangOpts().ModulesLocalVisibility)
774 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
775
776 VisibleModules.setVisible(M: Mod, Loc: DirectiveLoc);
777
778 // The enclosing context is now part of this module.
779 // FIXME: Consider creating a child DeclContext to hold the entities
780 // lexically within the module.
781 if (getLangOpts().trackLocalOwningModule()) {
782 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
783 cast<Decl>(Val: DC)->setModuleOwnershipKind(
784 getLangOpts().ModulesLocalVisibility
785 ? Decl::ModuleOwnershipKind::VisibleWhenImported
786 : Decl::ModuleOwnershipKind::Visible);
787 cast<Decl>(Val: DC)->setLocalOwningModule(Mod);
788 }
789 }
790}
791
792void Sema::ActOnAnnotModuleEnd(SourceLocation EomLoc, Module *Mod) {
793 if (getLangOpts().ModulesLocalVisibility) {
794 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
795 // Leaving a module hides namespace names, so our visible namespace cache
796 // is now out of date.
797 VisibleNamespaceCache.clear();
798 }
799
800 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
801 "left the wrong module scope");
802 ModuleScopes.pop_back();
803
804 // We got to the end of processing a local module. Create an
805 // ImportDecl as we would for an imported module.
806 FileID File = getSourceManager().getFileID(SpellingLoc: EomLoc);
807 SourceLocation DirectiveLoc;
808 if (EomLoc == getSourceManager().getLocForEndOfFile(FID: File)) {
809 // We reached the end of a #included module header. Use the #include loc.
810 assert(File != getSourceManager().getMainFileID() &&
811 "end of submodule in main source file");
812 DirectiveLoc = getSourceManager().getIncludeLoc(FID: File);
813 } else {
814 // We reached an EOM pragma. Use the pragma location.
815 DirectiveLoc = EomLoc;
816 }
817 BuildModuleInclude(DirectiveLoc, Mod);
818
819 // Any further declarations are in whatever module we returned to.
820 if (getLangOpts().trackLocalOwningModule()) {
821 // The parser guarantees that this is the same context that we entered
822 // the module within.
823 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
824 cast<Decl>(Val: DC)->setLocalOwningModule(getCurrentModule());
825 if (!getCurrentModule())
826 cast<Decl>(Val: DC)->setModuleOwnershipKind(
827 Decl::ModuleOwnershipKind::Unowned);
828 }
829 }
830}
831
832void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
833 Module *Mod) {
834 // Bail if we're not allowed to implicitly import a module here.
835 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
836 VisibleModules.isVisible(M: Mod))
837 return;
838
839 // Create the implicit import declaration.
840 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
841 ImportDecl *ImportD = ImportDecl::CreateImplicit(C&: getASTContext(), DC: TU,
842 StartLoc: Loc, Imported: Mod, EndLoc: Loc);
843 TU->addDecl(D: ImportD);
844 Consumer.HandleImplicitImportDecl(D: ImportD);
845
846 // Make the module visible.
847 getModuleLoader().makeModuleVisible(Mod, Visibility: Module::AllVisible, ImportLoc: Loc);
848 VisibleModules.setVisible(M: Mod, Loc);
849}
850
851Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
852 SourceLocation LBraceLoc) {
853 ExportDecl *D = ExportDecl::Create(C&: Context, DC: CurContext, ExportLoc);
854
855 // Set this temporarily so we know the export-declaration was braced.
856 D->setRBraceLoc(LBraceLoc);
857
858 CurContext->addDecl(D);
859 PushDeclContext(S, DC: D);
860
861 // C++2a [module.interface]p1:
862 // An export-declaration shall appear only [...] in the purview of a module
863 // interface unit. An export-declaration shall not appear directly or
864 // indirectly within [...] a private-module-fragment.
865 if (!getLangOpts().HLSL) {
866 if (!isCurrentModulePurview()) {
867 Diag(Loc: ExportLoc, DiagID: diag::err_export_not_in_module_interface) << 0;
868 D->setInvalidDecl();
869 return D;
870 } else if (currentModuleIsImplementation()) {
871 Diag(Loc: ExportLoc, DiagID: diag::err_export_not_in_module_interface) << 1;
872 Diag(Loc: ModuleScopes.back().BeginLoc,
873 DiagID: diag::note_not_module_interface_add_export)
874 << FixItHint::CreateInsertion(InsertionLoc: ModuleScopes.back().BeginLoc, Code: "export ");
875 D->setInvalidDecl();
876 return D;
877 } else if (ModuleScopes.back().Module->Kind ==
878 Module::PrivateModuleFragment) {
879 Diag(Loc: ExportLoc, DiagID: diag::err_export_in_private_module_fragment);
880 Diag(Loc: ModuleScopes.back().BeginLoc, DiagID: diag::note_private_module_fragment);
881 D->setInvalidDecl();
882 return D;
883 }
884 }
885
886 for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
887 if (const auto *ND = dyn_cast<NamespaceDecl>(Val: DC)) {
888 // An export-declaration shall not appear directly or indirectly within
889 // an unnamed namespace [...]
890 if (ND->isAnonymousNamespace()) {
891 Diag(Loc: ExportLoc, DiagID: diag::err_export_within_anonymous_namespace);
892 Diag(Loc: ND->getLocation(), DiagID: diag::note_anonymous_namespace);
893 // Don't diagnose internal-linkage declarations in this region.
894 D->setInvalidDecl();
895 return D;
896 }
897
898 // A declaration is exported if it is [...] a namespace-definition
899 // that contains an exported declaration.
900 //
901 // Defer exporting the namespace until after we leave it, in order to
902 // avoid marking all subsequent declarations in the namespace as exported.
903 if (!getLangOpts().HLSL && !DeferredExportedNamespaces.insert(Ptr: ND).second)
904 break;
905 }
906 }
907
908 // [...] its declaration or declaration-seq shall not contain an
909 // export-declaration.
910 if (auto *ED = getEnclosingExportDecl(D)) {
911 Diag(Loc: ExportLoc, DiagID: diag::err_export_within_export);
912 if (ED->hasBraces())
913 Diag(Loc: ED->getLocation(), DiagID: diag::note_export);
914 D->setInvalidDecl();
915 return D;
916 }
917
918 if (!getLangOpts().HLSL)
919 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
920
921 return D;
922}
923
924static bool checkExportedDecl(Sema &, Decl *, SourceLocation);
925
926/// Check that it's valid to export all the declarations in \p DC.
927static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
928 SourceLocation BlockStart) {
929 bool AllUnnamed = true;
930 for (auto *D : DC->decls())
931 AllUnnamed &= checkExportedDecl(S, D, BlockStart);
932 return AllUnnamed;
933}
934
935/// Check that it's valid to export \p D.
936static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
937
938 // HLSL: export declaration is valid only on functions
939 if (S.getLangOpts().HLSL) {
940 // Export-within-export was already diagnosed in ActOnStartExportDecl
941 if (!isa<FunctionDecl, ExportDecl>(Val: D)) {
942 S.Diag(Loc: D->getBeginLoc(), DiagID: diag::err_hlsl_export_not_on_function);
943 D->setInvalidDecl();
944 return false;
945 }
946
947 if (isa<FunctionDecl>(Val: D)) {
948 FunctionDecl *FD = cast<FunctionDecl>(Val: D);
949 for (const ParmVarDecl *PVD : FD->parameters()) {
950 if (PVD->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
951 S.Diag(Loc: D->getBeginLoc(), DiagID: diag::err_hlsl_attr_incompatible)
952 << "'export'" << "'groupshared' parameter";
953 D->setInvalidDecl();
954 return false;
955 }
956 }
957 }
958 }
959
960 // C++20 [module.interface]p3:
961 // [...] it shall not declare a name with internal linkage.
962 bool HasName = false;
963 if (auto *ND = dyn_cast<NamedDecl>(Val: D)) {
964 // Don't diagnose anonymous union objects; we'll diagnose their members
965 // instead.
966 HasName = (bool)ND->getDeclName();
967 if (HasName && ND->getFormalLinkage() == Linkage::Internal) {
968 S.Diag(Loc: ND->getLocation(), DiagID: diag::err_export_internal) << ND;
969 if (BlockStart.isValid())
970 S.Diag(Loc: BlockStart, DiagID: diag::note_export);
971 return false;
972 }
973 }
974
975 // C++2a [module.interface]p5:
976 // all entities to which all of the using-declarators ultimately refer
977 // shall have been introduced with a name having external linkage
978 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: D)) {
979 NamedDecl *Target = USD->getUnderlyingDecl();
980 Linkage Lk = Target->getFormalLinkage();
981 if (Lk == Linkage::Internal || Lk == Linkage::Module) {
982 S.Diag(Loc: USD->getLocation(), DiagID: diag::err_export_using_internal)
983 << (Lk == Linkage::Internal ? 0 : 1) << Target;
984 S.Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
985 if (BlockStart.isValid())
986 S.Diag(Loc: BlockStart, DiagID: diag::note_export);
987 return false;
988 }
989 }
990
991 // Recurse into namespace-scope DeclContexts. (Only namespace-scope
992 // declarations are exported).
993 if (auto *DC = dyn_cast<DeclContext>(Val: D)) {
994 if (!isa<NamespaceDecl>(Val: D))
995 return true;
996
997 if (auto *ND = dyn_cast<NamedDecl>(Val: D)) {
998 if (!ND->getDeclName()) {
999 S.Diag(Loc: ND->getLocation(), DiagID: diag::err_export_anon_ns_internal);
1000 if (BlockStart.isValid())
1001 S.Diag(Loc: BlockStart, DiagID: diag::note_export);
1002 return false;
1003 } else if (!DC->decls().empty() &&
1004 DC->getRedeclContext()->isFileContext()) {
1005 return checkExportedDeclContext(S, DC, BlockStart);
1006 }
1007 }
1008 }
1009 return true;
1010}
1011
1012Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
1013 auto *ED = cast<ExportDecl>(Val: D);
1014 if (RBraceLoc.isValid())
1015 ED->setRBraceLoc(RBraceLoc);
1016
1017 PopDeclContext();
1018
1019 if (!D->isInvalidDecl()) {
1020 SourceLocation BlockStart =
1021 ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
1022 for (auto *Child : ED->decls()) {
1023 checkExportedDecl(S&: *this, D: Child, BlockStart);
1024 if (auto *FD = dyn_cast<FunctionDecl>(Val: Child)) {
1025 // [dcl.inline]/7
1026 // If an inline function or variable that is attached to a named module
1027 // is declared in a definition domain, it shall be defined in that
1028 // domain.
1029 // So, if the current declaration does not have a definition, we must
1030 // check at the end of the TU (or when the PMF starts) to see that we
1031 // have a definition at that point.
1032 if (FD->isInlineSpecified() && !FD->isDefined())
1033 PendingInlineFuncDecls.insert(Ptr: FD);
1034 }
1035 }
1036 }
1037
1038 // Anything exported from a module should never be considered unused.
1039 for (auto *Exported : ED->decls())
1040 Exported->markUsed(C&: getASTContext());
1041
1042 return D;
1043}
1044
1045Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc) {
1046 // We shouldn't create new global module fragment if there is already
1047 // one.
1048 if (!TheGlobalModuleFragment) {
1049 ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
1050 TheGlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
1051 Loc: BeginLoc, Parent: getCurrentModule());
1052 }
1053
1054 assert(TheGlobalModuleFragment && "module creation should not fail");
1055
1056 // Enter the scope of the global module.
1057 ModuleScopes.push_back(Elt: {.BeginLoc: BeginLoc, .Module: TheGlobalModuleFragment,
1058 /*OuterVisibleModules=*/{}});
1059 VisibleModules.setVisible(M: TheGlobalModuleFragment, Loc: BeginLoc);
1060
1061 return TheGlobalModuleFragment;
1062}
1063
1064void Sema::PopGlobalModuleFragment() {
1065 assert(!ModuleScopes.empty() &&
1066 getCurrentModule()->isExplicitGlobalModule() &&
1067 "left the wrong module scope, which is not global module fragment");
1068 ModuleScopes.pop_back();
1069}
1070
1071Module *Sema::PushImplicitGlobalModuleFragment(SourceLocation BeginLoc) {
1072 if (!TheImplicitGlobalModuleFragment) {
1073 ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
1074 TheImplicitGlobalModuleFragment =
1075 Map.createImplicitGlobalModuleFragmentForModuleUnit(Loc: BeginLoc,
1076 Parent: getCurrentModule());
1077 }
1078 assert(TheImplicitGlobalModuleFragment && "module creation should not fail");
1079
1080 // Enter the scope of the global module.
1081 ModuleScopes.push_back(Elt: {.BeginLoc: BeginLoc, .Module: TheImplicitGlobalModuleFragment,
1082 /*OuterVisibleModules=*/{}});
1083 VisibleModules.setVisible(M: TheImplicitGlobalModuleFragment, Loc: BeginLoc);
1084 return TheImplicitGlobalModuleFragment;
1085}
1086
1087void Sema::PopImplicitGlobalModuleFragment() {
1088 assert(!ModuleScopes.empty() &&
1089 getCurrentModule()->isImplicitGlobalModule() &&
1090 "left the wrong module scope, which is not global module fragment");
1091 ModuleScopes.pop_back();
1092}
1093
1094bool Sema::isCurrentModulePurview() const {
1095 if (!getCurrentModule())
1096 return false;
1097
1098 /// Does this Module scope describe part of the purview of a standard named
1099 /// C++ module?
1100 switch (getCurrentModule()->Kind) {
1101 case Module::ModuleInterfaceUnit:
1102 case Module::ModuleImplementationUnit:
1103 case Module::ModulePartitionInterface:
1104 case Module::ModulePartitionImplementation:
1105 case Module::PrivateModuleFragment:
1106 case Module::ImplicitGlobalModuleFragment:
1107 return true;
1108 default:
1109 return false;
1110 }
1111}
1112
1113//===----------------------------------------------------------------------===//
1114// Checking Exposure in modules //
1115//===----------------------------------------------------------------------===//
1116
1117namespace {
1118class ExposureChecker {
1119public:
1120 ExposureChecker(Sema &S) : SemaRef(S) {}
1121
1122 bool checkExposure(const VarDecl *D, bool Diag);
1123 bool checkExposure(const CXXRecordDecl *D, bool Diag);
1124 bool checkExposure(const Stmt *S, bool Diag);
1125 bool checkExposure(const FunctionDecl *D, bool Diag);
1126 bool checkExposure(const NamedDecl *D, bool Diag);
1127 void checkExposureInContext(const DeclContext *DC);
1128 bool isExposureCandidate(const NamedDecl *D);
1129
1130 bool isTULocal(QualType Ty);
1131 bool isTULocal(const NamedDecl *ND);
1132 bool isTULocal(const Expr *E);
1133
1134 Sema &SemaRef;
1135
1136private:
1137 llvm::DenseSet<const NamedDecl *> ExposureSet;
1138 llvm::DenseSet<const NamedDecl *> KnownNonExposureSet;
1139 llvm::DenseSet<const NamedDecl *> CheckingDecls;
1140};
1141
1142bool ExposureChecker::isTULocal(QualType Ty) {
1143 // [basic.link]p15:
1144 // An entity is TU-local if it is
1145 // - a type, type alias, namespace, namespace alias, function, variable, or
1146 // template that
1147 // -- has internal linkage, or
1148 return Ty->getLinkage() == Linkage::Internal;
1149
1150 // TODO:
1151 // [basic.link]p15.2:
1152 // a type with no name that is defined outside a class-specifier, function
1153 // body, or initializer or is introduced by a defining-type-specifier that
1154 // is used to declare only TU-local entities,
1155}
1156
1157bool ExposureChecker::isTULocal(const NamedDecl *D) {
1158 if (!D)
1159 return false;
1160
1161 // [basic.link]p15:
1162 // An entity is TU-local if it is
1163 // - a type, type alias, namespace, namespace alias, function, variable, or
1164 // template that
1165 // -- has internal linkage, or
1166 if (D->getLinkageInternal() == Linkage::Internal)
1167 return true;
1168
1169 if (D->isInAnonymousNamespace())
1170 return true;
1171
1172 // [basic.link]p15.1.2:
1173 // does not have a name with linkage and is declared, or introduced by a
1174 // lambda-expression, within the definition of a TU-local entity,
1175 if (D->getLinkageInternal() == Linkage::None)
1176 if (auto *ND = dyn_cast<NamedDecl>(Val: D->getDeclContext());
1177 ND && isTULocal(D: ND))
1178 return true;
1179
1180 // [basic.link]p15.3, p15.4:
1181 // - a specialization of a TU-local template,
1182 // - a specialization of a template with any TU-local template argument, or
1183 ArrayRef<TemplateArgument> TemplateArgs;
1184 NamedDecl *PrimaryTemplate = nullptr;
1185 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: D)) {
1186 TemplateArgs = CTSD->getTemplateArgs().asArray();
1187 PrimaryTemplate = CTSD->getSpecializedTemplate();
1188 if (isTULocal(D: PrimaryTemplate))
1189 return true;
1190 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: D)) {
1191 TemplateArgs = VTSD->getTemplateArgs().asArray();
1192 PrimaryTemplate = VTSD->getSpecializedTemplate();
1193 if (isTULocal(D: PrimaryTemplate))
1194 return true;
1195 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
1196 if (auto *TAList = FD->getTemplateSpecializationArgs())
1197 TemplateArgs = TAList->asArray();
1198
1199 PrimaryTemplate = FD->getPrimaryTemplate();
1200 if (isTULocal(D: PrimaryTemplate))
1201 return true;
1202 }
1203
1204 if (!PrimaryTemplate)
1205 // Following off, we only check for specializations.
1206 return false;
1207
1208 if (KnownNonExposureSet.count(V: D))
1209 return false;
1210
1211 for (auto &TA : TemplateArgs) {
1212 switch (TA.getKind()) {
1213 case TemplateArgument::Type:
1214 if (isTULocal(Ty: TA.getAsType()))
1215 return true;
1216 break;
1217 case TemplateArgument::Declaration:
1218 if (isTULocal(D: TA.getAsDecl()))
1219 return true;
1220 break;
1221 default:
1222 break;
1223 }
1224 }
1225
1226 // Avoid recursions.
1227 if (CheckingDecls.count(V: D))
1228 return false;
1229 CheckingDecls.insert(V: D);
1230 llvm::scope_exit RemoveCheckingDecls([&] { CheckingDecls.erase(V: D); });
1231
1232 // [basic.link]p15.5
1233 // - a specialization of a template whose (possibly instantiated) declaration
1234 // is an exposure.
1235 if (ExposureSet.count(V: PrimaryTemplate) ||
1236 checkExposure(D: PrimaryTemplate, /*Diag=*/false))
1237 return true;
1238
1239 // Avoid calling checkExposure again since it is expensive.
1240 KnownNonExposureSet.insert(V: D);
1241 return false;
1242}
1243
1244bool ExposureChecker::isTULocal(const Expr *E) {
1245 if (!E)
1246 return false;
1247
1248 // [basic.link]p16:
1249 // A value or object is TU-local if either
1250 // - it is of TU-local type,
1251 if (isTULocal(Ty: E->getType()))
1252 return true;
1253
1254 E = E->IgnoreParenImpCasts();
1255 // [basic.link]p16.2:
1256 // - it is, or is a pointer to, a TU-local function or the object associated
1257 // with a TU-local variable,
1258 // - it is an object of class or array type and any of its subobjects or any
1259 // of the objects or functions to which its non-static data members of
1260 // reference type refer is TU-local and is usable in constant expressions, or
1261 // FIXME: But how can we know the value of pointers or arrays at compile time?
1262 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
1263 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: DRE->getFoundDecl()))
1264 return isTULocal(D: FD);
1265 else if (auto *VD = dyn_cast_or_null<VarDecl>(Val: DRE->getFoundDecl()))
1266 return isTULocal(D: VD);
1267 else if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Val: DRE->getFoundDecl()))
1268 return isTULocal(D: RD);
1269 }
1270
1271 // TODO:
1272 // [basic.link]p16.4:
1273 // it is a reflection value that represents...
1274
1275 return false;
1276}
1277
1278bool ExposureChecker::isExposureCandidate(const NamedDecl *D) {
1279 if (!D)
1280 return false;
1281
1282 // [basic.link]p17:
1283 // If a (possibly instantiated) declaration of, or a deduction guide for,
1284 // a non-TU-local entity in a module interface unit
1285 // (outside the private-module-fragment, if any) or
1286 // module partition is an exposure, the program is ill-formed.
1287 Module *M = D->getOwningModule();
1288 if (!M)
1289 return false;
1290 // If M is implicit global module, the declaration must be in the purview of
1291 // a module unit.
1292 if (M->isImplicitGlobalModule()) {
1293 M = M->Parent;
1294 assert(M && "Implicit global module must have a parent");
1295 }
1296
1297 if (!M->isInterfaceOrPartition())
1298 return false;
1299
1300 if (D->isImplicit())
1301 return false;
1302
1303 // [basic.link]p14:
1304 // A declaration is an exposure if it either names a TU-local entity
1305 // (defined below), ignoring:
1306 // ...
1307 // - friend declarations in a class definition
1308 if (D->getFriendObjectKind() &&
1309 isa<CXXRecordDecl>(Val: D->getLexicalDeclContext()))
1310 return false;
1311
1312 return true;
1313}
1314
1315bool ExposureChecker::checkExposure(const NamedDecl *D, bool Diag) {
1316 if (!isExposureCandidate(D))
1317 return false;
1318
1319 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1320 return checkExposure(D: FD, Diag);
1321 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
1322 return checkExposure(D: FTD->getTemplatedDecl(), Diag);
1323
1324 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1325 return checkExposure(D: VD, Diag);
1326 if (auto *VTD = dyn_cast<VarTemplateDecl>(Val: D))
1327 return checkExposure(D: VTD->getTemplatedDecl(), Diag);
1328
1329 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1330 return checkExposure(D: RD, Diag);
1331
1332 if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: D))
1333 return checkExposure(D: CTD->getTemplatedDecl(), Diag);
1334
1335 return false;
1336}
1337
1338bool ExposureChecker::checkExposure(const FunctionDecl *FD, bool Diag) {
1339 bool IsExposure = false;
1340 if (isTULocal(Ty: FD->getReturnType())) {
1341 IsExposure = true;
1342 if (Diag)
1343 SemaRef.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(),
1344 DiagID: diag::warn_exposure)
1345 << FD->getReturnType();
1346 }
1347
1348 for (ParmVarDecl *Parms : FD->parameters())
1349 if (isTULocal(Ty: Parms->getType())) {
1350 IsExposure = true;
1351 if (Diag)
1352 SemaRef.Diag(Loc: Parms->getLocation(), DiagID: diag::warn_exposure)
1353 << Parms->getType();
1354 }
1355
1356 bool IsImplicitInstantiation =
1357 FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1358
1359 // [basic.link]p14:
1360 // A declaration is an exposure if it either names a TU-local entity
1361 // (defined below), ignoring:
1362 // - the function-body for a non-inline function or function template
1363 // (but not the deduced return
1364 // type for a (possibly instantiated) definition of a function with a
1365 // declared return type that uses a placeholder type
1366 // ([dcl.spec.auto])),
1367 Diag &=
1368 (FD->isInlined() || IsImplicitInstantiation) && !FD->isDependentContext();
1369
1370 IsExposure |= checkExposure(S: FD->getBody(), Diag);
1371 if (IsExposure)
1372 ExposureSet.insert(V: FD);
1373
1374 return IsExposure;
1375}
1376
1377bool ExposureChecker::checkExposure(const VarDecl *VD, bool Diag) {
1378 bool IsExposure = false;
1379 // [basic.link]p14:
1380 // A declaration is an exposure if it either names a TU-local entity (defined
1381 // below), ignoring:
1382 // ...
1383 // or defines a constexpr variable initialized to a TU-local value (defined
1384 // below).
1385 if (VD->isConstexpr() && isTULocal(E: VD->getInit())) {
1386 IsExposure = true;
1387 if (Diag)
1388 SemaRef.Diag(Loc: VD->getInit()->getExprLoc(), DiagID: diag::warn_exposure)
1389 << VD->getInit();
1390 }
1391
1392 if (isTULocal(Ty: VD->getType())) {
1393 IsExposure = true;
1394 if (Diag)
1395 SemaRef.Diag(Loc: VD->getLocation(), DiagID: diag::warn_exposure) << VD->getType();
1396 }
1397
1398 // [basic.link]p14:
1399 // ..., ignoring:
1400 // - the initializer for a variable or variable template (but not the
1401 // variable's type),
1402 //
1403 // Note: although the spec says to ignore the initializer for all variable,
1404 // for the code we generated now for inline variables, it is dangerous if the
1405 // initializer of an inline variable is TULocal.
1406 Diag &= !VD->getDeclContext()->isDependentContext() && VD->isInline();
1407 IsExposure |= checkExposure(S: VD->getInit(), Diag);
1408 if (IsExposure)
1409 ExposureSet.insert(V: VD);
1410
1411 return IsExposure;
1412}
1413
1414bool ExposureChecker::checkExposure(const CXXRecordDecl *RD, bool Diag) {
1415 if (!RD->hasDefinition())
1416 return false;
1417
1418 bool IsExposure = false;
1419 for (CXXMethodDecl *Method : RD->methods())
1420 IsExposure |= checkExposure(FD: Method, Diag);
1421
1422 for (FieldDecl *FD : RD->fields()) {
1423 if (isTULocal(Ty: FD->getType())) {
1424 IsExposure = true;
1425 if (Diag)
1426 SemaRef.Diag(Loc: FD->getLocation(), DiagID: diag::warn_exposure) << FD->getType();
1427 }
1428 }
1429
1430 for (const CXXBaseSpecifier &Base : RD->bases()) {
1431 if (isTULocal(Ty: Base.getType())) {
1432 IsExposure = true;
1433 if (Diag)
1434 SemaRef.Diag(Loc: Base.getBaseTypeLoc(), DiagID: diag::warn_exposure)
1435 << Base.getType();
1436 }
1437 }
1438
1439 if (IsExposure)
1440 ExposureSet.insert(V: RD);
1441
1442 return IsExposure;
1443}
1444
1445class ReferenceTULocalChecker : public DynamicRecursiveASTVisitor {
1446public:
1447 using CallbackTy = std::function<void(DeclRefExpr *, ValueDecl *)>;
1448
1449 ReferenceTULocalChecker(ExposureChecker &C, CallbackTy &&Callback)
1450 : Checker(C), Callback(std::move(Callback)) {}
1451
1452 bool VisitDeclRefExpr(DeclRefExpr *DRE) override {
1453 ValueDecl *Referenced = DRE->getDecl();
1454 if (!Referenced)
1455 return true;
1456
1457 if (!Checker.isTULocal(D: Referenced))
1458 // We don't care if the referenced declaration is not TU-local.
1459 return true;
1460
1461 Qualifiers Qual = DRE->getType().getQualifiers();
1462 // [basic.link]p14:
1463 // A declaration is an exposure if it either names a TU-local entity
1464 // (defined below), ignoring:
1465 // ...
1466 // - any reference to a non-volatile const object ...
1467 if (Qual.hasConst() && !Qual.hasVolatile())
1468 return true;
1469
1470 // [basic.link]p14:
1471 // ..., ignoring:
1472 // ...
1473 // (p14.4) - ... or reference with internal or no linkage initialized with
1474 // a constant expression that is not an odr-use
1475 ASTContext &Context = Referenced->getASTContext();
1476 Linkage L = Referenced->getLinkageInternal();
1477 if (DRE->isNonOdrUse() && (L == Linkage::Internal || L == Linkage::None))
1478 if (auto *VD = dyn_cast<VarDecl>(Val: Referenced);
1479 VD && VD->getInit() && !VD->getInit()->isValueDependent() &&
1480 VD->getInit()->isConstantInitializer(Ctx&: Context, /*IsForRef=*/ForRef: false))
1481 return true;
1482
1483 Callback(DRE, Referenced);
1484 return true;
1485 }
1486
1487 ExposureChecker &Checker;
1488 CallbackTy Callback;
1489};
1490
1491bool ExposureChecker::checkExposure(const Stmt *S, bool Diag) {
1492 if (!S)
1493 return false;
1494
1495 bool HasReferencedTULocals = false;
1496 ReferenceTULocalChecker Checker(
1497 *this, [this, &HasReferencedTULocals, Diag](DeclRefExpr *DRE,
1498 ValueDecl *Referenced) {
1499 if (Diag) {
1500 SemaRef.Diag(Loc: DRE->getExprLoc(), DiagID: diag::warn_exposure) << Referenced;
1501 }
1502 HasReferencedTULocals = true;
1503 });
1504 Checker.TraverseStmt(S: const_cast<Stmt *>(S));
1505 return HasReferencedTULocals;
1506}
1507
1508void ExposureChecker::checkExposureInContext(const DeclContext *DC) {
1509 for (auto *TopD : DC->noload_decls()) {
1510 if (auto *Export = dyn_cast<ExportDecl>(Val: TopD)) {
1511 checkExposureInContext(DC: Export);
1512 continue;
1513 }
1514
1515 if (auto *LinkageSpec = dyn_cast<LinkageSpecDecl>(Val: TopD)) {
1516 checkExposureInContext(DC: LinkageSpec);
1517 continue;
1518 }
1519
1520 auto *TopND = dyn_cast<NamedDecl>(Val: TopD);
1521 if (!TopND)
1522 continue;
1523
1524 if (auto *Namespace = dyn_cast<NamespaceDecl>(Val: TopND)) {
1525 checkExposureInContext(DC: Namespace);
1526 continue;
1527 }
1528
1529 // [basic.link]p17:
1530 // If a (possibly instantiated) declaration of, or a deduction guide for,
1531 // a non-TU-local entity in a module interface unit
1532 // (outside the private-module-fragment, if any) or
1533 // module partition is an exposure, the program is ill-formed.
1534 if (!TopND->isFromASTFile() && isExposureCandidate(D: TopND) &&
1535 !isTULocal(D: TopND))
1536 checkExposure(D: TopND, /*Diag=*/true);
1537 }
1538}
1539
1540} // namespace
1541
1542void Sema::checkExposure(const TranslationUnitDecl *TU) {
1543 if (!TU)
1544 return;
1545
1546 ExposureChecker Checker(*this);
1547
1548 Module *M = TU->getOwningModule();
1549 if (M && M->isInterfaceOrPartition())
1550 Checker.checkExposureInContext(DC: TU);
1551
1552 // [basic.link]p18:
1553 // If a declaration that appears in one translation unit names a TU-local
1554 // entity declared in another translation unit that is not a header unit,
1555 // the program is ill-formed.
1556 for (auto FDAndInstantiationLocPair : PendingCheckReferenceForTULocal) {
1557 FunctionDecl *FD = FDAndInstantiationLocPair.first;
1558 SourceLocation PointOfInstantiation = FDAndInstantiationLocPair.second;
1559
1560 if (!FD->hasBody())
1561 continue;
1562
1563 ReferenceTULocalChecker(Checker, [&, this](DeclRefExpr *DRE,
1564 ValueDecl *Referenced) {
1565 // A "defect" in current implementation. Now an implicit instantiation of
1566 // a template, the instantiation is considered to be in the same module
1567 // unit as the template instead of the module unit where the instantiation
1568 // happens.
1569 //
1570 // See test/Modules/Exposre-2.cppm for example.
1571 if (!Referenced->isFromASTFile())
1572 return;
1573
1574 if (!Referenced->isInAnotherModuleUnit())
1575 return;
1576
1577 // This is not standard conforming. But given there are too many static
1578 // (inline) functions in headers in existing code, it is more user
1579 // friendly to ignore them temporarily now. maybe we can have another flag
1580 // for this.
1581 if (Referenced->getOwningModule()->isExplicitGlobalModule() &&
1582 isa<FunctionDecl>(Val: Referenced))
1583 return;
1584
1585 Diag(Loc: PointOfInstantiation,
1586 DiagID: diag::warn_reference_tu_local_entity_in_other_tu)
1587 << FD << Referenced
1588 << Referenced->getOwningModule()->getTopLevelModuleName();
1589 }).TraverseStmt(S: FD->getBody());
1590 }
1591}
1592
1593void Sema::checkReferenceToTULocalFromOtherTU(
1594 FunctionDecl *FD, SourceLocation PointOfInstantiation) {
1595 // Checking if a declaration have any reference to TU-local entities in other
1596 // TU is expensive. Try to avoid it as much as possible.
1597 if (!FD || !HadImportedNamedModules)
1598 return;
1599
1600 PendingCheckReferenceForTULocal.push_back(
1601 Elt: std::make_pair(x&: FD, y&: PointOfInstantiation));
1602}
1603