clang 23.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 (OptionalFileEntryRef FE = M->getASTFile())
390 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
391 << FE->getName();
392 Mod = M;
393 break;
394 }
395
396 // Create a Module for the module that we're defining.
397 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
400 assert(Mod && "module creation should not fail");
401 break;
402 }
403
405 // C++20 A module-declaration that contains neither an export-
406 // keyword nor a module-partition implicitly imports the primary
407 // module interface unit of the module as if by a module-import-
408 // declaration.
409 IdentifierLoc ModuleNameLoc(Path[0].getLoc(),
410 PP.getIdentifierInfo(ModuleName));
411
412 // The module loader will assume we're trying to import the module that
413 // we're building if `LangOpts.CurrentModule` equals to 'ModuleName'.
414 // Change the value for `LangOpts.CurrentModule` temporarily to make the
415 // module loader work properly.
416 const_cast<LangOptions &>(getLangOpts()).CurrentModule = "";
419 /*IsInclusionDirective=*/false);
420 const_cast<LangOptions &>(getLangOpts()).CurrentModule = ModuleName;
421
422 if (!Interface) {
423 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
424 // Create an empty module interface unit for error recovery.
425 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
426 } else {
427 Mod = Map.createModuleForImplementationUnit(ModuleLoc, ModuleName);
428 }
429 } break;
430
432 // Create an interface, but note that it is an implementation
433 // unit.
434 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
436 break;
437 }
438
439 if (!this->TheGlobalModuleFragment) {
440 ModuleScopes.push_back({});
441 if (getLangOpts().ModulesLocalVisibility)
442 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
443 } else {
444 // We're done with the global module fragment now.
446 }
447
448 // Switch from the global module fragment (if any) to the named module.
449 ModuleScopes.back().BeginLoc = StartLoc;
450 ModuleScopes.back().Module = Mod;
451 VisibleModules.setVisible(Mod, ModuleLoc);
452
453 // From now on, we have an owning module for all declarations we see.
454 // In C++20 modules, those declaration would be reachable when imported
455 // unless explicitily exported.
456 // Otherwise, those declarations are module-private unless explicitly
457 // exported.
458 auto *TU = Context.getTranslationUnitDecl();
459 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
460 TU->setLocalOwningModule(Mod);
461
462 // We are in the module purview, but before any other (non import)
463 // statements, so imports are allowed.
465
467
468 if (auto *Listener = getASTMutationListener())
469 Listener->EnteringModulePurview();
470
471 // We already potentially made an implicit import (in the case of a module
472 // implementation unit importing its interface). Make this module visible
473 // and return the import decl to be added to the current TU.
474 if (Interface) {
475 HadImportedNamedModules = true;
476
478 Mod, ModuleLoc,
479 /*IsImportingPrimaryModuleInterface=*/true);
480
481 // Make the import decl for the interface in the impl module.
482 ImportDecl *Import = ImportDecl::Create(Context, CurContext, ModuleLoc,
483 Interface, Path[0].getLoc());
484 CurContext->addDecl(Import);
485
486 // Sequence initialization of the imported module before that of the current
487 // module, if any.
488 Context.addModuleInitializer(ModuleScopes.back().Module, Import);
489 Mod->Imports.insert(Interface); // As if we imported it.
490 // Also save this as a shortcut to checking for decls in the interface
491 ThePrimaryInterface = Interface;
492 // If we made an implicit import of the module interface, then return the
493 // imported module decl.
494 return ConvertDeclToDeclGroup(Import);
495 }
496
497 return nullptr;
498}
499
502 SourceLocation PrivateLoc) {
503 // C++20 [basic.link]/2:
504 // A private-module-fragment shall appear only in a primary module
505 // interface unit.
506 switch (ModuleScopes.empty() ? Module::ExplicitGlobalModuleFragment
507 : ModuleScopes.back().Module->Kind) {
514 Diag(PrivateLoc, diag::err_private_module_fragment_not_module);
515 return nullptr;
516
518 Diag(PrivateLoc, diag::err_private_module_fragment_redefined);
519 Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition);
520 return nullptr;
521
523 Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface);
524 Diag(ModuleScopes.back().BeginLoc,
525 diag::note_not_module_interface_add_export)
526 << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
527 return nullptr;
528
530 break;
531 }
532
533 // FIXME: Check that this translation unit does not import any partitions;
534 // such imports would violate [basic.link]/2's "shall be the only module unit"
535 // restriction.
536
537 // We've finished the public fragment of the translation unit.
539
540 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
541 Module *PrivateModuleFragment =
542 Map.createPrivateModuleFragmentForInterfaceUnit(
543 ModuleScopes.back().Module, PrivateLoc);
544 assert(PrivateModuleFragment && "module creation should not fail");
545
546 // Enter the scope of the private module fragment.
547 ModuleScopes.push_back({});
548 ModuleScopes.back().BeginLoc = ModuleLoc;
549 ModuleScopes.back().Module = PrivateModuleFragment;
550 VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
551
552 // All declarations created from now on are scoped to the private module
553 // fragment (and are neither visible nor reachable in importers of the module
554 // interface).
555 auto *TU = Context.getTranslationUnitDecl();
556 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
557 TU->setLocalOwningModule(PrivateModuleFragment);
558
559 // FIXME: Consider creating an explicit representation of this declaration.
560 return nullptr;
561}
562
564 SourceLocation ExportLoc,
565 SourceLocation ImportLoc, ModuleIdPath Path,
566 bool IsPartition) {
567 assert((!IsPartition || getLangOpts().CPlusPlusModules) &&
568 "partition seen in non-C++20 code?");
569
570 // For a C++20 module name, flatten into a single identifier with the source
571 // location of the first component.
573
574 std::string ModuleName;
575 if (IsPartition) {
576 // We already checked that we are in a module purview in the parser.
577 assert(!ModuleScopes.empty() && "in a module purview, but no module?");
578 Module *NamedMod = ModuleScopes.back().Module;
579 // If we are importing into a partition, find the owning named module,
580 // otherwise, the name of the importing named module.
581 ModuleName = NamedMod->getPrimaryModuleInterfaceName().str();
582 ModuleName += ":";
583 ModuleName += ModuleLoader::getFlatNameFromPath(Path);
585 IdentifierLoc(Path[0].getLoc(), PP.getIdentifierInfo(ModuleName));
587 } else if (getLangOpts().CPlusPlusModules) {
588 ModuleName = ModuleLoader::getFlatNameFromPath(Path);
590 IdentifierLoc(Path[0].getLoc(), PP.getIdentifierInfo(ModuleName));
592 }
593
594 // Diagnose self-import before attempting a load.
595 // [module.import]/9
596 // A module implementation unit of a module M that is not a module partition
597 // shall not contain a module-import-declaration nominating M.
598 // (for an implementation, the module interface is imported implicitly,
599 // but that's handled in the module decl code).
600
601 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview() &&
602 getCurrentModule()->Name == ModuleName) {
603 Diag(ImportLoc, diag::err_module_self_import_cxx20)
604 << ModuleName << currentModuleIsImplementation();
605 return true;
606 }
607
609 ImportLoc, Path, Module::AllVisible, /*IsInclusionDirective=*/false);
610 if (!Mod)
611 return true;
612
613 if (!Mod->isInterfaceOrPartition() && !ModuleName.empty() &&
614 !getLangOpts().ObjC) {
615 Diag(ImportLoc, diag::err_module_import_non_interface_nor_parition)
616 << ModuleName;
617 return true;
618 }
619
620 return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
621}
622
623/// Determine whether \p D is lexically within an export-declaration.
624static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
625 for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
626 if (auto *ED = dyn_cast<ExportDecl>(DC))
627 return ED;
628 return nullptr;
629}
630
632 SourceLocation ExportLoc,
633 SourceLocation ImportLoc, Module *Mod,
634 ModuleIdPath Path) {
635 if (Mod->isHeaderUnit())
636 Diag(ImportLoc, diag::warn_experimental_header_unit);
637
638 if (Mod->isNamedModule())
639 makeTransitiveImportsVisible(getASTContext(), VisibleModules, Mod,
640 getCurrentModule(), ImportLoc);
641 else
642 VisibleModules.setVisible(Mod, ImportLoc);
643
645 "We can only import a partition unit in a named module.");
647 getCurrentModule()->isModuleInterfaceUnit())
648 Diag(ImportLoc,
649 diag::warn_import_implementation_partition_unit_in_interface_unit)
650 << Mod->Name;
651
652 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
653
654 // FIXME: we should support importing a submodule within a different submodule
655 // of the same top-level module. Until we do, make it an error rather than
656 // silently ignoring the import.
657 // FIXME: Should we warn on a redundant import of the current module?
658 if (Mod->isForBuilding(getLangOpts())) {
659 Diag(ImportLoc, getLangOpts().isCompilingModule()
660 ? diag::err_module_self_import
661 : diag::err_module_import_in_implementation)
663 }
664
665 SmallVector<SourceLocation, 2> IdentifierLocs;
666
667 if (Path.empty()) {
668 // If this was a header import, pad out with dummy locations.
669 // FIXME: Pass in and use the location of the header-name token in this
670 // case.
671 for (Module *ModCheck = Mod; ModCheck; ModCheck = ModCheck->Parent)
672 IdentifierLocs.push_back(SourceLocation());
673 } else if (getLangOpts().CPlusPlusModules && !Mod->Parent) {
674 // A single identifier for the whole name.
675 IdentifierLocs.push_back(Path[0].getLoc());
676 } else {
677 Module *ModCheck = Mod;
678 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
679 // If we've run out of module parents, just drop the remaining
680 // identifiers. We need the length to be consistent.
681 if (!ModCheck)
682 break;
683 ModCheck = ModCheck->Parent;
684
685 IdentifierLocs.push_back(Path[I].getLoc());
686 }
687 }
688
689 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
690 Mod, IdentifierLocs);
691 CurContext->addDecl(Import);
692
693 // Sequence initialization of the imported module before that of the current
694 // module, if any.
695 if (!ModuleScopes.empty())
696 Context.addModuleInitializer(ModuleScopes.back().Module, Import);
697
698 // A module (partition) implementation unit shall not be exported.
699 if (getLangOpts().CPlusPlusModules && ExportLoc.isValid() &&
701 Diag(ExportLoc, diag::err_export_partition_impl)
702 << SourceRange(ExportLoc, Path.back().getLoc());
703 } else if (ExportLoc.isValid() &&
704 (ModuleScopes.empty() || currentModuleIsImplementation())) {
705 // [module.interface]p1:
706 // An export-declaration shall inhabit a namespace scope and appear in the
707 // purview of a module interface unit.
708 Diag(ExportLoc, diag::err_export_not_in_module_interface);
709 } else if (!ModuleScopes.empty()) {
710 // Re-export the module if the imported module is exported.
711 // Note that we don't need to add re-exported module to Imports field
712 // since `Exports` implies the module is imported already.
713 if (ExportLoc.isValid() || getEnclosingExportDecl(Import))
714 getCurrentModule()->Exports.emplace_back(Mod, false);
715 else
716 getCurrentModule()->Imports.insert(Mod);
717 }
718
719 HadImportedNamedModules = true;
720
721 return Import;
722}
723
725 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
726 BuildModuleInclude(DirectiveLoc, Mod);
727}
728
730 // Determine whether we're in the #include buffer for a module. The #includes
731 // in that buffer do not qualify as module imports; they're just an
732 // implementation detail of us building the module.
733 //
734 // FIXME: Should we even get ActOnAnnotModuleInclude calls for those?
735 bool IsInModuleIncludes =
738
739 // If we are really importing a module (not just checking layering) due to an
740 // #include in the main file, synthesize an ImportDecl.
741 if (getLangOpts().Modules && !IsInModuleIncludes) {
744 DirectiveLoc, Mod,
745 DirectiveLoc);
746 if (!ModuleScopes.empty())
747 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
748 TU->addDecl(ImportD);
749 Consumer.HandleImplicitImportDecl(ImportD);
750 }
751
753 VisibleModules.setVisible(Mod, DirectiveLoc);
754
755 if (getLangOpts().isCompilingModule()) {
756 Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
757 getLangOpts().CurrentModule, DirectiveLoc, false, false);
758 (void)ThisModule;
759 // For named modules, the current module name is not known while parsing the
760 // global module fragment and lookupModule may return null.
761 assert((getLangOpts().getCompilingModule() ==
763 ThisModule) &&
764 "was expecting a module if building a Clang module");
765 }
766}
767
769 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
770
771 ModuleScopes.push_back({});
772 ModuleScopes.back().Module = Mod;
773 if (getLangOpts().ModulesLocalVisibility)
774 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
775
776 VisibleModules.setVisible(Mod, DirectiveLoc);
777
778 // The enclosing context is now part of this module.
779 // FIXME: Consider creating a child DeclContext to hold the entities
780 // lexically within the module.
781 if (getLangOpts().trackLocalOwningModule()) {
782 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
783 cast<Decl>(DC)->setModuleOwnershipKind(
784 getLangOpts().ModulesLocalVisibility
787 cast<Decl>(DC)->setLocalOwningModule(Mod);
788 }
789 }
790}
791
793 if (getLangOpts().ModulesLocalVisibility) {
794 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
795 // Leaving a module hides namespace names, so our visible namespace cache
796 // is now out of date.
797 VisibleNamespaceCache.clear();
798 }
799
800 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
801 "left the wrong module scope");
802 ModuleScopes.pop_back();
803
804 // We got to the end of processing a local module. Create an
805 // ImportDecl as we would for an imported module.
807 SourceLocation DirectiveLoc;
808 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
809 // We reached the end of a #included module header. Use the #include loc.
810 assert(File != getSourceManager().getMainFileID() &&
811 "end of submodule in main source file");
812 DirectiveLoc = getSourceManager().getIncludeLoc(File);
813 } else {
814 // We reached an EOM pragma. Use the pragma location.
815 DirectiveLoc = EomLoc;
816 }
817 BuildModuleInclude(DirectiveLoc, Mod);
818
819 // Any further declarations are in whatever module we returned to.
820 if (getLangOpts().trackLocalOwningModule()) {
821 // The parser guarantees that this is the same context that we entered
822 // the module within.
823 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
824 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
825 if (!getCurrentModule())
826 cast<Decl>(DC)->setModuleOwnershipKind(
828 }
829 }
830}
831
833 Module *Mod) {
834 // Bail if we're not allowed to implicitly import a module here.
835 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
836 VisibleModules.isVisible(Mod))
837 return;
838
839 // Create the implicit import declaration.
842 Loc, Mod, Loc);
843 TU->addDecl(ImportD);
844 Consumer.HandleImplicitImportDecl(ImportD);
845
846 // Make the module visible.
848 VisibleModules.setVisible(Mod, Loc);
849}
850
852 SourceLocation LBraceLoc) {
854
855 // Set this temporarily so we know the export-declaration was braced.
856 D->setRBraceLoc(LBraceLoc);
857
858 CurContext->addDecl(D);
859 PushDeclContext(S, D);
860
861 // C++2a [module.interface]p1:
862 // An export-declaration shall appear only [...] in the purview of a module
863 // interface unit. An export-declaration shall not appear directly or
864 // indirectly within [...] a private-module-fragment.
865 if (!getLangOpts().HLSL) {
866 if (!isCurrentModulePurview()) {
867 Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
868 D->setInvalidDecl();
869 return D;
870 } else if (currentModuleIsImplementation()) {
871 Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
872 Diag(ModuleScopes.back().BeginLoc,
873 diag::note_not_module_interface_add_export)
874 << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
875 D->setInvalidDecl();
876 return D;
877 } else if (ModuleScopes.back().Module->Kind ==
879 Diag(ExportLoc, diag::err_export_in_private_module_fragment);
880 Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
881 D->setInvalidDecl();
882 return D;
883 }
884 }
885
886 for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
887 if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
888 // An export-declaration shall not appear directly or indirectly within
889 // an unnamed namespace [...]
890 if (ND->isAnonymousNamespace()) {
891 Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
892 Diag(ND->getLocation(), diag::note_anonymous_namespace);
893 // Don't diagnose internal-linkage declarations in this region.
894 D->setInvalidDecl();
895 return D;
896 }
897
898 // A declaration is exported if it is [...] a namespace-definition
899 // that contains an exported declaration.
900 //
901 // Defer exporting the namespace until after we leave it, in order to
902 // avoid marking all subsequent declarations in the namespace as exported.
903 if (!getLangOpts().HLSL && !DeferredExportedNamespaces.insert(ND).second)
904 break;
905 }
906 }
907
908 // [...] its declaration or declaration-seq shall not contain an
909 // export-declaration.
910 if (auto *ED = getEnclosingExportDecl(D)) {
911 Diag(ExportLoc, diag::err_export_within_export);
912 if (ED->hasBraces())
913 Diag(ED->getLocation(), diag::note_export);
914 D->setInvalidDecl();
915 return D;
916 }
917
918 if (!getLangOpts().HLSL)
920
921 return D;
922}
923
924static bool checkExportedDecl(Sema &, Decl *, SourceLocation);
925
926/// Check that it's valid to export all the declarations in \p DC.
928 SourceLocation BlockStart) {
929 bool AllUnnamed = true;
930 for (auto *D : DC->decls())
931 AllUnnamed &= checkExportedDecl(S, D, BlockStart);
932 return AllUnnamed;
933}
934
935/// Check that it's valid to export \p D.
936static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
937
938 // HLSL: export declaration is valid only on functions
939 if (S.getLangOpts().HLSL) {
940 // Export-within-export was already diagnosed in ActOnStartExportDecl
942 S.Diag(D->getBeginLoc(), diag::err_hlsl_export_not_on_function);
943 D->setInvalidDecl();
944 return false;
945 }
946 }
947
948 // C++20 [module.interface]p3:
949 // [...] it shall not declare a name with internal linkage.
950 bool HasName = false;
951 if (auto *ND = dyn_cast<NamedDecl>(D)) {
952 // Don't diagnose anonymous union objects; we'll diagnose their members
953 // instead.
954 HasName = (bool)ND->getDeclName();
955 if (HasName && ND->getFormalLinkage() == Linkage::Internal) {
956 S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
957 if (BlockStart.isValid())
958 S.Diag(BlockStart, diag::note_export);
959 return false;
960 }
961 }
962
963 // C++2a [module.interface]p5:
964 // all entities to which all of the using-declarators ultimately refer
965 // shall have been introduced with a name having external linkage
966 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
967 NamedDecl *Target = USD->getUnderlyingDecl();
968 Linkage Lk = Target->getFormalLinkage();
969 if (Lk == Linkage::Internal || Lk == Linkage::Module) {
970 S.Diag(USD->getLocation(), diag::err_export_using_internal)
971 << (Lk == Linkage::Internal ? 0 : 1) << Target;
972 S.Diag(Target->getLocation(), diag::note_using_decl_target);
973 if (BlockStart.isValid())
974 S.Diag(BlockStart, diag::note_export);
975 return false;
976 }
977 }
978
979 // Recurse into namespace-scope DeclContexts. (Only namespace-scope
980 // declarations are exported).
981 if (auto *DC = dyn_cast<DeclContext>(D)) {
982 if (!isa<NamespaceDecl>(D))
983 return true;
984
985 if (auto *ND = dyn_cast<NamedDecl>(D)) {
986 if (!ND->getDeclName()) {
987 S.Diag(ND->getLocation(), diag::err_export_anon_ns_internal);
988 if (BlockStart.isValid())
989 S.Diag(BlockStart, diag::note_export);
990 return false;
991 } else if (!DC->decls().empty() &&
992 DC->getRedeclContext()->isFileContext()) {
993 return checkExportedDeclContext(S, DC, BlockStart);
994 }
995 }
996 }
997 return true;
998}
999
1001 auto *ED = cast<ExportDecl>(D);
1002 if (RBraceLoc.isValid())
1003 ED->setRBraceLoc(RBraceLoc);
1004
1006
1007 if (!D->isInvalidDecl()) {
1008 SourceLocation BlockStart =
1009 ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
1010 for (auto *Child : ED->decls()) {
1011 checkExportedDecl(*this, Child, BlockStart);
1012 if (auto *FD = dyn_cast<FunctionDecl>(Child)) {
1013 // [dcl.inline]/7
1014 // If an inline function or variable that is attached to a named module
1015 // is declared in a definition domain, it shall be defined in that
1016 // domain.
1017 // So, if the current declaration does not have a definition, we must
1018 // check at the end of the TU (or when the PMF starts) to see that we
1019 // have a definition at that point.
1020 if (FD->isInlineSpecified() && !FD->isDefined())
1021 PendingInlineFuncDecls.insert(FD);
1022 }
1023 }
1024 }
1025
1026 // Anything exported from a module should never be considered unused.
1027 for (auto *Exported : ED->decls())
1028 Exported->markUsed(getASTContext());
1029
1030 return D;
1031}
1032
1033Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc) {
1034 // We shouldn't create new global module fragment if there is already
1035 // one.
1036 if (!TheGlobalModuleFragment) {
1038 TheGlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
1039 BeginLoc, getCurrentModule());
1040 }
1041
1042 assert(TheGlobalModuleFragment && "module creation should not fail");
1043
1044 // Enter the scope of the global module.
1045 ModuleScopes.push_back({BeginLoc, TheGlobalModuleFragment,
1046 /*OuterVisibleModules=*/{}});
1047 VisibleModules.setVisible(TheGlobalModuleFragment, BeginLoc);
1048
1049 return TheGlobalModuleFragment;
1050}
1051
1052void Sema::PopGlobalModuleFragment() {
1053 assert(!ModuleScopes.empty() &&
1054 getCurrentModule()->isExplicitGlobalModule() &&
1055 "left the wrong module scope, which is not global module fragment");
1056 ModuleScopes.pop_back();
1057}
1058
1059Module *Sema::PushImplicitGlobalModuleFragment(SourceLocation BeginLoc) {
1060 if (!TheImplicitGlobalModuleFragment) {
1061 ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
1062 TheImplicitGlobalModuleFragment =
1065 }
1066 assert(TheImplicitGlobalModuleFragment && "module creation should not fail");
1067
1068 // Enter the scope of the global module.
1069 ModuleScopes.push_back({BeginLoc, TheImplicitGlobalModuleFragment,
1070 /*OuterVisibleModules=*/{}});
1071 VisibleModules.setVisible(TheImplicitGlobalModuleFragment, BeginLoc);
1072 return TheImplicitGlobalModuleFragment;
1073}
1074
1075void Sema::PopImplicitGlobalModuleFragment() {
1076 assert(!ModuleScopes.empty() &&
1077 getCurrentModule()->isImplicitGlobalModule() &&
1078 "left the wrong module scope, which is not global module fragment");
1079 ModuleScopes.pop_back();
1080}
1081
1082bool Sema::isCurrentModulePurview() const {
1083 if (!getCurrentModule())
1084 return false;
1085
1086 /// Does this Module scope describe part of the purview of a standard named
1087 /// C++ module?
1088 switch (getCurrentModule()->Kind) {
1095 return true;
1096 default:
1097 return false;
1098 }
1099}
1100
1101//===----------------------------------------------------------------------===//
1102// Checking Exposure in modules //
1103//===----------------------------------------------------------------------===//
1104
1105namespace {
1106class ExposureChecker {
1107public:
1108 ExposureChecker(Sema &S) : SemaRef(S) {}
1109
1110 bool checkExposure(const VarDecl *D, bool Diag);
1111 bool checkExposure(const CXXRecordDecl *D, bool Diag);
1112 bool checkExposure(const Stmt *S, bool Diag);
1113 bool checkExposure(const FunctionDecl *D, bool Diag);
1114 bool checkExposure(const NamedDecl *D, bool Diag);
1115 void checkExposureInContext(const DeclContext *DC);
1116 bool isExposureCandidate(const NamedDecl *D);
1117
1118 bool isTULocal(QualType Ty);
1119 bool isTULocal(const NamedDecl *ND);
1120 bool isTULocal(const Expr *E);
1121
1122 Sema &SemaRef;
1123
1124private:
1125 llvm::DenseSet<const NamedDecl *> ExposureSet;
1126 llvm::DenseSet<const NamedDecl *> KnownNonExposureSet;
1127 llvm::DenseSet<const NamedDecl *> CheckingDecls;
1128};
1129
1130bool ExposureChecker::isTULocal(QualType Ty) {
1131 // [basic.link]p15:
1132 // An entity is TU-local if it is
1133 // - a type, type alias, namespace, namespace alias, function, variable, or
1134 // template that
1135 // -- has internal linkage, or
1136 return Ty->getLinkage() == Linkage::Internal;
1137
1138 // TODO:
1139 // [basic.link]p15.2:
1140 // a type with no name that is defined outside a class-specifier, function
1141 // body, or initializer or is introduced by a defining-type-specifier that
1142 // is used to declare only TU-local entities,
1143}
1144
1145bool ExposureChecker::isTULocal(const NamedDecl *D) {
1146 if (!D)
1147 return false;
1148
1149 // [basic.link]p15:
1150 // An entity is TU-local if it is
1151 // - a type, type alias, namespace, namespace alias, function, variable, or
1152 // template that
1153 // -- has internal linkage, or
1155 return true;
1156
1157 if (D->isInAnonymousNamespace())
1158 return true;
1159
1160 // [basic.link]p15.1.2:
1161 // does not have a name with linkage and is declared, or introduced by a
1162 // lambda-expression, within the definition of a TU-local entity,
1164 if (auto *ND = dyn_cast<NamedDecl>(D->getDeclContext());
1165 ND && isTULocal(ND))
1166 return true;
1167
1168 // [basic.link]p15.3, p15.4:
1169 // - a specialization of a TU-local template,
1170 // - a specialization of a template with any TU-local template argument, or
1171 ArrayRef<TemplateArgument> TemplateArgs;
1172 NamedDecl *PrimaryTemplate = nullptr;
1173 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
1174 TemplateArgs = CTSD->getTemplateArgs().asArray();
1175 PrimaryTemplate = CTSD->getSpecializedTemplate();
1176 if (isTULocal(PrimaryTemplate))
1177 return true;
1178 } else if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
1179 TemplateArgs = VTSD->getTemplateArgs().asArray();
1180 PrimaryTemplate = VTSD->getSpecializedTemplate();
1181 if (isTULocal(PrimaryTemplate))
1182 return true;
1183 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1184 if (auto *TAList = FD->getTemplateSpecializationArgs())
1185 TemplateArgs = TAList->asArray();
1186
1187 PrimaryTemplate = FD->getPrimaryTemplate();
1188 if (isTULocal(PrimaryTemplate))
1189 return true;
1190 }
1191
1192 if (!PrimaryTemplate)
1193 // Following off, we only check for specializations.
1194 return false;
1195
1196 if (KnownNonExposureSet.count(D))
1197 return false;
1198
1199 for (auto &TA : TemplateArgs) {
1200 switch (TA.getKind()) {
1202 if (isTULocal(TA.getAsType()))
1203 return true;
1204 break;
1206 if (isTULocal(TA.getAsDecl()))
1207 return true;
1208 break;
1209 default:
1210 break;
1211 }
1212 }
1213
1214 // Avoid recursions.
1215 if (CheckingDecls.count(D))
1216 return false;
1217 CheckingDecls.insert(D);
1218 llvm::scope_exit RemoveCheckingDecls([&] { CheckingDecls.erase(D); });
1219
1220 // [basic.link]p15.5
1221 // - a specialization of a template whose (possibly instantiated) declaration
1222 // is an exposure.
1223 if (ExposureSet.count(PrimaryTemplate) ||
1224 checkExposure(PrimaryTemplate, /*Diag=*/false))
1225 return true;
1226
1227 // Avoid calling checkExposure again since it is expensive.
1228 KnownNonExposureSet.insert(D);
1229 return false;
1230}
1231
1232bool ExposureChecker::isTULocal(const Expr *E) {
1233 if (!E)
1234 return false;
1235
1236 // [basic.link]p16:
1237 // A value or object is TU-local if either
1238 // - it is of TU-local type,
1239 if (isTULocal(E->getType()))
1240 return true;
1241
1242 E = E->IgnoreParenImpCasts();
1243 // [basic.link]p16.2:
1244 // - it is, or is a pointer to, a TU-local function or the object associated
1245 // with a TU-local variable,
1246 // - it is an object of class or array type and any of its subobjects or any
1247 // of the objects or functions to which its non-static data members of
1248 // reference type refer is TU-local and is usable in constant expressions, or
1249 // FIXME: But how can we know the value of pointers or arrays at compile time?
1250 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
1251 if (auto *FD = dyn_cast_or_null<FunctionDecl>(DRE->getFoundDecl()))
1252 return isTULocal(FD);
1253 else if (auto *VD = dyn_cast_or_null<VarDecl>(DRE->getFoundDecl()))
1254 return isTULocal(VD);
1255 else if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(DRE->getFoundDecl()))
1256 return isTULocal(RD);
1257 }
1258
1259 // TODO:
1260 // [basic.link]p16.4:
1261 // it is a reflection value that represents...
1262
1263 return false;
1264}
1265
1266bool ExposureChecker::isExposureCandidate(const NamedDecl *D) {
1267 if (!D)
1268 return false;
1269
1270 // [basic.link]p17:
1271 // If a (possibly instantiated) declaration of, or a deduction guide for,
1272 // a non-TU-local entity in a module interface unit
1273 // (outside the private-module-fragment, if any) or
1274 // module partition is an exposure, the program is ill-formed.
1275 Module *M = D->getOwningModule();
1276 if (!M)
1277 return false;
1278 // If M is implicit global module, the declaration must be in the purview of
1279 // a module unit.
1280 if (M->isImplicitGlobalModule()) {
1281 M = M->Parent;
1282 assert(M && "Implicit global module must have a parent");
1283 }
1284
1285 if (!M->isInterfaceOrPartition())
1286 return false;
1287
1288 if (D->isImplicit())
1289 return false;
1290
1291 // [basic.link]p14:
1292 // A declaration is an exposure if it either names a TU-local entity
1293 // (defined below), ignoring:
1294 // ...
1295 // - friend declarations in a class definition
1296 if (D->getFriendObjectKind() &&
1298 return false;
1299
1300 return true;
1301}
1302
1303bool ExposureChecker::checkExposure(const NamedDecl *D, bool Diag) {
1304 if (!isExposureCandidate(D))
1305 return false;
1306
1307 if (auto *FD = dyn_cast<FunctionDecl>(D))
1308 return checkExposure(FD, Diag);
1309 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
1310 return checkExposure(FTD->getTemplatedDecl(), Diag);
1311
1312 if (auto *VD = dyn_cast<VarDecl>(D))
1313 return checkExposure(VD, Diag);
1314 if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
1315 return checkExposure(VTD->getTemplatedDecl(), Diag);
1316
1317 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1318 return checkExposure(RD, Diag);
1319
1320 if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
1321 return checkExposure(CTD->getTemplatedDecl(), Diag);
1322
1323 return false;
1324}
1325
1326bool ExposureChecker::checkExposure(const FunctionDecl *FD, bool Diag) {
1327 bool IsExposure = false;
1328 if (isTULocal(FD->getReturnType())) {
1329 IsExposure = true;
1330 if (Diag)
1331 SemaRef.Diag(FD->getReturnTypeSourceRange().getBegin(),
1332 diag::warn_exposure)
1333 << FD->getReturnType();
1334 }
1335
1336 for (ParmVarDecl *Parms : FD->parameters())
1337 if (isTULocal(Parms->getType())) {
1338 IsExposure = true;
1339 if (Diag)
1340 SemaRef.Diag(Parms->getLocation(), diag::warn_exposure)
1341 << Parms->getType();
1342 }
1343
1344 bool IsImplicitInstantiation =
1346
1347 // [basic.link]p14:
1348 // A declaration is an exposure if it either names a TU-local entity
1349 // (defined below), ignoring:
1350 // - the function-body for a non-inline function or function template
1351 // (but not the deduced return
1352 // type for a (possibly instantiated) definition of a function with a
1353 // declared return type that uses a placeholder type
1354 // ([dcl.spec.auto])),
1355 Diag &=
1356 (FD->isInlined() || IsImplicitInstantiation) && !FD->isDependentContext();
1357
1358 IsExposure |= checkExposure(FD->getBody(), Diag);
1359 if (IsExposure)
1360 ExposureSet.insert(FD);
1361
1362 return IsExposure;
1363}
1364
1365bool ExposureChecker::checkExposure(const VarDecl *VD, bool Diag) {
1366 bool IsExposure = false;
1367 // [basic.link]p14:
1368 // A declaration is an exposure if it either names a TU-local entity (defined
1369 // below), ignoring:
1370 // ...
1371 // or defines a constexpr variable initialized to a TU-local value (defined
1372 // below).
1373 if (VD->isConstexpr() && isTULocal(VD->getInit())) {
1374 IsExposure = true;
1375 if (Diag)
1376 SemaRef.Diag(VD->getInit()->getExprLoc(), diag::warn_exposure)
1377 << VD->getInit();
1378 }
1379
1380 if (isTULocal(VD->getType())) {
1381 IsExposure = true;
1382 if (Diag)
1383 SemaRef.Diag(VD->getLocation(), diag::warn_exposure) << VD->getType();
1384 }
1385
1386 // [basic.link]p14:
1387 // ..., ignoring:
1388 // - the initializer for a variable or variable template (but not the
1389 // variable's type),
1390 //
1391 // Note: although the spec says to ignore the initializer for all variable,
1392 // for the code we generated now for inline variables, it is dangerous if the
1393 // initializer of an inline variable is TULocal.
1394 Diag &= !VD->getDeclContext()->isDependentContext() && VD->isInline();
1395 IsExposure |= checkExposure(VD->getInit(), Diag);
1396 if (IsExposure)
1397 ExposureSet.insert(VD);
1398
1399 return IsExposure;
1400}
1401
1402bool ExposureChecker::checkExposure(const CXXRecordDecl *RD, bool Diag) {
1403 if (!RD->hasDefinition())
1404 return false;
1405
1406 bool IsExposure = false;
1407 for (CXXMethodDecl *Method : RD->methods())
1408 IsExposure |= checkExposure(Method, Diag);
1409
1410 for (FieldDecl *FD : RD->fields()) {
1411 if (isTULocal(FD->getType())) {
1412 IsExposure = true;
1413 if (Diag)
1414 SemaRef.Diag(FD->getLocation(), diag::warn_exposure) << FD->getType();
1415 }
1416 }
1417
1418 for (const CXXBaseSpecifier &Base : RD->bases()) {
1419 if (isTULocal(Base.getType())) {
1420 IsExposure = true;
1421 if (Diag)
1422 SemaRef.Diag(Base.getBaseTypeLoc(), diag::warn_exposure)
1423 << Base.getType();
1424 }
1425 }
1426
1427 if (IsExposure)
1428 ExposureSet.insert(RD);
1429
1430 return IsExposure;
1431}
1432
1433class ReferenceTULocalChecker : public DynamicRecursiveASTVisitor {
1434public:
1435 using CallbackTy = std::function<void(DeclRefExpr *, ValueDecl *)>;
1436
1437 ReferenceTULocalChecker(ExposureChecker &C, CallbackTy &&Callback)
1438 : Checker(C), Callback(std::move(Callback)) {}
1439
1440 bool VisitDeclRefExpr(DeclRefExpr *DRE) override {
1441 ValueDecl *Referenced = DRE->getDecl();
1442 if (!Referenced)
1443 return true;
1444
1445 if (!Checker.isTULocal(Referenced))
1446 // We don't care if the referenced declaration is not TU-local.
1447 return true;
1448
1449 Qualifiers Qual = DRE->getType().getQualifiers();
1450 // [basic.link]p14:
1451 // A declaration is an exposure if it either names a TU-local entity
1452 // (defined below), ignoring:
1453 // ...
1454 // - any reference to a non-volatile const object ...
1455 if (Qual.hasConst() && !Qual.hasVolatile())
1456 return true;
1457
1458 // [basic.link]p14:
1459 // ..., ignoring:
1460 // ...
1461 // (p14.4) - ... or reference with internal or no linkage initialized with
1462 // a constant expression that is not an odr-use
1463 ASTContext &Context = Referenced->getASTContext();
1464 Linkage L = Referenced->getLinkageInternal();
1465 if (DRE->isNonOdrUse() && (L == Linkage::Internal || L == Linkage::None))
1466 if (auto *VD = dyn_cast<VarDecl>(Referenced);
1467 VD && VD->getInit() && !VD->getInit()->isValueDependent() &&
1468 VD->getInit()->isConstantInitializer(Context, /*IsForRef=*/false))
1469 return true;
1470
1471 Callback(DRE, Referenced);
1472 return true;
1473 }
1474
1475 ExposureChecker &Checker;
1476 CallbackTy Callback;
1477};
1478
1479bool ExposureChecker::checkExposure(const Stmt *S, bool Diag) {
1480 if (!S)
1481 return false;
1482
1483 bool HasReferencedTULocals = false;
1484 ReferenceTULocalChecker Checker(
1485 *this, [this, &HasReferencedTULocals, Diag](DeclRefExpr *DRE,
1486 ValueDecl *Referenced) {
1487 if (Diag) {
1488 SemaRef.Diag(DRE->getExprLoc(), diag::warn_exposure) << Referenced;
1489 }
1490 HasReferencedTULocals = true;
1491 });
1492 Checker.TraverseStmt(const_cast<Stmt *>(S));
1493 return HasReferencedTULocals;
1494}
1495
1496void ExposureChecker::checkExposureInContext(const DeclContext *DC) {
1497 for (auto *TopD : DC->noload_decls()) {
1498 if (auto *Export = dyn_cast<ExportDecl>(TopD)) {
1499 checkExposureInContext(Export);
1500 continue;
1501 }
1502
1503 if (auto *LinkageSpec = dyn_cast<LinkageSpecDecl>(TopD)) {
1504 checkExposureInContext(LinkageSpec);
1505 continue;
1506 }
1507
1508 auto *TopND = dyn_cast<NamedDecl>(TopD);
1509 if (!TopND)
1510 continue;
1511
1512 if (auto *Namespace = dyn_cast<NamespaceDecl>(TopND)) {
1513 checkExposureInContext(Namespace);
1514 continue;
1515 }
1516
1517 // [basic.link]p17:
1518 // If a (possibly instantiated) declaration of, or a deduction guide for,
1519 // a non-TU-local entity in a module interface unit
1520 // (outside the private-module-fragment, if any) or
1521 // module partition is an exposure, the program is ill-formed.
1522 if (!TopND->isFromASTFile() && isExposureCandidate(TopND) &&
1523 !isTULocal(TopND))
1524 checkExposure(TopND, /*Diag=*/true);
1525 }
1526}
1527
1528} // namespace
1529
1530void Sema::checkExposure(const TranslationUnitDecl *TU) {
1531 if (!TU)
1532 return;
1533
1534 ExposureChecker Checker(*this);
1535
1536 Module *M = TU->getOwningModule();
1537 if (M && M->isInterfaceOrPartition())
1538 Checker.checkExposureInContext(TU);
1539
1540 // [basic.link]p18:
1541 // If a declaration that appears in one translation unit names a TU-local
1542 // entity declared in another translation unit that is not a header unit,
1543 // the program is ill-formed.
1544 for (auto FDAndInstantiationLocPair : PendingCheckReferenceForTULocal) {
1545 FunctionDecl *FD = FDAndInstantiationLocPair.first;
1546 SourceLocation PointOfInstantiation = FDAndInstantiationLocPair.second;
1547
1548 if (!FD->hasBody())
1549 continue;
1550
1551 ReferenceTULocalChecker(Checker, [&, this](DeclRefExpr *DRE,
1552 ValueDecl *Referenced) {
1553 // A "defect" in current implementation. Now an implicit instantiation of
1554 // a template, the instantiation is considered to be in the same module
1555 // unit as the template instead of the module unit where the instantiation
1556 // happens.
1557 //
1558 // See test/Modules/Exposre-2.cppm for example.
1559 if (!Referenced->isFromASTFile())
1560 return;
1561
1562 if (!Referenced->isInAnotherModuleUnit())
1563 return;
1564
1565 // This is not standard conforming. But given there are too many static
1566 // (inline) functions in headers in existing code, it is more user
1567 // friendly to ignore them temporarily now. maybe we can have another flag
1568 // for this.
1569 if (Referenced->getOwningModule()->isExplicitGlobalModule() &&
1570 isa<FunctionDecl>(Referenced))
1571 return;
1572
1573 Diag(PointOfInstantiation,
1574 diag::warn_reference_tu_local_entity_in_other_tu)
1575 << FD << Referenced
1576 << Referenced->getOwningModule()->getTopLevelModuleName();
1577 }).TraverseStmt(FD->getBody());
1578 }
1579}
1580
1581void Sema::checkReferenceToTULocalFromOtherTU(
1582 FunctionDecl *FD, SourceLocation PointOfInstantiation) {
1583 // Checking if a declaration have any reference to TU-local entities in other
1584 // TU is expensive. Try to avoid it as much as possible.
1585 if (!FD || !HadImportedNamedModules)
1586 return;
1587
1588 PendingCheckReferenceForTULocal.push_back(
1589 std::make_pair(FD, PointOfInstantiation));
1590}
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:220
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:1270
ValueDecl * getDecl()
Definition Expr.h:1338
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1468
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:546
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: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: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:439
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:5131
static ExportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExportLoc)
Definition Decl.cpp:6085
void setRBraceLoc(SourceLocation L)
Definition Decl.h:5151
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:3089
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:3346
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
QualType getType() const
Definition Expr.h:144
Represents a member of a struct/union/class.
Definition Decl.h:3160
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:103
Represents a function declaration or definition.
Definition Decl.h:2000
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3279
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4024
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2921
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4417
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3199
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:5052
static ImportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, Module *Imported, ArrayRef< SourceLocation > IdentifierLocs)
Create a new module import declaration.
Definition Decl.cpp:6041
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:6049
@ 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.
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: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 isImplicitGlobalModule() const
Definition Module.h:245
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: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:1790
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:8332
bool hasConst() const
Definition TypeBase.h:457
bool hasVolatile() const
Definition TypeBase.h:467
field_range fields() const
Definition Decl.h:4527
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:856
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:1242
@ PartitionImplementation
'module X:Y;'
Definition Sema.h:9900
@ Interface
'export module X;'
Definition Sema.h:9897
@ Implementation
'module X;'
Definition Sema.h:9898
@ PartitionInterface
'export module X:Y;'
Definition Sema.h:9899
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:13617
ASTContext & Context
Definition Sema.h:1288
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:9884
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:1493
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:79
ASTContext & getASTContext() const
Definition Sema.h:927
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:920
Preprocessor & PP
Definition Sema.h:1287
SemaHLSL & HLSL()
Definition Sema.h:1458
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...
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:9879
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1421
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:925
void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
bool isModuleVisible(const Module *M, bool ModulePrivate=false)
bool isSFINAEContext() const
Definition Sema.h:13696
ASTConsumer & Consumer
Definition Sema.h:1289
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition Sema.h:9906
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9907
@ GlobalFragment
after 'module;' but before 'module X;'
Definition Sema.h:9908
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
Definition Sema.h:9915
@ ImportAllowed
after 'module X;' but before any non-import decl.
Definition Sema.h:9909
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:1279
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:651
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:86
@ 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:4892
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:926
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1569
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1551
const Expr * getInit() const
Definition Decl.h:1368
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:489
@ Normal
A normal translation unit fragment.
Definition Sema.h:493
@ 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