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