Bug Summary

File:tools/clang/lib/Sema/SemaModule.cpp
Warning:line 579, 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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.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-10~svn374877/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/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-10/lib/clang/10.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-10~svn374877/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -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-2019-10-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaModule.cpp

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

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