clang 24.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/ScopeExit.h"
22#include "llvm/ADT/StringExtras.h"
23
24using namespace clang;
25using namespace sema;
26
28 SourceLocation ImportLoc, DeclContext *DC,
29 bool FromInclude = false) {
30 SourceLocation ExternCLoc;
31
32 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
33 switch (LSD->getLanguage()) {
35 if (ExternCLoc.isInvalid())
36 ExternCLoc = LSD->getBeginLoc();
37 break;
39 break;
40 }
41 DC = LSD->getParent();
42 }
43
44 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
45 DC = DC->getParent();
46
47 if (!isa<TranslationUnitDecl>(DC)) {
48 S.Diag(ImportLoc, (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(cast<Decl>(DC)->getBeginLoc(),
53 diag::note_module_import_not_at_top_level)
54 << DC;
55 } else if (!M->IsExternC && ExternCLoc.isValid()) {
56 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
57 << M->getFullModuleName();
58 S.Diag(ExternCLoc, 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
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(Imported, 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
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
125 Worklist.push_back(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(Importing))
134 continue;
135 Visited.insert(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(Importing, ImportLoc);
140
141 if (isImportingModuleUnitFromSameModule(Ctx, Importing, CurrentModule,
142 FoundPrimaryModuleInterface)) {
143 for (Module *TransImported : Importing->Imports)
144 Worklist.push_back(TransImported);
145
146 for (auto [Exports, _] : Importing->Exports)
147 Worklist.push_back(Exports);
148 }
149 }
150}
151
154 // We start in the global module;
155 Module *GlobalModule =
156 PushGlobalModuleFragment(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(SourceMgr.getMainFileID());
179
180 StringRef HUName = getLangOpts().CurrentModule;
181 if (HUName.empty()) {
182 HUName =
183 SourceMgr.getFileEntryRefForID(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(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(SourceMgr.getMainFileID());
196 assert(F && "failed to find the header unit source?");
197 Module::Header H{HUName.str(), HUName.str(), *F};
198 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
199 Module *Mod = Map.createHeaderUnit(StartOfTU, HUName, H);
200 assert(Mod && "module creation should not fail");
201 ModuleScopes.push_back({}); // No GMF
202 ModuleScopes.back().BeginLoc = StartOfTU;
203 ModuleScopes.back().Module = Mod;
204 VisibleModules.setVisible(Mod, 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.
217 SourceLocation Loc) {
218 enum {
219 Valid = -1,
220 Invalid = 0,
221 Reserved = 1,
222 } Reason = Valid;
223
224 if (II->isStr("module") || II->isStr("import"))
225 Reason = Invalid;
226 else if (II->isReserved(S.getLangOpts()) !=
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, diag::err_invalid_module_name) << II;
241 case Reserved:
242 S.Diag(Loc, diag::warn_reserved_module_name) << II;
243 return false;
244 }
245 llvm_unreachable("fell off a fully covered switch");
246}
247
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;
261
262 bool IsPartition = !Partition.empty();
263 if (IsPartition)
264 switch (MDK) {
267 break;
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()) {
282 // It's OK to compile a module interface as a normal translation unit.
283 break;
284
287 break;
288
289 // We were asked to compile a module interface unit but this is a module
290 // implementation unit.
291 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
292 << FixItHint::CreateInsertion(ModuleLoc, "export ");
294 break;
295
297 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
298 return nullptr;
299
301 Diag(ModuleLoc, 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(ModuleLoc, diag::err_module_redeclaration);
313 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
314 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(ModuleLoc, diag::err_module_decl_not_at_start);
327 SourceLocation BeginLoc = PP.getMainFileFirstPPTokenLoc();
328 Diag(BeginLoc, diag::note_global_module_introducer_missing)
329 << FixItHint::CreateInsertion(BeginLoc, "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(Path[0].getLoc()) &&
343 (FirstComponentName == "std" ||
344 (FirstComponentName.starts_with("std") &&
345 llvm::all_of(FirstComponentName.drop_front(3), &llvm::isDigit))))
346 Diag(Path[0].getLoc(), 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(*this, Part.getIdentifierInfo(), 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(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(Path.front().getLoc(), diag::err_current_module_name_mismatch)
369 << SourceRange(Path.front().getLoc(), IsPartition
370 ? Partition.back().getLoc()
371 : Path.back().getLoc())
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) {
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(ModuleName)) {
386 Diag(Path[0].getLoc(), diag::err_module_redefinition) << ModuleName;
387 if (M->DefinitionLoc.isValid())
388 Diag(M->DefinitionLoc, diag::note_prev_module_definition);
389 else if (const ModuleFileName *FileName = M->getASTFileName())
390 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
391 << *FileName;
392 // A Clang module or a header unit cannot be used as the current named
393 // module while recovering from it. See clang/test/Modules/GH204632.cppm
394 // for an example.
395 if (!M->isNamedModule())
396 return nullptr;
397 Mod = M;
398 break;
399 }
400
401 // Create a Module for the module that we're defining.
402 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
405 assert(Mod && "module creation should not fail");
406 break;
407 }
408
410 // C++20 A module-declaration that contains neither an export-
411 // keyword nor a module-partition implicitly imports the primary
412 // module interface unit of the module as if by a module-import-
413 // declaration.
414 IdentifierLoc ModuleNameLoc(Path[0].getLoc(),
415 PP.getIdentifierInfo(ModuleName));
416
417 // The module loader will assume we're trying to import the module that
418 // we're building if `LangOpts.CurrentModule` equals to 'ModuleName'.
419 // Change the value for `LangOpts.CurrentModule` temporarily to make the
420 // module loader work properly.
421 const_cast<LangOptions &>(getLangOpts()).CurrentModule = "";
424 /*IsInclusionDirective=*/false);
425 const_cast<LangOptions &>(getLangOpts()).CurrentModule = ModuleName;
426
427 // A Clang module or a header unit cannot serve as the primary module
428 // interface while recovering from an implementation unit declaration.
429 if (Interface && !Interface->isNamedModule()) {
430 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
431 return nullptr;
432 }
433
434 if (!Interface) {
435 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
436 // Create an empty module interface unit for error recovery.
437 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
438 } else {
439 Mod = Map.createModuleForImplementationUnit(ModuleLoc, ModuleName);
440 }
441 } break;
442
444 // Create an interface, but note that it is an implementation
445 // unit.
446 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
448 break;
449 }
450
451 if (!this->TheGlobalModuleFragment) {
452 ModuleScopes.push_back({});
453 if (getLangOpts().ModulesLocalVisibility)
454 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
455 } else {
456 // We're done with the global module fragment now.
458 }
459
460 // Switch from the global module fragment (if any) to the named module.
461 ModuleScopes.back().BeginLoc = StartLoc;
462 ModuleScopes.back().Module = Mod;
463 VisibleModules.setVisible(Mod, ModuleLoc);
464
465 // From now on, we have an owning module for all declarations we see.
466 // In C++20 modules, those declaration would be reachable when imported
467 // unless explicitily exported.
468 // Otherwise, those declarations are module-private unless explicitly
469 // exported.
470 auto *TU = Context.getTranslationUnitDecl();
471 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
472 TU->setLocalOwningModule(Mod);
473
474 // We are in the module purview, but before any other (non import)
475 // statements, so imports are allowed.
477
479
480 // We already potentially made an implicit import (in the case of a module
481 // implementation unit importing its interface). Make this module visible
482 // and return the import decl to be added to the current TU.
483 if (Interface) {
484 HadImportedNamedModules = true;
485
487 Mod, ModuleLoc,
488 /*IsImportingPrimaryModuleInterface=*/true);
489
490 // Make the import decl for the interface in the impl module.
491 ImportDecl *Import = ImportDecl::Create(Context, CurContext, ModuleLoc,
492 Interface, Path[0].getLoc());
493 CurContext->addDecl(Import);
494
495 // Sequence initialization of the imported module before that of the current
496 // module, if any.
497 Context.addModuleInitializer(ModuleScopes.back().Module, Import);
498 Mod->Imports.push_back(Interface); // As if we imported it.
499 // Also save this as a shortcut to checking for decls in the interface
500 ThePrimaryInterface = Interface;
501 // If we made an implicit import of the module interface, then return the
502 // imported module decl.
503 return ConvertDeclToDeclGroup(Import);
504 }
505
506 return nullptr;
507}
508
511 SourceLocation PrivateLoc) {
512 // C++20 [basic.link]/2:
513 // A private-module-fragment shall appear only in a primary module
514 // interface unit.
515 switch (ModuleScopes.empty() ? Module::ExplicitGlobalModuleFragment
516 : ModuleScopes.back().Module->Kind) {
523 Diag(PrivateLoc, diag::err_private_module_fragment_not_module);
524 return nullptr;
525
527 Diag(PrivateLoc, diag::err_private_module_fragment_redefined);
528 Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition);
529 return nullptr;
530
532 Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface);
533 Diag(ModuleScopes.back().BeginLoc,
534 diag::note_not_module_interface_add_export)
535 << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
536 return nullptr;
537
539 break;
540 }
541
542 // FIXME: Check that this translation unit does not import any partitions;
543 // such imports would violate [basic.link]/2's "shall be the only module unit"
544 // restriction.
545
546 // We've finished the public fragment of the translation unit.
548
549 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
550 Module *PrivateModuleFragment =
551 Map.createPrivateModuleFragmentForInterfaceUnit(
552 ModuleScopes.back().Module, PrivateLoc);
553 assert(PrivateModuleFragment && "module creation should not fail");
554
555 // Enter the scope of the private module fragment.
556 ModuleScopes.push_back({});
557 ModuleScopes.back().BeginLoc = ModuleLoc;
558 ModuleScopes.back().Module = PrivateModuleFragment;
559 VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
560
561 // All declarations created from now on are scoped to the private module
562 // fragment (and are neither visible nor reachable in importers of the module
563 // interface).
564 auto *TU = Context.getTranslationUnitDecl();
565 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
566 TU->setLocalOwningModule(PrivateModuleFragment);
567
568 // FIXME: Consider creating an explicit representation of this declaration.
569 return nullptr;
570}
571
573 SourceLocation ExportLoc,
574 SourceLocation ImportLoc, ModuleIdPath Path,
575 bool IsPartition) {
576 assert((!IsPartition || getLangOpts().CPlusPlusModules) &&
577 "partition seen in non-C++20 code?");
578
579 // For a C++20 module name, flatten into a single identifier with the source
580 // location of the first component.
582
583 std::string ModuleName;
584 if (IsPartition) {
585 // We already checked that we are in a module purview in the parser.
586 assert(!ModuleScopes.empty() && "in a module purview, but no module?");
587 Module *NamedMod = ModuleScopes.back().Module;
588 // If we are importing into a partition, find the owning named module,
589 // otherwise, the name of the importing named module.
590 ModuleName = NamedMod->getPrimaryModuleInterfaceName().str();
591 ModuleName += ":";
592 ModuleName += ModuleLoader::getFlatNameFromPath(Path);
594 IdentifierLoc(Path[0].getLoc(), PP.getIdentifierInfo(ModuleName));
596 } else if (getLangOpts().CPlusPlusModules) {
597 ModuleName = ModuleLoader::getFlatNameFromPath(Path);
599 IdentifierLoc(Path[0].getLoc(), PP.getIdentifierInfo(ModuleName));
601 }
602
603 // Diagnose self-import before attempting a load.
604 // [module.import]/9
605 // A module implementation unit of a module M that is not a module partition
606 // shall not contain a module-import-declaration nominating M.
607 // (for an implementation, the module interface is imported implicitly,
608 // but that's handled in the module decl code).
609
610 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview() &&
611 getCurrentModule()->Name == ModuleName) {
612 Diag(ImportLoc, diag::err_module_self_import_cxx20)
613 << ModuleName << currentModuleIsImplementation();
614 return true;
615 }
616
618 ImportLoc, Path, Module::AllVisible, /*IsInclusionDirective=*/false);
619 if (!Mod)
620 return true;
621
622 if (!Mod->isInterfaceOrPartition() && !ModuleName.empty() &&
623 !getLangOpts().ObjC) {
624 Diag(ImportLoc, diag::err_module_import_non_interface_nor_parition)
625 << ModuleName;
626 return true;
627 }
628
629 return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
630}
631
632/// Determine whether \p D is lexically within an export-declaration.
633static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
634 for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
635 if (auto *ED = dyn_cast<ExportDecl>(DC))
636 return ED;
637 return nullptr;
638}
639
641 SourceLocation ExportLoc,
642 SourceLocation ImportLoc, Module *Mod,
643 ModuleIdPath Path) {
644 if (Mod->isHeaderUnit())
645 Diag(ImportLoc, diag::warn_experimental_header_unit);
646
647 if (Mod->isNamedModule())
648 makeTransitiveImportsVisible(getASTContext(), VisibleModules, Mod,
649 getCurrentModule(), ImportLoc);
650 else
651 VisibleModules.setVisible(Mod, ImportLoc);
652
654 "We can only import a partition unit in a named module.");
656 getCurrentModule()->isModuleInterfaceUnit())
657 Diag(ImportLoc,
658 diag::warn_import_implementation_partition_unit_in_interface_unit)
659 << Mod->Name;
660
661 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
662
663 // FIXME: we should support importing a submodule within a different submodule
664 // of the same top-level module. Until we do, make it an error rather than
665 // silently ignoring the import.
666 // FIXME: Should we warn on a redundant import of the current module?
667 if (Mod->isForBuilding(getLangOpts())) {
668 Diag(ImportLoc, getLangOpts().isCompilingModule()
669 ? diag::err_module_self_import
670 : diag::err_module_import_in_implementation)
672 }
673
674 SmallVector<SourceLocation, 2> IdentifierLocs;
675
676 if (Path.empty()) {
677 // If this was a header import, pad out with dummy locations.
678 // FIXME: Pass in and use the location of the header-name token in this
679 // case.
680 for (Module *ModCheck = Mod; ModCheck; ModCheck = ModCheck->Parent)
681 IdentifierLocs.push_back(SourceLocation());
682 } else if (getLangOpts().CPlusPlusModules && !Mod->Parent) {
683 // A single identifier for the whole name.
684 IdentifierLocs.push_back(Path[0].getLoc());
685 } else {
686 Module *ModCheck = Mod;
687 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
688 // If we've run out of module parents, just drop the remaining
689 // identifiers. We need the length to be consistent.
690 if (!ModCheck)
691 break;
692 ModCheck = ModCheck->Parent;
693
694 IdentifierLocs.push_back(Path[I].getLoc());
695 }
696 }
697
698 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
699 Mod, IdentifierLocs);
700 CurContext->addDecl(Import);
701
702 // Sequence initialization of the imported module before that of the current
703 // module, if any.
704 if (!ModuleScopes.empty())
705 Context.addModuleInitializer(ModuleScopes.back().Module, Import);
706
707 // A module (partition) implementation unit shall not be exported.
708 if (getLangOpts().CPlusPlusModules && ExportLoc.isValid() &&
710 Diag(ExportLoc, diag::err_export_partition_impl)
711 << SourceRange(ExportLoc, Path.back().getLoc());
712 } else if (ExportLoc.isValid() &&
713 (ModuleScopes.empty() || currentModuleIsImplementation())) {
714 // [module.interface]p1:
715 // An export-declaration shall inhabit a namespace scope and appear in the
716 // purview of a module interface unit.
717 Diag(ExportLoc, diag::err_export_not_in_module_interface);
718 } else if (!ModuleScopes.empty()) {
719 // Re-export the module if the imported module is exported.
720 // Note that we don't need to add re-exported module to Imports field
721 // since `Exports` implies the module is imported already.
722 if (ExportLoc.isValid() || getEnclosingExportDecl(Import))
723 getCurrentModule()->Exports.emplace_back(Mod, false);
724 else
725 getCurrentModule()->Imports.push_back(Mod);
726 }
727
728 HadImportedNamedModules = true;
729
730 return Import;
731}
732
734 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
735 BuildModuleInclude(DirectiveLoc, Mod);
736}
737
739 // Determine whether we're in the #include buffer for a module. The #includes
740 // in that buffer do not qualify as module imports; they're just an
741 // implementation detail of us building the module.
742 //
743 // FIXME: Should we even get ActOnAnnotModuleInclude calls for those?
744 bool IsInModuleIncludes =
747
748 // If we are really importing a module (not just checking layering) due to an
749 // #include in the main file, synthesize an ImportDecl.
750 if (getLangOpts().Modules && !IsInModuleIncludes) {
753 DirectiveLoc, Mod,
754 DirectiveLoc);
755 if (!ModuleScopes.empty())
756 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
757 TU->addDecl(ImportD);
758 Consumer.HandleImplicitImportDecl(ImportD);
759 }
760
762 VisibleModules.setVisible(Mod, DirectiveLoc);
763
764 if (getLangOpts().isCompilingModule()) {
765 Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
766 getLangOpts().CurrentModule, DirectiveLoc, false, false);
767 (void)ThisModule;
768 // For named modules, the current module name is not known while parsing the
769 // global module fragment and lookupModule may return null.
770 assert((getLangOpts().getCompilingModule() ==
772 ThisModule) &&
773 "was expecting a module if building a Clang module");
774 }
775}
776
778 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
779
780 ModuleScopes.push_back({});
781 ModuleScopes.back().Module = Mod;
782 if (getLangOpts().ModulesLocalVisibility)
783 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
784
785 VisibleModules.setVisible(Mod, DirectiveLoc);
786
787 // The enclosing context is now part of this module.
788 // FIXME: Consider creating a child DeclContext to hold the entities
789 // lexically within the module.
790 if (getLangOpts().trackLocalOwningModule()) {
791 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
792 cast<Decl>(DC)->setModuleOwnershipKind(
793 getLangOpts().ModulesLocalVisibility
796 cast<Decl>(DC)->setLocalOwningModule(Mod);
797 }
798 }
799}
800
802 if (getLangOpts().ModulesLocalVisibility) {
803 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
804 // Leaving a module hides namespace names, so our visible namespace cache
805 // is now out of date.
806 VisibleNamespaceCache.clear();
807 }
808
809 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
810 "left the wrong module scope");
811 ModuleScopes.pop_back();
812
813 // We got to the end of processing a local module. Create an
814 // ImportDecl as we would for an imported module.
816 SourceLocation DirectiveLoc;
817 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
818 // We reached the end of a #included module header. Use the #include loc.
819 assert(File != getSourceManager().getMainFileID() &&
820 "end of submodule in main source file");
821 DirectiveLoc = getSourceManager().getIncludeLoc(File);
822 } else {
823 // We reached an EOM pragma. Use the pragma location.
824 DirectiveLoc = EomLoc;
825 }
826 BuildModuleInclude(DirectiveLoc, Mod);
827
828 // Any further declarations are in whatever module we returned to.
829 if (getLangOpts().trackLocalOwningModule()) {
830 // The parser guarantees that this is the same context that we entered
831 // the module within.
832 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
833 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
834 if (!getCurrentModule())
835 cast<Decl>(DC)->setModuleOwnershipKind(
837 }
838 }
839}
840
842 Module *Mod) {
843 // Bail if we're not allowed to implicitly import a module here.
844 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
845 VisibleModules.isVisible(Mod))
846 return;
847
848 // Create the implicit import declaration.
851 Loc, Mod, Loc);
852 TU->addDecl(ImportD);
853 Consumer.HandleImplicitImportDecl(ImportD);
854
855 // Make the module visible.
857 VisibleModules.setVisible(Mod, Loc);
858}
859
861 SourceLocation LBraceLoc) {
863
864 // Set this temporarily so we know the export-declaration was braced.
865 D->setRBraceLoc(LBraceLoc);
866
867 CurContext->addDecl(D);
868 PushDeclContext(S, D);
869
870 // C++2a [module.interface]p1:
871 // An export-declaration shall appear only [...] in the purview of a module
872 // interface unit. An export-declaration shall not appear directly or
873 // indirectly within [...] a private-module-fragment.
874 if (!getLangOpts().HLSL) {
875 if (!isCurrentModulePurview()) {
876 Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
877 D->setInvalidDecl();
878 return D;
879 } else if (currentModuleIsImplementation()) {
880 Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
881 Diag(ModuleScopes.back().BeginLoc,
882 diag::note_not_module_interface_add_export)
883 << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
884 D->setInvalidDecl();
885 return D;
886 } else if (ModuleScopes.back().Module->Kind ==
888 Diag(ExportLoc, diag::err_export_in_private_module_fragment);
889 Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
890 D->setInvalidDecl();
891 return D;
892 }
893 }
894
895 for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
896 if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
897 // An export-declaration shall not appear directly or indirectly within
898 // an unnamed namespace [...]
899 if (ND->isAnonymousNamespace()) {
900 Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
901 Diag(ND->getLocation(), diag::note_anonymous_namespace);
902 // Don't diagnose internal-linkage declarations in this region.
903 D->setInvalidDecl();
904 return D;
905 }
906
907 // A declaration is exported if it is [...] a namespace-definition
908 // that contains an exported declaration.
909 //
910 // Defer exporting the namespace until after we leave it, in order to
911 // avoid marking all subsequent declarations in the namespace as exported.
912 if (!getLangOpts().HLSL && !DeferredExportedNamespaces.insert(ND).second)
913 break;
914 }
915 }
916
917 // [...] its declaration or declaration-seq shall not contain an
918 // export-declaration.
919 if (auto *ED = getEnclosingExportDecl(D)) {
920 Diag(ExportLoc, diag::err_export_within_export);
921 if (ED->hasBraces())
922 Diag(ED->getLocation(), diag::note_export);
923 D->setInvalidDecl();
924 return D;
925 }
926
927 if (!getLangOpts().HLSL)
929
930 return D;
931}
932
933static bool checkExportedDecl(Sema &, Decl *, SourceLocation);
934
935/// Check that it's valid to export all the declarations in \p DC.
937 SourceLocation BlockStart) {
938 bool AllUnnamed = true;
939 for (auto *D : DC->decls())
940 AllUnnamed &= checkExportedDecl(S, D, BlockStart);
941 return AllUnnamed;
942}
943
944/// Check that it's valid to export \p D.
945static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
946
947 // HLSL: export declaration is valid only on functions
948 if (S.getLangOpts().HLSL) {
949 // Export-within-export was already diagnosed in ActOnStartExportDecl
951 S.Diag(D->getBeginLoc(), diag::err_hlsl_export_not_on_function);
952 D->setInvalidDecl();
953 return false;
954 }
955
956 if (isa<FunctionDecl>(D)) {
958 for (const ParmVarDecl *PVD : FD->parameters()) {
959 if (PVD->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
960 S.Diag(D->getBeginLoc(), diag::err_hlsl_attr_incompatible)
961 << "'export'" << "'groupshared' parameter";
962 D->setInvalidDecl();
963 return false;
964 }
965 }
966 }
967 }
968
969 // C++20 [module.interface]p3:
970 // [...] it shall not declare a name with internal linkage.
971 bool HasName = false;
972 if (auto *ND = dyn_cast<NamedDecl>(D)) {
973 // Don't diagnose anonymous union objects; we'll diagnose their members
974 // instead.
975 HasName = (bool)ND->getDeclName();
976 if (HasName && ND->getFormalLinkage() == Linkage::Internal) {
977 S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
978 if (BlockStart.isValid())
979 S.Diag(BlockStart, diag::note_export);
980 return false;
981 }
982 }
983
984 // C++2a [module.interface]p5:
985 // all entities to which all of the using-declarators ultimately refer
986 // shall have been introduced with a name having external linkage
987 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
988 NamedDecl *Target = USD->getUnderlyingDecl();
989 Linkage Lk = Target->getFormalLinkage();
990 if (Lk == Linkage::Internal || Lk == Linkage::Module) {
991 S.Diag(USD->getLocation(), diag::err_export_using_internal)
992 << (Lk == Linkage::Internal ? 0 : 1) << Target;
993 S.Diag(Target->getLocation(), diag::note_using_decl_target);
994 if (BlockStart.isValid())
995 S.Diag(BlockStart, diag::note_export);
996 return false;
997 }
998 }
999
1000 // Recurse into namespace-scope DeclContexts. (Only namespace-scope
1001 // declarations are exported).
1002 if (auto *DC = dyn_cast<DeclContext>(D)) {
1003 if (!isa<NamespaceDecl>(D))
1004 return true;
1005
1006 if (auto *ND = dyn_cast<NamedDecl>(D)) {
1007 if (!ND->getDeclName()) {
1008 S.Diag(ND->getLocation(), diag::err_export_anon_ns_internal);
1009 if (BlockStart.isValid())
1010 S.Diag(BlockStart, diag::note_export);
1011 return false;
1012 } else if (!DC->decls().empty() &&
1013 DC->getRedeclContext()->isFileContext()) {
1014 return checkExportedDeclContext(S, DC, BlockStart);
1015 }
1016 }
1017 }
1018 return true;
1019}
1020
1022 auto *ED = cast<ExportDecl>(D);
1023 if (RBraceLoc.isValid())
1024 ED->setRBraceLoc(RBraceLoc);
1025
1027
1028 if (!D->isInvalidDecl()) {
1029 SourceLocation BlockStart =
1030 ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
1031 for (auto *Child : ED->decls()) {
1032 checkExportedDecl(*this, Child, BlockStart);
1033 if (auto *FD = dyn_cast<FunctionDecl>(Child)) {
1034 // [dcl.inline]/7
1035 // If an inline function or variable that is attached to a named module
1036 // is declared in a definition domain, it shall be defined in that
1037 // domain.
1038 // So, if the current declaration does not have a definition, we must
1039 // check at the end of the TU (or when the PMF starts) to see that we
1040 // have a definition at that point.
1041 if (FD->isInlineSpecified() && !FD->isDefined())
1042 PendingInlineFuncDecls.insert(FD);
1043 }
1044 }
1045 }
1046
1047 // Anything exported from a module should never be considered unused.
1048 for (auto *Exported : ED->decls())
1049 Exported->markUsed(getASTContext());
1050
1051 return D;
1052}
1053
1054Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc) {
1055 // We shouldn't create new global module fragment if there is already
1056 // one.
1057 if (!TheGlobalModuleFragment) {
1059 TheGlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
1060 BeginLoc, getCurrentModule());
1061 }
1062
1063 assert(TheGlobalModuleFragment && "module creation should not fail");
1064
1065 // Enter the scope of the global module.
1066 ModuleScopes.push_back({BeginLoc, TheGlobalModuleFragment,
1067 /*OuterVisibleModules=*/{}});
1068 VisibleModules.setVisible(TheGlobalModuleFragment, BeginLoc);
1069
1070 return TheGlobalModuleFragment;
1071}
1072
1073void Sema::PopGlobalModuleFragment() {
1074 assert(!ModuleScopes.empty() &&
1075 getCurrentModule()->isExplicitGlobalModule() &&
1076 "left the wrong module scope, which is not global module fragment");
1077 ModuleScopes.pop_back();
1078}
1079
1080Module *Sema::PushImplicitGlobalModuleFragment(SourceLocation BeginLoc) {
1081 if (!TheImplicitGlobalModuleFragment) {
1082 ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
1083 TheImplicitGlobalModuleFragment =
1086 }
1087 assert(TheImplicitGlobalModuleFragment && "module creation should not fail");
1088
1089 // Enter the scope of the global module.
1090 ModuleScopes.push_back({BeginLoc, TheImplicitGlobalModuleFragment,
1091 /*OuterVisibleModules=*/{}});
1092 VisibleModules.setVisible(TheImplicitGlobalModuleFragment, BeginLoc);
1093 return TheImplicitGlobalModuleFragment;
1094}
1095
1096void Sema::PopImplicitGlobalModuleFragment() {
1097 assert(!ModuleScopes.empty() &&
1098 getCurrentModule()->isImplicitGlobalModule() &&
1099 "left the wrong module scope, which is not global module fragment");
1100 ModuleScopes.pop_back();
1101}
1102
1103bool Sema::isCurrentModulePurview() const {
1104 if (!getCurrentModule())
1105 return false;
1106
1107 /// Does this Module scope describe part of the purview of a standard named
1108 /// C++ module?
1109 switch (getCurrentModule()->Kind) {
1116 return true;
1117 default:
1118 return false;
1119 }
1120}
1121
1122//===----------------------------------------------------------------------===//
1123// Checking Exposure in modules //
1124//===----------------------------------------------------------------------===//
1125
1126namespace {
1127class ExposureChecker {
1128public:
1129 ExposureChecker(Sema &S) : SemaRef(S) {}
1130
1131 bool checkExposure(const VarDecl *D, bool Diag);
1132 bool checkExposure(const CXXRecordDecl *D, bool Diag);
1133 bool checkExposure(const Stmt *S, bool Diag);
1134 bool checkExposure(const FunctionDecl *D, bool Diag);
1135 bool checkExposure(const NamedDecl *D, bool Diag);
1136 void checkExposureInContext(const DeclContext *DC);
1137 bool isExposureCandidate(const NamedDecl *D);
1138
1139 bool isTULocal(QualType Ty);
1140 bool isTULocal(const NamedDecl *ND);
1141 bool isTULocal(const Expr *E);
1142
1143 Sema &SemaRef;
1144
1145private:
1146 llvm::DenseSet<const NamedDecl *> ExposureSet;
1147 llvm::DenseSet<const NamedDecl *> KnownNonExposureSet;
1148 llvm::DenseSet<const NamedDecl *> CheckingDecls;
1149};
1150
1151bool ExposureChecker::isTULocal(QualType Ty) {
1152 // [basic.link]p15:
1153 // An entity is TU-local if it is
1154 // - a type, type alias, namespace, namespace alias, function, variable, or
1155 // template that
1156 // -- has internal linkage, or
1157 return Ty->getLinkage() == Linkage::Internal;
1158
1159 // TODO:
1160 // [basic.link]p15.2:
1161 // a type with no name that is defined outside a class-specifier, function
1162 // body, or initializer or is introduced by a defining-type-specifier that
1163 // is used to declare only TU-local entities,
1164}
1165
1166bool ExposureChecker::isTULocal(const NamedDecl *D) {
1167 if (!D)
1168 return false;
1169
1170 // [basic.link]p15:
1171 // An entity is TU-local if it is
1172 // - a type, type alias, namespace, namespace alias, function, variable, or
1173 // template that
1174 // -- has internal linkage, or
1176 return true;
1177
1178 if (D->isInAnonymousNamespace())
1179 return true;
1180
1181 // [basic.link]p15.1.2:
1182 // does not have a name with linkage and is declared, or introduced by a
1183 // lambda-expression, within the definition of a TU-local entity,
1185 if (auto *ND = dyn_cast<NamedDecl>(D->getDeclContext());
1186 ND && isTULocal(ND))
1187 return true;
1188
1189 // [basic.link]p15.3, p15.4:
1190 // - a specialization of a TU-local template,
1191 // - a specialization of a template with any TU-local template argument, or
1192 ArrayRef<TemplateArgument> TemplateArgs;
1193 NamedDecl *PrimaryTemplate = nullptr;
1194 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
1195 TemplateArgs = CTSD->getTemplateArgs().asArray();
1196 PrimaryTemplate = CTSD->getSpecializedTemplate();
1197 if (isTULocal(PrimaryTemplate))
1198 return true;
1199 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
1200 TemplateArgs = VTSD->getTemplateArgs().asArray();
1201 PrimaryTemplate = VTSD->getSpecializedTemplate();
1202 if (isTULocal(PrimaryTemplate))
1203 return true;
1204 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1205 if (auto *TAList = FD->getTemplateSpecializationArgs())
1206 TemplateArgs = TAList->asArray();
1207
1208 PrimaryTemplate = FD->getPrimaryTemplate();
1209 if (isTULocal(PrimaryTemplate))
1210 return true;
1211 }
1212
1213 if (!PrimaryTemplate)
1214 // Following off, we only check for specializations.
1215 return false;
1216
1217 if (KnownNonExposureSet.count(D))
1218 return false;
1219
1220 for (auto &TA : TemplateArgs) {
1221 switch (TA.getKind()) {
1223 if (isTULocal(TA.getAsType()))
1224 return true;
1225 break;
1227 if (isTULocal(TA.getAsDecl()))
1228 return true;
1229 break;
1230 default:
1231 break;
1232 }
1233 }
1234
1235 // Avoid recursions.
1236 if (CheckingDecls.count(D))
1237 return false;
1238 CheckingDecls.insert(D);
1239 llvm::scope_exit RemoveCheckingDecls([&] { CheckingDecls.erase(D); });
1240
1241 // [basic.link]p15.5
1242 // - a specialization of a template whose (possibly instantiated) declaration
1243 // is an exposure.
1244 if (ExposureSet.count(PrimaryTemplate) ||
1245 checkExposure(PrimaryTemplate, /*Diag=*/false))
1246 return true;
1247
1248 // Avoid calling checkExposure again since it is expensive.
1249 KnownNonExposureSet.insert(D);
1250 return false;
1251}
1252
1253bool ExposureChecker::isTULocal(const Expr *E) {
1254 if (!E)
1255 return false;
1256
1257 // [basic.link]p16:
1258 // A value or object is TU-local if either
1259 // - it is of TU-local type,
1260 if (isTULocal(E->getType()))
1261 return true;
1262
1263 E = E->IgnoreParenImpCasts();
1264 // [basic.link]p16.2:
1265 // - it is, or is a pointer to, a TU-local function or the object associated
1266 // with a TU-local variable,
1267 // - it is an object of class or array type and any of its subobjects or any
1268 // of the objects or functions to which its non-static data members of
1269 // reference type refer is TU-local and is usable in constant expressions, or
1270 // FIXME: But how can we know the value of pointers or arrays at compile time?
1271 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
1272 if (auto *FD = dyn_cast_or_null<FunctionDecl>(DRE->getFoundDecl()))
1273 return isTULocal(FD);
1274 else if (auto *VD = dyn_cast_or_null<VarDecl>(DRE->getFoundDecl()))
1275 return isTULocal(VD);
1276 else if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(DRE->getFoundDecl()))
1277 return isTULocal(RD);
1278 }
1279
1280 // TODO:
1281 // [basic.link]p16.4:
1282 // it is a reflection value that represents...
1283
1284 return false;
1285}
1286
1287bool ExposureChecker::isExposureCandidate(const NamedDecl *D) {
1288 if (!D)
1289 return false;
1290
1291 // [basic.link]p17:
1292 // If a (possibly instantiated) declaration of, or a deduction guide for,
1293 // a non-TU-local entity in a module interface unit
1294 // (outside the private-module-fragment, if any) or
1295 // module partition is an exposure, the program is ill-formed.
1296 Module *M = D->getOwningModule();
1297 if (!M)
1298 return false;
1299 // If M is implicit global module, the declaration must be in the purview of
1300 // a module unit.
1301 if (M->isImplicitGlobalModule()) {
1302 M = M->Parent;
1303 assert(M && "Implicit global module must have a parent");
1304 }
1305
1306 if (!M->isInterfaceOrPartition())
1307 return false;
1308
1309 if (D->isImplicit())
1310 return false;
1311
1312 // [basic.link]p14:
1313 // A declaration is an exposure if it either names a TU-local entity
1314 // (defined below), ignoring:
1315 // ...
1316 // - friend declarations in a class definition
1317 if (D->getFriendObjectKind() &&
1319 return false;
1320
1321 return true;
1322}
1323
1324bool ExposureChecker::checkExposure(const NamedDecl *D, bool Diag) {
1325 if (!isExposureCandidate(D))
1326 return false;
1327
1328 if (auto *FD = dyn_cast<FunctionDecl>(D))
1329 return checkExposure(FD, Diag);
1330 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
1331 return checkExposure(FTD->getTemplatedDecl(), Diag);
1332
1333 if (auto *VD = dyn_cast<VarDecl>(D))
1334 return checkExposure(VD, Diag);
1335 if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
1336 return checkExposure(VTD->getTemplatedDecl(), Diag);
1337
1338 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1339 return checkExposure(RD, Diag);
1340
1341 if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
1342 return checkExposure(CTD->getTemplatedDecl(), Diag);
1343
1344 return false;
1345}
1346
1347bool ExposureChecker::checkExposure(const FunctionDecl *FD, bool Diag) {
1348 bool IsExposure = false;
1349 if (isTULocal(FD->getReturnType())) {
1350 IsExposure = true;
1351 if (Diag)
1352 SemaRef.Diag(FD->getReturnTypeSourceRange().getBegin(),
1353 diag::warn_exposure)
1354 << FD->getReturnType();
1355 }
1356
1357 for (ParmVarDecl *Parms : FD->parameters())
1358 if (isTULocal(Parms->getType())) {
1359 IsExposure = true;
1360 if (Diag)
1361 SemaRef.Diag(Parms->getLocation(), diag::warn_exposure)
1362 << Parms->getType();
1363 }
1364
1365 bool IsImplicitInstantiation =
1367
1368 // [basic.link]p14:
1369 // A declaration is an exposure if it either names a TU-local entity
1370 // (defined below), ignoring:
1371 // - the function-body for a non-inline function or function template
1372 // (but not the deduced return
1373 // type for a (possibly instantiated) definition of a function with a
1374 // declared return type that uses a placeholder type
1375 // ([dcl.spec.auto])),
1376 Diag &=
1377 (FD->isInlined() || IsImplicitInstantiation) && !FD->isDependentContext();
1378
1379 IsExposure |= checkExposure(FD->getBody(), Diag);
1380 if (IsExposure)
1381 ExposureSet.insert(FD);
1382
1383 return IsExposure;
1384}
1385
1386bool ExposureChecker::checkExposure(const VarDecl *VD, bool Diag) {
1387 bool IsExposure = false;
1388 // [basic.link]p14:
1389 // A declaration is an exposure if it either names a TU-local entity (defined
1390 // below), ignoring:
1391 // ...
1392 // or defines a constexpr variable initialized to a TU-local value (defined
1393 // below).
1394 if (VD->isConstexpr() && isTULocal(VD->getInit())) {
1395 IsExposure = true;
1396 if (Diag)
1397 SemaRef.Diag(VD->getInit()->getExprLoc(), diag::warn_exposure)
1398 << VD->getInit();
1399 }
1400
1401 if (isTULocal(VD->getType())) {
1402 IsExposure = true;
1403 if (Diag)
1404 SemaRef.Diag(VD->getLocation(), diag::warn_exposure) << VD->getType();
1405 }
1406
1407 // [basic.link]p14:
1408 // ..., ignoring:
1409 // - the initializer for a variable or variable template (but not the
1410 // variable's type),
1411 //
1412 // Note: although the spec says to ignore the initializer for all variable,
1413 // for the code we generated now for inline variables, it is dangerous if the
1414 // initializer of an inline variable is TULocal.
1415 Diag &= !VD->getDeclContext()->isDependentContext() && VD->isInline();
1416 IsExposure |= checkExposure(VD->getInit(), Diag);
1417 if (IsExposure)
1418 ExposureSet.insert(VD);
1419
1420 return IsExposure;
1421}
1422
1423bool ExposureChecker::checkExposure(const CXXRecordDecl *RD, bool Diag) {
1424 if (!RD->hasDefinition())
1425 return false;
1426
1427 bool IsExposure = false;
1428 for (CXXMethodDecl *Method : RD->methods())
1429 IsExposure |= checkExposure(Method, Diag);
1430
1431 for (FieldDecl *FD : RD->fields()) {
1432 if (isTULocal(FD->getType())) {
1433 IsExposure = true;
1434 if (Diag)
1435 SemaRef.Diag(FD->getLocation(), diag::warn_exposure) << FD->getType();
1436 }
1437 }
1438
1439 for (const CXXBaseSpecifier &Base : RD->bases()) {
1440 if (isTULocal(Base.getType())) {
1441 IsExposure = true;
1442 if (Diag)
1443 SemaRef.Diag(Base.getBaseTypeLoc(), diag::warn_exposure)
1444 << Base.getType();
1445 }
1446 }
1447
1448 if (IsExposure)
1449 ExposureSet.insert(RD);
1450
1451 return IsExposure;
1452}
1453
1454class ReferenceTULocalChecker : public DynamicRecursiveASTVisitor {
1455public:
1456 using CallbackTy = std::function<void(SourceLocation, NamedDecl *)>;
1457
1458 ReferenceTULocalChecker(ExposureChecker &C, CallbackTy &&Callback)
1459 : Checker(C), Callback(std::move(Callback)) {}
1460
1461 bool VisitDeclRefExpr(DeclRefExpr *DRE) override {
1462 ValueDecl *Referenced = DRE->getDecl();
1463 if (!Referenced)
1464 return true;
1465
1466 if (!Checker.isTULocal(Referenced))
1467 // We don't care if the referenced declaration is not TU-local.
1468 return true;
1469
1470 Qualifiers Qual = DRE->getType().getQualifiers();
1471 // [basic.link]p14:
1472 // A declaration is an exposure if it either names a TU-local entity
1473 // (defined below), ignoring:
1474 // ...
1475 // - any reference to a non-volatile const object ...
1476 if (Qual.hasConst() && !Qual.hasVolatile())
1477 return true;
1478
1479 // [basic.link]p14:
1480 // ..., ignoring:
1481 // ...
1482 // (p14.4) - ... or reference with internal or no linkage initialized with
1483 // a constant expression that is not an odr-use
1484 ASTContext &Context = Referenced->getASTContext();
1485 Linkage L = Referenced->getLinkageInternal();
1486 if (DRE->isNonOdrUse() && (L == Linkage::Internal || L == Linkage::None))
1487 if (auto *VD = dyn_cast<VarDecl>(Referenced);
1488 VD && VD->getInit() && !VD->getInit()->isValueDependent() &&
1489 VD->getInit()->isConstantInitializer(Context))
1490 return true;
1491
1492 Callback(DRE->getExprLoc(), Referenced);
1493 return true;
1494 }
1495
1496 bool VisitTagTypeLoc(TagTypeLoc TL) override {
1497 TagDecl *Referenced = TL.getDecl();
1498 if (Checker.isTULocal(Referenced))
1499 Callback(TL.getNameLoc(), Referenced);
1500 return true;
1501 }
1502
1503 ExposureChecker &Checker;
1504 CallbackTy Callback;
1505};
1506
1507bool ExposureChecker::checkExposure(const Stmt *S, bool Diag) {
1508 if (!S)
1509 return false;
1510
1511 bool HasReferencedTULocals = false;
1512 ReferenceTULocalChecker Checker(
1513 *this, [this, &HasReferencedTULocals, Diag](SourceLocation Loc,
1514 NamedDecl *Referenced) {
1515 if (Diag) {
1516 SemaRef.Diag(Loc, diag::warn_exposure) << Referenced;
1517 }
1518 HasReferencedTULocals = true;
1519 });
1520 Checker.TraverseStmt(const_cast<Stmt *>(S));
1521 return HasReferencedTULocals;
1522}
1523
1524void ExposureChecker::checkExposureInContext(const DeclContext *DC) {
1525 for (auto *TopD : DC->noload_decls()) {
1526 if (auto *Export = dyn_cast<ExportDecl>(TopD)) {
1527 checkExposureInContext(Export);
1528 continue;
1529 }
1530
1531 if (auto *LinkageSpec = dyn_cast<LinkageSpecDecl>(TopD)) {
1532 checkExposureInContext(LinkageSpec);
1533 continue;
1534 }
1535
1536 auto *TopND = dyn_cast<NamedDecl>(TopD);
1537 if (!TopND)
1538 continue;
1539
1540 if (auto *Namespace = dyn_cast<NamespaceDecl>(TopND)) {
1541 checkExposureInContext(Namespace);
1542 continue;
1543 }
1544
1545 // [basic.link]p17:
1546 // If a (possibly instantiated) declaration of, or a deduction guide for,
1547 // a non-TU-local entity in a module interface unit
1548 // (outside the private-module-fragment, if any) or
1549 // module partition is an exposure, the program is ill-formed.
1550 if (!TopND->isFromASTFile() && isExposureCandidate(TopND) &&
1551 !isTULocal(TopND))
1552 checkExposure(TopND, /*Diag=*/true);
1553 }
1554}
1555
1556} // namespace
1557
1558void Sema::checkExposure(const TranslationUnitDecl *TU) {
1559 if (!TU)
1560 return;
1561
1562 ExposureChecker Checker(*this);
1563
1564 Module *M = TU->getOwningModule();
1565 if (M && M->isInterfaceOrPartition())
1566 Checker.checkExposureInContext(TU);
1567
1568 // [basic.link]p18:
1569 // If a declaration that appears in one translation unit names a TU-local
1570 // entity declared in another translation unit that is not a header unit,
1571 // the program is ill-formed.
1572 for (auto FDAndInstantiationLocPair : PendingCheckReferenceForTULocal) {
1573 FunctionDecl *FD = FDAndInstantiationLocPair.first;
1574 SourceLocation PointOfInstantiation = FDAndInstantiationLocPair.second;
1575
1576 // Substitution may fail before an instantiated body is formed. The pattern
1577 // still contains non-dependent references to TU-local entities, use the
1578 // instantiation pattern as the body.
1579 const FunctionDecl *BodyOwner = FD;
1580 if (!BodyOwner->hasBody())
1581 BodyOwner = FD->getTemplateInstantiationPattern();
1582 if (!BodyOwner || !BodyOwner->hasBody())
1583 continue;
1584
1585 ReferenceTULocalChecker(Checker, [&, this](SourceLocation,
1586 NamedDecl *Referenced) {
1587 // A "defect" in current implementation. Now an implicit instantiation of
1588 // a template, the instantiation is considered to be in the same module
1589 // unit as the template instead of the module unit where the instantiation
1590 // happens.
1591 //
1592 // See test/Modules/Exposre-2.cppm for example.
1593 if (!Referenced->isFromASTFile())
1594 return;
1595
1596 if (!Referenced->isInAnotherModuleUnit())
1597 return;
1598
1599 // This is not standard conforming. But given there are too many static
1600 // (inline) functions in headers in existing code, it is more user
1601 // friendly to ignore them temporarily now. maybe we can have another flag
1602 // for this.
1603 if (Referenced->getOwningModule()->isExplicitGlobalModule() &&
1604 isa<FunctionDecl>(Referenced))
1605 return;
1606
1607 Diag(PointOfInstantiation,
1608 diag::warn_reference_tu_local_entity_in_other_tu)
1609 << FD << Referenced
1610 << Referenced->getOwningModule()->getTopLevelModuleName();
1611 }).TraverseStmt(BodyOwner->getBody());
1612 }
1613}
1614
1615void Sema::checkReferenceToTULocalFromOtherTU(
1616 FunctionDecl *FD, SourceLocation PointOfInstantiation) {
1617 // Checking if a declaration have any reference to TU-local entities in other
1618 // TU is expensive. Try to avoid it as much as possible.
1619 if (!FD || !HadImportedNamedModules)
1620 return;
1621
1622 PendingCheckReferenceForTULocal.push_back(
1623 std::make_pair(FD, PointOfInstantiation));
1624}
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 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:223
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:2145
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:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2142
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:2411
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2403
ValueDecl * getDecl()
Definition Expr.h:1358
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1488
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:1243
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
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:854
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition DeclBase.h:805
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
bool isInAnonymousNamespace() const
Definition DeclBase.cpp:443
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
@ 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:242
@ ModulePrivate
This declaration has an owning module, but is only visible to lookups that occur within that module.
Definition DeclBase.h:248
@ 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:898
Represents a standard C++ module export declaration.
Definition Decl.h:5266
static ExportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExportLoc)
Definition Decl.cpp:6158
void setRBraceLoc(SourceLocation L)
Definition Decl.h:5286
This represents one expression.
Definition Expr.h:113
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3101
bool isConstantInitializer(ASTContext &Ctx, bool ForRef=false, const Expr **Culprit=nullptr) const
Returns true if this expression can be emitted to IR as a constant, and thus can be used as a constan...
Definition Expr.cpp:3358
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:145
Represents a member of a struct/union/class.
Definition Decl.h:3294
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:105
Represents a function declaration or definition.
Definition Decl.h:2058
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3267
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4067
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3051
QualType getReturnType() const
Definition Decl.h:2975
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2904
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition Decl.cpp:4307
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4460
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3187
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:5187
static ImportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, Module *Imported, ArrayRef< SourceLocation > IdentifierLocs)
Create a new module import declaration.
Definition Decl.cpp:6114
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:6122
@ 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.
Identifies a module file to be loaded.
Definition Module.h:109
virtual ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective)=0
Attempt to load the given module.
static std::string getFlatNameFromPath(ModuleIdPath Path)
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:340
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:950
SmallVector< ExportDecl, 2 > Exports
The set of export declarations.
Definition Module.h:671
bool isForBuilding(const LangOptions &LangOpts) const
Determine whether this module can be built in this compilation.
Definition Module.cpp:156
bool isInterfaceOrPartition() const
Definition Module.h:889
bool isModulePartitionImplementation() const
Is this a module partition implementation unit.
Definition Module.h:877
@ AllVisible
All of the names in this module are visible.
Definition Module.h:647
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:389
ModuleKind Kind
The kind of this module.
Definition Module.h:385
std::string Name
The name of this module.
Definition Module.h:343
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition Module.h:595
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition Module.h:905
bool isModulePartition() const
Is this a module partition.
Definition Module.h:871
bool isExplicitGlobalModule() const
Definition Module.h:441
bool isImplicitGlobalModule() const
Definition Module.h:444
bool isHeaderUnit() const
Is this module a header unit.
Definition Module.h:887
@ ModuleImplementationUnit
This is a C++20 module implementation unit.
Definition Module.h:363
@ ModuleMapModule
This is a module that was defined by a module map and built out of header files.
Definition Module.h:354
@ ImplicitGlobalModuleFragment
This is an implicit fragment of the global module which contains only language linkage declarations (...
Definition Module.h:381
@ ModulePartitionInterface
This is a C++20 module partition interface.
Definition Module.h:366
@ ModuleInterfaceUnit
This is a C++20 module interface unit.
Definition Module.h:360
@ ModuleHeaderUnit
This is a C++20 header unit.
Definition Module.h:357
@ ModulePartitionImplementation
This is a C++20 module partition implementation.
Definition Module.h:369
@ PrivateModuleFragment
This is the private module fragment within some C++ module.
Definition Module.h:376
@ ExplicitGlobalModuleFragment
This is the explicit Global Module Fragment of a modular TU.
Definition Module.h:373
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:240
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:423
llvm::SmallVector< ModuleRef, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition Module.h:658
This represents a decl that may have a name.
Definition Decl.h:274
Linkage getLinkageInternal() const
Determine what kind of linkage this entity has.
Definition Decl.cpp:1182
Represents a parameter to a function.
Definition Decl.h:1819
HeaderSearch & getHeaderSearchInfo() const
A (possibly-)qualified type.
Definition TypeBase.h:938
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8542
bool hasConst() const
Definition TypeBase.h:458
bool hasVolatile() const
Definition TypeBase.h:468
field_range fields() const
Definition Decl.h:4662
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)
Emit a diagnostic.
Definition SemaBase.cpp:61
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:864
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:1259
@ PartitionImplementation
'module X:Y;'
Definition Sema.h:9918
@ Interface
'export module X;'
Definition Sema.h:9915
@ Implementation
'module X;'
Definition Sema.h:9916
@ PartitionInterface
'export module X:Y;'
Definition Sema.h:9917
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:13725
ASTContext & Context
Definition Sema.h:1305
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:9901
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:1517
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:81
ASTContext & getASTContext() const
Definition Sema.h:936
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:929
Preprocessor & PP
Definition Sema.h:1304
SemaHLSL & HLSL()
Definition Sema.h:1482
void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind)
Definition Sema.cpp:1237
DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc)
The parser has processed a global-module-fragment declaration that begins the definition of the globa...
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:9896
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1445
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:934
void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
bool isModuleVisible(const Module *M, bool ModulePrivate=false)
bool isSFINAEContext() const
Definition Sema.h:13796
ASTConsumer & Consumer
Definition Sema.h:1306
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition Sema.h:9924
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9925
@ GlobalFragment
after 'module;' but before 'module X;'
Definition Sema.h:9926
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
Definition Sema.h:9933
@ ImportAllowed
after 'module X;' but before any non-import decl.
Definition Sema.h:9927
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
Definition Sema.cpp:110
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:1296
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
TagDecl * getDecl() const
Definition TypeLoc.h:796
SourceLocation getNameLoc() const
Definition TypeLoc.h:822
@ 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:105
Linkage getLinkage() const
Determine the linkage of this type.
Definition Type.cpp:5060
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:932
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1593
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1575
const Expr * getInit() const
Definition Decl.h:1391
A set of visible modules.
Definition Module.h:1095
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:655
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
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:484
@ Normal
A normal translation unit fragment.
Definition Sema.h:488
@ 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:195
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:487