Bug Summary

File:clang/lib/Sema/SemaModule.cpp
Warning:line 577, column 3
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaModule.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaModule.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaModule.cpp

1//===--- SemaModule.cpp - Semantic Analysis for Modules -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for modules (C++ modules syntax,
10// Objective-C modules syntax, and Clang header modules).
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTConsumer.h"
15#include "clang/Lex/HeaderSearch.h"
16#include "clang/Lex/Preprocessor.h"
17#include "clang/Sema/SemaInternal.h"
18
19using namespace clang;
20using namespace sema;
21
22static void checkModuleImportContext(Sema &S, Module *M,
23 SourceLocation ImportLoc, DeclContext *DC,
24 bool FromInclude = false) {
25 SourceLocation ExternCLoc;
26
27 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
28 switch (LSD->getLanguage()) {
29 case LinkageSpecDecl::lang_c:
30 if (ExternCLoc.isInvalid())
31 ExternCLoc = LSD->getBeginLoc();
32 break;
33 case LinkageSpecDecl::lang_cxx:
34 break;
35 }
36 DC = LSD->getParent();
37 }
38
39 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
40 DC = DC->getParent();
41
42 if (!isa<TranslationUnitDecl>(DC)) {
43 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
44 ? diag::ext_module_import_not_at_top_level_noop
45 : diag::err_module_import_not_at_top_level_fatal)
46 << M->getFullModuleName() << DC;
47 S.Diag(cast<Decl>(DC)->getBeginLoc(),
48 diag::note_module_import_not_at_top_level)
49 << DC;
50 } else if (!M->IsExternC && ExternCLoc.isValid()) {
51 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
52 << M->getFullModuleName();
53 S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
54 }
55}
56
57Sema::DeclGroupPtrTy
58Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc) {
59 if (!ModuleScopes.empty() &&
60 ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment) {
61 // Under -std=c++2a -fmodules-ts, we can find an explicit 'module;' after
62 // already implicitly entering the global module fragment. That's OK.
63 assert(getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS &&((getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS
&& "unexpectedly encountered multiple global module fragment decls"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS && \"unexpectedly encountered multiple global module fragment decls\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaModule.cpp"
, 64, __PRETTY_FUNCTION__))
64 "unexpectedly encountered multiple global module fragment decls")((getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS
&& "unexpectedly encountered multiple global module fragment decls"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS && \"unexpectedly encountered multiple global module fragment decls\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaModule.cpp"
, 64, __PRETTY_FUNCTION__))
;
65 ModuleScopes.back().BeginLoc = ModuleLoc;
66 return nullptr;
67 }
68
69 // We start in the global module; all those declarations are implicitly
70 // module-private (though they do not have module linkage).
71 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
72 auto *GlobalModule = Map.createGlobalModuleFragmentForModuleUnit(ModuleLoc);
73 assert(GlobalModule && "module creation should not fail")((GlobalModule && "module creation should not fail") ?
static_cast<void> (0) : __assert_fail ("GlobalModule && \"module creation should not fail\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaModule.cpp"
, 73, __PRETTY_FUNCTION__))
;
74
75 // Enter the scope of the global module.
76 ModuleScopes.push_back({});
77 ModuleScopes.back().BeginLoc = ModuleLoc;
78 ModuleScopes.back().Module = GlobalModule;
79 VisibleModules.setVisible(GlobalModule, ModuleLoc);
80
81 // All declarations created from now on are owned by the global module.
82 auto *TU = Context.getTranslationUnitDecl();
83 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
84 TU->setLocalOwningModule(GlobalModule);
85
86 // FIXME: Consider creating an explicit representation of this declaration.
87 return nullptr;
88}
89
90Sema::DeclGroupPtrTy
91Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc,
92 ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl) {
93 assert((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) &&(((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules)
&& "should only have module decl in Modules TS or C++20"
) ? static_cast<void> (0) : __assert_fail ("(getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) && \"should only have module decl in Modules TS or C++20\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaModule.cpp"
, 94, __PRETTY_FUNCTION__))
94 "should only have module decl in Modules TS or C++20")(((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules)
&& "should only have module decl in Modules TS or C++20"
) ? static_cast<void> (0) : __assert_fail ("(getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) && \"should only have module decl in Modules TS or C++20\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaModule.cpp"
, 94, __PRETTY_FUNCTION__))
;
95
96 // A module implementation unit requires that we are not compiling a module
97 // of any kind. A module interface unit requires that we are not compiling a
98 // module map.
99 switch (getLangOpts().getCompilingModule()) {
100 case LangOptions::CMK_None:
101 // It's OK to compile a module interface as a normal translation unit.
102 break;
103
104 case LangOptions::CMK_ModuleInterface:
105 if (MDK != ModuleDeclKind::Implementation)
106 break;
107
108 // We were asked to compile a module interface unit but this is a module
109 // implementation unit. That indicates the 'export' is missing.
110 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
111 << FixItHint::CreateInsertion(ModuleLoc, "export ");
112 MDK = ModuleDeclKind::Interface;
113 break;
114
115 case LangOptions::CMK_ModuleMap:
116 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
117 return nullptr;
118
119 case LangOptions::CMK_HeaderModule:
120 Diag(ModuleLoc, diag::err_module_decl_in_header_module);
121 return nullptr;
122 }
123
124 assert(ModuleScopes.size() <= 1 && "expected to be at global module scope")((ModuleScopes.size() <= 1 && "expected to be at global module scope"
) ? static_cast<void> (0) : __assert_fail ("ModuleScopes.size() <= 1 && \"expected to be at global module scope\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaModule.cpp"
, 124, __PRETTY_FUNCTION__))
;
125
126 // FIXME: Most of this work should be done by the preprocessor rather than
127 // here, in order to support macro import.
128
129 // Only one module-declaration is permitted per source file.
130 if (!ModuleScopes.empty() &&
131 ModuleScopes.back().Module->isModulePurview()) {
132 Diag(ModuleLoc, diag::err_module_redeclaration);
133 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
134 diag::note_prev_module_declaration);
135 return nullptr;
136 }
137
138 // Find the global module fragment we're adopting into this module, if any.
139 Module *GlobalModuleFragment = nullptr;
140 if (!ModuleScopes.empty() &&
141 ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment)
142 GlobalModuleFragment = ModuleScopes.back().Module;
143
144 // In C++20, the module-declaration must be the first declaration if there
145 // is no global module fragment.
146 if (getLangOpts().CPlusPlusModules && !IsFirstDecl && !GlobalModuleFragment) {
147 Diag(ModuleLoc, diag::err_module_decl_not_at_start);
148 SourceLocation BeginLoc =
149 ModuleScopes.empty()
150 ? SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID())
151 : ModuleScopes.back().BeginLoc;
152 if (BeginLoc.isValid()) {
153 Diag(BeginLoc, diag::note_global_module_introducer_missing)
154 << FixItHint::CreateInsertion(BeginLoc, "module;\n");
155 }
156 }
157
158 // Flatten the dots in a module name. Unlike Clang's hierarchical module map
159 // modules, the dots here are just another character that can appear in a
160 // module name.
161 std::string ModuleName;
162 for (auto &Piece : Path) {
163 if (!ModuleName.empty())
164 ModuleName += ".";
165 ModuleName += Piece.first->getName();
166 }
167
168 // If a module name was explicitly specified on the command line, it must be
169 // correct.
170 if (!getLangOpts().CurrentModule.empty() &&
171 getLangOpts().CurrentModule != ModuleName) {
172 Diag(Path.front().second, diag::err_current_module_name_mismatch)
173 << SourceRange(Path.front().second, Path.back().second)
174 << getLangOpts().CurrentModule;
175 return nullptr;
176 }
177 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
178
179 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
180 Module *Mod;
181
182 switch (MDK) {
183 case ModuleDeclKind::Interface: {
184 // We can't have parsed or imported a definition of this module or parsed a
185 // module map defining it already.
186 if (auto *M = Map.findModule(ModuleName)) {
187 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
188 if (M->DefinitionLoc.isValid())
189 Diag(M->DefinitionLoc, diag::note_prev_module_definition);
190 else if (const auto *FE = M->getASTFile())
191 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
192 << FE->getName();
193 Mod = M;
194 break;
195 }
196
197 // Create a Module for the module that we're defining.
198 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
199 GlobalModuleFragment);
200 assert(Mod && "module creation should not fail")((Mod && "module creation should not fail") ? static_cast
<void> (0) : __assert_fail ("Mod && \"module creation should not fail\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaModule.cpp"
, 200, __PRETTY_FUNCTION__))
;
201 break;
202 }
203
204 case ModuleDeclKind::Implementation:
205 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
206 PP.getIdentifierInfo(ModuleName), Path[0].second);
207 Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
208 Module::AllVisible,
209 /*IsInclusionDirective=*/false);
210 if (!Mod) {
211 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
212 // Create an empty module interface unit for error recovery.
213 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
214 GlobalModuleFragment);
215 }
216 break;
217 }
218
219 if (!GlobalModuleFragment) {
220 ModuleScopes.push_back({});
221 if (getLangOpts().ModulesLocalVisibility)
222 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
223 } else {
224 // We're done with the global module fragment now.
225 ActOnEndOfTranslationUnitFragment(TUFragmentKind::Global);
226 }
227
228 // Switch from the global module fragment (if any) to the named module.
229 ModuleScopes.back().BeginLoc = StartLoc;
230 ModuleScopes.back().Module = Mod;
231 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
232 VisibleModules.setVisible(Mod, ModuleLoc);
233
234 // From now on, we have an owning module for all declarations we see.
235 // However, those declarations are module-private unless explicitly
236 // exported.
237 auto *TU = Context.getTranslationUnitDecl();
238 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
239 TU->setLocalOwningModule(Mod);
240
241 // FIXME: Create a ModuleDecl.
242 return nullptr;
243}
244
245Sema::DeclGroupPtrTy
246Sema::ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
247 SourceLocation PrivateLoc) {
248 // C++20 [basic.link]/2:
249 // A private-module-fragment shall appear only in a primary module
250 // interface unit.
251 switch (ModuleScopes.empty() ? Module::GlobalModuleFragment
252 : ModuleScopes.back().Module->Kind) {
253 case Module::ModuleMapModule:
254 case Module::GlobalModuleFragment:
255 Diag(PrivateLoc, diag::err_private_module_fragment_not_module);
256 return nullptr;
257
258 case Module::PrivateModuleFragment:
259 Diag(PrivateLoc, diag::err_private_module_fragment_redefined);
260 Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition);
261 return nullptr;
262
263 case Module::ModuleInterfaceUnit:
264 break;
265 }
266
267 if (!ModuleScopes.back().ModuleInterface) {
268 Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface);
269 Diag(ModuleScopes.back().BeginLoc,
270 diag::note_not_module_interface_add_export)
271 << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
272 return nullptr;
273 }
274
275 // FIXME: Check this isn't a module interface partition.
276 // FIXME: Check that this translation unit does not import any partitions;
277 // such imports would violate [basic.link]/2's "shall be the only module unit"
278 // restriction.
279
280 // We've finished the public fragment of the translation unit.
281 ActOnEndOfTranslationUnitFragment(TUFragmentKind::Normal);
282
283 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
284 Module *PrivateModuleFragment =
285 Map.createPrivateModuleFragmentForInterfaceUnit(
286 ModuleScopes.back().Module, PrivateLoc);
287 assert(PrivateModuleFragment && "module creation should not fail")((PrivateModuleFragment && "module creation should not fail"
) ? static_cast<void> (0) : __assert_fail ("PrivateModuleFragment && \"module creation should not fail\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaModule.cpp"
, 287, __PRETTY_FUNCTION__))
;
288
289 // Enter the scope of the private module fragment.
290 ModuleScopes.push_back({});
291 ModuleScopes.back().BeginLoc = ModuleLoc;
292 ModuleScopes.back().Module = PrivateModuleFragment;
293 ModuleScopes.back().ModuleInterface = true;
294 VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
295
296 // All declarations created from now on are scoped to the private module
297 // fragment (and are neither visible nor reachable in importers of the module
298 // interface).
299 auto *TU = Context.getTranslationUnitDecl();
300 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
301 TU->setLocalOwningModule(PrivateModuleFragment);
302
303 // FIXME: Consider creating an explicit representation of this declaration.
304 return nullptr;
305}
306
307DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
308 SourceLocation ExportLoc,
309 SourceLocation ImportLoc,
310 ModuleIdPath Path) {
311 // Flatten the module path for a Modules TS module name.
312 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
313 if (getLangOpts().ModulesTS) {
314 std::string ModuleName;
315 for (auto &Piece : Path) {
316 if (!ModuleName.empty())
317 ModuleName += ".";
318 ModuleName += Piece.first->getName();
319 }
320 ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
321 Path = ModuleIdPath(ModuleNameLoc);
322 }
323
324 Module *Mod =
325 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
326 /*IsInclusionDirective=*/false);
327 if (!Mod)
328 return true;
329
330 return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
331}
332
333/// Determine whether \p D is lexically within an export-declaration.
334static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
335 for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
336 if (auto *ED = dyn_cast<ExportDecl>(DC))
337 return ED;
338 return nullptr;
339}
340
341DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
342 SourceLocation ExportLoc,
343 SourceLocation ImportLoc,
344 Module *Mod, ModuleIdPath Path) {
345 VisibleModules.setVisible(Mod, ImportLoc);
346
347 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
348
349 // FIXME: we should support importing a submodule within a different submodule
350 // of the same top-level module. Until we do, make it an error rather than
351 // silently ignoring the import.
352 // Import-from-implementation is valid in the Modules TS. FIXME: Should we
353 // warn on a redundant import of the current module?
354 // FIXME: Import of a module from an implementation partition of the same
355 // module is permitted.
356 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
357 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) {
358 Diag(ImportLoc, getLangOpts().isCompilingModule()
359 ? diag::err_module_self_import
360 : diag::err_module_import_in_implementation)
361 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
362 }
363
364 SmallVector<SourceLocation, 2> IdentifierLocs;
365 Module *ModCheck = Mod;
366 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
367 // If we've run out of module parents, just drop the remaining identifiers.
368 // We need the length to be consistent.
369 if (!ModCheck)
370 break;
371 ModCheck = ModCheck->Parent;
372
373 IdentifierLocs.push_back(Path[I].second);
374 }
375
376 // If this was a header import, pad out with dummy locations.
377 // FIXME: Pass in and use the location of the header-name token in this case.
378 if (Path.empty()) {
379 for (; ModCheck; ModCheck = ModCheck->Parent) {
380 IdentifierLocs.push_back(SourceLocation());
381 }
382 }
383
384 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
385 Mod, IdentifierLocs);
386 CurContext->addDecl(Import);
387
388 // Sequence initialization of the imported module before that of the current
389 // module, if any.
390 if (!ModuleScopes.empty())
391 Context.addModuleInitializer(ModuleScopes.back().Module, Import);
392
393 // Re-export the module if needed.
394 if (!ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) {
395 if (ExportLoc.isValid() || getEnclosingExportDecl(Import))
396 getCurrentModule()->Exports.emplace_back(Mod, false);
397 } else if (ExportLoc.isValid()) {
398 Diag(ExportLoc, diag::err_export_not_in_module_interface);
399 }
400
401 return Import;
402}
403
404void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
405 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
406 BuildModuleInclude(DirectiveLoc, Mod);
407}
408
409void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
410 // Determine whether we're in the #include buffer for a module. The #includes
411 // in that buffer do not qualify as module imports; they're just an
412 // implementation detail of us building the module.
413 //
414 // FIXME: Should we even get ActOnModuleInclude calls for those?
415 bool IsInModuleIncludes =
416 TUKind == TU_Module &&
417 getSourceManager().isWrittenInMainFile(DirectiveLoc);
418
419 bool ShouldAddImport = !IsInModuleIncludes;
420
421 // If this module import was due to an inclusion directive, create an
422 // implicit import declaration to capture it in the AST.
423 if (ShouldAddImport) {
424 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
425 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
426 DirectiveLoc, Mod,
427 DirectiveLoc);
428 if (!ModuleScopes.empty())
429 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
430 TU->addDecl(ImportD);
431 Consumer.HandleImplicitImportDecl(ImportD);
432 }
433
434 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
435 VisibleModules.setVisible(Mod, DirectiveLoc);
436}
437
438void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
439 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
440
441 ModuleScopes.push_back({});
442 ModuleScopes.back().Module = Mod;
443 if (getLangOpts().ModulesLocalVisibility)
444 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
445
446 VisibleModules.setVisible(Mod, DirectiveLoc);
447
448 // The enclosing context is now part of this module.
449 // FIXME: Consider creating a child DeclContext to hold the entities
450 // lexically within the module.
451 if (getLangOpts().trackLocalOwningModule()) {
452 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
453 cast<Decl>(DC)->setModuleOwnershipKind(
454 getLangOpts().ModulesLocalVisibility
455 ? Decl::ModuleOwnershipKind::VisibleWhenImported
456 : Decl::ModuleOwnershipKind::Visible);
457 cast<Decl>(DC)->setLocalOwningModule(Mod);
458 }
459 }
460}
461
462void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
463 if (getLangOpts().ModulesLocalVisibility) {
464 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
465 // Leaving a module hides namespace names, so our visible namespace cache
466 // is now out of date.
467 VisibleNamespaceCache.clear();
468 }
469
470 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&((!ModuleScopes.empty() && ModuleScopes.back().Module
== Mod && "left the wrong module scope") ? static_cast
<void> (0) : __assert_fail ("!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && \"left the wrong module scope\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaModule.cpp"
, 471, __PRETTY_FUNCTION__))
471 "left the wrong module scope")((!ModuleScopes.empty() && ModuleScopes.back().Module
== Mod && "left the wrong module scope") ? static_cast
<void> (0) : __assert_fail ("!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && \"left the wrong module scope\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaModule.cpp"
, 471, __PRETTY_FUNCTION__))
;
472 ModuleScopes.pop_back();
473
474 // We got to the end of processing a local module. Create an
475 // ImportDecl as we would for an imported module.
476 FileID File = getSourceManager().getFileID(EomLoc);
477 SourceLocation DirectiveLoc;
478 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
479 // We reached the end of a #included module header. Use the #include loc.
480 assert(File != getSourceManager().getMainFileID() &&((File != getSourceManager().getMainFileID() && "end of submodule in main source file"
) ? static_cast<void> (0) : __assert_fail ("File != getSourceManager().getMainFileID() && \"end of submodule in main source file\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaModule.cpp"
, 481, __PRETTY_FUNCTION__))
481 "end of submodule in main source file")((File != getSourceManager().getMainFileID() && "end of submodule in main source file"
) ? static_cast<void> (0) : __assert_fail ("File != getSourceManager().getMainFileID() && \"end of submodule in main source file\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaModule.cpp"
, 481, __PRETTY_FUNCTION__))
;
482 DirectiveLoc = getSourceManager().getIncludeLoc(File);
483 } else {
484 // We reached an EOM pragma. Use the pragma location.
485 DirectiveLoc = EomLoc;
486 }
487 BuildModuleInclude(DirectiveLoc, Mod);
488
489 // Any further declarations are in whatever module we returned to.
490 if (getLangOpts().trackLocalOwningModule()) {
491 // The parser guarantees that this is the same context that we entered
492 // the module within.
493 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
494 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
495 if (!getCurrentModule())
496 cast<Decl>(DC)->setModuleOwnershipKind(
497 Decl::ModuleOwnershipKind::Unowned);
498 }
499 }
500}
501
502void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
503 Module *Mod) {
504 // Bail if we're not allowed to implicitly import a module here.
505 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
506 VisibleModules.isVisible(Mod))
507 return;
508
509 // Create the implicit import declaration.
510 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
511 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
512 Loc, Mod, Loc);
513 TU->addDecl(ImportD);
514 Consumer.HandleImplicitImportDecl(ImportD);
515
516 // Make the module visible.
517 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
518 VisibleModules.setVisible(Mod, Loc);
519}
520
521/// We have parsed the start of an export declaration, including the '{'
522/// (if present).
523Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
524 SourceLocation LBraceLoc) {
525 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
526
527 // Set this temporarily so we know the export-declaration was braced.
528 D->setRBraceLoc(LBraceLoc);
529
530 // C++2a [module.interface]p1:
531 // An export-declaration shall appear only [...] in the purview of a module
532 // interface unit. An export-declaration shall not appear directly or
533 // indirectly within [...] a private-module-fragment.
534 if (ModuleScopes.empty() || !ModuleScopes.back().Module->isModulePurview()) {
1
Taking true branch
535 Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
2
Calling '~SemaDiagnosticBuilder'
5
Returning from '~SemaDiagnosticBuilder'
536 } else if (!ModuleScopes.back().ModuleInterface) {
537 Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
538 Diag(ModuleScopes.back().BeginLoc,
539 diag::note_not_module_interface_add_export)
540 << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
541 } else if (ModuleScopes.back().Module->Kind ==
542 Module::PrivateModuleFragment) {
543 Diag(ExportLoc, diag::err_export_in_private_module_fragment);
544 Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
545 }
546
547 for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
6
Assuming pointer value is null
7
Loop condition is false. Execution continues on line 571
548 if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
549 // An export-declaration shall not appear directly or indirectly within
550 // an unnamed namespace [...]
551 if (ND->isAnonymousNamespace()) {
552 Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
553 Diag(ND->getLocation(), diag::note_anonymous_namespace);
554 // Don't diagnose internal-linkage declarations in this region.
555 D->setInvalidDecl();
556 break;
557 }
558
559 // A declaration is exported if it is [...] a namespace-definition
560 // that contains an exported declaration.
561 //
562 // Defer exporting the namespace until after we leave it, in order to
563 // avoid marking all subsequent declarations in the namespace as exported.
564 if (!DeferredExportedNamespaces.insert(ND).second)
565 break;
566 }
567 }
568
569 // [...] its declaration or declaration-seq shall not contain an
570 // export-declaration.
571 if (auto *ED = getEnclosingExportDecl(D)) {
8
Assuming 'ED' is null
9
Taking false branch
572 Diag(ExportLoc, diag::err_export_within_export);
573 if (ED->hasBraces())
574 Diag(ED->getLocation(), diag::note_export);
575 }
576
577 CurContext->addDecl(D);
10
Called C++ object pointer is null
578 PushDeclContext(S, D);
579 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
580 return D;
581}
582
583static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
584 SourceLocation BlockStart);
585
586namespace {
587enum class UnnamedDeclKind {
588 Empty,
589 StaticAssert,
590 Asm,
591 UsingDirective,
592 Context
593};
594}
595
596static llvm::Optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) {
597 if (isa<EmptyDecl>(D))
598 return UnnamedDeclKind::Empty;
599 if (isa<StaticAssertDecl>(D))
600 return UnnamedDeclKind::StaticAssert;
601 if (isa<FileScopeAsmDecl>(D))
602 return UnnamedDeclKind::Asm;
603 if (isa<UsingDirectiveDecl>(D))
604 return UnnamedDeclKind::UsingDirective;
605 // Everything else either introduces one or more names or is ill-formed.
606 return llvm::None;
607}
608
609unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) {
610 switch (UDK) {
611 case UnnamedDeclKind::Empty:
612 case UnnamedDeclKind::StaticAssert:
613 // Allow empty-declarations and static_asserts in an export block as an
614 // extension.
615 return InBlock ? diag::ext_export_no_name_block : diag::err_export_no_name;
616
617 case UnnamedDeclKind::UsingDirective:
618 // Allow exporting using-directives as an extension.
619 return diag::ext_export_using_directive;
620
621 case UnnamedDeclKind::Context:
622 // Allow exporting DeclContexts that transitively contain no declarations
623 // as an extension.
624 return diag::ext_export_no_names;
625
626 case UnnamedDeclKind::Asm:
627 return diag::err_export_no_name;
628 }
629 llvm_unreachable("unknown kind")::llvm::llvm_unreachable_internal("unknown kind", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaModule.cpp"
, 629)
;
630}
631
632static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D,
633 SourceLocation BlockStart) {
634 S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid()))
635 << (unsigned)UDK;
636 if (BlockStart.isValid())
637 S.Diag(BlockStart, diag::note_export);
638}
639
640/// Check that it's valid to export \p D.
641static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
642 // C++2a [module.interface]p3:
643 // An exported declaration shall declare at least one name
644 if (auto UDK = getUnnamedDeclKind(D))
645 diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
646
647 // [...] shall not declare a name with internal linkage.
648 if (auto *ND = dyn_cast<NamedDecl>(D)) {
649 // Don't diagnose anonymous union objects; we'll diagnose their members
650 // instead.
651 if (ND->getDeclName() && ND->getFormalLinkage() == InternalLinkage) {
652 S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
653 if (BlockStart.isValid())
654 S.Diag(BlockStart, diag::note_export);
655 }
656 }
657
658 // C++2a [module.interface]p5:
659 // all entities to which all of the using-declarators ultimately refer
660 // shall have been introduced with a name having external linkage
661 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
662 NamedDecl *Target = USD->getUnderlyingDecl();
663 if (Target->getFormalLinkage() == InternalLinkage) {
664 S.Diag(USD->getLocation(), diag::err_export_using_internal) << Target;
665 S.Diag(Target->getLocation(), diag::note_using_decl_target);
666 if (BlockStart.isValid())
667 S.Diag(BlockStart, diag::note_export);
668 }
669 }
670
671 // Recurse into namespace-scope DeclContexts. (Only namespace-scope
672 // declarations are exported.)
673 if (auto *DC = dyn_cast<DeclContext>(D))
674 if (DC->getRedeclContext()->isFileContext() && !isa<EnumDecl>(D))
675 return checkExportedDeclContext(S, DC, BlockStart);
676 return false;
677}
678
679/// Check that it's valid to export all the declarations in \p DC.
680static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
681 SourceLocation BlockStart) {
682 bool AllUnnamed = true;
683 for (auto *D : DC->decls())
684 AllUnnamed &= checkExportedDecl(S, D, BlockStart);
685 return AllUnnamed;
686}
687
688/// Complete the definition of an export declaration.
689Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
690 auto *ED = cast<ExportDecl>(D);
691 if (RBraceLoc.isValid())
692 ED->setRBraceLoc(RBraceLoc);
693
694 PopDeclContext();
695
696 if (!D->isInvalidDecl()) {
697 SourceLocation BlockStart =
698 ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
699 for (auto *Child : ED->decls()) {
700 if (checkExportedDecl(*this, Child, BlockStart)) {
701 // If a top-level child is a linkage-spec declaration, it might contain
702 // no declarations (transitively), in which case it's ill-formed.
703 diagExportedUnnamedDecl(*this, UnnamedDeclKind::Context, Child,
704 BlockStart);
705 }
706 }
707 }
708
709 return D;
710}

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
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 defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Availability.h"
21#include "clang/AST/ComparisonCategories.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprConcepts.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExternalASTSource.h"
29#include "clang/AST/LocInfoType.h"
30#include "clang/AST/MangleNumberingContext.h"
31#include "clang/AST/NSAPI.h"
32#include "clang/AST/PrettyPrinter.h"
33#include "clang/AST/StmtCXX.h"
34#include "clang/AST/TypeLoc.h"
35#include "clang/AST/TypeOrdering.h"
36#include "clang/Basic/BitmaskEnum.h"
37#include "clang/Basic/ExpressionTraits.h"
38#include "clang/Basic/Module.h"
39#include "clang/Basic/OpenMPKinds.h"
40#include "clang/Basic/PragmaKinds.h"
41#include "clang/Basic/Specifiers.h"
42#include "clang/Basic/TemplateKinds.h"
43#include "clang/Basic/TypeTraits.h"
44#include "clang/Sema/AnalysisBasedWarnings.h"
45#include "clang/Sema/CleanupInfo.h"
46#include "clang/Sema/DeclSpec.h"
47#include "clang/Sema/ExternalSemaSource.h"
48#include "clang/Sema/IdentifierResolver.h"
49#include "clang/Sema/ObjCMethodList.h"
50#include "clang/Sema/Ownership.h"
51#include "clang/Sema/Scope.h"
52#include "clang/Sema/SemaConcept.h"
53#include "clang/Sema/TypoCorrection.h"
54#include "clang/Sema/Weak.h"
55#include "llvm/ADT/ArrayRef.h"
56#include "llvm/ADT/Optional.h"
57#include "llvm/ADT/SetVector.h"
58#include "llvm/ADT/SmallBitVector.h"
59#include "llvm/ADT/SmallPtrSet.h"
60#include "llvm/ADT/SmallVector.h"
61#include "llvm/ADT/TinyPtrVector.h"
62#include "llvm/Frontend/OpenMP/OMPConstants.h"
63#include <deque>
64#include <memory>
65#include <string>
66#include <tuple>
67#include <vector>
68
69namespace llvm {
70 class APSInt;
71 template <typename ValueT> struct DenseMapInfo;
72 template <typename ValueT, typename ValueInfoT> class DenseSet;
73 class SmallBitVector;
74 struct InlineAsmIdentifierInfo;
75}
76
77namespace clang {
78 class ADLResult;
79 class ASTConsumer;
80 class ASTContext;
81 class ASTMutationListener;
82 class ASTReader;
83 class ASTWriter;
84 class ArrayType;
85 class ParsedAttr;
86 class BindingDecl;
87 class BlockDecl;
88 class CapturedDecl;
89 class CXXBasePath;
90 class CXXBasePaths;
91 class CXXBindTemporaryExpr;
92 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
93 class CXXConstructorDecl;
94 class CXXConversionDecl;
95 class CXXDeleteExpr;
96 class CXXDestructorDecl;
97 class CXXFieldCollector;
98 class CXXMemberCallExpr;
99 class CXXMethodDecl;
100 class CXXScopeSpec;
101 class CXXTemporary;
102 class CXXTryStmt;
103 class CallExpr;
104 class ClassTemplateDecl;
105 class ClassTemplatePartialSpecializationDecl;
106 class ClassTemplateSpecializationDecl;
107 class VarTemplatePartialSpecializationDecl;
108 class CodeCompleteConsumer;
109 class CodeCompletionAllocator;
110 class CodeCompletionTUInfo;
111 class CodeCompletionResult;
112 class CoroutineBodyStmt;
113 class Decl;
114 class DeclAccessPair;
115 class DeclContext;
116 class DeclRefExpr;
117 class DeclaratorDecl;
118 class DeducedTemplateArgument;
119 class DependentDiagnostic;
120 class DesignatedInitExpr;
121 class Designation;
122 class EnableIfAttr;
123 class EnumConstantDecl;
124 class Expr;
125 class ExtVectorType;
126 class FormatAttr;
127 class FriendDecl;
128 class FunctionDecl;
129 class FunctionProtoType;
130 class FunctionTemplateDecl;
131 class ImplicitConversionSequence;
132 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
133 class InitListExpr;
134 class InitializationKind;
135 class InitializationSequence;
136 class InitializedEntity;
137 class IntegerLiteral;
138 class LabelStmt;
139 class LambdaExpr;
140 class LangOptions;
141 class LocalInstantiationScope;
142 class LookupResult;
143 class MacroInfo;
144 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
145 class ModuleLoader;
146 class MultiLevelTemplateArgumentList;
147 class NamedDecl;
148 class ObjCCategoryDecl;
149 class ObjCCategoryImplDecl;
150 class ObjCCompatibleAliasDecl;
151 class ObjCContainerDecl;
152 class ObjCImplDecl;
153 class ObjCImplementationDecl;
154 class ObjCInterfaceDecl;
155 class ObjCIvarDecl;
156 template <class T> class ObjCList;
157 class ObjCMessageExpr;
158 class ObjCMethodDecl;
159 class ObjCPropertyDecl;
160 class ObjCProtocolDecl;
161 class OMPThreadPrivateDecl;
162 class OMPRequiresDecl;
163 class OMPDeclareReductionDecl;
164 class OMPDeclareSimdDecl;
165 class OMPClause;
166 struct OMPVarListLocTy;
167 struct OverloadCandidate;
168 enum class OverloadCandidateParamOrder : char;
169 enum OverloadCandidateRewriteKind : unsigned;
170 class OverloadCandidateSet;
171 class OverloadExpr;
172 class ParenListExpr;
173 class ParmVarDecl;
174 class Preprocessor;
175 class PseudoDestructorTypeStorage;
176 class PseudoObjectExpr;
177 class QualType;
178 class StandardConversionSequence;
179 class Stmt;
180 class StringLiteral;
181 class SwitchStmt;
182 class TemplateArgument;
183 class TemplateArgumentList;
184 class TemplateArgumentLoc;
185 class TemplateDecl;
186 class TemplateInstantiationCallback;
187 class TemplateParameterList;
188 class TemplatePartialOrderingContext;
189 class TemplateTemplateParmDecl;
190 class Token;
191 class TypeAliasDecl;
192 class TypedefDecl;
193 class TypedefNameDecl;
194 class TypeLoc;
195 class TypoCorrectionConsumer;
196 class UnqualifiedId;
197 class UnresolvedLookupExpr;
198 class UnresolvedMemberExpr;
199 class UnresolvedSetImpl;
200 class UnresolvedSetIterator;
201 class UsingDecl;
202 class UsingShadowDecl;
203 class ValueDecl;
204 class VarDecl;
205 class VarTemplateSpecializationDecl;
206 class VisibilityAttr;
207 class VisibleDeclConsumer;
208 class IndirectFieldDecl;
209 struct DeductionFailureInfo;
210 class TemplateSpecCandidateSet;
211
212namespace sema {
213 class AccessedEntity;
214 class BlockScopeInfo;
215 class Capture;
216 class CapturedRegionScopeInfo;
217 class CapturingScopeInfo;
218 class CompoundScopeInfo;
219 class DelayedDiagnostic;
220 class DelayedDiagnosticPool;
221 class FunctionScopeInfo;
222 class LambdaScopeInfo;
223 class PossiblyUnreachableDiag;
224 class SemaPPCallbacks;
225 class TemplateDeductionInfo;
226}
227
228namespace threadSafety {
229 class BeforeSet;
230 void threadSafetyCleanup(BeforeSet* Cache);
231}
232
233// FIXME: No way to easily map from TemplateTypeParmTypes to
234// TemplateTypeParmDecls, so we have this horrible PointerUnion.
235typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
236 SourceLocation> UnexpandedParameterPack;
237
238/// Describes whether we've seen any nullability information for the given
239/// file.
240struct FileNullability {
241 /// The first pointer declarator (of any pointer kind) in the file that does
242 /// not have a corresponding nullability annotation.
243 SourceLocation PointerLoc;
244
245 /// The end location for the first pointer declarator in the file. Used for
246 /// placing fix-its.
247 SourceLocation PointerEndLoc;
248
249 /// Which kind of pointer declarator we saw.
250 uint8_t PointerKind;
251
252 /// Whether we saw any type nullability annotations in the given file.
253 bool SawTypeNullability = false;
254};
255
256/// A mapping from file IDs to a record of whether we've seen nullability
257/// information in that file.
258class FileNullabilityMap {
259 /// A mapping from file IDs to the nullability information for each file ID.
260 llvm::DenseMap<FileID, FileNullability> Map;
261
262 /// A single-element cache based on the file ID.
263 struct {
264 FileID File;
265 FileNullability Nullability;
266 } Cache;
267
268public:
269 FileNullability &operator[](FileID file) {
270 // Check the single-element cache.
271 if (file == Cache.File)
272 return Cache.Nullability;
273
274 // It's not in the single-element cache; flush the cache if we have one.
275 if (!Cache.File.isInvalid()) {
276 Map[Cache.File] = Cache.Nullability;
277 }
278
279 // Pull this entry into the cache.
280 Cache.File = file;
281 Cache.Nullability = Map[file];
282 return Cache.Nullability;
283 }
284};
285
286/// Keeps track of expected type during expression parsing. The type is tied to
287/// a particular token, all functions that update or consume the type take a
288/// start location of the token they are looking at as a parameter. This allows
289/// to avoid updating the type on hot paths in the parser.
290class PreferredTypeBuilder {
291public:
292 PreferredTypeBuilder() = default;
293 explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
294
295 void enterCondition(Sema &S, SourceLocation Tok);
296 void enterReturn(Sema &S, SourceLocation Tok);
297 void enterVariableInit(SourceLocation Tok, Decl *D);
298 /// Computing a type for the function argument may require running
299 /// overloading, so we postpone its computation until it is actually needed.
300 ///
301 /// Clients should be very careful when using this funciton, as it stores a
302 /// function_ref, clients should make sure all calls to get() with the same
303 /// location happen while function_ref is alive.
304 void enterFunctionArgument(SourceLocation Tok,
305 llvm::function_ref<QualType()> ComputeType);
306
307 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
308 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
309 SourceLocation OpLoc);
310 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
311 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
312 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
313 /// Handles all type casts, including C-style cast, C++ casts, etc.
314 void enterTypeCast(SourceLocation Tok, QualType CastType);
315
316 QualType get(SourceLocation Tok) const {
317 if (Tok != ExpectedLoc)
318 return QualType();
319 if (!Type.isNull())
320 return Type;
321 if (ComputeType)
322 return ComputeType();
323 return QualType();
324 }
325
326private:
327 /// Start position of a token for which we store expected type.
328 SourceLocation ExpectedLoc;
329 /// Expected type for a token starting at ExpectedLoc.
330 QualType Type;
331 /// A function to compute expected type at ExpectedLoc. It is only considered
332 /// if Type is null.
333 llvm::function_ref<QualType()> ComputeType;
334};
335
336/// Sema - This implements semantic analysis and AST building for C.
337class Sema final {
338 Sema(const Sema &) = delete;
339 void operator=(const Sema &) = delete;
340
341 /// A key method to reduce duplicate debug info from Sema.
342 virtual void anchor();
343
344 ///Source of additional semantic information.
345 ExternalSemaSource *ExternalSource;
346
347 ///Whether Sema has generated a multiplexer and has to delete it.
348 bool isMultiplexExternalSource;
349
350 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
351
352 bool isVisibleSlow(const NamedDecl *D);
353
354 /// Determine whether two declarations should be linked together, given that
355 /// the old declaration might not be visible and the new declaration might
356 /// not have external linkage.
357 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
358 const NamedDecl *New) {
359 if (isVisible(Old))
360 return true;
361 // See comment in below overload for why it's safe to compute the linkage
362 // of the new declaration here.
363 if (New->isExternallyDeclarable()) {
364 assert(Old->isExternallyDeclarable() &&((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 365, __PRETTY_FUNCTION__))
365 "should not have found a non-externally-declarable previous decl")((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 365, __PRETTY_FUNCTION__))
;
366 return true;
367 }
368 return false;
369 }
370 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
371
372 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
373 QualType ResultTy,
374 ArrayRef<QualType> Args);
375
376public:
377 /// The maximum alignment, same as in llvm::Value. We duplicate them here
378 /// because that allows us not to duplicate the constants in clang code,
379 /// which we must to since we can't directly use the llvm constants.
380 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
381 ///
382 /// This is the greatest alignment value supported by load, store, and alloca
383 /// instructions, and global values.
384 static const unsigned MaxAlignmentExponent = 29;
385 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
386
387 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
388 typedef OpaquePtr<TemplateName> TemplateTy;
389 typedef OpaquePtr<QualType> TypeTy;
390
391 OpenCLOptions OpenCLFeatures;
392 FPOptions FPFeatures;
393
394 const LangOptions &LangOpts;
395 Preprocessor &PP;
396 ASTContext &Context;
397 ASTConsumer &Consumer;
398 DiagnosticsEngine &Diags;
399 SourceManager &SourceMgr;
400
401 /// Flag indicating whether or not to collect detailed statistics.
402 bool CollectStats;
403
404 /// Code-completion consumer.
405 CodeCompleteConsumer *CodeCompleter;
406
407 /// CurContext - This is the current declaration context of parsing.
408 DeclContext *CurContext;
409
410 /// Generally null except when we temporarily switch decl contexts,
411 /// like in \see ActOnObjCTemporaryExitContainerContext.
412 DeclContext *OriginalLexicalContext;
413
414 /// VAListTagName - The declaration name corresponding to __va_list_tag.
415 /// This is used as part of a hack to omit that class from ADL results.
416 DeclarationName VAListTagName;
417
418 bool MSStructPragmaOn; // True when \#pragma ms_struct on
419
420 /// Controls member pointer representation format under the MS ABI.
421 LangOptions::PragmaMSPointersToMembersKind
422 MSPointerToMemberRepresentationMethod;
423
424 /// Stack of active SEH __finally scopes. Can be empty.
425 SmallVector<Scope*, 2> CurrentSEHFinally;
426
427 /// Source location for newly created implicit MSInheritanceAttrs
428 SourceLocation ImplicitMSInheritanceAttrLoc;
429
430 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
431 /// `TransformTypos` in order to keep track of any TypoExprs that are created
432 /// recursively during typo correction and wipe them away if the correction
433 /// fails.
434 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
435
436 /// pragma clang section kind
437 enum PragmaClangSectionKind {
438 PCSK_Invalid = 0,
439 PCSK_BSS = 1,
440 PCSK_Data = 2,
441 PCSK_Rodata = 3,
442 PCSK_Text = 4,
443 PCSK_Relro = 5
444 };
445
446 enum PragmaClangSectionAction {
447 PCSA_Set = 0,
448 PCSA_Clear = 1
449 };
450
451 struct PragmaClangSection {
452 std::string SectionName;
453 bool Valid = false;
454 SourceLocation PragmaLocation;
455
456 void Act(SourceLocation PragmaLocation,
457 PragmaClangSectionAction Action,
458 StringLiteral* Name);
459 };
460
461 PragmaClangSection PragmaClangBSSSection;
462 PragmaClangSection PragmaClangDataSection;
463 PragmaClangSection PragmaClangRodataSection;
464 PragmaClangSection PragmaClangRelroSection;
465 PragmaClangSection PragmaClangTextSection;
466
467 enum PragmaMsStackAction {
468 PSK_Reset = 0x0, // #pragma ()
469 PSK_Set = 0x1, // #pragma (value)
470 PSK_Push = 0x2, // #pragma (push[, id])
471 PSK_Pop = 0x4, // #pragma (pop[, id])
472 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
473 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
474 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
475 };
476
477 template<typename ValueType>
478 struct PragmaStack {
479 struct Slot {
480 llvm::StringRef StackSlotLabel;
481 ValueType Value;
482 SourceLocation PragmaLocation;
483 SourceLocation PragmaPushLocation;
484 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
485 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
486 : StackSlotLabel(StackSlotLabel), Value(Value),
487 PragmaLocation(PragmaLocation),
488 PragmaPushLocation(PragmaPushLocation) {}
489 };
490 void Act(SourceLocation PragmaLocation,
491 PragmaMsStackAction Action,
492 llvm::StringRef StackSlotLabel,
493 ValueType Value);
494
495 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
496 // method body to restore the stacks on exit, so it works like this:
497 //
498 // struct S {
499 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
500 // void Method {}
501 // #pragma <name>(pop, InternalPragmaSlot)
502 // };
503 //
504 // It works even with #pragma vtordisp, although MSVC doesn't support
505 // #pragma vtordisp(push [, id], n)
506 // syntax.
507 //
508 // Push / pop a named sentinel slot.
509 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
510 assert((Action == PSK_Push || Action == PSK_Pop) &&(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 511, __PRETTY_FUNCTION__))
511 "Can only push / pop #pragma stack sentinels!")(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 511, __PRETTY_FUNCTION__))
;
512 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
513 }
514
515 // Constructors.
516 explicit PragmaStack(const ValueType &Default)
517 : DefaultValue(Default), CurrentValue(Default) {}
518
519 bool hasValue() const { return CurrentValue != DefaultValue; }
520
521 SmallVector<Slot, 2> Stack;
522 ValueType DefaultValue; // Value used for PSK_Reset action.
523 ValueType CurrentValue;
524 SourceLocation CurrentPragmaLocation;
525 };
526 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
527 // we shouldn't do so if they're in a module).
528
529 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
530 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
531 ///
532 /// 0: Suppress all vtordisps
533 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
534 /// structors
535 /// 2: Always insert vtordisps to support RTTI on partially constructed
536 /// objects
537 PragmaStack<MSVtorDispMode> VtorDispStack;
538 // #pragma pack.
539 // Sentinel to represent when the stack is set to mac68k alignment.
540 static const unsigned kMac68kAlignmentSentinel = ~0U;
541 PragmaStack<unsigned> PackStack;
542 // The current #pragma pack values and locations at each #include.
543 struct PackIncludeState {
544 unsigned CurrentValue;
545 SourceLocation CurrentPragmaLocation;
546 bool HasNonDefaultValue, ShouldWarnOnInclude;
547 };
548 SmallVector<PackIncludeState, 8> PackIncludeStack;
549 // Segment #pragmas.
550 PragmaStack<StringLiteral *> DataSegStack;
551 PragmaStack<StringLiteral *> BSSSegStack;
552 PragmaStack<StringLiteral *> ConstSegStack;
553 PragmaStack<StringLiteral *> CodeSegStack;
554
555 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
556 // Actions should be performed only if we enter / exit a C++ method body.
557 class PragmaStackSentinelRAII {
558 public:
559 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
560 ~PragmaStackSentinelRAII();
561
562 private:
563 Sema &S;
564 StringRef SlotLabel;
565 bool ShouldAct;
566 };
567
568 /// A mapping that describes the nullability we've seen in each header file.
569 FileNullabilityMap NullabilityMap;
570
571 /// Last section used with #pragma init_seg.
572 StringLiteral *CurInitSeg;
573 SourceLocation CurInitSegLoc;
574
575 /// VisContext - Manages the stack for \#pragma GCC visibility.
576 void *VisContext; // Really a "PragmaVisStack*"
577
578 /// This an attribute introduced by \#pragma clang attribute.
579 struct PragmaAttributeEntry {
580 SourceLocation Loc;
581 ParsedAttr *Attribute;
582 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
583 bool IsUsed;
584 };
585
586 /// A push'd group of PragmaAttributeEntries.
587 struct PragmaAttributeGroup {
588 /// The location of the push attribute.
589 SourceLocation Loc;
590 /// The namespace of this push group.
591 const IdentifierInfo *Namespace;
592 SmallVector<PragmaAttributeEntry, 2> Entries;
593 };
594
595 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
596
597 /// The declaration that is currently receiving an attribute from the
598 /// #pragma attribute stack.
599 const Decl *PragmaAttributeCurrentTargetDecl;
600
601 /// This represents the last location of a "#pragma clang optimize off"
602 /// directive if such a directive has not been closed by an "on" yet. If
603 /// optimizations are currently "on", this is set to an invalid location.
604 SourceLocation OptimizeOffPragmaLocation;
605
606 /// Flag indicating if Sema is building a recovery call expression.
607 ///
608 /// This flag is used to avoid building recovery call expressions
609 /// if Sema is already doing so, which would cause infinite recursions.
610 bool IsBuildingRecoveryCallExpr;
611
612 /// Used to control the generation of ExprWithCleanups.
613 CleanupInfo Cleanup;
614
615 /// ExprCleanupObjects - This is the stack of objects requiring
616 /// cleanup that are created by the current full expression. The
617 /// element type here is ExprWithCleanups::Object.
618 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
619
620 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
621 /// to a variable (constant) that may or may not be odr-used in this Expr, and
622 /// we won't know until all lvalue-to-rvalue and discarded value conversions
623 /// have been applied to all subexpressions of the enclosing full expression.
624 /// This is cleared at the end of each full expression.
625 using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
626 MaybeODRUseExprSet MaybeODRUseExprs;
627
628 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
629
630 /// Stack containing information about each of the nested
631 /// function, block, and method scopes that are currently active.
632 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
633
634 /// Stack containing information needed when in C++2a an 'auto' is encountered
635 /// in a function declaration parameter type specifier in order to invent a
636 /// corresponding template parameter in the enclosing abbreviated function
637 /// template. This information is also present in LambdaScopeInfo, stored in
638 /// the FunctionScopes stack.
639 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
640
641 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
642 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
643 ExtVectorDeclsType;
644
645 /// ExtVectorDecls - This is a list all the extended vector types. This allows
646 /// us to associate a raw vector type with one of the ext_vector type names.
647 /// This is only necessary for issuing pretty diagnostics.
648 ExtVectorDeclsType ExtVectorDecls;
649
650 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
651 std::unique_ptr<CXXFieldCollector> FieldCollector;
652
653 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
654
655 /// Set containing all declared private fields that are not used.
656 NamedDeclSetType UnusedPrivateFields;
657
658 /// Set containing all typedefs that are likely unused.
659 llvm::SmallSetVector<const TypedefNameDecl *, 4>
660 UnusedLocalTypedefNameCandidates;
661
662 /// Delete-expressions to be analyzed at the end of translation unit
663 ///
664 /// This list contains class members, and locations of delete-expressions
665 /// that could not be proven as to whether they mismatch with new-expression
666 /// used in initializer of the field.
667 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
668 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
669 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
670
671 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
672
673 /// PureVirtualClassDiagSet - a set of class declarations which we have
674 /// emitted a list of pure virtual functions. Used to prevent emitting the
675 /// same list more than once.
676 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
677
678 /// ParsingInitForAutoVars - a set of declarations with auto types for which
679 /// we are currently parsing the initializer.
680 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
681
682 /// Look for a locally scoped extern "C" declaration by the given name.
683 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
684
685 typedef LazyVector<VarDecl *, ExternalSemaSource,
686 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
687 TentativeDefinitionsType;
688
689 /// All the tentative definitions encountered in the TU.
690 TentativeDefinitionsType TentativeDefinitions;
691
692 /// All the external declarations encoutered and used in the TU.
693 SmallVector<VarDecl *, 4> ExternalDeclarations;
694
695 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
696 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
697 UnusedFileScopedDeclsType;
698
699 /// The set of file scoped decls seen so far that have not been used
700 /// and must warn if not used. Only contains the first declaration.
701 UnusedFileScopedDeclsType UnusedFileScopedDecls;
702
703 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
704 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
705 DelegatingCtorDeclsType;
706
707 /// All the delegating constructors seen so far in the file, used for
708 /// cycle detection at the end of the TU.
709 DelegatingCtorDeclsType DelegatingCtorDecls;
710
711 /// All the overriding functions seen during a class definition
712 /// that had their exception spec checks delayed, plus the overridden
713 /// function.
714 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
715 DelayedOverridingExceptionSpecChecks;
716
717 /// All the function redeclarations seen during a class definition that had
718 /// their exception spec checks delayed, plus the prior declaration they
719 /// should be checked against. Except during error recovery, the new decl
720 /// should always be a friend declaration, as that's the only valid way to
721 /// redeclare a special member before its class is complete.
722 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
723 DelayedEquivalentExceptionSpecChecks;
724
725 typedef llvm::MapVector<const FunctionDecl *,
726 std::unique_ptr<LateParsedTemplate>>
727 LateParsedTemplateMapT;
728 LateParsedTemplateMapT LateParsedTemplateMap;
729
730 /// Callback to the parser to parse templated functions when needed.
731 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
732 typedef void LateTemplateParserCleanupCB(void *P);
733 LateTemplateParserCB *LateTemplateParser;
734 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
735 void *OpaqueParser;
736
737 void SetLateTemplateParser(LateTemplateParserCB *LTP,
738 LateTemplateParserCleanupCB *LTPCleanup,
739 void *P) {
740 LateTemplateParser = LTP;
741 LateTemplateParserCleanup = LTPCleanup;
742 OpaqueParser = P;
743 }
744
745 class DelayedDiagnostics;
746
747 class DelayedDiagnosticsState {
748 sema::DelayedDiagnosticPool *SavedPool;
749 friend class Sema::DelayedDiagnostics;
750 };
751 typedef DelayedDiagnosticsState ParsingDeclState;
752 typedef DelayedDiagnosticsState ProcessingContextState;
753
754 /// A class which encapsulates the logic for delaying diagnostics
755 /// during parsing and other processing.
756 class DelayedDiagnostics {
757 /// The current pool of diagnostics into which delayed
758 /// diagnostics should go.
759 sema::DelayedDiagnosticPool *CurPool;
760
761 public:
762 DelayedDiagnostics() : CurPool(nullptr) {}
763
764 /// Adds a delayed diagnostic.
765 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
766
767 /// Determines whether diagnostics should be delayed.
768 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
769
770 /// Returns the current delayed-diagnostics pool.
771 sema::DelayedDiagnosticPool *getCurrentPool() const {
772 return CurPool;
773 }
774
775 /// Enter a new scope. Access and deprecation diagnostics will be
776 /// collected in this pool.
777 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
778 DelayedDiagnosticsState state;
779 state.SavedPool = CurPool;
780 CurPool = &pool;
781 return state;
782 }
783
784 /// Leave a delayed-diagnostic state that was previously pushed.
785 /// Do not emit any of the diagnostics. This is performed as part
786 /// of the bookkeeping of popping a pool "properly".
787 void popWithoutEmitting(DelayedDiagnosticsState state) {
788 CurPool = state.SavedPool;
789 }
790
791 /// Enter a new scope where access and deprecation diagnostics are
792 /// not delayed.
793 DelayedDiagnosticsState pushUndelayed() {
794 DelayedDiagnosticsState state;
795 state.SavedPool = CurPool;
796 CurPool = nullptr;
797 return state;
798 }
799
800 /// Undo a previous pushUndelayed().
801 void popUndelayed(DelayedDiagnosticsState state) {
802 assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 802, __PRETTY_FUNCTION__))
;
803 CurPool = state.SavedPool;
804 }
805 } DelayedDiagnostics;
806
807 /// A RAII object to temporarily push a declaration context.
808 class ContextRAII {
809 private:
810 Sema &S;
811 DeclContext *SavedContext;
812 ProcessingContextState SavedContextState;
813 QualType SavedCXXThisTypeOverride;
814
815 public:
816 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
817 : S(S), SavedContext(S.CurContext),
818 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
819 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
820 {
821 assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast
<void> (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 821, __PRETTY_FUNCTION__))
;
822 S.CurContext = ContextToPush;
823 if (NewThisContext)
824 S.CXXThisTypeOverride = QualType();
825 }
826
827 void pop() {
828 if (!SavedContext) return;
829 S.CurContext = SavedContext;
830 S.DelayedDiagnostics.popUndelayed(SavedContextState);
831 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
832 SavedContext = nullptr;
833 }
834
835 ~ContextRAII() {
836 pop();
837 }
838 };
839
840 /// Whether the AST is currently being rebuilt to correct immediate
841 /// invocations. Immediate invocation candidates and references to consteval
842 /// functions aren't tracked when this is set.
843 bool RebuildingImmediateInvocation = false;
844
845 /// Used to change context to isConstantEvaluated without pushing a heavy
846 /// ExpressionEvaluationContextRecord object.
847 bool isConstantEvaluatedOverride;
848
849 bool isConstantEvaluated() {
850 return ExprEvalContexts.back().isConstantEvaluated() ||
851 isConstantEvaluatedOverride;
852 }
853
854 /// RAII object to handle the state changes required to synthesize
855 /// a function body.
856 class SynthesizedFunctionScope {
857 Sema &S;
858 Sema::ContextRAII SavedContext;
859 bool PushedCodeSynthesisContext = false;
860
861 public:
862 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
863 : S(S), SavedContext(S, DC) {
864 S.PushFunctionScope();
865 S.PushExpressionEvaluationContext(
866 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
867 if (auto *FD = dyn_cast<FunctionDecl>(DC))
868 FD->setWillHaveBody(true);
869 else
870 assert(isa<ObjCMethodDecl>(DC))((isa<ObjCMethodDecl>(DC)) ? static_cast<void> (0
) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 870, __PRETTY_FUNCTION__))
;
871 }
872
873 void addContextNote(SourceLocation UseLoc) {
874 assert(!PushedCodeSynthesisContext)((!PushedCodeSynthesisContext) ? static_cast<void> (0) :
__assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 874, __PRETTY_FUNCTION__))
;
875
876 Sema::CodeSynthesisContext Ctx;
877 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
878 Ctx.PointOfInstantiation = UseLoc;
879 Ctx.Entity = cast<Decl>(S.CurContext);
880 S.pushCodeSynthesisContext(Ctx);
881
882 PushedCodeSynthesisContext = true;
883 }
884
885 ~SynthesizedFunctionScope() {
886 if (PushedCodeSynthesisContext)
887 S.popCodeSynthesisContext();
888 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
889 FD->setWillHaveBody(false);
890 S.PopExpressionEvaluationContext();
891 S.PopFunctionScopeInfo();
892 }
893 };
894
895 /// WeakUndeclaredIdentifiers - Identifiers contained in
896 /// \#pragma weak before declared. rare. may alias another
897 /// identifier, declared or undeclared
898 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
899
900 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
901 /// \#pragma redefine_extname before declared. Used in Solaris system headers
902 /// to define functions that occur in multiple standards to call the version
903 /// in the currently selected standard.
904 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
905
906
907 /// Load weak undeclared identifiers from the external source.
908 void LoadExternalWeakUndeclaredIdentifiers();
909
910 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
911 /// \#pragma weak during processing of other Decls.
912 /// I couldn't figure out a clean way to generate these in-line, so
913 /// we store them here and handle separately -- which is a hack.
914 /// It would be best to refactor this.
915 SmallVector<Decl*,2> WeakTopLevelDecl;
916
917 IdentifierResolver IdResolver;
918
919 /// Translation Unit Scope - useful to Objective-C actions that need
920 /// to lookup file scope declarations in the "ordinary" C decl namespace.
921 /// For example, user-defined classes, built-in "id" type, etc.
922 Scope *TUScope;
923
924 /// The C++ "std" namespace, where the standard library resides.
925 LazyDeclPtr StdNamespace;
926
927 /// The C++ "std::bad_alloc" class, which is defined by the C++
928 /// standard library.
929 LazyDeclPtr StdBadAlloc;
930
931 /// The C++ "std::align_val_t" enum class, which is defined by the C++
932 /// standard library.
933 LazyDeclPtr StdAlignValT;
934
935 /// The C++ "std::experimental" namespace, where the experimental parts
936 /// of the standard library resides.
937 NamespaceDecl *StdExperimentalNamespaceCache;
938
939 /// The C++ "std::initializer_list" template, which is defined in
940 /// \<initializer_list>.
941 ClassTemplateDecl *StdInitializerList;
942
943 /// The C++ "std::coroutine_traits" template, which is defined in
944 /// \<coroutine_traits>
945 ClassTemplateDecl *StdCoroutineTraitsCache;
946
947 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
948 RecordDecl *CXXTypeInfoDecl;
949
950 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
951 RecordDecl *MSVCGuidDecl;
952
953 /// Caches identifiers/selectors for NSFoundation APIs.
954 std::unique_ptr<NSAPI> NSAPIObj;
955
956 /// The declaration of the Objective-C NSNumber class.
957 ObjCInterfaceDecl *NSNumberDecl;
958
959 /// The declaration of the Objective-C NSValue class.
960 ObjCInterfaceDecl *NSValueDecl;
961
962 /// Pointer to NSNumber type (NSNumber *).
963 QualType NSNumberPointer;
964
965 /// Pointer to NSValue type (NSValue *).
966 QualType NSValuePointer;
967
968 /// The Objective-C NSNumber methods used to create NSNumber literals.
969 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
970
971 /// The declaration of the Objective-C NSString class.
972 ObjCInterfaceDecl *NSStringDecl;
973
974 /// Pointer to NSString type (NSString *).
975 QualType NSStringPointer;
976
977 /// The declaration of the stringWithUTF8String: method.
978 ObjCMethodDecl *StringWithUTF8StringMethod;
979
980 /// The declaration of the valueWithBytes:objCType: method.
981 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
982
983 /// The declaration of the Objective-C NSArray class.
984 ObjCInterfaceDecl *NSArrayDecl;
985
986 /// The declaration of the arrayWithObjects:count: method.
987 ObjCMethodDecl *ArrayWithObjectsMethod;
988
989 /// The declaration of the Objective-C NSDictionary class.
990 ObjCInterfaceDecl *NSDictionaryDecl;
991
992 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
993 ObjCMethodDecl *DictionaryWithObjectsMethod;
994
995 /// id<NSCopying> type.
996 QualType QIDNSCopying;
997
998 /// will hold 'respondsToSelector:'
999 Selector RespondsToSelectorSel;
1000
1001 /// A flag to remember whether the implicit forms of operator new and delete
1002 /// have been declared.
1003 bool GlobalNewDeleteDeclared;
1004
1005 /// A flag to indicate that we're in a context that permits abstract
1006 /// references to fields. This is really a
1007 bool AllowAbstractFieldReference;
1008
1009 /// Describes how the expressions currently being parsed are
1010 /// evaluated at run-time, if at all.
1011 enum class ExpressionEvaluationContext {
1012 /// The current expression and its subexpressions occur within an
1013 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1014 /// \c sizeof, where the type of the expression may be significant but
1015 /// no code will be generated to evaluate the value of the expression at
1016 /// run time.
1017 Unevaluated,
1018
1019 /// The current expression occurs within a braced-init-list within
1020 /// an unevaluated operand. This is mostly like a regular unevaluated
1021 /// context, except that we still instantiate constexpr functions that are
1022 /// referenced here so that we can perform narrowing checks correctly.
1023 UnevaluatedList,
1024
1025 /// The current expression occurs within a discarded statement.
1026 /// This behaves largely similarly to an unevaluated operand in preventing
1027 /// definitions from being required, but not in other ways.
1028 DiscardedStatement,
1029
1030 /// The current expression occurs within an unevaluated
1031 /// operand that unconditionally permits abstract references to
1032 /// fields, such as a SIZE operator in MS-style inline assembly.
1033 UnevaluatedAbstract,
1034
1035 /// The current context is "potentially evaluated" in C++11 terms,
1036 /// but the expression is evaluated at compile-time (like the values of
1037 /// cases in a switch statement).
1038 ConstantEvaluated,
1039
1040 /// The current expression is potentially evaluated at run time,
1041 /// which means that code may be generated to evaluate the value of the
1042 /// expression at run time.
1043 PotentiallyEvaluated,
1044
1045 /// The current expression is potentially evaluated, but any
1046 /// declarations referenced inside that expression are only used if
1047 /// in fact the current expression is used.
1048 ///
1049 /// This value is used when parsing default function arguments, for which
1050 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1051 /// through varargs) but do not want to mark declarations as "referenced"
1052 /// until the default argument is used.
1053 PotentiallyEvaluatedIfUsed
1054 };
1055
1056 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1057
1058 /// Data structure used to record current or nested
1059 /// expression evaluation contexts.
1060 struct ExpressionEvaluationContextRecord {
1061 /// The expression evaluation context.
1062 ExpressionEvaluationContext Context;
1063
1064 /// Whether the enclosing context needed a cleanup.
1065 CleanupInfo ParentCleanup;
1066
1067 /// Whether we are in a decltype expression.
1068 bool IsDecltype;
1069
1070 /// The number of active cleanup objects when we entered
1071 /// this expression evaluation context.
1072 unsigned NumCleanupObjects;
1073
1074 /// The number of typos encountered during this expression evaluation
1075 /// context (i.e. the number of TypoExprs created).
1076 unsigned NumTypos;
1077
1078 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1079
1080 /// The lambdas that are present within this context, if it
1081 /// is indeed an unevaluated context.
1082 SmallVector<LambdaExpr *, 2> Lambdas;
1083
1084 /// The declaration that provides context for lambda expressions
1085 /// and block literals if the normal declaration context does not
1086 /// suffice, e.g., in a default function argument.
1087 Decl *ManglingContextDecl;
1088
1089 /// If we are processing a decltype type, a set of call expressions
1090 /// for which we have deferred checking the completeness of the return type.
1091 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1092
1093 /// If we are processing a decltype type, a set of temporary binding
1094 /// expressions for which we have deferred checking the destructor.
1095 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1096
1097 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1098
1099 /// Expressions appearing as the LHS of a volatile assignment in this
1100 /// context. We produce a warning for these when popping the context if
1101 /// they are not discarded-value expressions nor unevaluated operands.
1102 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1103
1104 /// Set of candidates for starting an immediate invocation.
1105 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1106
1107 /// Set of DeclRefExprs referencing a consteval function when used in a
1108 /// context not already known to be immediately invoked.
1109 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1110
1111 /// \brief Describes whether we are in an expression constext which we have
1112 /// to handle differently.
1113 enum ExpressionKind {
1114 EK_Decltype, EK_TemplateArgument, EK_Other
1115 } ExprContext;
1116
1117 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1118 unsigned NumCleanupObjects,
1119 CleanupInfo ParentCleanup,
1120 Decl *ManglingContextDecl,
1121 ExpressionKind ExprContext)
1122 : Context(Context), ParentCleanup(ParentCleanup),
1123 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1124 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1125
1126 bool isUnevaluated() const {
1127 return Context == ExpressionEvaluationContext::Unevaluated ||
1128 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1129 Context == ExpressionEvaluationContext::UnevaluatedList;
1130 }
1131 bool isConstantEvaluated() const {
1132 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1133 }
1134 };
1135
1136 /// A stack of expression evaluation contexts.
1137 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1138
1139 /// Emit a warning for all pending noderef expressions that we recorded.
1140 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1141
1142 /// Compute the mangling number context for a lambda expression or
1143 /// block literal. Also return the extra mangling decl if any.
1144 ///
1145 /// \param DC - The DeclContext containing the lambda expression or
1146 /// block literal.
1147 std::tuple<MangleNumberingContext *, Decl *>
1148 getCurrentMangleNumberContext(const DeclContext *DC);
1149
1150
1151 /// SpecialMemberOverloadResult - The overloading result for a special member
1152 /// function.
1153 ///
1154 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1155 /// integer are used to determine whether overload resolution succeeded.
1156 class SpecialMemberOverloadResult {
1157 public:
1158 enum Kind {
1159 NoMemberOrDeleted,
1160 Ambiguous,
1161 Success
1162 };
1163
1164 private:
1165 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1166
1167 public:
1168 SpecialMemberOverloadResult() : Pair() {}
1169 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1170 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1171
1172 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1173 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1174
1175 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1176 void setKind(Kind K) { Pair.setInt(K); }
1177 };
1178
1179 class SpecialMemberOverloadResultEntry
1180 : public llvm::FastFoldingSetNode,
1181 public SpecialMemberOverloadResult {
1182 public:
1183 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1184 : FastFoldingSetNode(ID)
1185 {}
1186 };
1187
1188 /// A cache of special member function overload resolution results
1189 /// for C++ records.
1190 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1191
1192 /// A cache of the flags available in enumerations with the flag_bits
1193 /// attribute.
1194 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1195
1196 /// The kind of translation unit we are processing.
1197 ///
1198 /// When we're processing a complete translation unit, Sema will perform
1199 /// end-of-translation-unit semantic tasks (such as creating
1200 /// initializers for tentative definitions in C) once parsing has
1201 /// completed. Modules and precompiled headers perform different kinds of
1202 /// checks.
1203 TranslationUnitKind TUKind;
1204
1205 llvm::BumpPtrAllocator BumpAlloc;
1206
1207 /// The number of SFINAE diagnostics that have been trapped.
1208 unsigned NumSFINAEErrors;
1209
1210 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1211 UnparsedDefaultArgInstantiationsMap;
1212
1213 /// A mapping from parameters with unparsed default arguments to the
1214 /// set of instantiations of each parameter.
1215 ///
1216 /// This mapping is a temporary data structure used when parsing
1217 /// nested class templates or nested classes of class templates,
1218 /// where we might end up instantiating an inner class before the
1219 /// default arguments of its methods have been parsed.
1220 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1221
1222 // Contains the locations of the beginning of unparsed default
1223 // argument locations.
1224 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1225
1226 /// UndefinedInternals - all the used, undefined objects which require a
1227 /// definition in this translation unit.
1228 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1229
1230 /// Determine if VD, which must be a variable or function, is an external
1231 /// symbol that nonetheless can't be referenced from outside this translation
1232 /// unit because its type has no linkage and it's not extern "C".
1233 bool isExternalWithNoLinkageType(ValueDecl *VD);
1234
1235 /// Obtain a sorted list of functions that are undefined but ODR-used.
1236 void getUndefinedButUsed(
1237 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1238
1239 /// Retrieves list of suspicious delete-expressions that will be checked at
1240 /// the end of translation unit.
1241 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1242 getMismatchingDeleteExpressions() const;
1243
1244 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1245 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1246
1247 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1248 /// We need to maintain a list, since selectors can have differing signatures
1249 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1250 /// of selectors are "overloaded").
1251 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1252 /// methods inside categories with a particular selector.
1253 GlobalMethodPool MethodPool;
1254
1255 /// Method selectors used in a \@selector expression. Used for implementation
1256 /// of -Wselector.
1257 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1258
1259 /// List of SourceLocations where 'self' is implicitly retained inside a
1260 /// block.
1261 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1262 ImplicitlyRetainedSelfLocs;
1263
1264 /// Kinds of C++ special members.
1265 enum CXXSpecialMember {
1266 CXXDefaultConstructor,
1267 CXXCopyConstructor,
1268 CXXMoveConstructor,
1269 CXXCopyAssignment,
1270 CXXMoveAssignment,
1271 CXXDestructor,
1272 CXXInvalid
1273 };
1274
1275 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1276 SpecialMemberDecl;
1277
1278 /// The C++ special members which we are currently in the process of
1279 /// declaring. If this process recursively triggers the declaration of the
1280 /// same special member, we should act as if it is not yet declared.
1281 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1282
1283 /// Kinds of defaulted comparison operator functions.
1284 enum class DefaultedComparisonKind : unsigned char {
1285 /// This is not a defaultable comparison operator.
1286 None,
1287 /// This is an operator== that should be implemented as a series of
1288 /// subobject comparisons.
1289 Equal,
1290 /// This is an operator<=> that should be implemented as a series of
1291 /// subobject comparisons.
1292 ThreeWay,
1293 /// This is an operator!= that should be implemented as a rewrite in terms
1294 /// of a == comparison.
1295 NotEqual,
1296 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1297 /// terms of a <=> comparison.
1298 Relational,
1299 };
1300
1301 /// The function definitions which were renamed as part of typo-correction
1302 /// to match their respective declarations. We want to keep track of them
1303 /// to ensure that we don't emit a "redefinition" error if we encounter a
1304 /// correctly named definition after the renamed definition.
1305 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1306
1307 /// Stack of types that correspond to the parameter entities that are
1308 /// currently being copy-initialized. Can be empty.
1309 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1310
1311 void ReadMethodPool(Selector Sel);
1312 void updateOutOfDateSelector(Selector Sel);
1313
1314 /// Private Helper predicate to check for 'self'.
1315 bool isSelfExpr(Expr *RExpr);
1316 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1317
1318 /// Cause the active diagnostic on the DiagosticsEngine to be
1319 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1320 /// should not be used elsewhere.
1321 void EmitCurrentDiagnostic(unsigned DiagID);
1322
1323 /// Records and restores the FPFeatures state on entry/exit of compound
1324 /// statements.
1325 class FPFeaturesStateRAII {
1326 public:
1327 FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1328 ~FPFeaturesStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1329
1330 private:
1331 Sema& S;
1332 FPOptions OldFPFeaturesState;
1333 };
1334
1335 void addImplicitTypedef(StringRef Name, QualType T);
1336
1337 bool WarnedStackExhausted = false;
1338
1339public:
1340 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1341 TranslationUnitKind TUKind = TU_Complete,
1342 CodeCompleteConsumer *CompletionConsumer = nullptr);
1343 ~Sema();
1344
1345 /// Perform initialization that occurs after the parser has been
1346 /// initialized but before it parses anything.
1347 void Initialize();
1348
1349 const LangOptions &getLangOpts() const { return LangOpts; }
1350 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1351 FPOptions &getFPOptions() { return FPFeatures; }
1352
1353 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1354 SourceManager &getSourceManager() const { return SourceMgr; }
1355 Preprocessor &getPreprocessor() const { return PP; }
1356 ASTContext &getASTContext() const { return Context; }
1357 ASTConsumer &getASTConsumer() const { return Consumer; }
1358 ASTMutationListener *getASTMutationListener() const;
1359 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1360
1361 ///Registers an external source. If an external source already exists,
1362 /// creates a multiplex external source and appends to it.
1363 ///
1364 ///\param[in] E - A non-null external sema source.
1365 ///
1366 void addExternalSource(ExternalSemaSource *E);
1367
1368 void PrintStats() const;
1369
1370 /// Warn that the stack is nearly exhausted.
1371 void warnStackExhausted(SourceLocation Loc);
1372
1373 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1374 /// guaranteed). Produces a warning if we're low on stack space and allocates
1375 /// more in that case. Use this in code that may recurse deeply (for example,
1376 /// in template instantiation) to avoid stack overflow.
1377 void runWithSufficientStackSpace(SourceLocation Loc,
1378 llvm::function_ref<void()> Fn);
1379
1380 /// Helper class that creates diagnostics with optional
1381 /// template instantiation stacks.
1382 ///
1383 /// This class provides a wrapper around the basic DiagnosticBuilder
1384 /// class that emits diagnostics. SemaDiagnosticBuilder is
1385 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1386 /// does) and, if the diagnostic comes from inside a template
1387 /// instantiation, printing the template instantiation stack as
1388 /// well.
1389 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1390 Sema &SemaRef;
1391 unsigned DiagID;
1392
1393 public:
1394 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1395 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1396
1397 // This is a cunning lie. DiagnosticBuilder actually performs move
1398 // construction in its copy constructor (but due to varied uses, it's not
1399 // possible to conveniently express this as actual move construction). So
1400 // the default copy ctor here is fine, because the base class disables the
1401 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1402 // in that case anwyay.
1403 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1404
1405 ~SemaDiagnosticBuilder() {
1406 // If we aren't active, there is nothing to do.
1407 if (!isActive()) return;
3
Taking false branch
1408
1409 // Otherwise, we need to emit the diagnostic. First flush the underlying
1410 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1411 // won't emit the diagnostic in its own destructor.
1412 //
1413 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1414 // do its own needless checks to see if the diagnostic needs to be
1415 // emitted. However, because we take care to ensure that the builder
1416 // objects never escape, a sufficiently smart compiler will be able to
1417 // eliminate that code.
1418 FlushCounts();
1419 Clear();
1420
1421 // Dispatch to Sema to emit the diagnostic.
1422 SemaRef.EmitCurrentDiagnostic(DiagID);
4
Value assigned to field 'CurContext'
1423 }
1424
1425 /// Teach operator<< to produce an object of the correct type.
1426 template<typename T>
1427 friend const SemaDiagnosticBuilder &operator<<(
1428 const SemaDiagnosticBuilder &Diag, const T &Value) {
1429 const DiagnosticBuilder &BaseDiag = Diag;
1430 BaseDiag << Value;
1431 return Diag;
1432 }
1433 };
1434
1435 /// Emit a diagnostic.
1436 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1437 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1438 return SemaDiagnosticBuilder(DB, *this, DiagID);
1439 }
1440
1441 /// Emit a partial diagnostic.
1442 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1443
1444 /// Build a partial diagnostic.
1445 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1446
1447 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1448
1449 /// Get a string to suggest for zero-initialization of a type.
1450 std::string
1451 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1452 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1453
1454 /// Calls \c Lexer::getLocForEndOfToken()
1455 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1456
1457 /// Retrieve the module loader associated with the preprocessor.
1458 ModuleLoader &getModuleLoader() const;
1459
1460 /// Invent a new identifier for parameters of abbreviated templates.
1461 IdentifierInfo *
1462 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1463 unsigned Index);
1464
1465 void emitAndClearUnusedLocalTypedefWarnings();
1466
1467 enum TUFragmentKind {
1468 /// The global module fragment, between 'module;' and a module-declaration.
1469 Global,
1470 /// A normal translation unit fragment. For a non-module unit, this is the
1471 /// entire translation unit. Otherwise, it runs from the module-declaration
1472 /// to the private-module-fragment (if any) or the end of the TU (if not).
1473 Normal,
1474 /// The private module fragment, between 'module :private;' and the end of
1475 /// the translation unit.
1476 Private
1477 };
1478
1479 void ActOnStartOfTranslationUnit();
1480 void ActOnEndOfTranslationUnit();
1481 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1482
1483 void CheckDelegatingCtorCycles();
1484
1485 Scope *getScopeForContext(DeclContext *Ctx);
1486
1487 void PushFunctionScope();
1488 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1489 sema::LambdaScopeInfo *PushLambdaScope();
1490
1491 /// This is used to inform Sema what the current TemplateParameterDepth
1492 /// is during Parsing. Currently it is used to pass on the depth
1493 /// when parsing generic lambda 'auto' parameters.
1494 void RecordParsingTemplateParameterDepth(unsigned Depth);
1495
1496 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1497 RecordDecl *RD, CapturedRegionKind K,
1498 unsigned OpenMPCaptureLevel = 0);
1499
1500 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1501 /// time after they've been popped.
1502 class PoppedFunctionScopeDeleter {
1503 Sema *Self;
1504
1505 public:
1506 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1507 void operator()(sema::FunctionScopeInfo *Scope) const;
1508 };
1509
1510 using PoppedFunctionScopePtr =
1511 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1512
1513 PoppedFunctionScopePtr
1514 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1515 const Decl *D = nullptr,
1516 QualType BlockType = QualType());
1517
1518 sema::FunctionScopeInfo *getCurFunction() const {
1519 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1520 }
1521
1522 sema::FunctionScopeInfo *getEnclosingFunction() const;
1523
1524 void setFunctionHasBranchIntoScope();
1525 void setFunctionHasBranchProtectedScope();
1526 void setFunctionHasIndirectGoto();
1527
1528 void PushCompoundScope(bool IsStmtExpr);
1529 void PopCompoundScope();
1530
1531 sema::CompoundScopeInfo &getCurCompoundScope() const;
1532
1533 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1534
1535 /// Retrieve the current block, if any.
1536 sema::BlockScopeInfo *getCurBlock();
1537
1538 /// Get the innermost lambda enclosing the current location, if any. This
1539 /// looks through intervening non-lambda scopes such as local functions and
1540 /// blocks.
1541 sema::LambdaScopeInfo *getEnclosingLambda() const;
1542
1543 /// Retrieve the current lambda scope info, if any.
1544 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1545 /// lambda scope info ignoring all inner capturing scopes that are not
1546 /// lambda scopes.
1547 sema::LambdaScopeInfo *
1548 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1549
1550 /// Retrieve the current generic lambda info, if any.
1551 sema::LambdaScopeInfo *getCurGenericLambda();
1552
1553 /// Retrieve the current captured region, if any.
1554 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1555
1556 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1557 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1558
1559 /// Called before parsing a function declarator belonging to a function
1560 /// declaration.
1561 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
1562 unsigned TemplateParameterDepth);
1563
1564 /// Called after parsing a function declarator belonging to a function
1565 /// declaration.
1566 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
1567
1568 void ActOnComment(SourceRange Comment);
1569
1570 //===--------------------------------------------------------------------===//
1571 // Type Analysis / Processing: SemaType.cpp.
1572 //
1573
1574 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1575 const DeclSpec *DS = nullptr);
1576 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1577 const DeclSpec *DS = nullptr);
1578 QualType BuildPointerType(QualType T,
1579 SourceLocation Loc, DeclarationName Entity);
1580 QualType BuildReferenceType(QualType T, bool LValueRef,
1581 SourceLocation Loc, DeclarationName Entity);
1582 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1583 Expr *ArraySize, unsigned Quals,
1584 SourceRange Brackets, DeclarationName Entity);
1585 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1586 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1587 SourceLocation AttrLoc);
1588 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1589 SourceLocation AttrLoc);
1590
1591 /// Same as above, but constructs the AddressSpace index if not provided.
1592 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1593 SourceLocation AttrLoc);
1594
1595 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1596
1597 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1598
1599 /// Build a function type.
1600 ///
1601 /// This routine checks the function type according to C++ rules and
1602 /// under the assumption that the result type and parameter types have
1603 /// just been instantiated from a template. It therefore duplicates
1604 /// some of the behavior of GetTypeForDeclarator, but in a much
1605 /// simpler form that is only suitable for this narrow use case.
1606 ///
1607 /// \param T The return type of the function.
1608 ///
1609 /// \param ParamTypes The parameter types of the function. This array
1610 /// will be modified to account for adjustments to the types of the
1611 /// function parameters.
1612 ///
1613 /// \param Loc The location of the entity whose type involves this
1614 /// function type or, if there is no such entity, the location of the
1615 /// type that will have function type.
1616 ///
1617 /// \param Entity The name of the entity that involves the function
1618 /// type, if known.
1619 ///
1620 /// \param EPI Extra information about the function type. Usually this will
1621 /// be taken from an existing function with the same prototype.
1622 ///
1623 /// \returns A suitable function type, if there are no errors. The
1624 /// unqualified type will always be a FunctionProtoType.
1625 /// Otherwise, returns a NULL type.
1626 QualType BuildFunctionType(QualType T,
1627 MutableArrayRef<QualType> ParamTypes,
1628 SourceLocation Loc, DeclarationName Entity,
1629 const FunctionProtoType::ExtProtoInfo &EPI);
1630
1631 QualType BuildMemberPointerType(QualType T, QualType Class,
1632 SourceLocation Loc,
1633 DeclarationName Entity);
1634 QualType BuildBlockPointerType(QualType T,
1635 SourceLocation Loc, DeclarationName Entity);
1636 QualType BuildParenType(QualType T);
1637 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1638 QualType BuildReadPipeType(QualType T,
1639 SourceLocation Loc);
1640 QualType BuildWritePipeType(QualType T,
1641 SourceLocation Loc);
1642
1643 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1644 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1645
1646 /// Package the given type and TSI into a ParsedType.
1647 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1648 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1649 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1650 static QualType GetTypeFromParser(ParsedType Ty,
1651 TypeSourceInfo **TInfo = nullptr);
1652 CanThrowResult canThrow(const Stmt *E);
1653 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1654 const FunctionProtoType *FPT);
1655 void UpdateExceptionSpec(FunctionDecl *FD,
1656 const FunctionProtoType::ExceptionSpecInfo &ESI);
1657 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1658 bool CheckDistantExceptionSpec(QualType T);
1659 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1660 bool CheckEquivalentExceptionSpec(
1661 const FunctionProtoType *Old, SourceLocation OldLoc,
1662 const FunctionProtoType *New, SourceLocation NewLoc);
1663 bool CheckEquivalentExceptionSpec(
1664 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1665 const FunctionProtoType *Old, SourceLocation OldLoc,
1666 const FunctionProtoType *New, SourceLocation NewLoc);
1667 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1668 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1669 const PartialDiagnostic &NestedDiagID,
1670 const PartialDiagnostic &NoteID,
1671 const PartialDiagnostic &NoThrowDiagID,
1672 const FunctionProtoType *Superset,
1673 SourceLocation SuperLoc,
1674 const FunctionProtoType *Subset,
1675 SourceLocation SubLoc);
1676 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1677 const PartialDiagnostic &NoteID,
1678 const FunctionProtoType *Target,
1679 SourceLocation TargetLoc,
1680 const FunctionProtoType *Source,
1681 SourceLocation SourceLoc);
1682
1683 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1684
1685 /// The parser has parsed the context-sensitive type 'instancetype'
1686 /// in an Objective-C message declaration. Return the appropriate type.
1687 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1688
1689 /// Abstract class used to diagnose incomplete types.
1690 struct TypeDiagnoser {
1691 TypeDiagnoser() {}
1692
1693 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1694 virtual ~TypeDiagnoser() {}
1695 };
1696
1697 static int getPrintable(int I) { return I; }
1698 static unsigned getPrintable(unsigned I) { return I; }
1699 static bool getPrintable(bool B) { return B; }
1700 static const char * getPrintable(const char *S) { return S; }
1701 static StringRef getPrintable(StringRef S) { return S; }
1702 static const std::string &getPrintable(const std::string &S) { return S; }
1703 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1704 return II;
1705 }
1706 static DeclarationName getPrintable(DeclarationName N) { return N; }
1707 static QualType getPrintable(QualType T) { return T; }
1708 static SourceRange getPrintable(SourceRange R) { return R; }
1709 static SourceRange getPrintable(SourceLocation L) { return L; }
1710 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1711 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1712
1713 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1714 unsigned DiagID;
1715 std::tuple<const Ts &...> Args;
1716
1717 template <std::size_t... Is>
1718 void emit(const SemaDiagnosticBuilder &DB,
1719 std::index_sequence<Is...>) const {
1720 // Apply all tuple elements to the builder in order.
1721 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1722 (void)Dummy;
1723 }
1724
1725 public:
1726 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1727 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1728 assert(DiagID != 0 && "no diagnostic for type diagnoser")((DiagID != 0 && "no diagnostic for type diagnoser") ?
static_cast<void> (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 1728, __PRETTY_FUNCTION__))
;
1729 }
1730
1731 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1732 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1733 emit(DB, std::index_sequence_for<Ts...>());
1734 DB << T;
1735 }
1736 };
1737
1738private:
1739 /// Methods for marking which expressions involve dereferencing a pointer
1740 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1741 /// they are parsed, meaning that a noderef pointer may not be accessed. For
1742 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1743 /// `*p`, but need to check that `address of` is called on it. This requires
1744 /// keeping a container of all pending expressions and checking if the address
1745 /// of them are eventually taken.
1746 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1747 void CheckAddressOfNoDeref(const Expr *E);
1748 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1749
1750 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1751 TypeDiagnoser *Diagnoser);
1752
1753 struct ModuleScope {
1754 SourceLocation BeginLoc;
1755 clang::Module *Module = nullptr;
1756 bool ModuleInterface = false;
1757 bool ImplicitGlobalModuleFragment = false;
1758 VisibleModuleSet OuterVisibleModules;
1759 };
1760 /// The modules we're currently parsing.
1761 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1762
1763 /// Namespace definitions that we will export when they finish.
1764 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1765
1766 /// Get the module whose scope we are currently within.
1767 Module *getCurrentModule() const {
1768 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1769 }
1770
1771 VisibleModuleSet VisibleModules;
1772
1773public:
1774 /// Get the module owning an entity.
1775 Module *getOwningModule(const Decl *Entity) {
1776 return Entity->getOwningModule();
1777 }
1778
1779 /// Make a merged definition of an existing hidden definition \p ND
1780 /// visible at the specified location.
1781 void makeMergedDefinitionVisible(NamedDecl *ND);
1782
1783 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1784
1785 /// Determine whether a declaration is visible to name lookup.
1786 bool isVisible(const NamedDecl *D) {
1787 return !D->isHidden() || isVisibleSlow(D);
1788 }
1789
1790 /// Determine whether any declaration of an entity is visible.
1791 bool
1792 hasVisibleDeclaration(const NamedDecl *D,
1793 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1794 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1795 }
1796 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1797 llvm::SmallVectorImpl<Module *> *Modules);
1798
1799 bool hasVisibleMergedDefinition(NamedDecl *Def);
1800 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1801
1802 /// Determine if \p D and \p Suggested have a structurally compatible
1803 /// layout as described in C11 6.2.7/1.
1804 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1805
1806 /// Determine if \p D has a visible definition. If not, suggest a declaration
1807 /// that should be made visible to expose the definition.
1808 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1809 bool OnlyNeedComplete = false);
1810 bool hasVisibleDefinition(const NamedDecl *D) {
1811 NamedDecl *Hidden;
1812 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1813 }
1814
1815 /// Determine if the template parameter \p D has a visible default argument.
1816 bool
1817 hasVisibleDefaultArgument(const NamedDecl *D,
1818 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1819
1820 /// Determine if there is a visible declaration of \p D that is an explicit
1821 /// specialization declaration for a specialization of a template. (For a
1822 /// member specialization, use hasVisibleMemberSpecialization.)
1823 bool hasVisibleExplicitSpecialization(
1824 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1825
1826 /// Determine if there is a visible declaration of \p D that is a member
1827 /// specialization declaration (as opposed to an instantiated declaration).
1828 bool hasVisibleMemberSpecialization(
1829 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1830
1831 /// Determine if \p A and \p B are equivalent internal linkage declarations
1832 /// from different modules, and thus an ambiguity error can be downgraded to
1833 /// an extension warning.
1834 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1835 const NamedDecl *B);
1836 void diagnoseEquivalentInternalLinkageDeclarations(
1837 SourceLocation Loc, const NamedDecl *D,
1838 ArrayRef<const NamedDecl *> Equiv);
1839
1840 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1841
1842 bool isCompleteType(SourceLocation Loc, QualType T) {
1843 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1844 }
1845 bool RequireCompleteType(SourceLocation Loc, QualType T,
1846 TypeDiagnoser &Diagnoser);
1847 bool RequireCompleteType(SourceLocation Loc, QualType T,
1848 unsigned DiagID);
1849
1850 template <typename... Ts>
1851 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1852 const Ts &...Args) {
1853 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1854 return RequireCompleteType(Loc, T, Diagnoser);
1855 }
1856
1857 void completeExprArrayBound(Expr *E);
1858 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1859 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1860
1861 template <typename... Ts>
1862 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1863 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1864 return RequireCompleteExprType(E, Diagnoser);
1865 }
1866
1867 bool RequireLiteralType(SourceLocation Loc, QualType T,
1868 TypeDiagnoser &Diagnoser);
1869 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1870
1871 template <typename... Ts>
1872 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1873 const Ts &...Args) {
1874 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1875 return RequireLiteralType(Loc, T, Diagnoser);
1876 }
1877
1878 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1879 const CXXScopeSpec &SS, QualType T,
1880 TagDecl *OwnedTagDecl = nullptr);
1881
1882 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1883 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1884 /// context, such as when building a type for decltype(auto).
1885 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1886 bool AsUnevaluated = true);
1887 QualType BuildUnaryTransformType(QualType BaseType,
1888 UnaryTransformType::UTTKind UKind,
1889 SourceLocation Loc);
1890
1891 //===--------------------------------------------------------------------===//
1892 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1893 //
1894
1895 struct SkipBodyInfo {
1896 SkipBodyInfo()
1897 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1898 New(nullptr) {}
1899 bool ShouldSkip;
1900 bool CheckSameAsPrevious;
1901 NamedDecl *Previous;
1902 NamedDecl *New;
1903 };
1904
1905 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1906
1907 void DiagnoseUseOfUnimplementedSelectors();
1908
1909 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1910
1911 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1912 Scope *S, CXXScopeSpec *SS = nullptr,
1913 bool isClassName = false, bool HasTrailingDot = false,
1914 ParsedType ObjectType = nullptr,
1915 bool IsCtorOrDtorName = false,
1916 bool WantNontrivialTypeSourceInfo = false,
1917 bool IsClassTemplateDeductionContext = true,
1918 IdentifierInfo **CorrectedII = nullptr);
1919 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1920 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1921 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1922 SourceLocation IILoc,
1923 Scope *S,
1924 CXXScopeSpec *SS,
1925 ParsedType &SuggestedType,
1926 bool IsTemplateName = false);
1927
1928 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1929 /// type name has failed in a dependent context. In these situations, we
1930 /// automatically form a DependentTypeName that will retry lookup in a related
1931 /// scope during instantiation.
1932 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1933 SourceLocation NameLoc,
1934 bool IsTemplateTypeArg);
1935
1936 /// Describes the result of the name lookup and resolution performed
1937 /// by \c ClassifyName().
1938 enum NameClassificationKind {
1939 /// This name is not a type or template in this context, but might be
1940 /// something else.
1941 NC_Unknown,
1942 /// Classification failed; an error has been produced.
1943 NC_Error,
1944 /// The name has been typo-corrected to a keyword.
1945 NC_Keyword,
1946 /// The name was classified as a type.
1947 NC_Type,
1948 /// The name was classified as a specific non-type, non-template
1949 /// declaration. ActOnNameClassifiedAsNonType should be called to
1950 /// convert the declaration to an expression.
1951 NC_NonType,
1952 /// The name was classified as an ADL-only function name.
1953 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
1954 /// result to an expression.
1955 NC_UndeclaredNonType,
1956 /// The name denotes a member of a dependent type that could not be
1957 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
1958 /// convert the result to an expression.
1959 NC_DependentNonType,
1960 /// The name was classified as a non-type, and an expression representing
1961 /// that name has been formed.
1962 NC_ContextIndependentExpr,
1963 /// The name was classified as a template whose specializations are types.
1964 NC_TypeTemplate,
1965 /// The name was classified as a variable template name.
1966 NC_VarTemplate,
1967 /// The name was classified as a function template name.
1968 NC_FunctionTemplate,
1969 /// The name was classified as an ADL-only function template name.
1970 NC_UndeclaredTemplate,
1971 /// The name was classified as a concept name.
1972 NC_Concept,
1973 };
1974
1975 class NameClassification {
1976 NameClassificationKind Kind;
1977 union {
1978 ExprResult Expr;
1979 NamedDecl *NonTypeDecl;
1980 TemplateName Template;
1981 ParsedType Type;
1982 };
1983
1984 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1985
1986 public:
1987 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1988
1989 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1990
1991 static NameClassification Error() {
1992 return NameClassification(NC_Error);
1993 }
1994
1995 static NameClassification Unknown() {
1996 return NameClassification(NC_Unknown);
1997 }
1998
1999 static NameClassification ContextIndependentExpr(ExprResult E) {
2000 NameClassification Result(NC_ContextIndependentExpr);
2001 Result.Expr = E;
2002 return Result;
2003 }
2004
2005 static NameClassification NonType(NamedDecl *D) {
2006 NameClassification Result(NC_NonType);
2007 Result.NonTypeDecl = D;
2008 return Result;
2009 }
2010
2011 static NameClassification UndeclaredNonType() {
2012 return NameClassification(NC_UndeclaredNonType);
2013 }
2014
2015 static NameClassification DependentNonType() {
2016 return NameClassification(NC_DependentNonType);
2017 }
2018
2019 static NameClassification TypeTemplate(TemplateName Name) {
2020 NameClassification Result(NC_TypeTemplate);
2021 Result.Template = Name;
2022 return Result;
2023 }
2024
2025 static NameClassification VarTemplate(TemplateName Name) {
2026 NameClassification Result(NC_VarTemplate);
2027 Result.Template = Name;
2028 return Result;
2029 }
2030
2031 static NameClassification FunctionTemplate(TemplateName Name) {
2032 NameClassification Result(NC_FunctionTemplate);
2033 Result.Template = Name;
2034 return Result;
2035 }
2036
2037 static NameClassification Concept(TemplateName Name) {
2038 NameClassification Result(NC_Concept);
2039 Result.Template = Name;
2040 return Result;
2041 }
2042
2043 static NameClassification UndeclaredTemplate(TemplateName Name) {
2044 NameClassification Result(NC_UndeclaredTemplate);
2045 Result.Template = Name;
2046 return Result;
2047 }
2048
2049 NameClassificationKind getKind() const { return Kind; }
2050
2051 ExprResult getExpression() const {
2052 assert(Kind == NC_ContextIndependentExpr)((Kind == NC_ContextIndependentExpr) ? static_cast<void>
(0) : __assert_fail ("Kind == NC_ContextIndependentExpr", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 2052, __PRETTY_FUNCTION__))
;
2053 return Expr;
2054 }
2055
2056 ParsedType getType() const {
2057 assert(Kind == NC_Type)((Kind == NC_Type) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 2057, __PRETTY_FUNCTION__))
;
2058 return Type;
2059 }
2060
2061 NamedDecl *getNonTypeDecl() const {
2062 assert(Kind == NC_NonType)((Kind == NC_NonType) ? static_cast<void> (0) : __assert_fail
("Kind == NC_NonType", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 2062, __PRETTY_FUNCTION__))
;
2063 return NonTypeDecl;
2064 }
2065
2066 TemplateName getTemplateName() const {
2067 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate
) ? static_cast<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 2069, __PRETTY_FUNCTION__))
2068 Kind == NC_VarTemplate || Kind == NC_Concept ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate
) ? static_cast<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 2069, __PRETTY_FUNCTION__))
2069 Kind == NC_UndeclaredTemplate)((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate
) ? static_cast<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 2069, __PRETTY_FUNCTION__))
;
2070 return Template;
2071 }
2072
2073 TemplateNameKind getTemplateNameKind() const {
2074 switch (Kind) {
2075 case NC_TypeTemplate:
2076 return TNK_Type_template;
2077 case NC_FunctionTemplate:
2078 return TNK_Function_template;
2079 case NC_VarTemplate:
2080 return TNK_Var_template;
2081 case NC_Concept:
2082 return TNK_Concept_template;
2083 case NC_UndeclaredTemplate:
2084 return TNK_Undeclared_template;
2085 default:
2086 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 2086)
;
2087 }
2088 }
2089 };
2090
2091 /// Perform name lookup on the given name, classifying it based on
2092 /// the results of name lookup and the following token.
2093 ///
2094 /// This routine is used by the parser to resolve identifiers and help direct
2095 /// parsing. When the identifier cannot be found, this routine will attempt
2096 /// to correct the typo and classify based on the resulting name.
2097 ///
2098 /// \param S The scope in which we're performing name lookup.
2099 ///
2100 /// \param SS The nested-name-specifier that precedes the name.
2101 ///
2102 /// \param Name The identifier. If typo correction finds an alternative name,
2103 /// this pointer parameter will be updated accordingly.
2104 ///
2105 /// \param NameLoc The location of the identifier.
2106 ///
2107 /// \param NextToken The token following the identifier. Used to help
2108 /// disambiguate the name.
2109 ///
2110 /// \param CCC The correction callback, if typo correction is desired.
2111 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2112 IdentifierInfo *&Name, SourceLocation NameLoc,
2113 const Token &NextToken,
2114 CorrectionCandidateCallback *CCC = nullptr);
2115
2116 /// Act on the result of classifying a name as an undeclared (ADL-only)
2117 /// non-type declaration.
2118 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2119 SourceLocation NameLoc);
2120 /// Act on the result of classifying a name as an undeclared member of a
2121 /// dependent base class.
2122 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2123 IdentifierInfo *Name,
2124 SourceLocation NameLoc,
2125 bool IsAddressOfOperand);
2126 /// Act on the result of classifying a name as a specific non-type
2127 /// declaration.
2128 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2129 NamedDecl *Found,
2130 SourceLocation NameLoc,
2131 const Token &NextToken);
2132
2133 /// Describes the detailed kind of a template name. Used in diagnostics.
2134 enum class TemplateNameKindForDiagnostics {
2135 ClassTemplate,
2136 FunctionTemplate,
2137 VarTemplate,
2138 AliasTemplate,
2139 TemplateTemplateParam,
2140 Concept,
2141 DependentTemplate
2142 };
2143 TemplateNameKindForDiagnostics
2144 getTemplateNameKindForDiagnostics(TemplateName Name);
2145
2146 /// Determine whether it's plausible that E was intended to be a
2147 /// template-name.
2148 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2149 if (!getLangOpts().CPlusPlus || E.isInvalid())
2150 return false;
2151 Dependent = false;
2152 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2153 return !DRE->hasExplicitTemplateArgs();
2154 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2155 return !ME->hasExplicitTemplateArgs();
2156 Dependent = true;
2157 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2158 return !DSDRE->hasExplicitTemplateArgs();
2159 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2160 return !DSME->hasExplicitTemplateArgs();
2161 // Any additional cases recognized here should also be handled by
2162 // diagnoseExprIntendedAsTemplateName.
2163 return false;
2164 }
2165 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2166 SourceLocation Less,
2167 SourceLocation Greater);
2168
2169 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2170
2171 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2172 MultiTemplateParamsArg TemplateParameterLists);
2173 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2174 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2175 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2176 DeclarationName Name, SourceLocation Loc,
2177 bool IsTemplateId);
2178 void
2179 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2180 SourceLocation FallbackLoc,
2181 SourceLocation ConstQualLoc = SourceLocation(),
2182 SourceLocation VolatileQualLoc = SourceLocation(),
2183 SourceLocation RestrictQualLoc = SourceLocation(),
2184 SourceLocation AtomicQualLoc = SourceLocation(),
2185 SourceLocation UnalignedQualLoc = SourceLocation());
2186
2187 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2188 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2189 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2190 const LookupResult &R);
2191 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2192 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2193 const LookupResult &R);
2194 void CheckShadow(Scope *S, VarDecl *D);
2195
2196 /// Warn if 'E', which is an expression that is about to be modified, refers
2197 /// to a shadowing declaration.
2198 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2199
2200 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2201
2202private:
2203 /// Map of current shadowing declarations to shadowed declarations. Warn if
2204 /// it looks like the user is trying to modify the shadowing declaration.
2205 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2206
2207public:
2208 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2209 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2210 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2211 TypedefNameDecl *NewTD);
2212 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2213 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2214 TypeSourceInfo *TInfo,
2215 LookupResult &Previous);
2216 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2217 LookupResult &Previous, bool &Redeclaration);
2218 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2219 TypeSourceInfo *TInfo,
2220 LookupResult &Previous,
2221 MultiTemplateParamsArg TemplateParamLists,
2222 bool &AddToScope,
2223 ArrayRef<BindingDecl *> Bindings = None);
2224 NamedDecl *
2225 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2226 MultiTemplateParamsArg TemplateParamLists);
2227 // Returns true if the variable declaration is a redeclaration
2228 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2229 void CheckVariableDeclarationType(VarDecl *NewVD);
2230 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2231 Expr *Init);
2232 void CheckCompleteVariableDeclaration(VarDecl *VD);
2233 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2234 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2235
2236 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2237 TypeSourceInfo *TInfo,
2238 LookupResult &Previous,
2239 MultiTemplateParamsArg TemplateParamLists,
2240 bool &AddToScope);
2241 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2242
2243 enum class CheckConstexprKind {
2244 /// Diagnose issues that are non-constant or that are extensions.
2245 Diagnose,
2246 /// Identify whether this function satisfies the formal rules for constexpr
2247 /// functions in the current lanugage mode (with no extensions).
2248 CheckValid
2249 };
2250
2251 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2252 CheckConstexprKind Kind);
2253
2254 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2255 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2256 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2257 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2258 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2259 // Returns true if the function declaration is a redeclaration
2260 bool CheckFunctionDeclaration(Scope *S,
2261 FunctionDecl *NewFD, LookupResult &Previous,
2262 bool IsMemberSpecialization);
2263 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2264 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2265 QualType NewT, QualType OldT);
2266 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2267 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2268 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2269 bool IsDefinition);
2270 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2271 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2272 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2273 SourceLocation Loc,
2274 QualType T);
2275 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2276 SourceLocation NameLoc, IdentifierInfo *Name,
2277 QualType T, TypeSourceInfo *TSInfo,
2278 StorageClass SC);
2279 void ActOnParamDefaultArgument(Decl *param,
2280 SourceLocation EqualLoc,
2281 Expr *defarg);
2282 void ActOnParamUnparsedDefaultArgument(Decl *param,
2283 SourceLocation EqualLoc,
2284 SourceLocation ArgLoc);
2285 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2286 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2287 SourceLocation EqualLoc);
2288
2289 // Contexts where using non-trivial C union types can be disallowed. This is
2290 // passed to err_non_trivial_c_union_in_invalid_context.
2291 enum NonTrivialCUnionContext {
2292 // Function parameter.
2293 NTCUC_FunctionParam,
2294 // Function return.
2295 NTCUC_FunctionReturn,
2296 // Default-initialized object.
2297 NTCUC_DefaultInitializedObject,
2298 // Variable with automatic storage duration.
2299 NTCUC_AutoVar,
2300 // Initializer expression that might copy from another object.
2301 NTCUC_CopyInit,
2302 // Assignment.
2303 NTCUC_Assignment,
2304 // Compound literal.
2305 NTCUC_CompoundLiteral,
2306 // Block capture.
2307 NTCUC_BlockCapture,
2308 // lvalue-to-rvalue conversion of volatile type.
2309 NTCUC_LValueToRValueVolatile,
2310 };
2311
2312 /// Emit diagnostics if the initializer or any of its explicit or
2313 /// implicitly-generated subexpressions require copying or
2314 /// default-initializing a type that is or contains a C union type that is
2315 /// non-trivial to copy or default-initialize.
2316 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2317
2318 // These flags are passed to checkNonTrivialCUnion.
2319 enum NonTrivialCUnionKind {
2320 NTCUK_Init = 0x1,
2321 NTCUK_Destruct = 0x2,
2322 NTCUK_Copy = 0x4,
2323 };
2324
2325 /// Emit diagnostics if a non-trivial C union type or a struct that contains
2326 /// a non-trivial C union is used in an invalid context.
2327 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2328 NonTrivialCUnionContext UseContext,
2329 unsigned NonTrivialKind);
2330
2331 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2332 void ActOnUninitializedDecl(Decl *dcl);
2333 void ActOnInitializerError(Decl *Dcl);
2334
2335 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2336 void ActOnCXXForRangeDecl(Decl *D);
2337 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2338 IdentifierInfo *Ident,
2339 ParsedAttributes &Attrs,
2340 SourceLocation AttrEnd);
2341 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2342 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2343 void CheckStaticLocalForDllExport(VarDecl *VD);
2344 void FinalizeDeclaration(Decl *D);
2345 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2346 ArrayRef<Decl *> Group);
2347 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2348
2349 /// Should be called on all declarations that might have attached
2350 /// documentation comments.
2351 void ActOnDocumentableDecl(Decl *D);
2352 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2353
2354 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2355 SourceLocation LocAfterDecls);
2356 void CheckForFunctionRedefinition(
2357 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2358 SkipBodyInfo *SkipBody = nullptr);
2359 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2360 MultiTemplateParamsArg TemplateParamLists,
2361 SkipBodyInfo *SkipBody = nullptr);
2362 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2363 SkipBodyInfo *SkipBody = nullptr);
2364 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
2365 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
2366 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2367 bool isObjCMethodDecl(Decl *D) {
2368 return D && isa<ObjCMethodDecl>(D);
2369 }
2370
2371 /// Determine whether we can delay parsing the body of a function or
2372 /// function template until it is used, assuming we don't care about emitting
2373 /// code for that function.
2374 ///
2375 /// This will be \c false if we may need the body of the function in the
2376 /// middle of parsing an expression (where it's impractical to switch to
2377 /// parsing a different function), for instance, if it's constexpr in C++11
2378 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2379 bool canDelayFunctionBody(const Declarator &D);
2380
2381 /// Determine whether we can skip parsing the body of a function
2382 /// definition, assuming we don't care about analyzing its body or emitting
2383 /// code for that function.
2384 ///
2385 /// This will be \c false only if we may need the body of the function in
2386 /// order to parse the rest of the program (for instance, if it is
2387 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2388 bool canSkipFunctionBody(Decl *D);
2389
2390 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2391 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2392 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2393 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2394 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2395
2396 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2397 /// attribute for which parsing is delayed.
2398 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2399
2400 /// Diagnose any unused parameters in the given sequence of
2401 /// ParmVarDecl pointers.
2402 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2403
2404 /// Diagnose whether the size of parameters or return value of a
2405 /// function or obj-c method definition is pass-by-value and larger than a
2406 /// specified threshold.
2407 void
2408 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2409 QualType ReturnTy, NamedDecl *D);
2410
2411 void DiagnoseInvalidJumps(Stmt *Body);
2412 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2413 SourceLocation AsmLoc,
2414 SourceLocation RParenLoc);
2415
2416 /// Handle a C++11 empty-declaration and attribute-declaration.
2417 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2418 SourceLocation SemiLoc);
2419
2420 enum class ModuleDeclKind {
2421 Interface, ///< 'export module X;'
2422 Implementation, ///< 'module X;'
2423 };
2424
2425 /// The parser has processed a module-declaration that begins the definition
2426 /// of a module interface or implementation.
2427 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2428 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2429 ModuleIdPath Path, bool IsFirstDecl);
2430
2431 /// The parser has processed a global-module-fragment declaration that begins
2432 /// the definition of the global module fragment of the current module unit.
2433 /// \param ModuleLoc The location of the 'module' keyword.
2434 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2435
2436 /// The parser has processed a private-module-fragment declaration that begins
2437 /// the definition of the private module fragment of the current module unit.
2438 /// \param ModuleLoc The location of the 'module' keyword.
2439 /// \param PrivateLoc The location of the 'private' keyword.
2440 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2441 SourceLocation PrivateLoc);
2442
2443 /// The parser has processed a module import declaration.
2444 ///
2445 /// \param StartLoc The location of the first token in the declaration. This
2446 /// could be the location of an '@', 'export', or 'import'.
2447 /// \param ExportLoc The location of the 'export' keyword, if any.
2448 /// \param ImportLoc The location of the 'import' keyword.
2449 /// \param Path The module access path.
2450 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2451 SourceLocation ExportLoc,
2452 SourceLocation ImportLoc, ModuleIdPath Path);
2453 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2454 SourceLocation ExportLoc,
2455 SourceLocation ImportLoc, Module *M,
2456 ModuleIdPath Path = {});
2457
2458 /// The parser has processed a module import translated from a
2459 /// #include or similar preprocessing directive.
2460 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2461 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2462
2463 /// The parsed has entered a submodule.
2464 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2465 /// The parser has left a submodule.
2466 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2467
2468 /// Create an implicit import of the given module at the given
2469 /// source location, for error recovery, if possible.
2470 ///
2471 /// This routine is typically used when an entity found by name lookup
2472 /// is actually hidden within a module that we know about but the user
2473 /// has forgotten to import.
2474 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2475 Module *Mod);
2476
2477 /// Kinds of missing import. Note, the values of these enumerators correspond
2478 /// to %select values in diagnostics.
2479 enum class MissingImportKind {
2480 Declaration,
2481 Definition,
2482 DefaultArgument,
2483 ExplicitSpecialization,
2484 PartialSpecialization
2485 };
2486
2487 /// Diagnose that the specified declaration needs to be visible but
2488 /// isn't, and suggest a module import that would resolve the problem.
2489 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2490 MissingImportKind MIK, bool Recover = true);
2491 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2492 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2493 MissingImportKind MIK, bool Recover);
2494
2495 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2496 SourceLocation LBraceLoc);
2497 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2498 SourceLocation RBraceLoc);
2499
2500 /// We've found a use of a templated declaration that would trigger an
2501 /// implicit instantiation. Check that any relevant explicit specializations
2502 /// and partial specializations are visible, and diagnose if not.
2503 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2504
2505 /// We've found a use of a template specialization that would select a
2506 /// partial specialization. Check that the partial specialization is visible,
2507 /// and diagnose if not.
2508 void checkPartialSpecializationVisibility(SourceLocation Loc,
2509 NamedDecl *Spec);
2510
2511 /// Retrieve a suitable printing policy for diagnostics.
2512 PrintingPolicy getPrintingPolicy() const {
2513 return getPrintingPolicy(Context, PP);
2514 }
2515
2516 /// Retrieve a suitable printing policy for diagnostics.
2517 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2518 const Preprocessor &PP);
2519
2520 /// Scope actions.
2521 void ActOnPopScope(SourceLocation Loc, Scope *S);
2522 void ActOnTranslationUnitScope(Scope *S);
2523
2524 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2525 RecordDecl *&AnonRecord);
2526 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2527 MultiTemplateParamsArg TemplateParams,
2528 bool IsExplicitInstantiation,
2529 RecordDecl *&AnonRecord);
2530
2531 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2532 AccessSpecifier AS,
2533 RecordDecl *Record,
2534 const PrintingPolicy &Policy);
2535
2536 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2537 RecordDecl *Record);
2538
2539 /// Common ways to introduce type names without a tag for use in diagnostics.
2540 /// Keep in sync with err_tag_reference_non_tag.
2541 enum NonTagKind {
2542 NTK_NonStruct,
2543 NTK_NonClass,
2544 NTK_NonUnion,
2545 NTK_NonEnum,
2546 NTK_Typedef,
2547 NTK_TypeAlias,
2548 NTK_Template,
2549 NTK_TypeAliasTemplate,
2550 NTK_TemplateTemplateArgument,
2551 };
2552
2553 /// Given a non-tag type declaration, returns an enum useful for indicating
2554 /// what kind of non-tag type this is.
2555 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2556
2557 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2558 TagTypeKind NewTag, bool isDefinition,
2559 SourceLocation NewTagLoc,
2560 const IdentifierInfo *Name);
2561
2562 enum TagUseKind {
2563 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2564 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2565 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2566 TUK_Friend // Friend declaration: 'friend struct foo;'
2567 };
2568
2569 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2570 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2571 SourceLocation NameLoc, const ParsedAttributesView &Attr,
2572 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2573 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2574 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2575 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2576 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2577 SkipBodyInfo *SkipBody = nullptr);
2578
2579 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2580 unsigned TagSpec, SourceLocation TagLoc,
2581 CXXScopeSpec &SS, IdentifierInfo *Name,
2582 SourceLocation NameLoc,
2583 const ParsedAttributesView &Attr,
2584 MultiTemplateParamsArg TempParamLists);
2585
2586 TypeResult ActOnDependentTag(Scope *S,
2587 unsigned TagSpec,
2588 TagUseKind TUK,
2589 const CXXScopeSpec &SS,
2590 IdentifierInfo *Name,
2591 SourceLocation TagLoc,
2592 SourceLocation NameLoc);
2593
2594 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2595 IdentifierInfo *ClassName,
2596 SmallVectorImpl<Decl *> &Decls);
2597 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2598 Declarator &D, Expr *BitfieldWidth);
2599
2600 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2601 Declarator &D, Expr *BitfieldWidth,
2602 InClassInitStyle InitStyle,
2603 AccessSpecifier AS);
2604 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2605 SourceLocation DeclStart, Declarator &D,
2606 Expr *BitfieldWidth,
2607 InClassInitStyle InitStyle,
2608 AccessSpecifier AS,
2609 const ParsedAttr &MSPropertyAttr);
2610
2611 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2612 TypeSourceInfo *TInfo,
2613 RecordDecl *Record, SourceLocation Loc,
2614 bool Mutable, Expr *BitfieldWidth,
2615 InClassInitStyle InitStyle,
2616 SourceLocation TSSL,
2617 AccessSpecifier AS, NamedDecl *PrevDecl,
2618 Declarator *D = nullptr);
2619
2620 bool CheckNontrivialField(FieldDecl *FD);
2621 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2622
2623 enum TrivialABIHandling {
2624 /// The triviality of a method unaffected by "trivial_abi".
2625 TAH_IgnoreTrivialABI,
2626
2627 /// The triviality of a method affected by "trivial_abi".
2628 TAH_ConsiderTrivialABI
2629 };
2630
2631 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2632 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2633 bool Diagnose = false);
2634
2635 /// For a defaulted function, the kind of defaulted function that it is.
2636 class DefaultedFunctionKind {
2637 CXXSpecialMember SpecialMember : 8;
2638 DefaultedComparisonKind Comparison : 8;
2639
2640 public:
2641 DefaultedFunctionKind()
2642 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
2643 }
2644 DefaultedFunctionKind(CXXSpecialMember CSM)
2645 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
2646 DefaultedFunctionKind(DefaultedComparisonKind Comp)
2647 : SpecialMember(CXXInvalid), Comparison(Comp) {}
2648
2649 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
2650 bool isComparison() const {
2651 return Comparison != DefaultedComparisonKind::None;
2652 }
2653
2654 explicit operator bool() const {
2655 return isSpecialMember() || isComparison();
2656 }
2657
2658 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
2659 DefaultedComparisonKind asComparison() const { return Comparison; }
2660
2661 /// Get the index of this function kind for use in diagnostics.
2662 unsigned getDiagnosticIndex() const {
2663 static_assert(CXXInvalid > CXXDestructor,
2664 "invalid should have highest index");
2665 static_assert((unsigned)DefaultedComparisonKind::None == 0,
2666 "none should be equal to zero");
2667 return SpecialMember + (unsigned)Comparison;
2668 }
2669 };
2670
2671 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
2672
2673 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
2674 return getDefaultedFunctionKind(MD).asSpecialMember();
2675 }
2676 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
2677 return getDefaultedFunctionKind(FD).asComparison();
2678 }
2679
2680 void ActOnLastBitfield(SourceLocation DeclStart,
2681 SmallVectorImpl<Decl *> &AllIvarDecls);
2682 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2683 Declarator &D, Expr *BitfieldWidth,
2684 tok::ObjCKeywordKind visibility);
2685
2686 // This is used for both record definitions and ObjC interface declarations.
2687 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2688 ArrayRef<Decl *> Fields, SourceLocation LBrac,
2689 SourceLocation RBrac, const ParsedAttributesView &AttrList);
2690
2691 /// ActOnTagStartDefinition - Invoked when we have entered the
2692 /// scope of a tag's definition (e.g., for an enumeration, class,
2693 /// struct, or union).
2694 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2695
2696 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2697 /// Differently from C++, actually parse the body and reject / error out
2698 /// in case of a structural mismatch.
2699 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2700 SkipBodyInfo &SkipBody);
2701
2702 typedef void *SkippedDefinitionContext;
2703
2704 /// Invoked when we enter a tag definition that we're skipping.
2705 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2706
2707 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2708
2709 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2710 /// C++ record definition's base-specifiers clause and are starting its
2711 /// member declarations.
2712 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2713 SourceLocation FinalLoc,
2714 bool IsFinalSpelledSealed,
2715 SourceLocation LBraceLoc);
2716
2717 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2718 /// the definition of a tag (enumeration, class, struct, or union).
2719 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2720 SourceRange BraceRange);
2721
2722 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2723
2724 void ActOnObjCContainerFinishDefinition();
2725
2726 /// Invoked when we must temporarily exit the objective-c container
2727 /// scope for parsing/looking-up C constructs.
2728 ///
2729 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2730 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2731 void ActOnObjCReenterContainerContext(DeclContext *DC);
2732
2733 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2734 /// error parsing the definition of a tag.
2735 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2736
2737 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2738 EnumConstantDecl *LastEnumConst,
2739 SourceLocation IdLoc,
2740 IdentifierInfo *Id,
2741 Expr *val);
2742 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2743 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2744 QualType EnumUnderlyingTy, bool IsFixed,
2745 const EnumDecl *Prev);
2746
2747 /// Determine whether the body of an anonymous enumeration should be skipped.
2748 /// \param II The name of the first enumerator.
2749 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2750 SourceLocation IILoc);
2751
2752 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2753 SourceLocation IdLoc, IdentifierInfo *Id,
2754 const ParsedAttributesView &Attrs,
2755 SourceLocation EqualLoc, Expr *Val);
2756 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2757 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
2758 const ParsedAttributesView &Attr);
2759
2760 DeclContext *getContainingDC(DeclContext *DC);
2761
2762 /// Set the current declaration context until it gets popped.
2763 void PushDeclContext(Scope *S, DeclContext *DC);
2764 void PopDeclContext();
2765
2766 /// EnterDeclaratorContext - Used when we must lookup names in the context
2767 /// of a declarator's nested name specifier.
2768 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2769 void ExitDeclaratorContext(Scope *S);
2770
2771 /// Push the parameters of D, which must be a function, into scope.
2772 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2773 void ActOnExitFunctionContext();
2774
2775 DeclContext *getFunctionLevelDeclContext();
2776
2777 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2778 /// to the function decl for the function being parsed. If we're currently
2779 /// in a 'block', this returns the containing context.
2780 FunctionDecl *getCurFunctionDecl();
2781
2782 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2783 /// the method decl for the method being parsed. If we're currently
2784 /// in a 'block', this returns the containing context.
2785 ObjCMethodDecl *getCurMethodDecl();
2786
2787 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2788 /// or C function we're in, otherwise return null. If we're currently
2789 /// in a 'block', this returns the containing context.
2790 NamedDecl *getCurFunctionOrMethodDecl();
2791
2792 /// Add this decl to the scope shadowed decl chains.
2793 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2794
2795 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2796 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2797 /// true if 'D' belongs to the given declaration context.
2798 ///
2799 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2800 /// enclosing namespace set of the context, rather than contained
2801 /// directly within it.
2802 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2803 bool AllowInlineNamespace = false);
2804
2805 /// Finds the scope corresponding to the given decl context, if it
2806 /// happens to be an enclosing scope. Otherwise return NULL.
2807 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2808
2809 /// Subroutines of ActOnDeclarator().
2810 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2811 TypeSourceInfo *TInfo);
2812 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2813
2814 /// Describes the kind of merge to perform for availability
2815 /// attributes (including "deprecated", "unavailable", and "availability").
2816 enum AvailabilityMergeKind {
2817 /// Don't merge availability attributes at all.
2818 AMK_None,
2819 /// Merge availability attributes for a redeclaration, which requires
2820 /// an exact match.
2821 AMK_Redeclaration,
2822 /// Merge availability attributes for an override, which requires
2823 /// an exact match or a weakening of constraints.
2824 AMK_Override,
2825 /// Merge availability attributes for an implementation of
2826 /// a protocol requirement.
2827 AMK_ProtocolImplementation,
2828 };
2829
2830 /// Describes the kind of priority given to an availability attribute.
2831 ///
2832 /// The sum of priorities deteremines the final priority of the attribute.
2833 /// The final priority determines how the attribute will be merged.
2834 /// An attribute with a lower priority will always remove higher priority
2835 /// attributes for the specified platform when it is being applied. An
2836 /// attribute with a higher priority will not be applied if the declaration
2837 /// already has an availability attribute with a lower priority for the
2838 /// specified platform. The final prirority values are not expected to match
2839 /// the values in this enumeration, but instead should be treated as a plain
2840 /// integer value. This enumeration just names the priority weights that are
2841 /// used to calculate that final vaue.
2842 enum AvailabilityPriority : int {
2843 /// The availability attribute was specified explicitly next to the
2844 /// declaration.
2845 AP_Explicit = 0,
2846
2847 /// The availability attribute was applied using '#pragma clang attribute'.
2848 AP_PragmaClangAttribute = 1,
2849
2850 /// The availability attribute for a specific platform was inferred from
2851 /// an availability attribute for another platform.
2852 AP_InferredFromOtherPlatform = 2
2853 };
2854
2855 /// Attribute merging methods. Return true if a new attribute was added.
2856 AvailabilityAttr *
2857 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
2858 IdentifierInfo *Platform, bool Implicit,
2859 VersionTuple Introduced, VersionTuple Deprecated,
2860 VersionTuple Obsoleted, bool IsUnavailable,
2861 StringRef Message, bool IsStrict, StringRef Replacement,
2862 AvailabilityMergeKind AMK, int Priority);
2863 TypeVisibilityAttr *
2864 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2865 TypeVisibilityAttr::VisibilityType Vis);
2866 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2867 VisibilityAttr::VisibilityType Vis);
2868 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
2869 StringRef Uuid);
2870 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
2871 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
2872 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
2873 const AttributeCommonInfo &CI,
2874 bool BestCase,
2875 MSInheritanceModel Model);
2876 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
2877 IdentifierInfo *Format, int FormatIdx,
2878 int FirstArg);
2879 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
2880 StringRef Name);
2881 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
2882 StringRef Name);
2883 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
2884 const AttributeCommonInfo &CI,
2885 const IdentifierInfo *Ident);
2886 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
2887 NoSpeculativeLoadHardeningAttr *
2888 mergeNoSpeculativeLoadHardeningAttr(Decl *D,
2889 const NoSpeculativeLoadHardeningAttr &AL);
2890 SpeculativeLoadHardeningAttr *
2891 mergeSpeculativeLoadHardeningAttr(Decl *D,
2892 const SpeculativeLoadHardeningAttr &AL);
2893 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
2894 const AttributeCommonInfo &CI);
2895 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
2896 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
2897 const InternalLinkageAttr &AL);
2898 CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
2899 CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
2900
2901 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2902 AvailabilityMergeKind AMK = AMK_Redeclaration);
2903 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2904 LookupResult &OldDecls);
2905 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2906 bool MergeTypeWithOld);
2907 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2908 Scope *S, bool MergeTypeWithOld);
2909 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2910 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2911 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2912 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2913 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2914 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2915 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2916
2917 // AssignmentAction - This is used by all the assignment diagnostic functions
2918 // to represent what is actually causing the operation
2919 enum AssignmentAction {
2920 AA_Assigning,
2921 AA_Passing,
2922 AA_Returning,
2923 AA_Converting,
2924 AA_Initializing,
2925 AA_Sending,
2926 AA_Casting,
2927 AA_Passing_CFAudited
2928 };
2929
2930 /// C++ Overloading.
2931 enum OverloadKind {
2932 /// This is a legitimate overload: the existing declarations are
2933 /// functions or function templates with different signatures.
2934 Ovl_Overload,
2935
2936 /// This is not an overload because the signature exactly matches
2937 /// an existing declaration.
2938 Ovl_Match,
2939
2940 /// This is not an overload because the lookup results contain a
2941 /// non-function.
2942 Ovl_NonFunction
2943 };
2944 OverloadKind CheckOverload(Scope *S,
2945 FunctionDecl *New,
2946 const LookupResult &OldDecls,
2947 NamedDecl *&OldDecl,
2948 bool IsForUsingDecl);
2949 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2950 bool ConsiderCudaAttrs = true,
2951 bool ConsiderRequiresClauses = true);
2952
2953 enum class AllowedExplicit {
2954 /// Allow no explicit functions to be used.
2955 None,
2956 /// Allow explicit conversion functions but not explicit constructors.
2957 Conversions,
2958 /// Allow both explicit conversion functions and explicit constructors.
2959 All
2960 };
2961
2962 ImplicitConversionSequence
2963 TryImplicitConversion(Expr *From, QualType ToType,
2964 bool SuppressUserConversions,
2965 AllowedExplicit AllowExplicit,
2966 bool InOverloadResolution,
2967 bool CStyle,
2968 bool AllowObjCWritebackConversion);
2969
2970 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2971 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2972 bool IsComplexPromotion(QualType FromType, QualType ToType);
2973 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2974 bool InOverloadResolution,
2975 QualType& ConvertedType, bool &IncompatibleObjC);
2976 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2977 QualType& ConvertedType, bool &IncompatibleObjC);
2978 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2979 QualType &ConvertedType);
2980 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2981 QualType& ConvertedType);
2982 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2983 const FunctionProtoType *NewType,
2984 unsigned *ArgPos = nullptr);
2985 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2986 QualType FromType, QualType ToType);
2987
2988 void maybeExtendBlockObject(ExprResult &E);
2989 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2990 bool CheckPointerConversion(Expr *From, QualType ToType,
2991 CastKind &Kind,
2992 CXXCastPath& BasePath,
2993 bool IgnoreBaseAccess,
2994 bool Diagnose = true);
2995 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2996 bool InOverloadResolution,
2997 QualType &ConvertedType);
2998 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2999 CastKind &Kind,
3000 CXXCastPath &BasePath,
3001 bool IgnoreBaseAccess);
3002 bool IsQualificationConversion(QualType FromType, QualType ToType,
3003 bool CStyle, bool &ObjCLifetimeConversion);
3004 bool IsFunctionConversion(QualType FromType, QualType ToType,
3005 QualType &ResultTy);
3006 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3007 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
3008
3009 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3010 const VarDecl *NRVOCandidate,
3011 QualType ResultType,
3012 Expr *Value,
3013 bool AllowNRVO = true);
3014
3015 bool CanPerformAggregateInitializationForOverloadResolution(
3016 const InitializedEntity &Entity, InitListExpr *From);
3017
3018 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3019 ExprResult Init);
3020 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3021 SourceLocation EqualLoc,
3022 ExprResult Init,
3023 bool TopLevelOfInitList = false,
3024 bool AllowExplicit = false);
3025 ExprResult PerformObjectArgumentInitialization(Expr *From,
3026 NestedNameSpecifier *Qualifier,
3027 NamedDecl *FoundDecl,
3028 CXXMethodDecl *Method);
3029
3030 /// Check that the lifetime of the initializer (and its subobjects) is
3031 /// sufficient for initializing the entity, and perform lifetime extension
3032 /// (when permitted) if not.
3033 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3034
3035 ExprResult PerformContextuallyConvertToBool(Expr *From);
3036 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3037
3038 /// Contexts in which a converted constant expression is required.
3039 enum CCEKind {
3040 CCEK_CaseValue, ///< Expression in a case label.
3041 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
3042 CCEK_TemplateArg, ///< Value of a non-type template parameter.
3043 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
3044 CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
3045 CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
3046 };
3047 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3048 llvm::APSInt &Value, CCEKind CCE);
3049 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3050 APValue &Value, CCEKind CCE);
3051
3052 /// Abstract base class used to perform a contextual implicit
3053 /// conversion from an expression to any type passing a filter.
3054 class ContextualImplicitConverter {
3055 public:
3056 bool Suppress;
3057 bool SuppressConversion;
3058
3059 ContextualImplicitConverter(bool Suppress = false,
3060 bool SuppressConversion = false)
3061 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3062
3063 /// Determine whether the specified type is a valid destination type
3064 /// for this conversion.
3065 virtual bool match(QualType T) = 0;
3066
3067 /// Emits a diagnostic complaining that the expression does not have
3068 /// integral or enumeration type.
3069 virtual SemaDiagnosticBuilder
3070 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3071
3072 /// Emits a diagnostic when the expression has incomplete class type.
3073 virtual SemaDiagnosticBuilder
3074 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3075
3076 /// Emits a diagnostic when the only matching conversion function
3077 /// is explicit.
3078 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3079 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3080
3081 /// Emits a note for the explicit conversion function.
3082 virtual SemaDiagnosticBuilder
3083 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3084
3085 /// Emits a diagnostic when there are multiple possible conversion
3086 /// functions.
3087 virtual SemaDiagnosticBuilder
3088 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3089
3090 /// Emits a note for one of the candidate conversions.
3091 virtual SemaDiagnosticBuilder
3092 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3093
3094 /// Emits a diagnostic when we picked a conversion function
3095 /// (for cases when we are not allowed to pick a conversion function).
3096 virtual SemaDiagnosticBuilder diagnoseConversion(
3097 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3098
3099 virtual ~ContextualImplicitConverter() {}
3100 };
3101
3102 class ICEConvertDiagnoser : public ContextualImplicitConverter {
3103 bool AllowScopedEnumerations;
3104
3105 public:
3106 ICEConvertDiagnoser(bool AllowScopedEnumerations,
3107 bool Suppress, bool SuppressConversion)
3108 : ContextualImplicitConverter(Suppress, SuppressConversion),
3109 AllowScopedEnumerations(AllowScopedEnumerations) {}
3110
3111 /// Match an integral or (possibly scoped) enumeration type.
3112 bool match(QualType T) override;
3113
3114 SemaDiagnosticBuilder
3115 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3116 return diagnoseNotInt(S, Loc, T);
3117 }
3118
3119 /// Emits a diagnostic complaining that the expression does not have
3120 /// integral or enumeration type.
3121 virtual SemaDiagnosticBuilder
3122 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3123 };
3124
3125 /// Perform a contextual implicit conversion.
3126 ExprResult PerformContextualImplicitConversion(
3127 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3128
3129
3130 enum ObjCSubscriptKind {
3131 OS_Array,
3132 OS_Dictionary,
3133 OS_Error
3134 };
3135 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3136
3137 // Note that LK_String is intentionally after the other literals, as
3138 // this is used for diagnostics logic.
3139 enum ObjCLiteralKind {
3140 LK_Array,
3141 LK_Dictionary,
3142 LK_Numeric,
3143 LK_Boxed,
3144 LK_String,
3145 LK_Block,
3146 LK_None
3147 };
3148 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3149
3150 ExprResult PerformObjectMemberConversion(Expr *From,
3151 NestedNameSpecifier *Qualifier,
3152 NamedDecl *FoundDecl,
3153 NamedDecl *Member);
3154
3155 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3156 // TODO: make this is a typesafe union.
3157 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
3158 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3159
3160 using ADLCallKind = CallExpr::ADLCallKind;
3161
3162 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3163 ArrayRef<Expr *> Args,
3164 OverloadCandidateSet &CandidateSet,
3165 bool SuppressUserConversions = false,
3166 bool PartialOverloading = false,
3167 bool AllowExplicit = true,
3168 bool AllowExplicitConversion = false,
3169 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3170 ConversionSequenceList EarlyConversions = None,
3171 OverloadCandidateParamOrder PO = {});
3172 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3173 ArrayRef<Expr *> Args,
3174 OverloadCandidateSet &CandidateSet,
3175 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3176 bool SuppressUserConversions = false,
3177 bool PartialOverloading = false,
3178 bool FirstArgumentIsBase = false);
3179 void AddMethodCandidate(DeclAccessPair FoundDecl,
3180 QualType ObjectType,
3181 Expr::Classification ObjectClassification,
3182 ArrayRef<Expr *> Args,
3183 OverloadCandidateSet& CandidateSet,
3184 bool SuppressUserConversion = false,
3185 OverloadCandidateParamOrder PO = {});
3186 void AddMethodCandidate(CXXMethodDecl *Method,
3187 DeclAccessPair FoundDecl,
3188 CXXRecordDecl *ActingContext, QualType ObjectType,
3189 Expr::Classification ObjectClassification,
3190 ArrayRef<Expr *> Args,
3191 OverloadCandidateSet& CandidateSet,
3192 bool SuppressUserConversions = false,
3193 bool PartialOverloading = false,
3194 ConversionSequenceList EarlyConversions = None,
3195 OverloadCandidateParamOrder PO = {});
3196 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3197 DeclAccessPair FoundDecl,
3198 CXXRecordDecl *ActingContext,
3199 TemplateArgumentListInfo *ExplicitTemplateArgs,
3200 QualType ObjectType,
3201 Expr::Classification ObjectClassification,
3202 ArrayRef<Expr *> Args,
3203 OverloadCandidateSet& CandidateSet,
3204 bool SuppressUserConversions = false,
3205 bool PartialOverloading = false,
3206 OverloadCandidateParamOrder PO = {});
3207 void AddTemplateOverloadCandidate(
3208 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3209 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3210 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3211 bool PartialOverloading = false, bool AllowExplicit = true,
3212 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3213 OverloadCandidateParamOrder PO = {});
3214 bool CheckNonDependentConversions(
3215 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3216 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3217 ConversionSequenceList &Conversions, bool SuppressUserConversions,
3218 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3219 Expr::Classification ObjectClassification = {},
3220 OverloadCandidateParamOrder PO = {});
3221 void AddConversionCandidate(
3222 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3223 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3224 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3225 bool AllowExplicit, bool AllowResultConversion = true);
3226 void AddTemplateConversionCandidate(
3227 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3228 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3229 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3230 bool AllowExplicit, bool AllowResultConversion = true);
3231 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3232 DeclAccessPair FoundDecl,
3233 CXXRecordDecl *ActingContext,
3234 const FunctionProtoType *Proto,
3235 Expr *Object, ArrayRef<Expr *> Args,
3236 OverloadCandidateSet& CandidateSet);
3237 void AddNonMemberOperatorCandidates(
3238 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3239 OverloadCandidateSet &CandidateSet,
3240 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3241 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3242 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3243 OverloadCandidateSet &CandidateSet,
3244 OverloadCandidateParamOrder PO = {});
3245 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3246 OverloadCandidateSet& CandidateSet,
3247 bool IsAssignmentOperator = false,
3248 unsigned NumContextualBoolArguments = 0);
3249 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3250 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3251 OverloadCandidateSet& CandidateSet);
3252 void AddArgumentDependentLookupCandidates(DeclarationName Name,
3253 SourceLocation Loc,
3254 ArrayRef<Expr *> Args,
3255 TemplateArgumentListInfo *ExplicitTemplateArgs,
3256 OverloadCandidateSet& CandidateSet,
3257 bool PartialOverloading = false);
3258
3259 // Emit as a 'note' the specific overload candidate
3260 void NoteOverloadCandidate(
3261 NamedDecl *Found, FunctionDecl *Fn,
3262 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3263 QualType DestType = QualType(), bool TakingAddress = false);
3264
3265 // Emit as a series of 'note's all template and non-templates identified by
3266 // the expression Expr
3267 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3268 bool TakingAddress = false);
3269
3270 /// Check the enable_if expressions on the given function. Returns the first
3271 /// failing attribute, or NULL if they were all successful.
3272 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
3273 bool MissingImplicitThis = false);
3274
3275 /// Find the failed Boolean condition within a given Boolean
3276 /// constant expression, and describe it with a string.
3277 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3278
3279 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3280 /// non-ArgDependent DiagnoseIfAttrs.
3281 ///
3282 /// Argument-dependent diagnose_if attributes should be checked each time a
3283 /// function is used as a direct callee of a function call.
3284 ///
3285 /// Returns true if any errors were emitted.
3286 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3287 const Expr *ThisArg,
3288 ArrayRef<const Expr *> Args,
3289 SourceLocation Loc);
3290
3291 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3292 /// ArgDependent DiagnoseIfAttrs.
3293 ///
3294 /// Argument-independent diagnose_if attributes should be checked on every use
3295 /// of a function.
3296 ///
3297 /// Returns true if any errors were emitted.
3298 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3299 SourceLocation Loc);
3300
3301 /// Returns whether the given function's address can be taken or not,
3302 /// optionally emitting a diagnostic if the address can't be taken.
3303 ///
3304 /// Returns false if taking the address of the function is illegal.
3305 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3306 bool Complain = false,
3307 SourceLocation Loc = SourceLocation());
3308
3309 // [PossiblyAFunctionType] --> [Return]
3310 // NonFunctionType --> NonFunctionType
3311 // R (A) --> R(A)
3312 // R (*)(A) --> R (A)
3313 // R (&)(A) --> R (A)
3314 // R (S::*)(A) --> R (A)
3315 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3316
3317 FunctionDecl *
3318 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3319 QualType TargetType,
3320 bool Complain,
3321 DeclAccessPair &Found,
3322 bool *pHadMultipleCandidates = nullptr);
3323
3324 FunctionDecl *
3325 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3326
3327 bool resolveAndFixAddressOfSingleOverloadCandidate(
3328 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3329
3330 FunctionDecl *
3331 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3332 bool Complain = false,
3333 DeclAccessPair *Found = nullptr);
3334
3335 bool ResolveAndFixSingleFunctionTemplateSpecialization(
3336 ExprResult &SrcExpr,
3337 bool DoFunctionPointerConverion = false,
3338 bool Complain = false,
3339 SourceRange OpRangeForComplaining = SourceRange(),
3340 QualType DestTypeForComplaining = QualType(),
3341 unsigned DiagIDForComplaining = 0);
3342
3343
3344 Expr *FixOverloadedFunctionReference(Expr *E,
3345 DeclAccessPair FoundDecl,
3346 FunctionDecl *Fn);
3347 ExprResult FixOverloadedFunctionReference(ExprResult,
3348 DeclAccessPair FoundDecl,
3349 FunctionDecl *Fn);
3350
3351 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3352 ArrayRef<Expr *> Args,
3353 OverloadCandidateSet &CandidateSet,
3354 bool PartialOverloading = false);
3355
3356 // An enum used to represent the different possible results of building a
3357 // range-based for loop.
3358 enum ForRangeStatus {
3359 FRS_Success,
3360 FRS_NoViableFunction,
3361 FRS_DiagnosticIssued
3362 };
3363
3364 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3365 SourceLocation RangeLoc,
3366 const DeclarationNameInfo &NameInfo,
3367 LookupResult &MemberLookup,
3368 OverloadCandidateSet *CandidateSet,
3369 Expr *Range, ExprResult *CallExpr);
3370
3371 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3372 UnresolvedLookupExpr *ULE,
3373 SourceLocation LParenLoc,
3374 MultiExprArg Args,
3375 SourceLocation RParenLoc,
3376 Expr *ExecConfig,
3377 bool AllowTypoCorrection=true,
3378 bool CalleesAddressIsTaken=false);
3379
3380 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3381 MultiExprArg Args, SourceLocation RParenLoc,
3382 OverloadCandidateSet *CandidateSet,
3383 ExprResult *Result);
3384
3385 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3386 UnaryOperatorKind Opc,
3387 const UnresolvedSetImpl &Fns,
3388 Expr *input, bool RequiresADL = true);
3389
3390 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
3391 OverloadedOperatorKind Op,
3392 const UnresolvedSetImpl &Fns,
3393 ArrayRef<Expr *> Args, bool RequiresADL = true);
3394 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3395 BinaryOperatorKind Opc,
3396 const UnresolvedSetImpl &Fns,
3397 Expr *LHS, Expr *RHS,
3398 bool RequiresADL = true,
3399 bool AllowRewrittenCandidates = true,
3400 FunctionDecl *DefaultedFn = nullptr);
3401 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
3402 const UnresolvedSetImpl &Fns,
3403 Expr *LHS, Expr *RHS,
3404 FunctionDecl *DefaultedFn);
3405
3406 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3407 SourceLocation RLoc,
3408 Expr *Base,Expr *Idx);
3409
3410 ExprResult
3411 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3412 SourceLocation LParenLoc,
3413 MultiExprArg Args,
3414 SourceLocation RParenLoc);
3415 ExprResult
3416 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3417 MultiExprArg Args,
3418 SourceLocation RParenLoc);
3419
3420 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3421 SourceLocation OpLoc,
3422 bool *NoArrowOperatorFound = nullptr);
3423
3424 /// CheckCallReturnType - Checks that a call expression's return type is
3425 /// complete. Returns true on failure. The location passed in is the location
3426 /// that best represents the call.
3427 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3428 CallExpr *CE, FunctionDecl *FD);
3429
3430 /// Helpers for dealing with blocks and functions.
3431 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3432 bool CheckParameterNames);
3433 void CheckCXXDefaultArguments(FunctionDecl *FD);
3434 void CheckExtraCXXDefaultArguments(Declarator &D);
3435 Scope *getNonFieldDeclScope(Scope *S);
3436
3437 /// \name Name lookup
3438 ///
3439 /// These routines provide name lookup that is used during semantic
3440 /// analysis to resolve the various kinds of names (identifiers,
3441 /// overloaded operator names, constructor names, etc.) into zero or
3442 /// more declarations within a particular scope. The major entry
3443 /// points are LookupName, which performs unqualified name lookup,
3444 /// and LookupQualifiedName, which performs qualified name lookup.
3445 ///
3446 /// All name lookup is performed based on some specific criteria,
3447 /// which specify what names will be visible to name lookup and how
3448 /// far name lookup should work. These criteria are important both
3449 /// for capturing language semantics (certain lookups will ignore
3450 /// certain names, for example) and for performance, since name
3451 /// lookup is often a bottleneck in the compilation of C++. Name
3452 /// lookup criteria is specified via the LookupCriteria enumeration.
3453 ///
3454 /// The results of name lookup can vary based on the kind of name
3455 /// lookup performed, the current language, and the translation
3456 /// unit. In C, for example, name lookup will either return nothing
3457 /// (no entity found) or a single declaration. In C++, name lookup
3458 /// can additionally refer to a set of overloaded functions or
3459 /// result in an ambiguity. All of the possible results of name
3460 /// lookup are captured by the LookupResult class, which provides
3461 /// the ability to distinguish among them.
3462 //@{
3463
3464 /// Describes the kind of name lookup to perform.
3465 enum LookupNameKind {
3466 /// Ordinary name lookup, which finds ordinary names (functions,
3467 /// variables, typedefs, etc.) in C and most kinds of names
3468 /// (functions, variables, members, types, etc.) in C++.
3469 LookupOrdinaryName = 0,
3470 /// Tag name lookup, which finds the names of enums, classes,
3471 /// structs, and unions.
3472 LookupTagName,
3473 /// Label name lookup.
3474 LookupLabel,
3475 /// Member name lookup, which finds the names of
3476 /// class/struct/union members.
3477 LookupMemberName,
3478 /// Look up of an operator name (e.g., operator+) for use with
3479 /// operator overloading. This lookup is similar to ordinary name
3480 /// lookup, but will ignore any declarations that are class members.
3481 LookupOperatorName,
3482 /// Look up a name following ~ in a destructor name. This is an ordinary
3483 /// lookup, but prefers tags to typedefs.
3484 LookupDestructorName,
3485 /// Look up of a name that precedes the '::' scope resolution
3486 /// operator in C++. This lookup completely ignores operator, object,
3487 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3488 LookupNestedNameSpecifierName,
3489 /// Look up a namespace name within a C++ using directive or
3490 /// namespace alias definition, ignoring non-namespace names (C++
3491 /// [basic.lookup.udir]p1).
3492 LookupNamespaceName,
3493 /// Look up all declarations in a scope with the given name,
3494 /// including resolved using declarations. This is appropriate
3495 /// for checking redeclarations for a using declaration.
3496 LookupUsingDeclName,
3497 /// Look up an ordinary name that is going to be redeclared as a
3498 /// name with linkage. This lookup ignores any declarations that
3499 /// are outside of the current scope unless they have linkage. See
3500 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3501 LookupRedeclarationWithLinkage,
3502 /// Look up a friend of a local class. This lookup does not look
3503 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3504 LookupLocalFriendName,
3505 /// Look up the name of an Objective-C protocol.
3506 LookupObjCProtocolName,
3507 /// Look up implicit 'self' parameter of an objective-c method.
3508 LookupObjCImplicitSelfParam,
3509 /// Look up the name of an OpenMP user-defined reduction operation.
3510 LookupOMPReductionName,
3511 /// Look up the name of an OpenMP user-defined mapper.
3512 LookupOMPMapperName,
3513 /// Look up any declaration with any name.
3514 LookupAnyName
3515 };
3516
3517 /// Specifies whether (or how) name lookup is being performed for a
3518 /// redeclaration (vs. a reference).
3519 enum RedeclarationKind {
3520 /// The lookup is a reference to this name that is not for the
3521 /// purpose of redeclaring the name.
3522 NotForRedeclaration = 0,
3523 /// The lookup results will be used for redeclaration of a name,
3524 /// if an entity by that name already exists and is visible.
3525 ForVisibleRedeclaration,
3526 /// The lookup results will be used for redeclaration of a name
3527 /// with external linkage; non-visible lookup results with external linkage
3528 /// may also be found.
3529 ForExternalRedeclaration
3530 };
3531
3532 RedeclarationKind forRedeclarationInCurContext() {
3533 // A declaration with an owning module for linkage can never link against
3534 // anything that is not visible. We don't need to check linkage here; if
3535 // the context has internal linkage, redeclaration lookup won't find things
3536 // from other TUs, and we can't safely compute linkage yet in general.
3537 if (cast<Decl>(CurContext)
3538 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3539 return ForVisibleRedeclaration;
3540 return ForExternalRedeclaration;
3541 }
3542
3543 /// The possible outcomes of name lookup for a literal operator.
3544 enum LiteralOperatorLookupResult {
3545 /// The lookup resulted in an error.
3546 LOLR_Error,
3547 /// The lookup found no match but no diagnostic was issued.
3548 LOLR_ErrorNoDiagnostic,
3549 /// The lookup found a single 'cooked' literal operator, which
3550 /// expects a normal literal to be built and passed to it.
3551 LOLR_Cooked,
3552 /// The lookup found a single 'raw' literal operator, which expects
3553 /// a string literal containing the spelling of the literal token.
3554 LOLR_Raw,
3555 /// The lookup found an overload set of literal operator templates,
3556 /// which expect the characters of the spelling of the literal token to be
3557 /// passed as a non-type template argument pack.
3558 LOLR_Template,
3559 /// The lookup found an overload set of literal operator templates,
3560 /// which expect the character type and characters of the spelling of the
3561 /// string literal token to be passed as template arguments.
3562 LOLR_StringTemplate
3563 };
3564
3565 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3566 CXXSpecialMember SM,
3567 bool ConstArg,
3568 bool VolatileArg,
3569 bool RValueThis,
3570 bool ConstThis,
3571 bool VolatileThis);
3572
3573 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3574 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3575 TypoRecoveryCallback;
3576
3577private:
3578 bool CppLookupName(LookupResult &R, Scope *S);
3579
3580 struct TypoExprState {
3581 std::unique_ptr<TypoCorrectionConsumer> Consumer;
3582 TypoDiagnosticGenerator DiagHandler;
3583 TypoRecoveryCallback RecoveryHandler;
3584 TypoExprState();
3585 TypoExprState(TypoExprState &&other) noexcept;
3586 TypoExprState &operator=(TypoExprState &&other) noexcept;
3587 };
3588
3589 /// The set of unhandled TypoExprs and their associated state.
3590 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3591
3592 /// Creates a new TypoExpr AST node.
3593 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3594 TypoDiagnosticGenerator TDG,
3595 TypoRecoveryCallback TRC);
3596
3597 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
3598 //
3599 // The boolean value will be true to indicate that the namespace was loaded
3600 // from an AST/PCH file, or false otherwise.
3601 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3602
3603 /// Whether we have already loaded known namespaces from an extenal
3604 /// source.
3605 bool LoadedExternalKnownNamespaces;
3606
3607 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
3608 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3609 /// should be skipped entirely.
3610 std::unique_ptr<TypoCorrectionConsumer>
3611 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3612 Sema::LookupNameKind LookupKind, Scope *S,
3613 CXXScopeSpec *SS,
3614 CorrectionCandidateCallback &CCC,
3615 DeclContext *MemberContext, bool EnteringContext,
3616 const ObjCObjectPointerType *OPT,
3617 bool ErrorRecovery);
3618
3619public:
3620 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3621
3622 /// Clears the state of the given TypoExpr.
3623 void clearDelayedTypo(TypoExpr *TE);
3624
3625 /// Look up a name, looking for a single declaration. Return
3626 /// null if the results were absent, ambiguous, or overloaded.
3627 ///
3628 /// It is preferable to use the elaborated form and explicitly handle
3629 /// ambiguity and overloaded.
3630 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3631 SourceLocation Loc,
3632 LookupNameKind NameKind,
3633 RedeclarationKind Redecl
3634 = NotForRedeclaration);
3635 bool LookupBuiltin(LookupResult &R);
3636 bool LookupName(LookupResult &R, Scope *S,
3637 bool AllowBuiltinCreation = false);
3638 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3639 bool InUnqualifiedLookup = false);
3640 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3641 CXXScopeSpec &SS);
3642 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3643 bool AllowBuiltinCreation = false,
3644 bool EnteringContext = false);
3645 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3646 RedeclarationKind Redecl
3647 = NotForRedeclaration);
3648 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3649
3650 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3651 QualType T1, QualType T2,
3652 UnresolvedSetImpl &Functions);
3653
3654 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3655 SourceLocation GnuLabelLoc = SourceLocation());
3656
3657 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3658 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3659 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3660 unsigned Quals);
3661 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3662 bool RValueThis, unsigned ThisQuals);
3663 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3664 unsigned Quals);
3665 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3666 bool RValueThis, unsigned ThisQuals);
3667 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3668
3669 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3670 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3671 ArrayRef<QualType> ArgTys,
3672 bool AllowRaw,
3673 bool AllowTemplate,
3674 bool AllowStringTemplate,
3675 bool DiagnoseMissing);
3676 bool isKnownName(StringRef name);
3677
3678 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
3679 enum class FunctionEmissionStatus {
3680 Emitted,
3681 CUDADiscarded, // Discarded due to CUDA/HIP hostness
3682 OMPDiscarded, // Discarded due to OpenMP hostness
3683 TemplateDiscarded, // Discarded due to uninstantiated templates
3684 Unknown,
3685 };
3686 FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl);
3687
3688 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
3689 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
3690
3691 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3692 ArrayRef<Expr *> Args, ADLResult &Functions);
3693
3694 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3695 VisibleDeclConsumer &Consumer,
3696 bool IncludeGlobalScope = true,
3697 bool LoadExternal = true);
3698 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3699 VisibleDeclConsumer &Consumer,
3700 bool IncludeGlobalScope = true,
3701 bool IncludeDependentBases = false,
3702 bool LoadExternal = true);
3703
3704 enum CorrectTypoKind {
3705 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3706 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3707 };
3708
3709 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3710 Sema::LookupNameKind LookupKind,
3711 Scope *S, CXXScopeSpec *SS,
3712 CorrectionCandidateCallback &CCC,
3713 CorrectTypoKind Mode,
3714 DeclContext *MemberContext = nullptr,
3715 bool EnteringContext = false,
3716 const ObjCObjectPointerType *OPT = nullptr,
3717 bool RecordFailure = true);
3718
3719 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3720 Sema::LookupNameKind LookupKind, Scope *S,
3721 CXXScopeSpec *SS,
3722 CorrectionCandidateCallback &CCC,
3723 TypoDiagnosticGenerator TDG,
3724 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3725 DeclContext *MemberContext = nullptr,
3726 bool EnteringContext = false,
3727 const ObjCObjectPointerType *OPT = nullptr);
3728
3729 /// Process any TypoExprs in the given Expr and its children,
3730 /// generating diagnostics as appropriate and returning a new Expr if there
3731 /// were typos that were all successfully corrected and ExprError if one or
3732 /// more typos could not be corrected.
3733 ///
3734 /// \param E The Expr to check for TypoExprs.
3735 ///
3736 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3737 /// initializer.
3738 ///
3739 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3740 /// it is an acceptable/usable result from a single combination of typo
3741 /// corrections. As long as the filter returns ExprError, different
3742 /// combinations of corrections will be tried until all are exhausted.
3743 ExprResult
3744 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3745 llvm::function_ref<ExprResult(Expr *)> Filter =
3746 [](Expr *E) -> ExprResult { return E; });
3747
3748 ExprResult
3749 CorrectDelayedTyposInExpr(Expr *E,
3750 llvm::function_ref<ExprResult(Expr *)> Filter) {
3751 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3752 }
3753
3754 ExprResult
3755 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3756 llvm::function_ref<ExprResult(Expr *)> Filter =
3757 [](Expr *E) -> ExprResult { return E; }) {
3758 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3759 }
3760
3761 ExprResult
3762 CorrectDelayedTyposInExpr(ExprResult ER,
3763 llvm::function_ref<ExprResult(Expr *)> Filter) {
3764 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3765 }
3766
3767 void diagnoseTypo(const TypoCorrection &Correction,
3768 const PartialDiagnostic &TypoDiag,
3769 bool ErrorRecovery = true);
3770
3771 void diagnoseTypo(const TypoCorrection &Correction,
3772 const PartialDiagnostic &TypoDiag,
3773 const PartialDiagnostic &PrevNote,
3774 bool ErrorRecovery = true);
3775
3776 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3777
3778 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3779 ArrayRef<Expr *> Args,
3780 AssociatedNamespaceSet &AssociatedNamespaces,
3781 AssociatedClassSet &AssociatedClasses);
3782
3783 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3784 bool ConsiderLinkage, bool AllowInlineNamespace);
3785
3786 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3787
3788 void DiagnoseAmbiguousLookup(LookupResult &Result);
3789 //@}
3790
3791 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3792 SourceLocation IdLoc,
3793 bool TypoCorrection = false);
3794 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3795 Scope *S, bool ForRedeclaration,
3796 SourceLocation Loc);
3797 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3798 Scope *S);
3799 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
3800 FunctionDecl *FD);
3801 void AddKnownFunctionAttributes(FunctionDecl *FD);
3802
3803 // More parsing and symbol table subroutines.
3804
3805 void ProcessPragmaWeak(Scope *S, Decl *D);
3806 // Decl attributes - this routine is the top level dispatcher.
3807 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3808 // Helper for delayed processing of attributes.
3809 void ProcessDeclAttributeDelayed(Decl *D,
3810 const ParsedAttributesView &AttrList);
3811 void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
3812 bool IncludeCXX11Attributes = true);
3813 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3814 const ParsedAttributesView &AttrList);
3815
3816 void checkUnusedDeclAttributes(Declarator &D);
3817
3818 /// Determine if type T is a valid subject for a nonnull and similar
3819 /// attributes. By default, we look through references (the behavior used by
3820 /// nonnull), but if the second parameter is true, then we treat a reference
3821 /// type as valid.
3822 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3823
3824 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
3825 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
3826 const FunctionDecl *FD = nullptr);
3827 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
3828 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
3829 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
3830 StringRef &Str,
3831 SourceLocation *ArgLocation = nullptr);
3832 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3833 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3834 bool checkMSInheritanceAttrOnDefinition(
3835 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3836 MSInheritanceModel SemanticSpelling);
3837
3838 void CheckAlignasUnderalignment(Decl *D);
3839
3840 /// Adjust the calling convention of a method to be the ABI default if it
3841 /// wasn't specified explicitly. This handles method types formed from
3842 /// function type typedefs and typename template arguments.
3843 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3844 SourceLocation Loc);
3845
3846 // Check if there is an explicit attribute, but only look through parens.
3847 // The intent is to look for an attribute on the current declarator, but not
3848 // one that came from a typedef.
3849 bool hasExplicitCallingConv(QualType T);
3850
3851 /// Get the outermost AttributedType node that sets a calling convention.
3852 /// Valid types should not have multiple attributes with different CCs.
3853 const AttributedType *getCallingConvAttributedType(QualType T) const;
3854
3855 /// Stmt attributes - this routine is the top level dispatcher.
3856 StmtResult ProcessStmtAttributes(Stmt *Stmt,
3857 const ParsedAttributesView &Attrs,
3858 SourceRange Range);
3859
3860 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3861 ObjCMethodDecl *MethodDecl,
3862 bool IsProtocolMethodDecl);
3863
3864 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3865 ObjCMethodDecl *Overridden,
3866 bool IsProtocolMethodDecl);
3867
3868 /// WarnExactTypedMethods - This routine issues a warning if method
3869 /// implementation declaration matches exactly that of its declaration.
3870 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3871 ObjCMethodDecl *MethodDecl,
3872 bool IsProtocolMethodDecl);
3873
3874 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3875
3876 /// CheckImplementationIvars - This routine checks if the instance variables
3877 /// listed in the implelementation match those listed in the interface.
3878 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3879 ObjCIvarDecl **Fields, unsigned nIvars,
3880 SourceLocation Loc);
3881
3882 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3883 /// remains unimplemented in the class or category \@implementation.
3884 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3885 ObjCContainerDecl* IDecl,
3886 bool IncompleteImpl = false);
3887
3888 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3889 /// which must be implemented by this implementation.
3890 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3891 ObjCContainerDecl *CDecl,
3892 bool SynthesizeProperties);
3893
3894 /// Diagnose any null-resettable synthesized setters.
3895 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3896
3897 /// DefaultSynthesizeProperties - This routine default synthesizes all
3898 /// properties which must be synthesized in the class's \@implementation.
3899 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3900 ObjCInterfaceDecl *IDecl,
3901 SourceLocation AtEnd);
3902 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3903
3904 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3905 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3906 /// declared in class 'IFace'.
3907 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3908 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3909
3910 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3911 /// backs the property is not used in the property's accessor.
3912 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3913 const ObjCImplementationDecl *ImplD);
3914
3915 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3916 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3917 /// It also returns ivar's property on success.
3918 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3919 const ObjCPropertyDecl *&PDecl) const;
3920
3921 /// Called by ActOnProperty to handle \@property declarations in
3922 /// class extensions.
3923 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3924 SourceLocation AtLoc,
3925 SourceLocation LParenLoc,
3926 FieldDeclarator &FD,
3927 Selector GetterSel,
3928 SourceLocation GetterNameLoc,
3929 Selector SetterSel,
3930 SourceLocation SetterNameLoc,
3931 const bool isReadWrite,
3932 unsigned &Attributes,
3933 const unsigned AttributesAsWritten,
3934 QualType T,
3935 TypeSourceInfo *TSI,
3936 tok::ObjCKeywordKind MethodImplKind);
3937
3938 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3939 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3940 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3941 ObjCContainerDecl *CDecl,
3942 SourceLocation AtLoc,
3943 SourceLocation LParenLoc,
3944 FieldDeclarator &FD,
3945 Selector GetterSel,
3946 SourceLocation GetterNameLoc,
3947 Selector SetterSel,
3948 SourceLocation SetterNameLoc,
3949 const bool isReadWrite,
3950 const unsigned Attributes,
3951 const unsigned AttributesAsWritten,
3952 QualType T,
3953 TypeSourceInfo *TSI,
3954 tok::ObjCKeywordKind MethodImplKind,
3955 DeclContext *lexicalDC = nullptr);
3956
3957 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3958 /// warning) when atomic property has one but not the other user-declared
3959 /// setter or getter.
3960 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3961 ObjCInterfaceDecl* IDecl);
3962
3963 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3964
3965 void DiagnoseMissingDesignatedInitOverrides(
3966 const ObjCImplementationDecl *ImplD,
3967 const ObjCInterfaceDecl *IFD);
3968
3969 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3970
3971 enum MethodMatchStrategy {
3972 MMS_loose,
3973 MMS_strict
3974 };
3975
3976 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3977 /// true, or false, accordingly.
3978 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3979 const ObjCMethodDecl *PrevMethod,
3980 MethodMatchStrategy strategy = MMS_strict);
3981
3982 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3983 /// or protocol against those declared in their implementations.
3984 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3985 const SelectorSet &ClsMap,
3986 SelectorSet &InsMapSeen,
3987 SelectorSet &ClsMapSeen,
3988 ObjCImplDecl* IMPDecl,
3989 ObjCContainerDecl* IDecl,
3990 bool &IncompleteImpl,
3991 bool ImmediateClass,
3992 bool WarnCategoryMethodImpl=false);
3993
3994 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3995 /// category matches with those implemented in its primary class and
3996 /// warns each time an exact match is found.
3997 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3998
3999 /// Add the given method to the list of globally-known methods.
4000 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
4001
4002 /// Returns default addr space for method qualifiers.
4003 LangAS getDefaultCXXMethodAddrSpace() const;
4004
4005private:
4006 /// AddMethodToGlobalPool - Add an instance or factory method to the global
4007 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4008 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4009
4010 /// LookupMethodInGlobalPool - Returns the instance or factory method and
4011 /// optionally warns if there are multiple signatures.
4012 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4013 bool receiverIdOrClass,
4014 bool instance);
4015
4016public:
4017 /// - Returns instance or factory methods in global method pool for
4018 /// given selector. It checks the desired kind first, if none is found, and
4019 /// parameter checkTheOther is set, it then checks the other kind. If no such
4020 /// method or only one method is found, function returns false; otherwise, it
4021 /// returns true.
4022 bool
4023 CollectMultipleMethodsInGlobalPool(Selector Sel,
4024 SmallVectorImpl<ObjCMethodDecl*>& Methods,
4025 bool InstanceFirst, bool CheckTheOther,
4026 const ObjCObjectType *TypeBound = nullptr);
4027
4028 bool
4029 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4030 SourceRange R, bool receiverIdOrClass,
4031 SmallVectorImpl<ObjCMethodDecl*>& Methods);
4032
4033 void
4034 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4035 Selector Sel, SourceRange R,
4036 bool receiverIdOrClass);
4037
4038private:
4039 /// - Returns a selector which best matches given argument list or
4040 /// nullptr if none could be found
4041 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4042 bool IsInstance,
4043 SmallVectorImpl<ObjCMethodDecl*>& Methods);
4044
4045
4046 /// Record the typo correction failure and return an empty correction.
4047 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4048 bool RecordFailure = true) {
4049 if (RecordFailure)
4050 TypoCorrectionFailures[Typo].insert(TypoLoc);
4051 return TypoCorrection();
4052 }
4053
4054public:
4055 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4056 /// unit are added to a global pool. This allows us to efficiently associate
4057 /// a selector with a method declaraation for purposes of typechecking
4058 /// messages sent to "id" (where the class of the object is unknown).
4059 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4060 AddMethodToGlobalPool(Method, impl, /*instance*/true);
4061 }
4062
4063 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4064 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4065 AddMethodToGlobalPool(Method, impl, /*instance*/false);
4066 }
4067
4068 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4069 /// pool.
4070 void AddAnyMethodToGlobalPool(Decl *D);
4071
4072 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4073 /// there are multiple signatures.
4074 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4075 bool receiverIdOrClass=false) {
4076 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4077 /*instance*/true);
4078 }
4079
4080 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4081 /// there are multiple signatures.
4082 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4083 bool receiverIdOrClass=false) {
4084 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4085 /*instance*/false);
4086 }
4087
4088 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4089 QualType ObjectType=QualType());
4090 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4091 /// implementation.
4092 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4093
4094 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4095 /// initialization.
4096 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4097 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4098
4099 //===--------------------------------------------------------------------===//
4100 // Statement Parsing Callbacks: SemaStmt.cpp.
4101public:
4102 class FullExprArg {
4103 public:
4104 FullExprArg() : E(nullptr) { }
4105 FullExprArg(Sema &actions) : E(nullptr) { }
4106
4107 ExprResult release() {
4108 return E;
4109 }
4110
4111 Expr *get() const { return E; }
4112
4113 Expr *operator->() {
4114 return E;
4115 }
4116
4117 private:
4118 // FIXME: No need to make the entire Sema class a friend when it's just
4119 // Sema::MakeFullExpr that needs access to the constructor below.
4120 friend class Sema;
4121
4122 explicit FullExprArg(Expr *expr) : E(expr) {}
4123
4124 Expr *E;
4125 };
4126
4127 FullExprArg MakeFullExpr(Expr *Arg) {
4128 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4129 }
4130 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4131 return FullExprArg(
4132 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4133 }
4134 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4135 ExprResult FE =
4136 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4137 /*DiscardedValue*/ true);
4138 return FullExprArg(FE.get());
4139 }
4140
4141 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4142 StmtResult ActOnExprStmtError();
4143
4144 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4145 bool HasLeadingEmptyMacro = false);
4146
4147 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4148 void ActOnFinishOfCompoundStmt();
4149 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4150 ArrayRef<Stmt *> Elts, bool isStmtExpr);
4151
4152 /// A RAII object to enter scope of a compound statement.
4153 class CompoundScopeRAII {
4154 public:
4155 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4156 S.ActOnStartOfCompoundStmt(IsStmtExpr);
4157 }
4158
4159 ~CompoundScopeRAII() {
4160 S.ActOnFinishOfCompoundStmt();
4161 }
4162
4163 private:
4164 Sema &S;
4165 };
4166
4167 /// An RAII helper that pops function a function scope on exit.
4168 struct FunctionScopeRAII {
4169 Sema &S;
4170 bool Active;
4171 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
4172 ~FunctionScopeRAII() {
4173 if (Active)
4174 S.PopFunctionScopeInfo();
4175 }
4176 void disable() { Active = false; }
4177 };
4178
4179 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4180 SourceLocation StartLoc,
4181 SourceLocation EndLoc);
4182 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4183 StmtResult ActOnForEachLValueExpr(Expr *E);
4184 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4185 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4186 SourceLocation DotDotDotLoc, ExprResult RHS,
4187 SourceLocation ColonLoc);
4188 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4189
4190 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4191 SourceLocation ColonLoc,
4192 Stmt *SubStmt, Scope *CurScope);
4193 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4194 SourceLocation ColonLoc, Stmt *SubStmt);
4195
4196 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
4197 ArrayRef<const Attr*> Attrs,
4198 Stmt *SubStmt);
4199
4200 class ConditionResult;
4201 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4202 Stmt *InitStmt,
4203 ConditionResult Cond, Stmt *ThenVal,
4204 SourceLocation ElseLoc, Stmt *ElseVal);
4205 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4206 Stmt *InitStmt,
4207 ConditionResult Cond, Stmt *ThenVal,
4208 SourceLocation ElseLoc, Stmt *ElseVal);
4209 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4210 Stmt *InitStmt,
4211 ConditionResult Cond);
4212 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4213 Stmt *Switch, Stmt *Body);
4214 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
4215 Stmt *Body);
4216 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4217 SourceLocation WhileLoc, SourceLocation CondLParen,
4218 Expr *Cond, SourceLocation CondRParen);
4219
4220 StmtResult ActOnForStmt(SourceLocation ForLoc,
4221 SourceLocation LParenLoc,
4222 Stmt *First,
4223 ConditionResult Second,
4224 FullExprArg Third,
4225 SourceLocation RParenLoc,
4226 Stmt *Body);
4227 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4228 Expr *collection);
4229 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4230 Stmt *First, Expr *collection,
4231 SourceLocation RParenLoc);
4232 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4233
4234 enum BuildForRangeKind {
4235 /// Initial building of a for-range statement.
4236 BFRK_Build,
4237 /// Instantiation or recovery rebuild of a for-range statement. Don't
4238 /// attempt any typo-correction.
4239 BFRK_Rebuild,
4240 /// Determining whether a for-range statement could be built. Avoid any
4241 /// unnecessary or irreversible actions.
4242 BFRK_Check
4243 };
4244
4245 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4246 SourceLocation CoawaitLoc,
4247 Stmt *InitStmt,
4248 Stmt *LoopVar,
4249 SourceLocation ColonLoc, Expr *Collection,
4250 SourceLocation RParenLoc,
4251 BuildForRangeKind Kind);
4252 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4253 SourceLocation CoawaitLoc,
4254 Stmt *InitStmt,
4255 SourceLocation ColonLoc,
4256 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4257 Expr *Cond, Expr *Inc,
4258 Stmt *LoopVarDecl,
4259 SourceLocation RParenLoc,
4260 BuildForRangeKind Kind);
4261 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4262
4263 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4264 SourceLocation LabelLoc,
4265 LabelDecl *TheDecl);
4266 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4267 SourceLocation StarLoc,
4268 Expr *DestExp);
4269 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4270 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4271
4272 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4273 CapturedRegionKind Kind, unsigned NumParams);
4274 typedef std::pair<StringRef, QualType> CapturedParamNameType;
4275 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4276 CapturedRegionKind Kind,
4277 ArrayRef<CapturedParamNameType> Params,
4278 unsigned OpenMPCaptureLevel = 0);
4279 StmtResult ActOnCapturedRegionEnd(Stmt *S);
4280 void ActOnCapturedRegionError();
4281 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4282 SourceLocation Loc,
4283 unsigned NumParams);
4284
4285 enum CopyElisionSemanticsKind {
4286 CES_Strict = 0,
4287 CES_AllowParameters = 1,
4288 CES_AllowDifferentTypes = 2,
4289 CES_AllowExceptionVariables = 4,
4290 CES_FormerDefault = (CES_AllowParameters),
4291 CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
4292 CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
4293 CES_AllowExceptionVariables),
4294 };
4295
4296 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
4297 CopyElisionSemanticsKind CESK);
4298 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
4299 CopyElisionSemanticsKind CESK);
4300
4301 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4302 Scope *CurScope);
4303 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4304 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4305
4306 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4307 bool IsVolatile, unsigned NumOutputs,
4308 unsigned NumInputs, IdentifierInfo **Names,
4309 MultiExprArg Constraints, MultiExprArg Exprs,
4310 Expr *AsmString, MultiExprArg Clobbers,
4311 unsigned NumLabels,
4312 SourceLocation RParenLoc);
4313
4314 void FillInlineAsmIdentifierInfo(Expr *Res,
4315 llvm::InlineAsmIdentifierInfo &Info);
4316 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4317 SourceLocation TemplateKWLoc,
4318 UnqualifiedId &Id,
4319 bool IsUnevaluatedContext);
4320 bool LookupInlineAsmField(StringRef Base, StringRef Member,
4321 unsigned &Offset, SourceLocation AsmLoc);
4322 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4323 SourceLocation AsmLoc);
4324 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4325 ArrayRef<Token> AsmToks,
4326 StringRef AsmString,
4327 unsigned NumOutputs, unsigned NumInputs,
4328 ArrayRef<StringRef> Constraints,
4329 ArrayRef<StringRef> Clobbers,
4330 ArrayRef<Expr*> Exprs,
4331 SourceLocation EndLoc);
4332 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4333 SourceLocation Location,
4334 bool AlwaysCreate);
4335
4336 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4337 SourceLocation StartLoc,
4338 SourceLocation IdLoc, IdentifierInfo *Id,
4339 bool Invalid = false);
4340
4341 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4342
4343 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4344 Decl *Parm, Stmt *Body);
4345
4346 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4347
4348 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4349 MultiStmtArg Catch, Stmt *Finally);
4350
4351 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4352 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4353 Scope *CurScope);
4354 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4355 Expr *operand);
4356 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4357 Expr *SynchExpr,
4358 Stmt *SynchBody);
4359
4360 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4361
4362 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4363 SourceLocation StartLoc,
4364 SourceLocation IdLoc,
4365 IdentifierInfo *Id);
4366
4367 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4368
4369 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4370 Decl *ExDecl, Stmt *HandlerBlock);
4371 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4372 ArrayRef<Stmt *> Handlers);
4373
4374 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4375 SourceLocation TryLoc, Stmt *TryBlock,
4376 Stmt *Handler);
4377 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4378 Expr *FilterExpr,
4379 Stmt *Block);
4380 void ActOnStartSEHFinallyBlock();
4381 void ActOnAbortSEHFinallyBlock();
4382 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4383 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4384
4385 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4386
4387 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4388
4389 /// If it's a file scoped decl that must warn if not used, keep track
4390 /// of it.
4391 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4392
4393 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4394 /// whose result is unused, warn.
4395 void DiagnoseUnusedExprResult(const Stmt *S);
4396 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4397 void DiagnoseUnusedDecl(const NamedDecl *ND);
4398
4399 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4400 /// statement as a \p Body, and it is located on the same line.
4401 ///
4402 /// This helps prevent bugs due to typos, such as:
4403 /// if (condition);
4404 /// do_stuff();
4405 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4406 const Stmt *Body,
4407 unsigned DiagID);
4408
4409 /// Warn if a for/while loop statement \p S, which is followed by
4410 /// \p PossibleBody, has a suspicious null statement as a body.
4411 void DiagnoseEmptyLoopBody(const Stmt *S,
4412 const Stmt *PossibleBody);
4413
4414 /// Warn if a value is moved to itself.
4415 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4416 SourceLocation OpLoc);
4417
4418 /// Warn if we're implicitly casting from a _Nullable pointer type to a
4419 /// _Nonnull one.
4420 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4421 SourceLocation Loc);
4422
4423 /// Warn when implicitly casting 0 to nullptr.
4424 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4425
4426 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
4427 return DelayedDiagnostics.push(pool);
4428 }
4429 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4430
4431 typedef ProcessingContextState ParsingClassState;
4432 ParsingClassState PushParsingClass() {
4433 ParsingClassDepth++;
4434 return DelayedDiagnostics.pushUndelayed();
4435 }
4436 void PopParsingClass(ParsingClassState state) {
4437 ParsingClassDepth--;
4438 DelayedDiagnostics.popUndelayed(state);
4439 }
4440
4441 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4442
4443 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4444 const ObjCInterfaceDecl *UnknownObjCClass,
4445 bool ObjCPropertyAccess,
4446 bool AvoidPartialAvailabilityChecks = false,
4447 ObjCInterfaceDecl *ClassReceiver = nullptr);
4448
4449 bool makeUnavailableInSystemHeader(SourceLocation loc,
4450 UnavailableAttr::ImplicitReason reason);
4451
4452 /// Issue any -Wunguarded-availability warnings in \c FD
4453 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4454
4455 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
4456
4457 //===--------------------------------------------------------------------===//
4458 // Expression Parsing Callbacks: SemaExpr.cpp.
4459
4460 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4461 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4462 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4463 bool ObjCPropertyAccess = false,
4464 bool AvoidPartialAvailabilityChecks = false,
4465 ObjCInterfaceDecl *ClassReciever = nullptr);
4466 void NoteDeletedFunction(FunctionDecl *FD);
4467 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4468 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4469 ObjCMethodDecl *Getter,
4470 SourceLocation Loc);
4471 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4472 ArrayRef<Expr *> Args);
4473
4474 void PushExpressionEvaluationContext(
4475 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4476 ExpressionEvaluationContextRecord::ExpressionKind Type =
4477 ExpressionEvaluationContextRecord::EK_Other);
4478 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4479 void PushExpressionEvaluationContext(
4480 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
4481 ExpressionEvaluationContextRecord::ExpressionKind Type =
4482 ExpressionEvaluationContextRecord::EK_Other);
4483 void PopExpressionEvaluationContext();
4484
4485 void DiscardCleanupsInEvaluationContext();
4486
4487 ExprResult TransformToPotentiallyEvaluated(Expr *E);
4488 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4489
4490 ExprResult CheckUnevaluatedOperand(Expr *E);
4491 void CheckUnusedVolatileAssignment(Expr *E);
4492
4493 ExprResult ActOnConstantExpression(ExprResult Res);
4494
4495 // Functions for marking a declaration referenced. These functions also
4496 // contain the relevant logic for marking if a reference to a function or
4497 // variable is an odr-use (in the C++11 sense). There are separate variants
4498 // for expressions referring to a decl; these exist because odr-use marking
4499 // needs to be delayed for some constant variables when we build one of the
4500 // named expressions.
4501 //
4502 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4503 // should usually be true. This only needs to be set to false if the lack of
4504 // odr-use cannot be determined from the current context (for instance,
4505 // because the name denotes a virtual function and was written without an
4506 // explicit nested-name-specifier).
4507 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4508 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4509 bool MightBeOdrUse = true);
4510 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4511 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4512 void MarkMemberReferenced(MemberExpr *E);
4513 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
4514 void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
4515 unsigned CapturingScopeIndex);
4516
4517 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
4518 void CleanupVarDeclMarking();
4519
4520 enum TryCaptureKind {
4521 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4522 };
4523
4524 /// Try to capture the given variable.
4525 ///
4526 /// \param Var The variable to capture.
4527 ///
4528 /// \param Loc The location at which the capture occurs.
4529 ///
4530 /// \param Kind The kind of capture, which may be implicit (for either a
4531 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4532 ///
4533 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4534 /// an explicit lambda capture.
4535 ///
4536 /// \param BuildAndDiagnose Whether we are actually supposed to add the
4537 /// captures or diagnose errors. If false, this routine merely check whether
4538 /// the capture can occur without performing the capture itself or complaining
4539 /// if the variable cannot be captured.
4540 ///
4541 /// \param CaptureType Will be set to the type of the field used to capture
4542 /// this variable in the innermost block or lambda. Only valid when the
4543 /// variable can be captured.
4544 ///
4545 /// \param DeclRefType Will be set to the type of a reference to the capture
4546 /// from within the current scope. Only valid when the variable can be
4547 /// captured.
4548 ///
4549 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4550 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4551 /// This is useful when enclosing lambdas must speculatively capture
4552 /// variables that may or may not be used in certain specializations of
4553 /// a nested generic lambda.
4554 ///
4555 /// \returns true if an error occurred (i.e., the variable cannot be
4556 /// captured) and false if the capture succeeded.
4557 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4558 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4559 QualType &CaptureType,
4560 QualType &DeclRefType,
4561 const unsigned *const FunctionScopeIndexToStopAt);
4562
4563 /// Try to capture the given variable.
4564 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4565 TryCaptureKind Kind = TryCapture_Implicit,
4566 SourceLocation EllipsisLoc = SourceLocation());
4567
4568 /// Checks if the variable must be captured.
4569 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4570
4571 /// Given a variable, determine the type that a reference to that
4572 /// variable will have in the given scope.
4573 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4574
4575 /// Mark all of the declarations referenced within a particular AST node as
4576 /// referenced. Used when template instantiation instantiates a non-dependent
4577 /// type -- entities referenced by the type are now referenced.
4578 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4579 void MarkDeclarationsReferencedInExpr(Expr *E,
4580 bool SkipLocalVariables = false);
4581
4582 /// Try to recover by turning the given expression into a
4583 /// call. Returns true if recovery was attempted or an error was
4584 /// emitted; this may also leave the ExprResult invalid.
4585 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4586 bool ForceComplain = false,
4587 bool (*IsPlausibleResult)(QualType) = nullptr);
4588
4589 /// Figure out if an expression could be turned into a call.
4590 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4591 UnresolvedSetImpl &NonTemplateOverloads);
4592
4593 /// Conditionally issue a diagnostic based on the current
4594 /// evaluation context.
4595 ///
4596 /// \param Statement If Statement is non-null, delay reporting the
4597 /// diagnostic until the function body is parsed, and then do a basic
4598 /// reachability analysis to determine if the statement is reachable.
4599 /// If it is unreachable, the diagnostic will not be emitted.
4600 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4601 const PartialDiagnostic &PD);
4602 /// Similar, but diagnostic is only produced if all the specified statements
4603 /// are reachable.
4604 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
4605 const PartialDiagnostic &PD);
4606
4607 // Primary Expressions.
4608 SourceRange getExprRange(Expr *E) const;
4609
4610 ExprResult ActOnIdExpression(
4611 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4612 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4613 CorrectionCandidateCallback *CCC = nullptr,
4614 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4615
4616 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4617 TemplateArgumentListInfo &Buffer,
4618 DeclarationNameInfo &NameInfo,
4619 const TemplateArgumentListInfo *&TemplateArgs);
4620
4621 bool
4622 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4623 CorrectionCandidateCallback &CCC,
4624 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4625 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4626
4627 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
4628 IdentifierInfo *II);
4629 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
4630
4631 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4632 IdentifierInfo *II,
4633 bool AllowBuiltinCreation=false);
4634
4635 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4636 SourceLocation TemplateKWLoc,
4637 const DeclarationNameInfo &NameInfo,
4638 bool isAddressOfOperand,
4639 const TemplateArgumentListInfo *TemplateArgs);
4640
4641 /// If \p D cannot be odr-used in the current expression evaluation context,
4642 /// return a reason explaining why. Otherwise, return NOUR_None.
4643 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
4644
4645 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4646 SourceLocation Loc,
4647 const CXXScopeSpec *SS = nullptr);
4648 DeclRefExpr *
4649 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4650 const DeclarationNameInfo &NameInfo,
4651 const CXXScopeSpec *SS = nullptr,
4652 NamedDecl *FoundD = nullptr,
4653 SourceLocation TemplateKWLoc = SourceLocation(),
4654 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4655 DeclRefExpr *
4656 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4657 const DeclarationNameInfo &NameInfo,
4658 NestedNameSpecifierLoc NNS,
4659 NamedDecl *FoundD = nullptr,
4660 SourceLocation TemplateKWLoc = SourceLocation(),
4661 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4662
4663 ExprResult
4664 BuildAnonymousStructUnionMemberReference(
4665 const CXXScopeSpec &SS,
4666 SourceLocation nameLoc,
4667 IndirectFieldDecl *indirectField,
4668 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4669 Expr *baseObjectExpr = nullptr,
4670 SourceLocation opLoc = SourceLocation());
4671
4672 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4673 SourceLocation TemplateKWLoc,
4674 LookupResult &R,
4675 const TemplateArgumentListInfo *TemplateArgs,
4676 const Scope *S);
4677 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4678 SourceLocation TemplateKWLoc,
4679 LookupResult &R,
4680 const TemplateArgumentListInfo *TemplateArgs,
4681 bool IsDefiniteInstance,
4682 const Scope *S);
4683 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4684 const LookupResult &R,
4685 bool HasTrailingLParen);
4686
4687 ExprResult
4688 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4689 const DeclarationNameInfo &NameInfo,
4690 bool IsAddressOfOperand, const Scope *S,
4691 TypeSourceInfo **RecoveryTSI = nullptr);
4692
4693 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4694 SourceLocation TemplateKWLoc,
4695 const DeclarationNameInfo &NameInfo,
4696 const TemplateArgumentListInfo *TemplateArgs);
4697
4698 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4699 LookupResult &R,
4700 bool NeedsADL,
4701 bool AcceptInvalidDecl = false);
4702 ExprResult BuildDeclarationNameExpr(
4703 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4704 NamedDecl *FoundD = nullptr,
4705 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4706 bool AcceptInvalidDecl = false);
4707
4708 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4709 DeclarationNameInfo &SuffixInfo,
4710 ArrayRef<Expr *> Args,
4711 SourceLocation LitEndLoc,
4712 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4713
4714 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4715 PredefinedExpr::IdentKind IK);
4716 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4717 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4718
4719 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4720
4721 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4722 ExprResult ActOnCharacterConstant(const Token &Tok,
4723 Scope *UDLScope = nullptr);
4724 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4725 ExprResult ActOnParenListExpr(SourceLocation L,
4726 SourceLocation R,
4727 MultiExprArg Val);
4728
4729 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4730 /// fragments (e.g. "foo" "bar" L"baz").
4731 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4732 Scope *UDLScope = nullptr);
4733
4734 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4735 SourceLocation DefaultLoc,
4736 SourceLocation RParenLoc,
4737 Expr *ControllingExpr,
4738 ArrayRef<ParsedType> ArgTypes,
4739 ArrayRef<Expr *> ArgExprs);
4740 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4741 SourceLocation DefaultLoc,
4742 SourceLocation RParenLoc,
4743 Expr *ControllingExpr,
4744 ArrayRef<TypeSourceInfo *> Types,
4745 ArrayRef<Expr *> Exprs);
4746
4747 // Binary/Unary Operators. 'Tok' is the token for the operator.
4748 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4749 Expr *InputExpr);
4750 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4751 UnaryOperatorKind Opc, Expr *Input);
4752 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4753 tok::TokenKind Op, Expr *Input);
4754
4755 bool isQualifiedMemberAccess(Expr *E);
4756 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4757
4758 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4759 SourceLocation OpLoc,
4760 UnaryExprOrTypeTrait ExprKind,
4761 SourceRange R);
4762 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4763 UnaryExprOrTypeTrait ExprKind);
4764 ExprResult
4765 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4766 UnaryExprOrTypeTrait ExprKind,
4767 bool IsType, void *TyOrEx,
4768 SourceRange ArgRange);
4769
4770 ExprResult CheckPlaceholderExpr(Expr *E);
4771 bool CheckVecStepExpr(Expr *E);
4772
4773 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4774 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4775 SourceRange ExprRange,
4776 UnaryExprOrTypeTrait ExprKind);
4777 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4778 SourceLocation OpLoc,
4779 IdentifierInfo &Name,
4780 SourceLocation NameLoc,
4781 SourceLocation RParenLoc);
4782 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4783 tok::TokenKind Kind, Expr *Input);
4784
4785 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4786 Expr *Idx, SourceLocation RLoc);
4787 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4788 Expr *Idx, SourceLocation RLoc);
4789 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4790 Expr *LowerBound, SourceLocation ColonLoc,
4791 Expr *Length, SourceLocation RBLoc);
4792
4793 // This struct is for use by ActOnMemberAccess to allow
4794 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4795 // changing the access operator from a '.' to a '->' (to see if that is the
4796 // change needed to fix an error about an unknown member, e.g. when the class
4797 // defines a custom operator->).
4798 struct ActOnMemberAccessExtraArgs {
4799 Scope *S;
4800 UnqualifiedId &Id;
4801 Decl *ObjCImpDecl;
4802 };
4803
4804 ExprResult BuildMemberReferenceExpr(
4805 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4806 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4807 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4808 const TemplateArgumentListInfo *TemplateArgs,
4809 const Scope *S,
4810 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4811
4812 ExprResult
4813 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4814 bool IsArrow, const CXXScopeSpec &SS,
4815 SourceLocation TemplateKWLoc,
4816 NamedDecl *FirstQualifierInScope, LookupResult &R,
4817 const TemplateArgumentListInfo *TemplateArgs,
4818 const Scope *S,
4819 bool SuppressQualifierCheck = false,
4820 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4821
4822 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4823 SourceLocation OpLoc,
4824 const CXXScopeSpec &SS, FieldDecl *Field,
4825 DeclAccessPair FoundDecl,
4826 const DeclarationNameInfo &MemberNameInfo);
4827
4828 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4829
4830 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4831 const CXXScopeSpec &SS,
4832 const LookupResult &R);
4833
4834 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4835 bool IsArrow, SourceLocation OpLoc,
4836 const CXXScopeSpec &SS,
4837 SourceLocation TemplateKWLoc,
4838 NamedDecl *FirstQualifierInScope,
4839 const DeclarationNameInfo &NameInfo,
4840 const TemplateArgumentListInfo *TemplateArgs);
4841
4842 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4843 SourceLocation OpLoc,
4844 tok::TokenKind OpKind,
4845 CXXScopeSpec &SS,
4846 SourceLocation TemplateKWLoc,
4847 UnqualifiedId &Member,
4848 Decl *ObjCImpDecl);
4849
4850 MemberExpr *
4851 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4852 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
4853 ValueDecl *Member, DeclAccessPair FoundDecl,
4854 bool HadMultipleCandidates,
4855 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4856 ExprValueKind VK, ExprObjectKind OK,
4857 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4858 MemberExpr *
4859 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4860 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
4861 ValueDecl *Member, DeclAccessPair FoundDecl,
4862 bool HadMultipleCandidates,
4863 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4864 ExprValueKind VK, ExprObjectKind OK,
4865 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4866
4867 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4868 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4869 FunctionDecl *FDecl,
4870 const FunctionProtoType *Proto,
4871 ArrayRef<Expr *> Args,
4872 SourceLocation RParenLoc,
4873 bool ExecConfig = false);
4874 void CheckStaticArrayArgument(SourceLocation CallLoc,
4875 ParmVarDecl *Param,
4876 const Expr *ArgExpr);
4877
4878 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4879 /// This provides the location of the left/right parens and a list of comma
4880 /// locations.
4881 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4882 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4883 Expr *ExecConfig = nullptr);
4884 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4885 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4886 Expr *ExecConfig = nullptr,
4887 bool IsExecConfig = false);
4888 enum class AtomicArgumentOrder { API, AST };
4889 ExprResult
4890 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4891 SourceLocation RParenLoc, MultiExprArg Args,
4892 AtomicExpr::AtomicOp Op,
4893 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
4894 ExprResult
4895 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
4896 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
4897 Expr *Config = nullptr, bool IsExecConfig = false,
4898 ADLCallKind UsesADL = ADLCallKind::NotADL);
4899
4900 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4901 MultiExprArg ExecConfig,
4902 SourceLocation GGGLoc);
4903
4904 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4905 Declarator &D, ParsedType &Ty,
4906 SourceLocation RParenLoc, Expr *CastExpr);
4907 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4908 TypeSourceInfo *Ty,
4909 SourceLocation RParenLoc,
4910 Expr *Op);
4911 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4912
4913 /// Build an altivec or OpenCL literal.
4914 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4915 SourceLocation RParenLoc, Expr *E,
4916 TypeSourceInfo *TInfo);
4917
4918 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4919
4920 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4921 ParsedType Ty,
4922 SourceLocation RParenLoc,
4923 Expr *InitExpr);
4924
4925 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4926 TypeSourceInfo *TInfo,
4927 SourceLocation RParenLoc,
4928 Expr *LiteralExpr);
4929
4930 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4931 MultiExprArg InitArgList,
4932 SourceLocation RBraceLoc);
4933
4934 ExprResult BuildInitList(SourceLocation LBraceLoc,
4935 MultiExprArg InitArgList,
4936 SourceLocation RBraceLoc);
4937
4938 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4939 SourceLocation EqualOrColonLoc,
4940 bool GNUSyntax,
4941 ExprResult Init);
4942
4943private:
4944 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4945
4946public:
4947 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4948 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4949 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4950 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4951 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4952 Expr *LHSExpr, Expr *RHSExpr);
4953
4954 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4955
4956 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4957 /// in the case of a the GNU conditional expr extension.
4958 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4959 SourceLocation ColonLoc,
4960 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4961
4962 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4963 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4964 LabelDecl *TheDecl);
4965
4966 void ActOnStartStmtExpr();
4967 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4968 SourceLocation RPLoc); // "({..})"
4969 // Handle the final expression in a statement expression.
4970 ExprResult ActOnStmtExprResult(ExprResult E);
4971 void ActOnStmtExprError();
4972
4973 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4974 struct OffsetOfComponent {
4975 SourceLocation LocStart, LocEnd;
4976 bool isBrackets; // true if [expr], false if .ident
4977 union {
4978 IdentifierInfo *IdentInfo;
4979 Expr *E;
4980 } U;
4981 };
4982
4983 /// __builtin_offsetof(type, a.b[123][456].c)
4984 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4985 TypeSourceInfo *TInfo,
4986 ArrayRef<OffsetOfComponent> Components,
4987 SourceLocation RParenLoc);
4988 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4989 SourceLocation BuiltinLoc,
4990 SourceLocation TypeLoc,
4991 ParsedType ParsedArgTy,
4992 ArrayRef<OffsetOfComponent> Components,
4993 SourceLocation RParenLoc);
4994
4995 // __builtin_choose_expr(constExpr, expr1, expr2)
4996 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4997 Expr *CondExpr, Expr *LHSExpr,
4998 Expr *RHSExpr, SourceLocation RPLoc);
4999
5000 // __builtin_va_arg(expr, type)
5001 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
5002 SourceLocation RPLoc);
5003 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
5004 TypeSourceInfo *TInfo, SourceLocation RPLoc);
5005
5006 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
5007 // __builtin_COLUMN()
5008 ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
5009 SourceLocation BuiltinLoc,
5010 SourceLocation RPLoc);
5011
5012 // Build a potentially resolved SourceLocExpr.
5013 ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
5014 SourceLocation BuiltinLoc, SourceLocation RPLoc,
5015 DeclContext *ParentContext);
5016
5017 // __null
5018 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
5019
5020 bool CheckCaseExpression(Expr *E);
5021
5022 /// Describes the result of an "if-exists" condition check.
5023 enum IfExistsResult {
5024 /// The symbol exists.
5025 IER_Exists,
5026
5027 /// The symbol does not exist.
5028 IER_DoesNotExist,
5029
5030 /// The name is a dependent name, so the results will differ
5031 /// from one instantiation to the next.
5032 IER_Dependent,
5033
5034 /// An error occurred.
5035 IER_Error
5036 };
5037
5038 IfExistsResult
5039 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
5040 const DeclarationNameInfo &TargetNameInfo);
5041
5042 IfExistsResult
5043 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5044 bool IsIfExists, CXXScopeSpec &SS,
5045 UnqualifiedId &Name);
5046
5047 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
5048 bool IsIfExists,
5049 NestedNameSpecifierLoc QualifierLoc,
5050 DeclarationNameInfo NameInfo,
5051 Stmt *Nested);
5052 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
5053 bool IsIfExists,
5054 CXXScopeSpec &SS, UnqualifiedId &Name,
5055 Stmt *Nested);
5056
5057 //===------------------------- "Block" Extension ------------------------===//
5058
5059 /// ActOnBlockStart - This callback is invoked when a block literal is
5060 /// started.
5061 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
5062
5063 /// ActOnBlockArguments - This callback allows processing of block arguments.
5064 /// If there are no arguments, this is still invoked.
5065 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
5066 Scope *CurScope);
5067
5068 /// ActOnBlockError - If there is an error parsing a block, this callback
5069 /// is invoked to pop the information about the block from the action impl.
5070 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
5071
5072 /// ActOnBlockStmtExpr - This is called when the body of a block statement
5073 /// literal was successfully completed. ^(int x){...}
5074 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
5075 Scope *CurScope);
5076
5077 //===---------------------------- Clang Extensions ----------------------===//
5078
5079 /// __builtin_convertvector(...)
5080 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5081 SourceLocation BuiltinLoc,
5082 SourceLocation RParenLoc);
5083
5084 //===---------------------------- OpenCL Features -----------------------===//
5085
5086 /// __builtin_astype(...)
5087 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5088 SourceLocation BuiltinLoc,
5089 SourceLocation RParenLoc);
5090
5091 //===---------------------------- C++ Features --------------------------===//
5092
5093 // Act on C++ namespaces
5094 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5095 SourceLocation NamespaceLoc,
5096 SourceLocation IdentLoc, IdentifierInfo *Ident,
5097 SourceLocation LBrace,
5098 const ParsedAttributesView &AttrList,
5099 UsingDirectiveDecl *&UsingDecl);
5100 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5101
5102 NamespaceDecl *getStdNamespace() const;
5103 NamespaceDecl *getOrCreateStdNamespace();
5104
5105 NamespaceDecl *lookupStdExperimentalNamespace();
5106
5107 CXXRecordDecl *getStdBadAlloc() const;
5108 EnumDecl *getStdAlignValT() const;
5109
5110private:
5111 // A cache representing if we've fully checked the various comparison category
5112 // types stored in ASTContext. The bit-index corresponds to the integer value
5113 // of a ComparisonCategoryType enumerator.
5114 llvm::SmallBitVector FullyCheckedComparisonCategories;
5115
5116 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5117 CXXScopeSpec &SS,
5118 ParsedType TemplateTypeTy,
5119 IdentifierInfo *MemberOrBase);
5120
5121public:
5122 enum class ComparisonCategoryUsage {
5123 /// The '<=>' operator was used in an expression and a builtin operator
5124 /// was selected.
5125 OperatorInExpression,
5126 /// A defaulted 'operator<=>' needed the comparison category. This
5127 /// typically only applies to 'std::strong_ordering', due to the implicit
5128 /// fallback return value.
5129 DefaultedOperator,
5130 };
5131
5132 /// Lookup the specified comparison category types in the standard
5133 /// library, an check the VarDecls possibly returned by the operator<=>
5134 /// builtins for that type.
5135 ///
5136 /// \return The type of the comparison category type corresponding to the
5137 /// specified Kind, or a null type if an error occurs
5138 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5139 SourceLocation Loc,
5140 ComparisonCategoryUsage Usage);
5141
5142 /// Tests whether Ty is an instance of std::initializer_list and, if
5143 /// it is and Element is not NULL, assigns the element type to Element.
5144 bool isStdInitializerList(QualType Ty, QualType *Element);
5145
5146 /// Looks for the std::initializer_list template and instantiates it
5147 /// with Element, or emits an error if it's not found.
5148 ///
5149 /// \returns The instantiated template, or null on error.
5150 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5151
5152 /// Determine whether Ctor is an initializer-list constructor, as
5153 /// defined in [dcl.init.list]p2.
5154 bool isInitListConstructor(const FunctionDecl *Ctor);
5155
5156 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5157 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5158 SourceLocation IdentLoc,
5159 IdentifierInfo *NamespcName,
5160 const ParsedAttributesView &AttrList);
5161
5162 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5163
5164 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
5165 SourceLocation NamespaceLoc,
5166 SourceLocation AliasLoc,
5167 IdentifierInfo *Alias,
5168 CXXScopeSpec &SS,
5169 SourceLocation IdentLoc,
5170 IdentifierInfo *Ident);
5171
5172 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5173 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
5174 const LookupResult &PreviousDecls,
5175 UsingShadowDecl *&PrevShadow);
5176 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
5177 NamedDecl *Target,
5178 UsingShadowDecl *PrevDecl);
5179
5180 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5181 bool HasTypenameKeyword,
5182 const CXXScopeSpec &SS,
5183 SourceLocation NameLoc,
5184 const LookupResult &Previous);
5185 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
5186 bool HasTypename,
5187 const CXXScopeSpec &SS,
5188 const DeclarationNameInfo &NameInfo,
5189 SourceLocation NameLoc);
5190
5191 NamedDecl *BuildUsingDeclaration(
5192 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5193 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5194 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5195 const ParsedAttributesView &AttrList, bool IsInstantiation);
5196 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5197 ArrayRef<NamedDecl *> Expansions);
5198
5199 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5200
5201 /// Given a derived-class using shadow declaration for a constructor and the
5202 /// correspnding base class constructor, find or create the implicit
5203 /// synthesized derived class constructor to use for this initialization.
5204 CXXConstructorDecl *
5205 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5206 ConstructorUsingShadowDecl *DerivedShadow);
5207
5208 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5209 SourceLocation UsingLoc,
5210 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5211 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5212 const ParsedAttributesView &AttrList);
5213 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5214 MultiTemplateParamsArg TemplateParams,
5215 SourceLocation UsingLoc, UnqualifiedId &Name,
5216 const ParsedAttributesView &AttrList,
5217 TypeResult Type, Decl *DeclFromDeclSpec);
5218
5219 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5220 /// including handling of its default argument expressions.
5221 ///
5222 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5223 ExprResult
5224 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5225 NamedDecl *FoundDecl,
5226 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5227 bool HadMultipleCandidates, bool IsListInitialization,
5228 bool IsStdInitListInitialization,
5229 bool RequiresZeroInit, unsigned ConstructKind,
5230 SourceRange ParenRange);
5231
5232 /// Build a CXXConstructExpr whose constructor has already been resolved if
5233 /// it denotes an inherited constructor.
5234 ExprResult
5235 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5236 CXXConstructorDecl *Constructor, bool Elidable,
5237 MultiExprArg Exprs,
5238 bool HadMultipleCandidates, bool IsListInitialization,
5239 bool IsStdInitListInitialization,
5240 bool RequiresZeroInit, unsigned ConstructKind,
5241 SourceRange ParenRange);
5242
5243 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5244 // the constructor can be elidable?
5245 ExprResult
5246 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5247 NamedDecl *FoundDecl,
5248 CXXConstructorDecl *Constructor, bool Elidable,
5249 MultiExprArg Exprs, bool HadMultipleCandidates,
5250 bool IsListInitialization,
5251 bool IsStdInitListInitialization, bool RequiresZeroInit,
5252 unsigned ConstructKind, SourceRange ParenRange);
5253
5254 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5255
5256
5257 /// Instantiate or parse a C++ default argument expression as necessary.
5258 /// Return true on error.
5259 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5260 ParmVarDecl *Param);
5261
5262 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
5263 /// the default expr if needed.
5264 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5265 FunctionDecl *FD,
5266 ParmVarDecl *Param);
5267
5268 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5269 /// constructed variable.
5270 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
5271
5272 /// Helper class that collects exception specifications for
5273 /// implicitly-declared special member functions.
5274 class ImplicitExceptionSpecification {
5275 // Pointer to allow copying
5276 Sema *Self;
5277 // We order exception specifications thus:
5278 // noexcept is the most restrictive, but is only used in C++11.
5279 // throw() comes next.
5280 // Then a throw(collected exceptions)
5281 // Finally no specification, which is expressed as noexcept(false).
5282 // throw(...) is used instead if any called function uses it.
5283 ExceptionSpecificationType ComputedEST;
5284 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5285 SmallVector<QualType, 4> Exceptions;
5286
5287 void ClearExceptions() {
5288 ExceptionsSeen.clear();
5289 Exceptions.clear();
5290 }
5291
5292 public:
5293 explicit ImplicitExceptionSpecification(Sema &Self)
5294 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5295 if (!Self.getLangOpts().CPlusPlus11)
5296 ComputedEST = EST_DynamicNone;
5297 }
5298
5299 /// Get the computed exception specification type.
5300 ExceptionSpecificationType getExceptionSpecType() const {
5301 assert(!isComputedNoexcept(ComputedEST) &&((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include/clang/Sema/Sema.h"
, 5302, __PRETTY_FUNCTION__))
5302