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
948 // C++20 [module.interface]p3:
949 // [...] it shall not declare a name with internal linkage.
950 bool HasName = false;
951 if (auto *ND = dyn_cast<NamedDecl>(Val: D)) {
952 // Don't diagnose anonymous union objects; we'll diagnose their members
953 // instead.
954 HasName = (bool)ND->getDeclName();
955 if (HasName && ND->getFormalLinkage() == Linkage::Internal) {
956 S.Diag(Loc: ND->getLocation(), DiagID: diag::err_export_internal) << ND;
957 if (BlockStart.isValid())
958 S.Diag(Loc: BlockStart, DiagID: diag::note_export);
959 return false;
960 }
961 }
962
963 // C++2a [module.interface]p5:
964 // all entities to which all of the using-declarators ultimately refer
965 // shall have been introduced with a name having external linkage
966 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: D)) {
967 NamedDecl *Target = USD->getUnderlyingDecl();
968 Linkage Lk = Target->getFormalLinkage();
969 if (Lk == Linkage::Internal || Lk == Linkage::Module) {
970 S.Diag(Loc: USD->getLocation(), DiagID: diag::err_export_using_internal)
971 << (Lk == Linkage::Internal ? 0 : 1) << Target;
972 S.Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
973 if (BlockStart.isValid())
974 S.Diag(Loc: BlockStart, DiagID: diag::note_export);
975 return false;
976 }
977 }
978
979 // Recurse into namespace-scope DeclContexts. (Only namespace-scope
980 // declarations are exported).
981 if (auto *DC = dyn_cast<DeclContext>(Val: D)) {
982 if (!isa<NamespaceDecl>(Val: D))
983 return true;
984
985 if (auto *ND = dyn_cast<NamedDecl>(Val: D)) {
986 if (!ND->getDeclName()) {
987 S.Diag(Loc: ND->getLocation(), DiagID: diag::err_export_anon_ns_internal);
988 if (BlockStart.isValid())
989 S.Diag(Loc: BlockStart, DiagID: diag::note_export);
990 return false;
991 } else if (!DC->decls().empty() &&
992 DC->getRedeclContext()->isFileContext()) {
993 return checkExportedDeclContext(S, DC, BlockStart);
994 }
995 }
996 }
997 return true;
998}
999
1000Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
1001 auto *ED = cast<ExportDecl>(Val: D);
1002 if (RBraceLoc.isValid())
1003 ED->setRBraceLoc(RBraceLoc);
1004
1005 PopDeclContext();
1006
1007 if (!D->isInvalidDecl()) {
1008 SourceLocation BlockStart =
1009 ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
1010 for (auto *Child : ED->decls()) {
1011 checkExportedDecl(S&: *this, D: Child, BlockStart);
1012 if (auto *FD = dyn_cast<FunctionDecl>(Val: Child)) {
1013 // [dcl.inline]/7
1014 // If an inline function or variable that is attached to a named module
1015 // is declared in a definition domain, it shall be defined in that
1016 // domain.
1017 // So, if the current declaration does not have a definition, we must
1018 // check at the end of the TU (or when the PMF starts) to see that we
1019 // have a definition at that point.
1020 if (FD->isInlineSpecified() && !FD->isDefined())
1021 PendingInlineFuncDecls.insert(Ptr: FD);
1022 }
1023 }
1024 }
1025
1026 // Anything exported from a module should never be considered unused.
1027 for (auto *Exported : ED->decls())
1028 Exported->markUsed(C&: getASTContext());
1029
1030 return D;
1031}
1032
1033Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc) {
1034 // We shouldn't create new global module fragment if there is already
1035 // one.
1036 if (!TheGlobalModuleFragment) {
1037 ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
1038 TheGlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
1039 Loc: BeginLoc, Parent: getCurrentModule());
1040 }
1041
1042 assert(TheGlobalModuleFragment && "module creation should not fail");
1043
1044 // Enter the scope of the global module.
1045 ModuleScopes.push_back(Elt: {.BeginLoc: BeginLoc, .Module: TheGlobalModuleFragment,
1046 /*OuterVisibleModules=*/{}});
1047 VisibleModules.setVisible(M: TheGlobalModuleFragment, Loc: BeginLoc);
1048
1049 return TheGlobalModuleFragment;
1050}
1051
1052void Sema::PopGlobalModuleFragment() {
1053 assert(!ModuleScopes.empty() &&
1054 getCurrentModule()->isExplicitGlobalModule() &&
1055 "left the wrong module scope, which is not global module fragment");
1056 ModuleScopes.pop_back();
1057}
1058
1059Module *Sema::PushImplicitGlobalModuleFragment(SourceLocation BeginLoc) {
1060 if (!TheImplicitGlobalModuleFragment) {
1061 ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
1062 TheImplicitGlobalModuleFragment =
1063 Map.createImplicitGlobalModuleFragmentForModuleUnit(Loc: BeginLoc,
1064 Parent: getCurrentModule());
1065 }
1066 assert(TheImplicitGlobalModuleFragment && "module creation should not fail");
1067
1068 // Enter the scope of the global module.
1069 ModuleScopes.push_back(Elt: {.BeginLoc: BeginLoc, .Module: TheImplicitGlobalModuleFragment,
1070 /*OuterVisibleModules=*/{}});
1071 VisibleModules.setVisible(M: TheImplicitGlobalModuleFragment, Loc: BeginLoc);
1072 return TheImplicitGlobalModuleFragment;
1073}
1074
1075void Sema::PopImplicitGlobalModuleFragment() {
1076 assert(!ModuleScopes.empty() &&
1077 getCurrentModule()->isImplicitGlobalModule() &&
1078 "left the wrong module scope, which is not global module fragment");
1079 ModuleScopes.pop_back();
1080}
1081
1082bool Sema::isCurrentModulePurview() const {
1083 if (!getCurrentModule())
1084 return false;
1085
1086 /// Does this Module scope describe part of the purview of a standard named
1087 /// C++ module?
1088 switch (getCurrentModule()->Kind) {
1089 case Module::ModuleInterfaceUnit:
1090 case Module::ModuleImplementationUnit:
1091 case Module::ModulePartitionInterface:
1092 case Module::ModulePartitionImplementation:
1093 case Module::PrivateModuleFragment:
1094 case Module::ImplicitGlobalModuleFragment:
1095 return true;
1096 default:
1097 return false;
1098 }
1099}
1100
1101//===----------------------------------------------------------------------===//
1102// Checking Exposure in modules //
1103//===----------------------------------------------------------------------===//
1104
1105namespace {
1106class ExposureChecker {
1107public:
1108 ExposureChecker(Sema &S) : SemaRef(S) {}
1109
1110 bool checkExposure(const VarDecl *D, bool Diag);
1111 bool checkExposure(const CXXRecordDecl *D, bool Diag);
1112 bool checkExposure(const Stmt *S, bool Diag);
1113 bool checkExposure(const FunctionDecl *D, bool Diag);
1114 bool checkExposure(const NamedDecl *D, bool Diag);
1115 void checkExposureInContext(const DeclContext *DC);
1116 bool isExposureCandidate(const NamedDecl *D);
1117
1118 bool isTULocal(QualType Ty);
1119 bool isTULocal(const NamedDecl *ND);
1120 bool isTULocal(const Expr *E);
1121
1122 Sema &SemaRef;
1123
1124private:
1125 llvm::DenseSet<const NamedDecl *> ExposureSet;
1126 llvm::DenseSet<const NamedDecl *> KnownNonExposureSet;
1127 llvm::DenseSet<const NamedDecl *> CheckingDecls;
1128};
1129
1130bool ExposureChecker::isTULocal(QualType Ty) {
1131 // [basic.link]p15:
1132 // An entity is TU-local if it is
1133 // - a type, type alias, namespace, namespace alias, function, variable, or
1134 // template that
1135 // -- has internal linkage, or
1136 return Ty->getLinkage() == Linkage::Internal;
1137
1138 // TODO:
1139 // [basic.link]p15.2:
1140 // a type with no name that is defined outside a class-specifier, function
1141 // body, or initializer or is introduced by a defining-type-specifier that
1142 // is used to declare only TU-local entities,
1143}
1144
1145bool ExposureChecker::isTULocal(const NamedDecl *D) {
1146 if (!D)
1147 return false;
1148
1149 // [basic.link]p15:
1150 // An entity is TU-local if it is
1151 // - a type, type alias, namespace, namespace alias, function, variable, or
1152 // template that
1153 // -- has internal linkage, or
1154 if (D->getLinkageInternal() == Linkage::Internal)
1155 return true;
1156
1157 if (D->isInAnonymousNamespace())
1158 return true;
1159
1160 // [basic.link]p15.1.2:
1161 // does not have a name with linkage and is declared, or introduced by a
1162 // lambda-expression, within the definition of a TU-local entity,
1163 if (D->getLinkageInternal() == Linkage::None)
1164 if (auto *ND = dyn_cast<NamedDecl>(Val: D->getDeclContext());
1165 ND && isTULocal(D: ND))
1166 return true;
1167
1168 // [basic.link]p15.3, p15.4:
1169 // - a specialization of a TU-local template,
1170 // - a specialization of a template with any TU-local template argument, or
1171 ArrayRef<TemplateArgument> TemplateArgs;
1172 NamedDecl *PrimaryTemplate = nullptr;
1173 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: D)) {
1174 TemplateArgs = CTSD->getTemplateArgs().asArray();
1175 PrimaryTemplate = CTSD->getSpecializedTemplate();
1176 if (isTULocal(D: PrimaryTemplate))
1177 return true;
1178 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: D)) {
1179 TemplateArgs = VTSD->getTemplateArgs().asArray();
1180 PrimaryTemplate = VTSD->getSpecializedTemplate();
1181 if (isTULocal(D: PrimaryTemplate))
1182 return true;
1183 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
1184 if (auto *TAList = FD->getTemplateSpecializationArgs())
1185 TemplateArgs = TAList->asArray();
1186
1187 PrimaryTemplate = FD->getPrimaryTemplate();
1188 if (isTULocal(D: PrimaryTemplate))
1189 return true;
1190 }
1191
1192 if (!PrimaryTemplate)
1193 // Following off, we only check for specializations.
1194 return false;
1195
1196 if (KnownNonExposureSet.count(V: D))
1197 return false;
1198
1199 for (auto &TA : TemplateArgs) {
1200 switch (TA.getKind()) {
1201 case TemplateArgument::Type:
1202 if (isTULocal(Ty: TA.getAsType()))
1203 return true;
1204 break;
1205 case TemplateArgument::Declaration:
1206 if (isTULocal(D: TA.getAsDecl()))
1207 return true;
1208 break;
1209 default:
1210 break;
1211 }
1212 }
1213
1214 // Avoid recursions.
1215 if (CheckingDecls.count(V: D))
1216 return false;
1217 CheckingDecls.insert(V: D);
1218 llvm::scope_exit RemoveCheckingDecls([&] { CheckingDecls.erase(V: D); });
1219
1220 // [basic.link]p15.5
1221 // - a specialization of a template whose (possibly instantiated) declaration
1222 // is an exposure.
1223 if (ExposureSet.count(V: PrimaryTemplate) ||
1224 checkExposure(D: PrimaryTemplate, /*Diag=*/false))
1225 return true;
1226
1227 // Avoid calling checkExposure again since it is expensive.
1228 KnownNonExposureSet.insert(V: D);
1229 return false;
1230}
1231
1232bool ExposureChecker::isTULocal(const Expr *E) {
1233 if (!E)
1234 return false;
1235
1236 // [basic.link]p16:
1237 // A value or object is TU-local if either
1238 // - it is of TU-local type,
1239 if (isTULocal(Ty: E->getType()))
1240 return true;
1241
1242 E = E->IgnoreParenImpCasts();
1243 // [basic.link]p16.2:
1244 // - it is, or is a pointer to, a TU-local function or the object associated
1245 // with a TU-local variable,
1246 // - it is an object of class or array type and any of its subobjects or any
1247 // of the objects or functions to which its non-static data members of
1248 // reference type refer is TU-local and is usable in constant expressions, or
1249 // FIXME: But how can we know the value of pointers or arrays at compile time?
1250 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
1251 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: DRE->getFoundDecl()))
1252 return isTULocal(D: FD);
1253 else if (auto *VD = dyn_cast_or_null<VarDecl>(Val: DRE->getFoundDecl()))
1254 return isTULocal(D: VD);
1255 else if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Val: DRE->getFoundDecl()))
1256 return isTULocal(D: RD);
1257 }
1258
1259 // TODO:
1260 // [basic.link]p16.4:
1261 // it is a reflection value that represents...
1262
1263 return false;
1264}
1265
1266bool ExposureChecker::isExposureCandidate(const NamedDecl *D) {
1267 if (!D)
1268 return false;
1269
1270 // [basic.link]p17:
1271 // If a (possibly instantiated) declaration of, or a deduction guide for,
1272 // a non-TU-local entity in a module interface unit
1273 // (outside the private-module-fragment, if any) or
1274 // module partition is an exposure, the program is ill-formed.
1275 Module *M = D->getOwningModule();
1276 if (!M)
1277 return false;
1278 // If M is implicit global module, the declaration must be in the purview of
1279 // a module unit.
1280 if (M->isImplicitGlobalModule()) {
1281 M = M->Parent;
1282 assert(M && "Implicit global module must have a parent");
1283 }
1284
1285 if (!M->isInterfaceOrPartition())
1286 return false;
1287
1288 if (D->isImplicit())
1289 return false;
1290
1291 // [basic.link]p14:
1292 // A declaration is an exposure if it either names a TU-local entity
1293 // (defined below), ignoring:
1294 // ...
1295 // - friend declarations in a class definition
1296 if (D->getFriendObjectKind() &&
1297 isa<CXXRecordDecl>(Val: D->getLexicalDeclContext()))
1298 return false;
1299
1300 return true;
1301}
1302
1303bool ExposureChecker::checkExposure(const NamedDecl *D, bool Diag) {
1304 if (!isExposureCandidate(D))
1305 return false;
1306
1307 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1308 return checkExposure(D: FD, Diag);
1309 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
1310 return checkExposure(D: FTD->getTemplatedDecl(), Diag);
1311
1312 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1313 return checkExposure(D: VD, Diag);
1314 if (auto *VTD = dyn_cast<VarTemplateDecl>(Val: D))
1315 return checkExposure(D: VTD->getTemplatedDecl(), Diag);
1316
1317 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1318 return checkExposure(D: RD, Diag);
1319
1320 if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: D))
1321 return checkExposure(D: CTD->getTemplatedDecl(), Diag);
1322
1323 return false;
1324}
1325
1326bool ExposureChecker::checkExposure(const FunctionDecl *FD, bool Diag) {
1327 bool IsExposure = false;
1328 if (isTULocal(Ty: FD->getReturnType())) {
1329 IsExposure = true;
1330 if (Diag)
1331 SemaRef.Diag(Loc: FD->getReturnTypeSourceRange().getBegin(),
1332 DiagID: diag::warn_exposure)
1333 << FD->getReturnType();
1334 }
1335
1336 for (ParmVarDecl *Parms : FD->parameters())
1337 if (isTULocal(Ty: Parms->getType())) {
1338 IsExposure = true;
1339 if (Diag)
1340 SemaRef.Diag(Loc: Parms->getLocation(), DiagID: diag::warn_exposure)
1341 << Parms->getType();
1342 }
1343
1344 bool IsImplicitInstantiation =
1345 FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1346
1347 // [basic.link]p14:
1348 // A declaration is an exposure if it either names a TU-local entity
1349 // (defined below), ignoring:
1350 // - the function-body for a non-inline function or function template
1351 // (but not the deduced return
1352 // type for a (possibly instantiated) definition of a function with a
1353 // declared return type that uses a placeholder type
1354 // ([dcl.spec.auto])),
1355 Diag &=
1356 (FD->isInlined() || IsImplicitInstantiation) && !FD->isDependentContext();
1357
1358 IsExposure |= checkExposure(S: FD->getBody(), Diag);
1359 if (IsExposure)
1360 ExposureSet.insert(V: FD);
1361
1362 return IsExposure;
1363}
1364
1365bool ExposureChecker::checkExposure(const VarDecl *VD, bool Diag) {
1366 bool IsExposure = false;
1367 // [basic.link]p14:
1368 // A declaration is an exposure if it either names a TU-local entity (defined
1369 // below), ignoring:
1370 // ...
1371 // or defines a constexpr variable initialized to a TU-local value (defined
1372 // below).
1373 if (VD->isConstexpr() && isTULocal(E: VD->getInit())) {
1374 IsExposure = true;
1375 if (Diag)
1376 SemaRef.Diag(Loc: VD->getInit()->getExprLoc(), DiagID: diag::warn_exposure)
1377 << VD->getInit();
1378 }
1379
1380 if (isTULocal(Ty: VD->getType())) {
1381 IsExposure = true;
1382 if (Diag)
1383 SemaRef.Diag(Loc: VD->getLocation(), DiagID: diag::warn_exposure) << VD->getType();
1384 }
1385
1386 // [basic.link]p14:
1387 // ..., ignoring:
1388 // - the initializer for a variable or variable template (but not the
1389 // variable's type),
1390 //
1391 // Note: although the spec says to ignore the initializer for all variable,
1392 // for the code we generated now for inline variables, it is dangerous if the
1393 // initializer of an inline variable is TULocal.
1394 Diag &= !VD->getDeclContext()->isDependentContext() && VD->isInline();
1395 IsExposure |= checkExposure(S: VD->getInit(), Diag);
1396 if (IsExposure)
1397 ExposureSet.insert(V: VD);
1398
1399 return IsExposure;
1400}
1401
1402bool ExposureChecker::checkExposure(const CXXRecordDecl *RD, bool Diag) {
1403 if (!RD->hasDefinition())
1404 return false;
1405
1406 bool IsExposure = false;
1407 for (CXXMethodDecl *Method : RD->methods())
1408 IsExposure |= checkExposure(FD: Method, Diag);
1409
1410 for (FieldDecl *FD : RD->fields()) {
1411 if (isTULocal(Ty: FD->getType())) {
1412 IsExposure = true;
1413 if (Diag)
1414 SemaRef.Diag(Loc: FD->getLocation(), DiagID: diag::warn_exposure) << FD->getType();
1415 }
1416 }
1417
1418 for (const CXXBaseSpecifier &Base : RD->bases()) {
1419 if (isTULocal(Ty: Base.getType())) {
1420 IsExposure = true;
1421 if (Diag)
1422 SemaRef.Diag(Loc: Base.getBaseTypeLoc(), DiagID: diag::warn_exposure)
1423 << Base.getType();
1424 }
1425 }
1426
1427 if (IsExposure)
1428 ExposureSet.insert(V: RD);
1429
1430 return IsExposure;
1431}
1432
1433class ReferenceTULocalChecker : public DynamicRecursiveASTVisitor {
1434public:
1435 using CallbackTy = std::function<void(DeclRefExpr *, ValueDecl *)>;
1436
1437 ReferenceTULocalChecker(ExposureChecker &C, CallbackTy &&Callback)
1438 : Checker(C), Callback(std::move(Callback)) {}
1439
1440 bool VisitDeclRefExpr(DeclRefExpr *DRE) override {
1441 ValueDecl *Referenced = DRE->getDecl();
1442 if (!Referenced)
1443 return true;
1444
1445 if (!Checker.isTULocal(D: Referenced))
1446 // We don't care if the referenced declaration is not TU-local.
1447 return true;
1448
1449 Qualifiers Qual = DRE->getType().getQualifiers();
1450 // [basic.link]p14:
1451 // A declaration is an exposure if it either names a TU-local entity
1452 // (defined below), ignoring:
1453 // ...
1454 // - any reference to a non-volatile const object ...
1455 if (Qual.hasConst() && !Qual.hasVolatile())
1456 return true;
1457
1458 // [basic.link]p14:
1459 // ..., ignoring:
1460 // ...
1461 // (p14.4) - ... or reference with internal or no linkage initialized with
1462 // a constant expression that is not an odr-use
1463 ASTContext &Context = Referenced->getASTContext();
1464 Linkage L = Referenced->getLinkageInternal();
1465 if (DRE->isNonOdrUse() && (L == Linkage::Internal || L == Linkage::None))
1466 if (auto *VD = dyn_cast<VarDecl>(Val: Referenced);
1467 VD && VD->getInit() && !VD->getInit()->isValueDependent() &&
1468 VD->getInit()->isConstantInitializer(Ctx&: Context, /*IsForRef=*/ForRef: false))
1469 return true;
1470
1471 Callback(DRE, Referenced);
1472 return true;
1473 }
1474
1475 ExposureChecker &Checker;
1476 CallbackTy Callback;
1477};
1478
1479bool ExposureChecker::checkExposure(const Stmt *S, bool Diag) {
1480 if (!S)
1481 return false;
1482
1483 bool HasReferencedTULocals = false;
1484 ReferenceTULocalChecker Checker(
1485 *this, [this, &HasReferencedTULocals, Diag](DeclRefExpr *DRE,
1486 ValueDecl *Referenced) {
1487 if (Diag) {
1488 SemaRef.Diag(Loc: DRE->getExprLoc(), DiagID: diag::warn_exposure) << Referenced;
1489 }
1490 HasReferencedTULocals = true;
1491 });
1492 Checker.TraverseStmt(S: const_cast<Stmt *>(S));
1493 return HasReferencedTULocals;
1494}
1495
1496void ExposureChecker::checkExposureInContext(const DeclContext *DC) {
1497 for (auto *TopD : DC->noload_decls()) {
1498 if (auto *Export = dyn_cast<ExportDecl>(Val: TopD)) {
1499 checkExposureInContext(DC: Export);
1500 continue;
1501 }
1502
1503 if (auto *LinkageSpec = dyn_cast<LinkageSpecDecl>(Val: TopD)) {
1504 checkExposureInContext(DC: LinkageSpec);
1505 continue;
1506 }
1507
1508 auto *TopND = dyn_cast<NamedDecl>(Val: TopD);
1509 if (!TopND)
1510 continue;
1511
1512 if (auto *Namespace = dyn_cast<NamespaceDecl>(Val: TopND)) {
1513 checkExposureInContext(DC: Namespace);
1514 continue;
1515 }
1516
1517 // [basic.link]p17:
1518 // If a (possibly instantiated) declaration of, or a deduction guide for,
1519 // a non-TU-local entity in a module interface unit
1520 // (outside the private-module-fragment, if any) or
1521 // module partition is an exposure, the program is ill-formed.
1522 if (!TopND->isFromASTFile() && isExposureCandidate(D: TopND) &&
1523 !isTULocal(D: TopND))
1524 checkExposure(D: TopND, /*Diag=*/true);
1525 }
1526}
1527
1528} // namespace
1529
1530void Sema::checkExposure(const TranslationUnitDecl *TU) {
1531 if (!TU)
1532 return;
1533
1534 ExposureChecker Checker(*this);
1535
1536 Module *M = TU->getOwningModule();
1537 if (M && M->isInterfaceOrPartition())
1538 Checker.checkExposureInContext(DC: TU);
1539
1540 // [basic.link]p18:
1541 // If a declaration that appears in one translation unit names a TU-local
1542 // entity declared in another translation unit that is not a header unit,
1543 // the program is ill-formed.
1544 for (auto FDAndInstantiationLocPair : PendingCheckReferenceForTULocal) {
1545 FunctionDecl *FD = FDAndInstantiationLocPair.first;
1546 SourceLocation PointOfInstantiation = FDAndInstantiationLocPair.second;
1547
1548 if (!FD->hasBody())
1549 continue;
1550
1551 ReferenceTULocalChecker(Checker, [&, this](DeclRefExpr *DRE,
1552 ValueDecl *Referenced) {
1553 // A "defect" in current implementation. Now an implicit instantiation of
1554 // a template, the instantiation is considered to be in the same module
1555 // unit as the template instead of the module unit where the instantiation
1556 // happens.
1557 //
1558 // See test/Modules/Exposre-2.cppm for example.
1559 if (!Referenced->isFromASTFile())
1560 return;
1561
1562 if (!Referenced->isInAnotherModuleUnit())
1563 return;
1564
1565 // This is not standard conforming. But given there are too many static
1566 // (inline) functions in headers in existing code, it is more user
1567 // friendly to ignore them temporarily now. maybe we can have another flag
1568 // for this.
1569 if (Referenced->getOwningModule()->isExplicitGlobalModule() &&
1570 isa<FunctionDecl>(Val: Referenced))
1571 return;
1572
1573 Diag(Loc: PointOfInstantiation,
1574 DiagID: diag::warn_reference_tu_local_entity_in_other_tu)
1575 << FD << Referenced
1576 << Referenced->getOwningModule()->getTopLevelModuleName();
1577 }).TraverseStmt(S: FD->getBody());
1578 }
1579}
1580
1581void Sema::checkReferenceToTULocalFromOtherTU(
1582 FunctionDecl *FD, SourceLocation PointOfInstantiation) {
1583 // Checking if a declaration have any reference to TU-local entities in other
1584 // TU is expensive. Try to avoid it as much as possible.
1585 if (!FD || !HadImportedNamedModules)
1586 return;
1587
1588 PendingCheckReferenceForTULocal.push_back(
1589 Elt: std::make_pair(x&: FD, y&: PointOfInstantiation));
1590}
1591