Bug Summary

File:build/source/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Warning:line 5580, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiateDecl.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

/build/source/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

1//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
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// This file implements C++ template instantiation for declarations.
9//
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTMutationListener.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/DependentDiagnostic.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/PrettyDeclStackTrace.h"
22#include "clang/AST/TypeLoc.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/Sema/EnterExpressionEvaluationContext.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/ScopeInfo.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateInstCallback.h"
32#include "llvm/Support/TimeProfiler.h"
33#include <optional>
34
35using namespace clang;
36
37static bool isDeclWithinFunction(const Decl *D) {
38 const DeclContext *DC = D->getDeclContext();
39 if (DC->isFunctionOrMethod())
40 return true;
41
42 if (DC->isRecord())
43 return cast<CXXRecordDecl>(DC)->isLocalClass();
44
45 return false;
46}
47
48template<typename DeclT>
49static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
50 const MultiLevelTemplateArgumentList &TemplateArgs) {
51 if (!OldDecl->getQualifierLoc())
52 return false;
53
54 assert((NewDecl->getFriendObjectKind() ||(static_cast <bool> ((NewDecl->getFriendObjectKind()
|| !OldDecl->getLexicalDeclContext()->isDependentContext
()) && "non-friend with qualified name defined in dependent context"
) ? void (0) : __assert_fail ("(NewDecl->getFriendObjectKind() || !OldDecl->getLexicalDeclContext()->isDependentContext()) && \"non-friend with qualified name defined in dependent context\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 56, __extension__
__PRETTY_FUNCTION__))
55 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&(static_cast <bool> ((NewDecl->getFriendObjectKind()
|| !OldDecl->getLexicalDeclContext()->isDependentContext
()) && "non-friend with qualified name defined in dependent context"
) ? void (0) : __assert_fail ("(NewDecl->getFriendObjectKind() || !OldDecl->getLexicalDeclContext()->isDependentContext()) && \"non-friend with qualified name defined in dependent context\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 56, __extension__
__PRETTY_FUNCTION__))
56 "non-friend with qualified name defined in dependent context")(static_cast <bool> ((NewDecl->getFriendObjectKind()
|| !OldDecl->getLexicalDeclContext()->isDependentContext
()) && "non-friend with qualified name defined in dependent context"
) ? void (0) : __assert_fail ("(NewDecl->getFriendObjectKind() || !OldDecl->getLexicalDeclContext()->isDependentContext()) && \"non-friend with qualified name defined in dependent context\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 56, __extension__
__PRETTY_FUNCTION__))
;
57 Sema::ContextRAII SavedContext(
58 SemaRef,
59 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
60 ? NewDecl->getLexicalDeclContext()
61 : OldDecl->getLexicalDeclContext()));
62
63 NestedNameSpecifierLoc NewQualifierLoc
64 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
65 TemplateArgs);
66
67 if (!NewQualifierLoc)
68 return true;
69
70 NewDecl->setQualifierInfo(NewQualifierLoc);
71 return false;
72}
73
74bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
75 DeclaratorDecl *NewDecl) {
76 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
77}
78
79bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
80 TagDecl *NewDecl) {
81 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
82}
83
84// Include attribute instantiation code.
85#include "clang/Sema/AttrTemplateInstantiate.inc"
86
87static void instantiateDependentAlignedAttr(
88 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
89 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
90 if (Aligned->isAlignmentExpr()) {
91 // The alignment expression is a constant expression.
92 EnterExpressionEvaluationContext Unevaluated(
93 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
94 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
95 if (!Result.isInvalid())
96 S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
97 } else {
98 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
99 TemplateArgs, Aligned->getLocation(),
100 DeclarationName());
101 if (Result)
102 S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
103 }
104}
105
106static void instantiateDependentAlignedAttr(
107 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
108 const AlignedAttr *Aligned, Decl *New) {
109 if (!Aligned->isPackExpansion()) {
110 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
111 return;
112 }
113
114 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
115 if (Aligned->isAlignmentExpr())
116 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
117 Unexpanded);
118 else
119 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
120 Unexpanded);
121 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 121, __extension__
__PRETTY_FUNCTION__))
;
122
123 // Determine whether we can expand this attribute pack yet.
124 bool Expand = true, RetainExpansion = false;
125 std::optional<unsigned> NumExpansions;
126 // FIXME: Use the actual location of the ellipsis.
127 SourceLocation EllipsisLoc = Aligned->getLocation();
128 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
129 Unexpanded, TemplateArgs, Expand,
130 RetainExpansion, NumExpansions))
131 return;
132
133 if (!Expand) {
134 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
135 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
136 } else {
137 for (unsigned I = 0; I != *NumExpansions; ++I) {
138 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
139 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
140 }
141 }
142}
143
144static void instantiateDependentAssumeAlignedAttr(
145 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
146 const AssumeAlignedAttr *Aligned, Decl *New) {
147 // The alignment expression is a constant expression.
148 EnterExpressionEvaluationContext Unevaluated(
149 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
150
151 Expr *E, *OE = nullptr;
152 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
153 if (Result.isInvalid())
154 return;
155 E = Result.getAs<Expr>();
156
157 if (Aligned->getOffset()) {
158 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
159 if (Result.isInvalid())
160 return;
161 OE = Result.getAs<Expr>();
162 }
163
164 S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
165}
166
167static void instantiateDependentAlignValueAttr(
168 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
169 const AlignValueAttr *Aligned, Decl *New) {
170 // The alignment expression is a constant expression.
171 EnterExpressionEvaluationContext Unevaluated(
172 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
173 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
174 if (!Result.isInvalid())
175 S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
176}
177
178static void instantiateDependentAllocAlignAttr(
179 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
180 const AllocAlignAttr *Align, Decl *New) {
181 Expr *Param = IntegerLiteral::Create(
182 S.getASTContext(),
183 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
184 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
185 S.AddAllocAlignAttr(New, *Align, Param);
186}
187
188static void instantiateDependentAnnotationAttr(
189 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
190 const AnnotateAttr *Attr, Decl *New) {
191 EnterExpressionEvaluationContext Unevaluated(
192 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
193
194 // If the attribute has delayed arguments it will have to instantiate those
195 // and handle them as new arguments for the attribute.
196 bool HasDelayedArgs = Attr->delayedArgs_size();
197
198 ArrayRef<Expr *> ArgsToInstantiate =
199 HasDelayedArgs
200 ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
201 : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
202
203 SmallVector<Expr *, 4> Args;
204 if (S.SubstExprs(ArgsToInstantiate,
205 /*IsCall=*/false, TemplateArgs, Args))
206 return;
207
208 StringRef Str = Attr->getAnnotation();
209 if (HasDelayedArgs) {
210 if (Args.size() < 1) {
211 S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
212 << Attr << 1;
213 return;
214 }
215
216 if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
217 return;
218
219 llvm::SmallVector<Expr *, 4> ActualArgs;
220 ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
221 std::swap(Args, ActualArgs);
222 }
223 S.AddAnnotationAttr(New, *Attr, Str, Args);
224}
225
226static Expr *instantiateDependentFunctionAttrCondition(
227 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
228 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
229 Expr *Cond = nullptr;
230 {
231 Sema::ContextRAII SwitchContext(S, New);
232 EnterExpressionEvaluationContext Unevaluated(
233 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
234 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
235 if (Result.isInvalid())
236 return nullptr;
237 Cond = Result.getAs<Expr>();
238 }
239 if (!Cond->isTypeDependent()) {
240 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
241 if (Converted.isInvalid())
242 return nullptr;
243 Cond = Converted.get();
244 }
245
246 SmallVector<PartialDiagnosticAt, 8> Diags;
247 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
248 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
249 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
250 for (const auto &P : Diags)
251 S.Diag(P.first, P.second);
252 return nullptr;
253 }
254 return Cond;
255}
256
257static void instantiateDependentEnableIfAttr(
258 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
259 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
260 Expr *Cond = instantiateDependentFunctionAttrCondition(
261 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
262
263 if (Cond)
264 New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
265 Cond, EIA->getMessage()));
266}
267
268static void instantiateDependentDiagnoseIfAttr(
269 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
270 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
271 Expr *Cond = instantiateDependentFunctionAttrCondition(
272 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
273
274 if (Cond)
275 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
276 S.getASTContext(), *DIA, Cond, DIA->getMessage(),
277 DIA->getDiagnosticType(), DIA->getArgDependent(), New));
278}
279
280// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
281// template A as the base and arguments from TemplateArgs.
282static void instantiateDependentCUDALaunchBoundsAttr(
283 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
284 const CUDALaunchBoundsAttr &Attr, Decl *New) {
285 // The alignment expression is a constant expression.
286 EnterExpressionEvaluationContext Unevaluated(
287 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
288
289 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
290 if (Result.isInvalid())
291 return;
292 Expr *MaxThreads = Result.getAs<Expr>();
293
294 Expr *MinBlocks = nullptr;
295 if (Attr.getMinBlocks()) {
296 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
297 if (Result.isInvalid())
298 return;
299 MinBlocks = Result.getAs<Expr>();
300 }
301
302 S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks);
303}
304
305static void
306instantiateDependentModeAttr(Sema &S,
307 const MultiLevelTemplateArgumentList &TemplateArgs,
308 const ModeAttr &Attr, Decl *New) {
309 S.AddModeAttr(New, Attr, Attr.getMode(),
310 /*InInstantiation=*/true);
311}
312
313/// Instantiation of 'declare simd' attribute and its arguments.
314static void instantiateOMPDeclareSimdDeclAttr(
315 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
316 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
317 // Allow 'this' in clauses with varlists.
318 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
319 New = FTD->getTemplatedDecl();
320 auto *FD = cast<FunctionDecl>(New);
321 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
322 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
323 SmallVector<unsigned, 4> LinModifiers;
324
325 auto SubstExpr = [&](Expr *E) -> ExprResult {
326 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
327 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
328 Sema::ContextRAII SavedContext(S, FD);
329 LocalInstantiationScope Local(S);
330 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
331 Local.InstantiatedLocal(
332 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
333 return S.SubstExpr(E, TemplateArgs);
334 }
335 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
336 FD->isCXXInstanceMember());
337 return S.SubstExpr(E, TemplateArgs);
338 };
339
340 // Substitute a single OpenMP clause, which is a potentially-evaluated
341 // full-expression.
342 auto Subst = [&](Expr *E) -> ExprResult {
343 EnterExpressionEvaluationContext Evaluated(
344 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
345 ExprResult Res = SubstExpr(E);
346 if (Res.isInvalid())
347 return Res;
348 return S.ActOnFinishFullExpr(Res.get(), false);
349 };
350
351 ExprResult Simdlen;
352 if (auto *E = Attr.getSimdlen())
353 Simdlen = Subst(E);
354
355 if (Attr.uniforms_size() > 0) {
356 for(auto *E : Attr.uniforms()) {
357 ExprResult Inst = Subst(E);
358 if (Inst.isInvalid())
359 continue;
360 Uniforms.push_back(Inst.get());
361 }
362 }
363
364 auto AI = Attr.alignments_begin();
365 for (auto *E : Attr.aligneds()) {
366 ExprResult Inst = Subst(E);
367 if (Inst.isInvalid())
368 continue;
369 Aligneds.push_back(Inst.get());
370 Inst = ExprEmpty();
371 if (*AI)
372 Inst = S.SubstExpr(*AI, TemplateArgs);
373 Alignments.push_back(Inst.get());
374 ++AI;
375 }
376
377 auto SI = Attr.steps_begin();
378 for (auto *E : Attr.linears()) {
379 ExprResult Inst = Subst(E);
380 if (Inst.isInvalid())
381 continue;
382 Linears.push_back(Inst.get());
383 Inst = ExprEmpty();
384 if (*SI)
385 Inst = S.SubstExpr(*SI, TemplateArgs);
386 Steps.push_back(Inst.get());
387 ++SI;
388 }
389 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
390 (void)S.ActOnOpenMPDeclareSimdDirective(
391 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
392 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
393 Attr.getRange());
394}
395
396/// Instantiation of 'declare variant' attribute and its arguments.
397static void instantiateOMPDeclareVariantAttr(
398 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
399 const OMPDeclareVariantAttr &Attr, Decl *New) {
400 // Allow 'this' in clauses with varlists.
401 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
402 New = FTD->getTemplatedDecl();
403 auto *FD = cast<FunctionDecl>(New);
404 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
405
406 auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
407 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
408 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
409 Sema::ContextRAII SavedContext(S, FD);
410 LocalInstantiationScope Local(S);
411 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
412 Local.InstantiatedLocal(
413 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
414 return S.SubstExpr(E, TemplateArgs);
415 }
416 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
417 FD->isCXXInstanceMember());
418 return S.SubstExpr(E, TemplateArgs);
419 };
420
421 // Substitute a single OpenMP clause, which is a potentially-evaluated
422 // full-expression.
423 auto &&Subst = [&SubstExpr, &S](Expr *E) {
424 EnterExpressionEvaluationContext Evaluated(
425 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
426 ExprResult Res = SubstExpr(E);
427 if (Res.isInvalid())
428 return Res;
429 return S.ActOnFinishFullExpr(Res.get(), false);
430 };
431
432 ExprResult VariantFuncRef;
433 if (Expr *E = Attr.getVariantFuncRef()) {
434 // Do not mark function as is used to prevent its emission if this is the
435 // only place where it is used.
436 EnterExpressionEvaluationContext Unevaluated(
437 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
438 VariantFuncRef = Subst(E);
439 }
440
441 // Copy the template version of the OMPTraitInfo and run substitute on all
442 // score and condition expressiosn.
443 OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo();
444 TI = *Attr.getTraitInfos();
445
446 // Try to substitute template parameters in score and condition expressions.
447 auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
448 if (E) {
449 EnterExpressionEvaluationContext Unevaluated(
450 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
451 ExprResult ER = Subst(E);
452 if (ER.isUsable())
453 E = ER.get();
454 else
455 return true;
456 }
457 return false;
458 };
459 if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
460 return;
461
462 Expr *E = VariantFuncRef.get();
463
464 // Check function/variant ref for `omp declare variant` but not for `omp
465 // begin declare variant` (which use implicit attributes).
466 std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
467 S.checkOpenMPDeclareVariantFunction(S.ConvertDeclToDeclGroup(New), E, TI,
468 Attr.appendArgs_size(),
469 Attr.getRange());
470
471 if (!DeclVarData)
472 return;
473
474 E = DeclVarData->second;
475 FD = DeclVarData->first;
476
477 if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
478 if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
479 if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
480 if (!VariantFTD->isThisDeclarationADefinition())
481 return;
482 Sema::TentativeAnalysisScope Trap(S);
483 const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy(
484 S.Context, TemplateArgs.getInnermost());
485
486 auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
487 New->getLocation());
488 if (!SubstFD)
489 return;
490 QualType NewType = S.Context.mergeFunctionTypes(
491 SubstFD->getType(), FD->getType(),
492 /* OfBlockPointer */ false,
493 /* Unqualified */ false, /* AllowCXX */ true);
494 if (NewType.isNull())
495 return;
496 S.InstantiateFunctionDefinition(
497 New->getLocation(), SubstFD, /* Recursive */ true,
498 /* DefinitionRequired */ false, /* AtEndOfTU */ false);
499 SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
500 E = DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(),
501 SourceLocation(), SubstFD,
502 /* RefersToEnclosingVariableOrCapture */ false,
503 /* NameLoc */ SubstFD->getLocation(),
504 SubstFD->getType(), ExprValueKind::VK_PRValue);
505 }
506 }
507 }
508
509 SmallVector<Expr *, 8> NothingExprs;
510 SmallVector<Expr *, 8> NeedDevicePtrExprs;
511 SmallVector<OMPInteropInfo, 4> AppendArgs;
512
513 for (Expr *E : Attr.adjustArgsNothing()) {
514 ExprResult ER = Subst(E);
515 if (ER.isInvalid())
516 continue;
517 NothingExprs.push_back(ER.get());
518 }
519 for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
520 ExprResult ER = Subst(E);
521 if (ER.isInvalid())
522 continue;
523 NeedDevicePtrExprs.push_back(ER.get());
524 }
525 for (OMPInteropInfo &II : Attr.appendArgs()) {
526 // When prefer_type is implemented for append_args handle them here too.
527 AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
528 }
529
530 S.ActOnOpenMPDeclareVariantDirective(
531 FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
532 SourceLocation(), Attr.getRange());
533}
534
535static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
536 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
537 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
538 // Both min and max expression are constant expressions.
539 EnterExpressionEvaluationContext Unevaluated(
540 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
541
542 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
543 if (Result.isInvalid())
544 return;
545 Expr *MinExpr = Result.getAs<Expr>();
546
547 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
548 if (Result.isInvalid())
549 return;
550 Expr *MaxExpr = Result.getAs<Expr>();
551
552 S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
553}
554
555static ExplicitSpecifier
556instantiateExplicitSpecifier(Sema &S,
557 const MultiLevelTemplateArgumentList &TemplateArgs,
558 ExplicitSpecifier ES, FunctionDecl *New) {
559 if (!ES.getExpr())
560 return ES;
561 Expr *OldCond = ES.getExpr();
562 Expr *Cond = nullptr;
563 {
564 EnterExpressionEvaluationContext Unevaluated(
565 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
566 ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
567 if (SubstResult.isInvalid()) {
568 return ExplicitSpecifier::Invalid();
569 }
570 Cond = SubstResult.get();
571 }
572 ExplicitSpecifier Result(Cond, ES.getKind());
573 if (!Cond->isTypeDependent())
574 S.tryResolveExplicitSpecifier(Result);
575 return Result;
576}
577
578static void instantiateDependentAMDGPUWavesPerEUAttr(
579 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
580 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
581 // Both min and max expression are constant expressions.
582 EnterExpressionEvaluationContext Unevaluated(
583 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
584
585 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
586 if (Result.isInvalid())
587 return;
588 Expr *MinExpr = Result.getAs<Expr>();
589
590 Expr *MaxExpr = nullptr;
591 if (auto Max = Attr.getMax()) {
592 Result = S.SubstExpr(Max, TemplateArgs);
593 if (Result.isInvalid())
594 return;
595 MaxExpr = Result.getAs<Expr>();
596 }
597
598 S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
599}
600
601// This doesn't take any template parameters, but we have a custom action that
602// needs to happen when the kernel itself is instantiated. We need to run the
603// ItaniumMangler to mark the names required to name this kernel.
604static void instantiateDependentSYCLKernelAttr(
605 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
606 const SYCLKernelAttr &Attr, Decl *New) {
607 New->addAttr(Attr.clone(S.getASTContext()));
608}
609
610/// Determine whether the attribute A might be relevant to the declaration D.
611/// If not, we can skip instantiating it. The attribute may or may not have
612/// been instantiated yet.
613static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
614 // 'preferred_name' is only relevant to the matching specialization of the
615 // template.
616 if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
617 QualType T = PNA->getTypedefType();
618 const auto *RD = cast<CXXRecordDecl>(D);
619 if (!T->isDependentType() && !RD->isDependentContext() &&
620 !declaresSameEntity(T->getAsCXXRecordDecl(), RD))
621 return false;
622 for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
623 if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
624 PNA->getTypedefType()))
625 return false;
626 return true;
627 }
628
629 if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
630 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
631 switch (BA->getID()) {
632 case Builtin::BIforward:
633 // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
634 // type and returns an lvalue reference type. The library implementation
635 // will produce an error in this case; don't get in its way.
636 if (FD && FD->getNumParams() >= 1 &&
637 FD->getParamDecl(0)->getType()->isRValueReferenceType() &&
638 FD->getReturnType()->isLValueReferenceType()) {
639 return false;
640 }
641 [[fallthrough]];
642 case Builtin::BImove:
643 case Builtin::BImove_if_noexcept:
644 // HACK: Super-old versions of libc++ (3.1 and earlier) provide
645 // std::forward and std::move overloads that sometimes return by value
646 // instead of by reference when building in C++98 mode. Don't treat such
647 // cases as builtins.
648 if (FD && !FD->getReturnType()->isReferenceType())
649 return false;
650 break;
651 }
652 }
653
654 return true;
655}
656
657void Sema::InstantiateAttrsForDecl(
658 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
659 Decl *New, LateInstantiatedAttrVec *LateAttrs,
660 LocalInstantiationScope *OuterMostScope) {
661 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
662 // FIXME: This function is called multiple times for the same template
663 // specialization. We should only instantiate attributes that were added
664 // since the previous instantiation.
665 for (const auto *TmplAttr : Tmpl->attrs()) {
666 if (!isRelevantAttr(*this, New, TmplAttr))
667 continue;
668
669 // FIXME: If any of the special case versions from InstantiateAttrs become
670 // applicable to template declaration, we'll need to add them here.
671 CXXThisScopeRAII ThisScope(
672 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
673 Qualifiers(), ND->isCXXInstanceMember());
674
675 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
676 TmplAttr, Context, *this, TemplateArgs);
677 if (NewAttr && isRelevantAttr(*this, New, NewAttr))
678 New->addAttr(NewAttr);
679 }
680 }
681}
682
683static Sema::RetainOwnershipKind
684attrToRetainOwnershipKind(const Attr *A) {
685 switch (A->getKind()) {
686 case clang::attr::CFConsumed:
687 return Sema::RetainOwnershipKind::CF;
688 case clang::attr::OSConsumed:
689 return Sema::RetainOwnershipKind::OS;
690 case clang::attr::NSConsumed:
691 return Sema::RetainOwnershipKind::NS;
692 default:
693 llvm_unreachable("Wrong argument supplied")::llvm::llvm_unreachable_internal("Wrong argument supplied", "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 693)
;
694 }
695}
696
697void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
698 const Decl *Tmpl, Decl *New,
699 LateInstantiatedAttrVec *LateAttrs,
700 LocalInstantiationScope *OuterMostScope) {
701 for (const auto *TmplAttr : Tmpl->attrs()) {
702 if (!isRelevantAttr(*this, New, TmplAttr))
703 continue;
704
705 // FIXME: This should be generalized to more than just the AlignedAttr.
706 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
707 if (Aligned && Aligned->isAlignmentDependent()) {
708 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
709 continue;
710 }
711
712 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
713 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
714 continue;
715 }
716
717 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
718 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
719 continue;
720 }
721
722 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
723 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
724 continue;
725 }
726
727 if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
728 instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
729 continue;
730 }
731
732 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
733 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
734 cast<FunctionDecl>(New));
735 continue;
736 }
737
738 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
739 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
740 cast<FunctionDecl>(New));
741 continue;
742 }
743
744 if (const auto *CUDALaunchBounds =
745 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
746 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
747 *CUDALaunchBounds, New);
748 continue;
749 }
750
751 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
752 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
753 continue;
754 }
755
756 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
757 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
758 continue;
759 }
760
761 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
762 instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
763 continue;
764 }
765
766 if (const auto *AMDGPUFlatWorkGroupSize =
767 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
768 instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
769 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
770 }
771
772 if (const auto *AMDGPUFlatWorkGroupSize =
773 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
774 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
775 *AMDGPUFlatWorkGroupSize, New);
776 }
777
778 // Existing DLL attribute on the instantiation takes precedence.
779 if (TmplAttr->getKind() == attr::DLLExport ||
780 TmplAttr->getKind() == attr::DLLImport) {
781 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
782 continue;
783 }
784 }
785
786 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
787 AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
788 continue;
789 }
790
791 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
792 isa<CFConsumedAttr>(TmplAttr)) {
793 AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr),
794 /*template instantiation=*/true);
795 continue;
796 }
797
798 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
799 if (!New->hasAttr<PointerAttr>())
800 New->addAttr(A->clone(Context));
801 continue;
802 }
803
804 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
805 if (!New->hasAttr<OwnerAttr>())
806 New->addAttr(A->clone(Context));
807 continue;
808 }
809
810 if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
811 instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
812 continue;
813 }
814
815 assert(!TmplAttr->isPackExpansion())(static_cast <bool> (!TmplAttr->isPackExpansion()) ?
void (0) : __assert_fail ("!TmplAttr->isPackExpansion()",
"clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 815, __extension__
__PRETTY_FUNCTION__))
;
816 if (TmplAttr->isLateParsed() && LateAttrs) {
817 // Late parsed attributes must be instantiated and attached after the
818 // enclosing class has been instantiated. See Sema::InstantiateClass.
819 LocalInstantiationScope *Saved = nullptr;
820 if (CurrentInstantiationScope)
821 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
822 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
823 } else {
824 // Allow 'this' within late-parsed attributes.
825 auto *ND = cast<NamedDecl>(New);
826 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
827 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
828 ND->isCXXInstanceMember());
829
830 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
831 *this, TemplateArgs);
832 if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
833 New->addAttr(NewAttr);
834 }
835 }
836}
837
838/// Update instantiation attributes after template was late parsed.
839///
840/// Some attributes are evaluated based on the body of template. If it is
841/// late parsed, such attributes cannot be evaluated when declaration is
842/// instantiated. This function is used to update instantiation attributes when
843/// template definition is ready.
844void Sema::updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst) {
845 for (const auto *Attr : Pattern->attrs()) {
846 if (auto *A = dyn_cast<StrictFPAttr>(Attr)) {
847 if (!Inst->hasAttr<StrictFPAttr>())
848 Inst->addAttr(A->clone(getASTContext()));
849 continue;
850 }
851 }
852}
853
854/// In the MS ABI, we need to instantiate default arguments of dllexported
855/// default constructors along with the constructor definition. This allows IR
856/// gen to emit a constructor closure which calls the default constructor with
857/// its default arguments.
858void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor) {
859 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&(static_cast <bool> (Context.getTargetInfo().getCXXABI(
).isMicrosoft() && Ctor->isDefaultConstructor()) ?
void (0) : __assert_fail ("Context.getTargetInfo().getCXXABI().isMicrosoft() && Ctor->isDefaultConstructor()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 860, __extension__
__PRETTY_FUNCTION__))
860 Ctor->isDefaultConstructor())(static_cast <bool> (Context.getTargetInfo().getCXXABI(
).isMicrosoft() && Ctor->isDefaultConstructor()) ?
void (0) : __assert_fail ("Context.getTargetInfo().getCXXABI().isMicrosoft() && Ctor->isDefaultConstructor()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 860, __extension__
__PRETTY_FUNCTION__))
;
861 unsigned NumParams = Ctor->getNumParams();
862 if (NumParams == 0)
863 return;
864 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
865 if (!Attr)
866 return;
867 for (unsigned I = 0; I != NumParams; ++I) {
868 (void)CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
869 Ctor->getParamDecl(I));
870 CleanupVarDeclMarking();
871 }
872}
873
874/// Get the previous declaration of a declaration for the purposes of template
875/// instantiation. If this finds a previous declaration, then the previous
876/// declaration of the instantiation of D should be an instantiation of the
877/// result of this function.
878template<typename DeclT>
879static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
880 DeclT *Result = D->getPreviousDecl();
881
882 // If the declaration is within a class, and the previous declaration was
883 // merged from a different definition of that class, then we don't have a
884 // previous declaration for the purpose of template instantiation.
885 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
886 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
887 return nullptr;
888
889 return Result;
890}
891
892Decl *
893TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
894 llvm_unreachable("Translation units cannot be instantiated")::llvm::llvm_unreachable_internal("Translation units cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 894)
;
895}
896
897Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
898 llvm_unreachable("HLSL buffer declarations cannot be instantiated")::llvm::llvm_unreachable_internal("HLSL buffer declarations cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 898)
;
899}
900
901Decl *
902TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
903 llvm_unreachable("pragma comment cannot be instantiated")::llvm::llvm_unreachable_internal("pragma comment cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 903)
;
904}
905
906Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
907 PragmaDetectMismatchDecl *D) {
908 llvm_unreachable("pragma comment cannot be instantiated")::llvm::llvm_unreachable_internal("pragma comment cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 908)
;
909}
910
911Decl *
912TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
913 llvm_unreachable("extern \"C\" context cannot be instantiated")::llvm::llvm_unreachable_internal("extern \"C\" context cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 913)
;
914}
915
916Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
917 llvm_unreachable("GUID declaration cannot be instantiated")::llvm::llvm_unreachable_internal("GUID declaration cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 917)
;
918}
919
920Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
921 UnnamedGlobalConstantDecl *D) {
922 llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated")::llvm::llvm_unreachable_internal("UnnamedGlobalConstantDecl cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 922)
;
923}
924
925Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
926 TemplateParamObjectDecl *D) {
927 llvm_unreachable("template parameter objects cannot be instantiated")::llvm::llvm_unreachable_internal("template parameter objects cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 927)
;
928}
929
930Decl *
931TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
932 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
933 D->getIdentifier());
934 Owner->addDecl(Inst);
935 return Inst;
936}
937
938Decl *
939TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
940 llvm_unreachable("Namespaces cannot be instantiated")::llvm::llvm_unreachable_internal("Namespaces cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 940)
;
941}
942
943Decl *
944TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
945 NamespaceAliasDecl *Inst
946 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
947 D->getNamespaceLoc(),
948 D->getAliasLoc(),
949 D->getIdentifier(),
950 D->getQualifierLoc(),
951 D->getTargetNameLoc(),
952 D->getNamespace());
953 Owner->addDecl(Inst);
954 return Inst;
955}
956
957Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
958 bool IsTypeAlias) {
959 bool Invalid = false;
960 TypeSourceInfo *DI = D->getTypeSourceInfo();
961 if (DI->getType()->isInstantiationDependentType() ||
962 DI->getType()->isVariablyModifiedType()) {
963 DI = SemaRef.SubstType(DI, TemplateArgs,
964 D->getLocation(), D->getDeclName());
965 if (!DI) {
966 Invalid = true;
967 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
968 }
969 } else {
970 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
971 }
972
973 // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
974 // libstdc++ relies upon this bug in its implementation of common_type. If we
975 // happen to be processing that implementation, fake up the g++ ?:
976 // semantics. See LWG issue 2141 for more information on the bug. The bugs
977 // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
978 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
979 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
980 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
981 DT->isReferenceType() &&
982 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
983 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
984 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
985 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
986 // Fold it to the (non-reference) type which g++ would have produced.
987 DI = SemaRef.Context.getTrivialTypeSourceInfo(
988 DI->getType().getNonReferenceType());
989
990 // Create the new typedef
991 TypedefNameDecl *Typedef;
992 if (IsTypeAlias)
993 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
994 D->getLocation(), D->getIdentifier(), DI);
995 else
996 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
997 D->getLocation(), D->getIdentifier(), DI);
998 if (Invalid)
999 Typedef->setInvalidDecl();
1000
1001 // If the old typedef was the name for linkage purposes of an anonymous
1002 // tag decl, re-establish that relationship for the new typedef.
1003 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1004 TagDecl *oldTag = oldTagType->getDecl();
1005 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1006 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
1007 assert(!newTag->hasNameForLinkage())(static_cast <bool> (!newTag->hasNameForLinkage()) ?
void (0) : __assert_fail ("!newTag->hasNameForLinkage()",
"clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1007, __extension__
__PRETTY_FUNCTION__))
;
1008 newTag->setTypedefNameForAnonDecl(Typedef);
1009 }
1010 }
1011
1012 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
1013 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
1014 TemplateArgs);
1015 if (!InstPrev)
1016 return nullptr;
1017
1018 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1019
1020 // If the typedef types are not identical, reject them.
1021 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1022
1023 Typedef->setPreviousDecl(InstPrevTypedef);
1024 }
1025
1026 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1027
1028 if (D->getUnderlyingType()->getAs<DependentNameType>())
1029 SemaRef.inferGslPointerAttribute(Typedef);
1030
1031 Typedef->setAccess(D->getAccess());
1032 Typedef->setReferenced(D->isReferenced());
1033
1034 return Typedef;
1035}
1036
1037Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1038 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1039 if (Typedef)
1040 Owner->addDecl(Typedef);
1041 return Typedef;
1042}
1043
1044Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1045 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1046 if (Typedef)
1047 Owner->addDecl(Typedef);
1048 return Typedef;
1049}
1050
1051Decl *
1052TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1053 // Create a local instantiation scope for this type alias template, which
1054 // will contain the instantiations of the template parameters.
1055 LocalInstantiationScope Scope(SemaRef);
1056
1057 TemplateParameterList *TempParams = D->getTemplateParameters();
1058 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1059 if (!InstParams)
1060 return nullptr;
1061
1062 TypeAliasDecl *Pattern = D->getTemplatedDecl();
1063
1064 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1065 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
1066 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1067 if (!Found.empty()) {
1068 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1069 }
1070 }
1071
1072 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1073 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1074 if (!AliasInst)
1075 return nullptr;
1076
1077 TypeAliasTemplateDecl *Inst
1078 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1079 D->getDeclName(), InstParams, AliasInst);
1080 AliasInst->setDescribedAliasTemplate(Inst);
1081 if (PrevAliasTemplate)
1082 Inst->setPreviousDecl(PrevAliasTemplate);
1083
1084 Inst->setAccess(D->getAccess());
1085
1086 if (!PrevAliasTemplate)
1087 Inst->setInstantiatedFromMemberTemplate(D);
1088
1089 Owner->addDecl(Inst);
1090
1091 return Inst;
1092}
1093
1094Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1095 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1096 D->getIdentifier());
1097 NewBD->setReferenced(D->isReferenced());
1098 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
1099 return NewBD;
1100}
1101
1102Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1103 // Transform the bindings first.
1104 SmallVector<BindingDecl*, 16> NewBindings;
1105 for (auto *OldBD : D->bindings())
1106 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1107 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1108
1109 auto *NewDD = cast_or_null<DecompositionDecl>(
1110 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1111
1112 if (!NewDD || NewDD->isInvalidDecl())
1113 for (auto *NewBD : NewBindings)
1114 NewBD->setInvalidDecl();
1115
1116 return NewDD;
1117}
1118
1119Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
1120 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1121}
1122
1123Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
1124 bool InstantiatingVarTemplate,
1125 ArrayRef<BindingDecl*> *Bindings) {
1126
1127 // Do substitution on the type of the declaration
1128 TypeSourceInfo *DI = SemaRef.SubstType(
1129 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1130 D->getDeclName(), /*AllowDeducedTST*/true);
1131 if (!DI)
1132 return nullptr;
1133
1134 if (DI->getType()->isFunctionType()) {
1135 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1136 << D->isStaticDataMember() << DI->getType();
1137 return nullptr;
1138 }
1139
1140 DeclContext *DC = Owner;
1141 if (D->isLocalExternDecl())
1142 SemaRef.adjustContextForLocalExternDecl(DC);
1143
1144 // Build the instantiated declaration.
1145 VarDecl *Var;
1146 if (Bindings)
1147 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1148 D->getLocation(), DI->getType(), DI,
1149 D->getStorageClass(), *Bindings);
1150 else
1151 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1152 D->getLocation(), D->getIdentifier(), DI->getType(),
1153 DI, D->getStorageClass());
1154
1155 // In ARC, infer 'retaining' for variables of retainable type.
1156 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1157 SemaRef.inferObjCARCLifetime(Var))
1158 Var->setInvalidDecl();
1159
1160 if (SemaRef.getLangOpts().OpenCL)
1161 SemaRef.deduceOpenCLAddressSpace(Var);
1162
1163 // Substitute the nested name specifier, if any.
1164 if (SubstQualifier(D, Var))
1165 return nullptr;
1166
1167 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1168 StartingScope, InstantiatingVarTemplate);
1169 if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1170 QualType RT;
1171 if (auto *F = dyn_cast<FunctionDecl>(DC))
1172 RT = F->getReturnType();
1173 else if (isa<BlockDecl>(DC))
1174 RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1175 ->getReturnType();
1176 else
1177 llvm_unreachable("Unknown context type")::llvm::llvm_unreachable_internal("Unknown context type", "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1177)
;
1178
1179 // This is the last chance we have of checking copy elision eligibility
1180 // for functions in dependent contexts. The sema actions for building
1181 // the return statement during template instantiation will have no effect
1182 // regarding copy elision, since NRVO propagation runs on the scope exit
1183 // actions, and these are not run on instantiation.
1184 // This might run through some VarDecls which were returned from non-taken
1185 // 'if constexpr' branches, and these will end up being constructed on the
1186 // return slot even if they will never be returned, as a sort of accidental
1187 // 'optimization'. Notably, functions with 'auto' return types won't have it
1188 // deduced by this point. Coupled with the limitation described
1189 // previously, this makes it very hard to support copy elision for these.
1190 Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1191 bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1192 Var->setNRVOVariable(NRVO);
1193 }
1194
1195 Var->setImplicit(D->isImplicit());
1196
1197 if (Var->isStaticLocal())
1198 SemaRef.CheckStaticLocalForDllExport(Var);
1199
1200 if (Var->getTLSKind())
1201 SemaRef.CheckThreadLocalForLargeAlignment(Var);
1202
1203 return Var;
1204}
1205
1206Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1207 AccessSpecDecl* AD
1208 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1209 D->getAccessSpecifierLoc(), D->getColonLoc());
1210 Owner->addHiddenDecl(AD);
1211 return AD;
1212}
1213
1214Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1215 bool Invalid = false;
1216 TypeSourceInfo *DI = D->getTypeSourceInfo();
1217 if (DI->getType()->isInstantiationDependentType() ||
1218 DI->getType()->isVariablyModifiedType()) {
1219 DI = SemaRef.SubstType(DI, TemplateArgs,
1220 D->getLocation(), D->getDeclName());
1221 if (!DI) {
1222 DI = D->getTypeSourceInfo();
1223 Invalid = true;
1224 } else if (DI->getType()->isFunctionType()) {
1225 // C++ [temp.arg.type]p3:
1226 // If a declaration acquires a function type through a type
1227 // dependent on a template-parameter and this causes a
1228 // declaration that does not use the syntactic form of a
1229 // function declarator to have function type, the program is
1230 // ill-formed.
1231 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1232 << DI->getType();
1233 Invalid = true;
1234 }
1235 } else {
1236 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1237 }
1238
1239 Expr *BitWidth = D->getBitWidth();
1240 if (Invalid)
1241 BitWidth = nullptr;
1242 else if (BitWidth) {
1243 // The bit-width expression is a constant expression.
1244 EnterExpressionEvaluationContext Unevaluated(
1245 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1246
1247 ExprResult InstantiatedBitWidth
1248 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1249 if (InstantiatedBitWidth.isInvalid()) {
1250 Invalid = true;
1251 BitWidth = nullptr;
1252 } else
1253 BitWidth = InstantiatedBitWidth.getAs<Expr>();
1254 }
1255
1256 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1257 DI->getType(), DI,
1258 cast<RecordDecl>(Owner),
1259 D->getLocation(),
1260 D->isMutable(),
1261 BitWidth,
1262 D->getInClassInitStyle(),
1263 D->getInnerLocStart(),
1264 D->getAccess(),
1265 nullptr);
1266 if (!Field) {
1267 cast<Decl>(Owner)->setInvalidDecl();
1268 return nullptr;
1269 }
1270
1271 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1272
1273 if (Field->hasAttrs())
1274 SemaRef.CheckAlignasUnderalignment(Field);
1275
1276 if (Invalid)
1277 Field->setInvalidDecl();
1278
1279 if (!Field->getDeclName()) {
1280 // Keep track of where this decl came from.
1281 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1282 }
1283 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1284 if (Parent->isAnonymousStructOrUnion() &&
1285 Parent->getRedeclContext()->isFunctionOrMethod())
1286 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1287 }
1288
1289 Field->setImplicit(D->isImplicit());
1290 Field->setAccess(D->getAccess());
1291 Owner->addDecl(Field);
1292
1293 return Field;
1294}
1295
1296Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1297 bool Invalid = false;
1298 TypeSourceInfo *DI = D->getTypeSourceInfo();
1299
1300 if (DI->getType()->isVariablyModifiedType()) {
1301 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1302 << D;
1303 Invalid = true;
1304 } else if (DI->getType()->isInstantiationDependentType()) {
1305 DI = SemaRef.SubstType(DI, TemplateArgs,
1306 D->getLocation(), D->getDeclName());
1307 if (!DI) {
1308 DI = D->getTypeSourceInfo();
1309 Invalid = true;
1310 } else if (DI->getType()->isFunctionType()) {
1311 // C++ [temp.arg.type]p3:
1312 // If a declaration acquires a function type through a type
1313 // dependent on a template-parameter and this causes a
1314 // declaration that does not use the syntactic form of a
1315 // function declarator to have function type, the program is
1316 // ill-formed.
1317 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1318 << DI->getType();
1319 Invalid = true;
1320 }
1321 } else {
1322 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1323 }
1324
1325 MSPropertyDecl *Property = MSPropertyDecl::Create(
1326 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1327 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1328
1329 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1330 StartingScope);
1331
1332 if (Invalid)
1333 Property->setInvalidDecl();
1334
1335 Property->setAccess(D->getAccess());
1336 Owner->addDecl(Property);
1337
1338 return Property;
1339}
1340
1341Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1342 NamedDecl **NamedChain =
1343 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1344
1345 int i = 0;
1346 for (auto *PI : D->chain()) {
1347 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1348 TemplateArgs);
1349 if (!Next)
1350 return nullptr;
1351
1352 NamedChain[i++] = Next;
1353 }
1354
1355 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1356 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1357 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1358 {NamedChain, D->getChainingSize()});
1359
1360 for (const auto *Attr : D->attrs())
1361 IndirectField->addAttr(Attr->clone(SemaRef.Context));
1362
1363 IndirectField->setImplicit(D->isImplicit());
1364 IndirectField->setAccess(D->getAccess());
1365 Owner->addDecl(IndirectField);
1366 return IndirectField;
1367}
1368
1369Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1370 // Handle friend type expressions by simply substituting template
1371 // parameters into the pattern type and checking the result.
1372 if (TypeSourceInfo *Ty = D->getFriendType()) {
1373 TypeSourceInfo *InstTy;
1374 // If this is an unsupported friend, don't bother substituting template
1375 // arguments into it. The actual type referred to won't be used by any
1376 // parts of Clang, and may not be valid for instantiating. Just use the
1377 // same info for the instantiated friend.
1378 if (D->isUnsupportedFriend()) {
1379 InstTy = Ty;
1380 } else {
1381 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1382 D->getLocation(), DeclarationName());
1383 }
1384 if (!InstTy)
1385 return nullptr;
1386
1387 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
1388 D->getFriendLoc(), InstTy);
1389 if (!FD)
1390 return nullptr;
1391
1392 FD->setAccess(AS_public);
1393 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1394 Owner->addDecl(FD);
1395 return FD;
1396 }
1397
1398 NamedDecl *ND = D->getFriendDecl();
1399 assert(ND && "friend decl must be a decl or a type!")(static_cast <bool> (ND && "friend decl must be a decl or a type!"
) ? void (0) : __assert_fail ("ND && \"friend decl must be a decl or a type!\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1399, __extension__
__PRETTY_FUNCTION__))
;
1400
1401 // All of the Visit implementations for the various potential friend
1402 // declarations have to be carefully written to work for friend
1403 // objects, with the most important detail being that the target
1404 // decl should almost certainly not be placed in Owner.
1405 Decl *NewND = Visit(ND);
1406 if (!NewND) return nullptr;
1407
1408 FriendDecl *FD =
1409 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1410 cast<NamedDecl>(NewND), D->getFriendLoc());
1411 FD->setAccess(AS_public);
1412 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1413 Owner->addDecl(FD);
1414 return FD;
1415}
1416
1417Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1418 Expr *AssertExpr = D->getAssertExpr();
1419
1420 // The expression in a static assertion is a constant expression.
1421 EnterExpressionEvaluationContext Unevaluated(
1422 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1423
1424 ExprResult InstantiatedAssertExpr
1425 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1426 if (InstantiatedAssertExpr.isInvalid())
1427 return nullptr;
1428
1429 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
1430 InstantiatedAssertExpr.get(),
1431 D->getMessage(),
1432 D->getRParenLoc(),
1433 D->isFailed());
1434}
1435
1436Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1437 EnumDecl *PrevDecl = nullptr;
1438 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1439 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1440 PatternPrev,
1441 TemplateArgs);
1442 if (!Prev) return nullptr;
1443 PrevDecl = cast<EnumDecl>(Prev);
1444 }
1445
1446 EnumDecl *Enum =
1447 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1448 D->getLocation(), D->getIdentifier(), PrevDecl,
1449 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1450 if (D->isFixed()) {
1451 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1452 // If we have type source information for the underlying type, it means it
1453 // has been explicitly set by the user. Perform substitution on it before
1454 // moving on.
1455 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1456 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1457 DeclarationName());
1458 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1459 Enum->setIntegerType(SemaRef.Context.IntTy);
1460 else
1461 Enum->setIntegerTypeSourceInfo(NewTI);
1462 } else {
1463 assert(!D->getIntegerType()->isDependentType()(static_cast <bool> (!D->getIntegerType()->isDependentType
() && "Dependent type without type source info") ? void
(0) : __assert_fail ("!D->getIntegerType()->isDependentType() && \"Dependent type without type source info\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1464, __extension__
__PRETTY_FUNCTION__))
1464 && "Dependent type without type source info")(static_cast <bool> (!D->getIntegerType()->isDependentType
() && "Dependent type without type source info") ? void
(0) : __assert_fail ("!D->getIntegerType()->isDependentType() && \"Dependent type without type source info\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1464, __extension__
__PRETTY_FUNCTION__))
;
1465 Enum->setIntegerType(D->getIntegerType());
1466 }
1467 }
1468
1469 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1470
1471 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1472 Enum->setAccess(D->getAccess());
1473 // Forward the mangling number from the template to the instantiated decl.
1474 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1475 // See if the old tag was defined along with a declarator.
1476 // If it did, mark the new tag as being associated with that declarator.
1477 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1478 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1479 // See if the old tag was defined along with a typedef.
1480 // If it did, mark the new tag as being associated with that typedef.
1481 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1482 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1483 if (SubstQualifier(D, Enum)) return nullptr;
1484 Owner->addDecl(Enum);
1485
1486 EnumDecl *Def = D->getDefinition();
1487 if (Def && Def != D) {
1488 // If this is an out-of-line definition of an enum member template, check
1489 // that the underlying types match in the instantiation of both
1490 // declarations.
1491 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1492 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1493 QualType DefnUnderlying =
1494 SemaRef.SubstType(TI->getType(), TemplateArgs,
1495 UnderlyingLoc, DeclarationName());
1496 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1497 DefnUnderlying, /*IsFixed=*/true, Enum);
1498 }
1499 }
1500
1501 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1502 // specialization causes the implicit instantiation of the declarations, but
1503 // not the definitions of scoped member enumerations.
1504 //
1505 // DR1484 clarifies that enumeration definitions inside of a template
1506 // declaration aren't considered entities that can be separately instantiated
1507 // from the rest of the entity they are declared inside of.
1508 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1509 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1510 InstantiateEnumDefinition(Enum, Def);
1511 }
1512
1513 return Enum;
1514}
1515
1516void TemplateDeclInstantiator::InstantiateEnumDefinition(
1517 EnumDecl *Enum, EnumDecl *Pattern) {
1518 Enum->startDefinition();
1519
1520 // Update the location to refer to the definition.
1521 Enum->setLocation(Pattern->getLocation());
1522
1523 SmallVector<Decl*, 4> Enumerators;
1524
1525 EnumConstantDecl *LastEnumConst = nullptr;
1526 for (auto *EC : Pattern->enumerators()) {
1527 // The specified value for the enumerator.
1528 ExprResult Value((Expr *)nullptr);
1529 if (Expr *UninstValue = EC->getInitExpr()) {
1530 // The enumerator's value expression is a constant expression.
1531 EnterExpressionEvaluationContext Unevaluated(
1532 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1533
1534 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1535 }
1536
1537 // Drop the initial value and continue.
1538 bool isInvalid = false;
1539 if (Value.isInvalid()) {
1540 Value = nullptr;
1541 isInvalid = true;
1542 }
1543
1544 EnumConstantDecl *EnumConst
1545 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1546 EC->getLocation(), EC->getIdentifier(),
1547 Value.get());
1548
1549 if (isInvalid) {
1550 if (EnumConst)
1551 EnumConst->setInvalidDecl();
1552 Enum->setInvalidDecl();
1553 }
1554
1555 if (EnumConst) {
1556 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1557
1558 EnumConst->setAccess(Enum->getAccess());
1559 Enum->addDecl(EnumConst);
1560 Enumerators.push_back(EnumConst);
1561 LastEnumConst = EnumConst;
1562
1563 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1564 !Enum->isScoped()) {
1565 // If the enumeration is within a function or method, record the enum
1566 // constant as a local.
1567 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1568 }
1569 }
1570 }
1571
1572 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1573 Enumerators, nullptr, ParsedAttributesView());
1574}
1575
1576Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1577 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.")::llvm::llvm_unreachable_internal("EnumConstantDecls can only occur within EnumDecls."
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1577)
;
1578}
1579
1580Decl *
1581TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1582 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.")::llvm::llvm_unreachable_internal("BuiltinTemplateDecls cannot be instantiated."
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1582)
;
1583}
1584
1585Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1586 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1587
1588 // Create a local instantiation scope for this class template, which
1589 // will contain the instantiations of the template parameters.
1590 LocalInstantiationScope Scope(SemaRef);
1591 TemplateParameterList *TempParams = D->getTemplateParameters();
1592 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1593 if (!InstParams)
1594 return nullptr;
1595
1596 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1597
1598 // Instantiate the qualifier. We have to do this first in case
1599 // we're a friend declaration, because if we are then we need to put
1600 // the new declaration in the appropriate context.
1601 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1602 if (QualifierLoc) {
1603 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1604 TemplateArgs);
1605 if (!QualifierLoc)
1606 return nullptr;
1607 }
1608
1609 CXXRecordDecl *PrevDecl = nullptr;
1610 ClassTemplateDecl *PrevClassTemplate = nullptr;
1611
1612 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1613 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1614 if (!Found.empty()) {
1615 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1616 if (PrevClassTemplate)
1617 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1618 }
1619 }
1620
1621 // If this isn't a friend, then it's a member template, in which
1622 // case we just want to build the instantiation in the
1623 // specialization. If it is a friend, we want to build it in
1624 // the appropriate context.
1625 DeclContext *DC = Owner;
1626 if (isFriend) {
1627 if (QualifierLoc) {
1628 CXXScopeSpec SS;
1629 SS.Adopt(QualifierLoc);
1630 DC = SemaRef.computeDeclContext(SS);
1631 if (!DC) return nullptr;
1632 } else {
1633 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1634 Pattern->getDeclContext(),
1635 TemplateArgs);
1636 }
1637
1638 // Look for a previous declaration of the template in the owning
1639 // context.
1640 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1641 Sema::LookupOrdinaryName,
1642 SemaRef.forRedeclarationInCurContext());
1643 SemaRef.LookupQualifiedName(R, DC);
1644
1645 if (R.isSingleResult()) {
1646 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1647 if (PrevClassTemplate)
1648 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1649 }
1650
1651 if (!PrevClassTemplate && QualifierLoc) {
1652 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1653 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1654 << QualifierLoc.getSourceRange();
1655 return nullptr;
1656 }
1657 }
1658
1659 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1660 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1661 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1662 /*DelayTypeCreation=*/true);
1663 if (QualifierLoc)
1664 RecordInst->setQualifierInfo(QualifierLoc);
1665
1666 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1667 StartingScope);
1668
1669 ClassTemplateDecl *Inst
1670 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1671 D->getIdentifier(), InstParams, RecordInst);
1672 RecordInst->setDescribedClassTemplate(Inst);
1673
1674 if (isFriend) {
1675 assert(!Owner->isDependentContext())(static_cast <bool> (!Owner->isDependentContext()) ?
void (0) : __assert_fail ("!Owner->isDependentContext()",
"clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1675, __extension__
__PRETTY_FUNCTION__))
;
1676 Inst->setLexicalDeclContext(Owner);
1677 RecordInst->setLexicalDeclContext(Owner);
1678
1679 if (PrevClassTemplate) {
1680 Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
1681 RecordInst->setTypeForDecl(
1682 PrevClassTemplate->getTemplatedDecl()->getTypeForDecl());
1683 const ClassTemplateDecl *MostRecentPrevCT =
1684 PrevClassTemplate->getMostRecentDecl();
1685 TemplateParameterList *PrevParams =
1686 MostRecentPrevCT->getTemplateParameters();
1687
1688 // Make sure the parameter lists match.
1689 if (!SemaRef.TemplateParameterListsAreEqual(
1690 RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
1691 PrevParams, true, Sema::TPL_TemplateMatch))
1692 return nullptr;
1693
1694 // Do some additional validation, then merge default arguments
1695 // from the existing declarations.
1696 if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1697 Sema::TPC_ClassTemplate))
1698 return nullptr;
1699
1700 Inst->setAccess(PrevClassTemplate->getAccess());
1701 } else {
1702 Inst->setAccess(D->getAccess());
1703 }
1704
1705 Inst->setObjectOfFriendDecl();
1706 // TODO: do we want to track the instantiation progeny of this
1707 // friend target decl?
1708 } else {
1709 Inst->setAccess(D->getAccess());
1710 if (!PrevClassTemplate)
1711 Inst->setInstantiatedFromMemberTemplate(D);
1712 }
1713
1714 Inst->setPreviousDecl(PrevClassTemplate);
1715
1716 // Trigger creation of the type for the instantiation.
1717 SemaRef.Context.getInjectedClassNameType(
1718 RecordInst, Inst->getInjectedClassNameSpecialization());
1719
1720 // Finish handling of friends.
1721 if (isFriend) {
1722 DC->makeDeclVisibleInContext(Inst);
1723 return Inst;
1724 }
1725
1726 if (D->isOutOfLine()) {
1727 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1728 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1729 }
1730
1731 Owner->addDecl(Inst);
1732
1733 if (!PrevClassTemplate) {
1734 // Queue up any out-of-line partial specializations of this member
1735 // class template; the client will force their instantiation once
1736 // the enclosing class has been instantiated.
1737 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1738 D->getPartialSpecializations(PartialSpecs);
1739 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1740 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1741 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1742 }
1743
1744 return Inst;
1745}
1746
1747Decl *
1748TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1749 ClassTemplatePartialSpecializationDecl *D) {
1750 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1751
1752 // Lookup the already-instantiated declaration in the instantiation
1753 // of the class template and return that.
1754 DeclContext::lookup_result Found
1755 = Owner->lookup(ClassTemplate->getDeclName());
1756 if (Found.empty())
1757 return nullptr;
1758
1759 ClassTemplateDecl *InstClassTemplate
1760 = dyn_cast<ClassTemplateDecl>(Found.front());
1761 if (!InstClassTemplate)
1762 return nullptr;
1763
1764 if (ClassTemplatePartialSpecializationDecl *Result
1765 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1766 return Result;
1767
1768 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1769}
1770
1771Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1772 assert(D->getTemplatedDecl()->isStaticDataMember() &&(static_cast <bool> (D->getTemplatedDecl()->isStaticDataMember
() && "Only static data member templates are allowed."
) ? void (0) : __assert_fail ("D->getTemplatedDecl()->isStaticDataMember() && \"Only static data member templates are allowed.\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1773, __extension__
__PRETTY_FUNCTION__))
1773 "Only static data member templates are allowed.")(static_cast <bool> (D->getTemplatedDecl()->isStaticDataMember
() && "Only static data member templates are allowed."
) ? void (0) : __assert_fail ("D->getTemplatedDecl()->isStaticDataMember() && \"Only static data member templates are allowed.\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1773, __extension__
__PRETTY_FUNCTION__))
;
1774
1775 // Create a local instantiation scope for this variable template, which
1776 // will contain the instantiations of the template parameters.
1777 LocalInstantiationScope Scope(SemaRef);
1778 TemplateParameterList *TempParams = D->getTemplateParameters();
1779 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1780 if (!InstParams)
1781 return nullptr;
1782
1783 VarDecl *Pattern = D->getTemplatedDecl();
1784 VarTemplateDecl *PrevVarTemplate = nullptr;
1785
1786 if (getPreviousDeclForInstantiation(Pattern)) {
1787 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1788 if (!Found.empty())
1789 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1790 }
1791
1792 VarDecl *VarInst =
1793 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1794 /*InstantiatingVarTemplate=*/true));
1795 if (!VarInst) return nullptr;
1796
1797 DeclContext *DC = Owner;
1798
1799 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1800 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1801 VarInst);
1802 VarInst->setDescribedVarTemplate(Inst);
1803 Inst->setPreviousDecl(PrevVarTemplate);
1804
1805 Inst->setAccess(D->getAccess());
1806 if (!PrevVarTemplate)
1807 Inst->setInstantiatedFromMemberTemplate(D);
1808
1809 if (D->isOutOfLine()) {
1810 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1811 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1812 }
1813
1814 Owner->addDecl(Inst);
1815
1816 if (!PrevVarTemplate) {
1817 // Queue up any out-of-line partial specializations of this member
1818 // variable template; the client will force their instantiation once
1819 // the enclosing class has been instantiated.
1820 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1821 D->getPartialSpecializations(PartialSpecs);
1822 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1823 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1824 OutOfLineVarPartialSpecs.push_back(
1825 std::make_pair(Inst, PartialSpecs[I]));
1826 }
1827
1828 return Inst;
1829}
1830
1831Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1832 VarTemplatePartialSpecializationDecl *D) {
1833 assert(D->isStaticDataMember() &&(static_cast <bool> (D->isStaticDataMember() &&
"Only static data member templates are allowed.") ? void (0)
: __assert_fail ("D->isStaticDataMember() && \"Only static data member templates are allowed.\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1834, __extension__
__PRETTY_FUNCTION__))
1834 "Only static data member templates are allowed.")(static_cast <bool> (D->isStaticDataMember() &&
"Only static data member templates are allowed.") ? void (0)
: __assert_fail ("D->isStaticDataMember() && \"Only static data member templates are allowed.\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1834, __extension__
__PRETTY_FUNCTION__))
;
1835
1836 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1837
1838 // Lookup the already-instantiated declaration and return that.
1839 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1840 assert(!Found.empty() && "Instantiation found nothing?")(static_cast <bool> (!Found.empty() && "Instantiation found nothing?"
) ? void (0) : __assert_fail ("!Found.empty() && \"Instantiation found nothing?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1840, __extension__
__PRETTY_FUNCTION__))
;
1841
1842 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1843 assert(InstVarTemplate && "Instantiation did not find a variable template?")(static_cast <bool> (InstVarTemplate && "Instantiation did not find a variable template?"
) ? void (0) : __assert_fail ("InstVarTemplate && \"Instantiation did not find a variable template?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1843, __extension__
__PRETTY_FUNCTION__))
;
1844
1845 if (VarTemplatePartialSpecializationDecl *Result =
1846 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1847 return Result;
1848
1849 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1850}
1851
1852Decl *
1853TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1854 // Create a local instantiation scope for this function template, which
1855 // will contain the instantiations of the template parameters and then get
1856 // merged with the local instantiation scope for the function template
1857 // itself.
1858 LocalInstantiationScope Scope(SemaRef);
1859 Sema::ConstraintEvalRAII<TemplateDeclInstantiator> RAII(*this);
1860
1861 TemplateParameterList *TempParams = D->getTemplateParameters();
1862 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1863 if (!InstParams)
1864 return nullptr;
1865
1866 FunctionDecl *Instantiated = nullptr;
1867 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1868 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1869 InstParams));
1870 else
1871 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1872 D->getTemplatedDecl(),
1873 InstParams));
1874
1875 if (!Instantiated)
1876 return nullptr;
1877
1878 // Link the instantiated function template declaration to the function
1879 // template from which it was instantiated.
1880 FunctionTemplateDecl *InstTemplate
1881 = Instantiated->getDescribedFunctionTemplate();
1882 InstTemplate->setAccess(D->getAccess());
1883 assert(InstTemplate &&(static_cast <bool> (InstTemplate && "VisitFunctionDecl/CXXMethodDecl didn't create a template!"
) ? void (0) : __assert_fail ("InstTemplate && \"VisitFunctionDecl/CXXMethodDecl didn't create a template!\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1884, __extension__
__PRETTY_FUNCTION__))
1884 "VisitFunctionDecl/CXXMethodDecl didn't create a template!")(static_cast <bool> (InstTemplate && "VisitFunctionDecl/CXXMethodDecl didn't create a template!"
) ? void (0) : __assert_fail ("InstTemplate && \"VisitFunctionDecl/CXXMethodDecl didn't create a template!\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1884, __extension__
__PRETTY_FUNCTION__))
;
1885
1886 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1887
1888 // Link the instantiation back to the pattern *unless* this is a
1889 // non-definition friend declaration.
1890 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1891 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1892 InstTemplate->setInstantiatedFromMemberTemplate(D);
1893
1894 // Make declarations visible in the appropriate context.
1895 if (!isFriend) {
1896 Owner->addDecl(InstTemplate);
1897 } else if (InstTemplate->getDeclContext()->isRecord() &&
1898 !getPreviousDeclForInstantiation(D)) {
1899 SemaRef.CheckFriendAccess(InstTemplate);
1900 }
1901
1902 return InstTemplate;
1903}
1904
1905Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1906 CXXRecordDecl *PrevDecl = nullptr;
1907 if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1908 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1909 PatternPrev,
1910 TemplateArgs);
1911 if (!Prev) return nullptr;
1912 PrevDecl = cast<CXXRecordDecl>(Prev);
1913 }
1914
1915 CXXRecordDecl *Record = nullptr;
1916 bool IsInjectedClassName = D->isInjectedClassName();
1917 if (D->isLambda())
1918 Record = CXXRecordDecl::CreateLambda(
1919 SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
1920 D->getLambdaDependencyKind(), D->isGenericLambda(),
1921 D->getLambdaCaptureDefault());
1922 else
1923 Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1924 D->getBeginLoc(), D->getLocation(),
1925 D->getIdentifier(), PrevDecl,
1926 /*DelayTypeCreation=*/IsInjectedClassName);
1927 // Link the type of the injected-class-name to that of the outer class.
1928 if (IsInjectedClassName)
1929 (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
1930
1931 // Substitute the nested name specifier, if any.
1932 if (SubstQualifier(D, Record))
1933 return nullptr;
1934
1935 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1936 StartingScope);
1937
1938 Record->setImplicit(D->isImplicit());
1939 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1940 // the tag decls introduced by friend class declarations don't have an access
1941 // specifier. Remove once this area of the code gets sorted out.
1942 if (D->getAccess() != AS_none)
1943 Record->setAccess(D->getAccess());
1944 if (!IsInjectedClassName)
1945 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1946
1947 // If the original function was part of a friend declaration,
1948 // inherit its namespace state.
1949 if (D->getFriendObjectKind())
1950 Record->setObjectOfFriendDecl();
1951
1952 // Make sure that anonymous structs and unions are recorded.
1953 if (D->isAnonymousStructOrUnion())
1954 Record->setAnonymousStructOrUnion(true);
1955
1956 if (D->isLocalClass())
1957 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1958
1959 // Forward the mangling number from the template to the instantiated decl.
1960 SemaRef.Context.setManglingNumber(Record,
1961 SemaRef.Context.getManglingNumber(D));
1962
1963 // See if the old tag was defined along with a declarator.
1964 // If it did, mark the new tag as being associated with that declarator.
1965 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1966 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1967
1968 // See if the old tag was defined along with a typedef.
1969 // If it did, mark the new tag as being associated with that typedef.
1970 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1971 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1972
1973 Owner->addDecl(Record);
1974
1975 // DR1484 clarifies that the members of a local class are instantiated as part
1976 // of the instantiation of their enclosing entity.
1977 if (D->isCompleteDefinition() && D->isLocalClass()) {
1978 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
1979
1980 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1981 TSK_ImplicitInstantiation,
1982 /*Complain=*/true);
1983
1984 // For nested local classes, we will instantiate the members when we
1985 // reach the end of the outermost (non-nested) local class.
1986 if (!D->isCXXClassMember())
1987 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1988 TSK_ImplicitInstantiation);
1989
1990 // This class may have local implicit instantiations that need to be
1991 // performed within this scope.
1992 LocalInstantiations.perform();
1993 }
1994
1995 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1996
1997 if (IsInjectedClassName)
1998 assert(Record->isInjectedClassName() && "Broken injected-class-name")(static_cast <bool> (Record->isInjectedClassName() &&
"Broken injected-class-name") ? void (0) : __assert_fail ("Record->isInjectedClassName() && \"Broken injected-class-name\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1998, __extension__
__PRETTY_FUNCTION__))
;
1999
2000 return Record;
2001}
2002
2003/// Adjust the given function type for an instantiation of the
2004/// given declaration, to cope with modifications to the function's type that
2005/// aren't reflected in the type-source information.
2006///
2007/// \param D The declaration we're instantiating.
2008/// \param TInfo The already-instantiated type.
2009static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
2010 FunctionDecl *D,
2011 TypeSourceInfo *TInfo) {
2012 const FunctionProtoType *OrigFunc
2013 = D->getType()->castAs<FunctionProtoType>();
2014 const FunctionProtoType *NewFunc
2015 = TInfo->getType()->castAs<FunctionProtoType>();
2016 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2017 return TInfo->getType();
2018
2019 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2020 NewEPI.ExtInfo = OrigFunc->getExtInfo();
2021 return Context.getFunctionType(NewFunc->getReturnType(),
2022 NewFunc->getParamTypes(), NewEPI);
2023}
2024
2025/// Normal class members are of more specific types and therefore
2026/// don't make it here. This function serves three purposes:
2027/// 1) instantiating function templates
2028/// 2) substituting friend and local function declarations
2029/// 3) substituting deduction guide declarations for nested class templates
2030Decl *TemplateDeclInstantiator::VisitFunctionDecl(
2031 FunctionDecl *D, TemplateParameterList *TemplateParams,
2032 RewriteKind FunctionRewriteKind) {
2033 // Check whether there is already a function template specialization for
2034 // this declaration.
2035 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2036 if (FunctionTemplate && !TemplateParams) {
2037 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2038
2039 void *InsertPos = nullptr;
2040 FunctionDecl *SpecFunc
2041 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2042
2043 // If we already have a function template specialization, return it.
2044 if (SpecFunc)
2045 return SpecFunc;
2046 }
2047
2048 bool isFriend;
2049 if (FunctionTemplate)
2050 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2051 else
2052 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2053
2054 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2055 Owner->isFunctionOrMethod() ||
2056 !(isa<Decl>(Owner) &&
2057 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2058 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2059
2060 ExplicitSpecifier InstantiatedExplicitSpecifier;
2061 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2062 InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
2063 SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
2064 if (InstantiatedExplicitSpecifier.isInvalid())
2065 return nullptr;
2066 }
2067
2068 SmallVector<ParmVarDecl *, 4> Params;
2069 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2070 if (!TInfo)
2071 return nullptr;
2072 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2073
2074 if (TemplateParams && TemplateParams->size()) {
2075 auto *LastParam =
2076 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2077 if (LastParam && LastParam->isImplicit() &&
2078 LastParam->hasTypeConstraint()) {
2079 // In abbreviated templates, the type-constraints of invented template
2080 // type parameters are instantiated with the function type, invalidating
2081 // the TemplateParameterList which relied on the template type parameter
2082 // not having a type constraint. Recreate the TemplateParameterList with
2083 // the updated parameter list.
2084 TemplateParams = TemplateParameterList::Create(
2085 SemaRef.Context, TemplateParams->getTemplateLoc(),
2086 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2087 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2088 }
2089 }
2090
2091 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2092 if (QualifierLoc) {
2093 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2094 TemplateArgs);
2095 if (!QualifierLoc)
2096 return nullptr;
2097 }
2098
2099 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2100
2101 // If we're instantiating a local function declaration, put the result
2102 // in the enclosing namespace; otherwise we need to find the instantiated
2103 // context.
2104 DeclContext *DC;
2105 if (D->isLocalExternDecl()) {
2106 DC = Owner;
2107 SemaRef.adjustContextForLocalExternDecl(DC);
2108 } else if (isFriend && QualifierLoc) {
2109 CXXScopeSpec SS;
2110 SS.Adopt(QualifierLoc);
2111 DC = SemaRef.computeDeclContext(SS);
2112 if (!DC) return nullptr;
2113 } else {
2114 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
2115 TemplateArgs);
2116 }
2117
2118 DeclarationNameInfo NameInfo
2119 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2120
2121 if (FunctionRewriteKind != RewriteKind::None)
2122 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2123
2124 FunctionDecl *Function;
2125 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2126 Function = CXXDeductionGuideDecl::Create(
2127 SemaRef.Context, DC, D->getInnerLocStart(),
2128 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2129 D->getSourceRange().getEnd());
2130 if (DGuide->isCopyDeductionCandidate())
2131 cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
2132 Function->setAccess(D->getAccess());
2133 } else {
2134 Function = FunctionDecl::Create(
2135 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2136 D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(),
2137 D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(),
2138 TrailingRequiresClause);
2139 Function->setFriendConstraintRefersToEnclosingTemplate(
2140 D->FriendConstraintRefersToEnclosingTemplate());
2141 Function->setRangeEnd(D->getSourceRange().getEnd());
2142 }
2143
2144 if (D->isInlined())
2145 Function->setImplicitlyInline();
2146
2147 if (QualifierLoc)
2148 Function->setQualifierInfo(QualifierLoc);
2149
2150 if (D->isLocalExternDecl())
2151 Function->setLocalExternDecl();
2152
2153 DeclContext *LexicalDC = Owner;
2154 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2155 assert(D->getDeclContext()->isFileContext())(static_cast <bool> (D->getDeclContext()->isFileContext
()) ? void (0) : __assert_fail ("D->getDeclContext()->isFileContext()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 2155, __extension__
__PRETTY_FUNCTION__))
;
2156 LexicalDC = D->getDeclContext();
2157 }
2158 else if (D->isLocalExternDecl()) {
2159 LexicalDC = SemaRef.CurContext;
2160 }
2161
2162 Function->setLexicalDeclContext(LexicalDC);
2163
2164 // Attach the parameters
2165 for (unsigned P = 0; P < Params.size(); ++P)
2166 if (Params[P])
2167 Params[P]->setOwningFunction(Function);
2168 Function->setParams(Params);
2169
2170 if (TrailingRequiresClause)
2171 Function->setTrailingRequiresClause(TrailingRequiresClause);
2172
2173 if (TemplateParams) {
2174 // Our resulting instantiation is actually a function template, since we
2175 // are substituting only the outer template parameters. For example, given
2176 //
2177 // template<typename T>
2178 // struct X {
2179 // template<typename U> friend void f(T, U);
2180 // };
2181 //
2182 // X<int> x;
2183 //
2184 // We are instantiating the friend function template "f" within X<int>,
2185 // which means substituting int for T, but leaving "f" as a friend function
2186 // template.
2187 // Build the function template itself.
2188 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2189 Function->getLocation(),
2190 Function->getDeclName(),
2191 TemplateParams, Function);
2192 Function->setDescribedFunctionTemplate(FunctionTemplate);
2193
2194 FunctionTemplate->setLexicalDeclContext(LexicalDC);
2195
2196 if (isFriend && D->isThisDeclarationADefinition()) {
2197 FunctionTemplate->setInstantiatedFromMemberTemplate(
2198 D->getDescribedFunctionTemplate());
2199 }
2200 } else if (FunctionTemplate) {
2201 // Record this function template specialization.
2202 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2203 Function->setFunctionTemplateSpecialization(FunctionTemplate,
2204 TemplateArgumentList::CreateCopy(SemaRef.Context,
2205 Innermost),
2206 /*InsertPos=*/nullptr);
2207 } else if (isFriend && D->isThisDeclarationADefinition()) {
2208 // Do not connect the friend to the template unless it's actually a
2209 // definition. We don't want non-template functions to be marked as being
2210 // template instantiations.
2211 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2212 } else if (!isFriend) {
2213 // If this is not a function template, and this is not a friend (that is,
2214 // this is a locally declared function), save the instantiation relationship
2215 // for the purposes of constraint instantiation.
2216 Function->setInstantiatedFromDecl(D);
2217 }
2218
2219 if (isFriend) {
2220 Function->setObjectOfFriendDecl();
2221 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2222 FT->setObjectOfFriendDecl();
2223 }
2224
2225 if (InitFunctionInstantiation(Function, D))
2226 Function->setInvalidDecl();
2227
2228 bool IsExplicitSpecialization = false;
2229
2230 LookupResult Previous(
2231 SemaRef, Function->getDeclName(), SourceLocation(),
2232 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
2233 : Sema::LookupOrdinaryName,
2234 D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
2235 : SemaRef.forRedeclarationInCurContext());
2236
2237 if (DependentFunctionTemplateSpecializationInfo *Info
2238 = D->getDependentSpecializationInfo()) {
2239 assert(isFriend && "non-friend has dependent specialization info?")(static_cast <bool> (isFriend && "non-friend has dependent specialization info?"
) ? void (0) : __assert_fail ("isFriend && \"non-friend has dependent specialization info?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 2239, __extension__
__PRETTY_FUNCTION__))
;
2240
2241 // Instantiate the explicit template arguments.
2242 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2243 Info->getRAngleLoc());
2244 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2245 ExplicitArgs))
2246 return nullptr;
2247
2248 // Map the candidate templates to their instantiations.
2249 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2250 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2251 Info->getTemplate(I),
2252 TemplateArgs);
2253 if (!Temp) return nullptr;
2254
2255 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2256 }
2257
2258 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2259 &ExplicitArgs,
2260 Previous))
2261 Function->setInvalidDecl();
2262
2263 IsExplicitSpecialization = true;
2264 } else if (const ASTTemplateArgumentListInfo *Info =
2265 D->getTemplateSpecializationArgsAsWritten()) {
2266 // The name of this function was written as a template-id.
2267 SemaRef.LookupQualifiedName(Previous, DC);
2268
2269 // Instantiate the explicit template arguments.
2270 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2271 Info->getRAngleLoc());
2272 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2273 ExplicitArgs))
2274 return nullptr;
2275
2276 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2277 &ExplicitArgs,
2278 Previous))
2279 Function->setInvalidDecl();
2280
2281 IsExplicitSpecialization = true;
2282 } else if (TemplateParams || !FunctionTemplate) {
2283 // Look only into the namespace where the friend would be declared to
2284 // find a previous declaration. This is the innermost enclosing namespace,
2285 // as described in ActOnFriendFunctionDecl.
2286 SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
2287
2288 // In C++, the previous declaration we find might be a tag type
2289 // (class or enum). In this case, the new declaration will hide the
2290 // tag type. Note that this does not apply if we're declaring a
2291 // typedef (C++ [dcl.typedef]p4).
2292 if (Previous.isSingleTagDecl())
2293 Previous.clear();
2294
2295 // Filter out previous declarations that don't match the scope. The only
2296 // effect this has is to remove declarations found in inline namespaces
2297 // for friend declarations with unqualified names.
2298 if (isFriend && !QualifierLoc) {
2299 SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
2300 /*ConsiderLinkage=*/ true,
2301 QualifierLoc.hasQualifier());
2302 }
2303 }
2304
2305 // Per [temp.inst], default arguments in function declarations at local scope
2306 // are instantiated along with the enclosing declaration. For example:
2307 //
2308 // template<typename T>
2309 // void ft() {
2310 // void f(int = []{ return T::value; }());
2311 // }
2312 // template void ft<int>(); // error: type 'int' cannot be used prior
2313 // to '::' because it has no members
2314 //
2315 // The error is issued during instantiation of ft<int>() because substitution
2316 // into the default argument fails; the default argument is instantiated even
2317 // though it is never used.
2318 if (Function->isLocalExternDecl()) {
2319 for (ParmVarDecl *PVD : Function->parameters()) {
2320 if (!PVD->hasDefaultArg())
2321 continue;
2322 if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
2323 // If substitution fails, the default argument is set to a
2324 // RecoveryExpr that wraps the uninstantiated default argument so
2325 // that downstream diagnostics are omitted.
2326 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
2327 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2328 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2329 { UninstExpr }, UninstExpr->getType());
2330 if (ErrorResult.isUsable())
2331 PVD->setDefaultArg(ErrorResult.get());
2332 }
2333 }
2334 }
2335
2336 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2337 IsExplicitSpecialization,
2338 Function->isThisDeclarationADefinition());
2339
2340 // Check the template parameter list against the previous declaration. The
2341 // goal here is to pick up default arguments added since the friend was
2342 // declared; we know the template parameter lists match, since otherwise
2343 // we would not have picked this template as the previous declaration.
2344 if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
2345 SemaRef.CheckTemplateParameterList(
2346 TemplateParams,
2347 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2348 Function->isThisDeclarationADefinition()
2349 ? Sema::TPC_FriendFunctionTemplateDefinition
2350 : Sema::TPC_FriendFunctionTemplate);
2351 }
2352
2353 // If we're introducing a friend definition after the first use, trigger
2354 // instantiation.
2355 // FIXME: If this is a friend function template definition, we should check
2356 // to see if any specializations have been used.
2357 if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2358 if (MemberSpecializationInfo *MSInfo =
2359 Function->getMemberSpecializationInfo()) {
2360 if (MSInfo->getPointOfInstantiation().isInvalid()) {
2361 SourceLocation Loc = D->getLocation(); // FIXME
2362 MSInfo->setPointOfInstantiation(Loc);
2363 SemaRef.PendingLocalImplicitInstantiations.push_back(
2364 std::make_pair(Function, Loc));
2365 }
2366 }
2367 }
2368
2369 if (D->isExplicitlyDefaulted()) {
2370 if (SubstDefaultedFunction(Function, D))
2371 return nullptr;
2372 }
2373 if (D->isDeleted())
2374 SemaRef.SetDeclDeleted(Function, D->getLocation());
2375
2376 NamedDecl *PrincipalDecl =
2377 (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2378
2379 // If this declaration lives in a different context from its lexical context,
2380 // add it to the corresponding lookup table.
2381 if (isFriend ||
2382 (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
2383 DC->makeDeclVisibleInContext(PrincipalDecl);
2384
2385 if (Function->isOverloadedOperator() && !DC->isRecord() &&
2386 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
2387 PrincipalDecl->setNonMemberOperator();
2388
2389 return Function;
2390}
2391
2392Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
2393 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2394 std::optional<const ASTTemplateArgumentListInfo *>
2395 ClassScopeSpecializationArgs,
2396 RewriteKind FunctionRewriteKind) {
2397 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2398 if (FunctionTemplate && !TemplateParams) {
2399 // We are creating a function template specialization from a function
2400 // template. Check whether there is already a function template
2401 // specialization for this particular set of template arguments.
2402 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2403
2404 void *InsertPos = nullptr;
2405 FunctionDecl *SpecFunc
2406 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2407
2408 // If we already have a function template specialization, return it.
2409 if (SpecFunc)
2410 return SpecFunc;
2411 }
2412
2413 bool isFriend;
2414 if (FunctionTemplate)
2415 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2416 else
2417 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2418
2419 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2420 !(isa<Decl>(Owner) &&
2421 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2422 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2423
2424 // Instantiate enclosing template arguments for friends.
2425 SmallVector<TemplateParameterList *, 4> TempParamLists;
2426 unsigned NumTempParamLists = 0;
2427 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2428 TempParamLists.resize(NumTempParamLists);
2429 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2430 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2431 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2432 if (!InstParams)
2433 return nullptr;
2434 TempParamLists[I] = InstParams;
2435 }
2436 }
2437
2438 ExplicitSpecifier InstantiatedExplicitSpecifier =
2439 instantiateExplicitSpecifier(SemaRef, TemplateArgs,
2440 ExplicitSpecifier::getFromDecl(D), D);
2441 if (InstantiatedExplicitSpecifier.isInvalid())
2442 return nullptr;
2443
2444 // Implicit destructors/constructors created for local classes in
2445 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2446 // Unfortunately there isn't enough context in those functions to
2447 // conditionally populate the TSI without breaking non-template related use
2448 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2449 // a proper transformation.
2450 if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
2451 !D->getTypeSourceInfo() &&
2452 isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
2453 TypeSourceInfo *TSI =
2454 SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
2455 D->setTypeSourceInfo(TSI);
2456 }
2457
2458 SmallVector<ParmVarDecl *, 4> Params;
2459 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2460 if (!TInfo)
2461 return nullptr;
2462 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2463
2464 if (TemplateParams && TemplateParams->size()) {
2465 auto *LastParam =
2466 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2467 if (LastParam && LastParam->isImplicit() &&
2468 LastParam->hasTypeConstraint()) {
2469 // In abbreviated templates, the type-constraints of invented template
2470 // type parameters are instantiated with the function type, invalidating
2471 // the TemplateParameterList which relied on the template type parameter
2472 // not having a type constraint. Recreate the TemplateParameterList with
2473 // the updated parameter list.
2474 TemplateParams = TemplateParameterList::Create(
2475 SemaRef.Context, TemplateParams->getTemplateLoc(),
2476 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2477 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2478 }
2479 }
2480
2481 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2482 if (QualifierLoc) {
2483 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2484 TemplateArgs);
2485 if (!QualifierLoc)
2486 return nullptr;
2487 }
2488
2489 DeclContext *DC = Owner;
2490 if (isFriend) {
2491 if (QualifierLoc) {
2492 CXXScopeSpec SS;
2493 SS.Adopt(QualifierLoc);
2494 DC = SemaRef.computeDeclContext(SS);
2495
2496 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2497 return nullptr;
2498 } else {
2499 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2500 D->getDeclContext(),
2501 TemplateArgs);
2502 }
2503 if (!DC) return nullptr;
2504 }
2505
2506 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2507 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2508
2509 DeclarationNameInfo NameInfo
2510 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2511
2512 if (FunctionRewriteKind != RewriteKind::None)
2513 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2514
2515 // Build the instantiated method declaration.
2516 CXXMethodDecl *Method = nullptr;
2517
2518 SourceLocation StartLoc = D->getInnerLocStart();
2519 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2520 Method = CXXConstructorDecl::Create(
2521 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2522 InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
2523 Constructor->isInlineSpecified(), false,
2524 Constructor->getConstexprKind(), InheritedConstructor(),
2525 TrailingRequiresClause);
2526 Method->setRangeEnd(Constructor->getEndLoc());
2527 if (Constructor->isDefaultConstructor() ||
2528 Constructor->isCopyOrMoveConstructor())
2529 Method->setIneligibleOrNotSelected(true);
2530 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2531 Method = CXXDestructorDecl::Create(
2532 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2533 Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
2534 Destructor->getConstexprKind(), TrailingRequiresClause);
2535 Method->setIneligibleOrNotSelected(true);
2536 Method->setRangeEnd(Destructor->getEndLoc());
2537 Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName(
2538 SemaRef.Context.getCanonicalType(
2539 SemaRef.Context.getTypeDeclType(Record))));
2540 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2541 Method = CXXConversionDecl::Create(
2542 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2543 Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
2544 InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
2545 Conversion->getEndLoc(), TrailingRequiresClause);
2546 } else {
2547 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2548 Method = CXXMethodDecl::Create(
2549 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
2550 D->UsesFPIntrin(), D->isInlineSpecified(), D->getConstexprKind(),
2551 D->getEndLoc(), TrailingRequiresClause);
2552 if (D->isMoveAssignmentOperator() || D->isCopyAssignmentOperator())
2553 Method->setIneligibleOrNotSelected(true);
2554 }
2555
2556 if (D->isInlined())
2557 Method->setImplicitlyInline();
2558
2559 if (QualifierLoc)
2560 Method->setQualifierInfo(QualifierLoc);
2561
2562 if (TemplateParams) {
2563 // Our resulting instantiation is actually a function template, since we
2564 // are substituting only the outer template parameters. For example, given
2565 //
2566 // template<typename T>
2567 // struct X {
2568 // template<typename U> void f(T, U);
2569 // };
2570 //
2571 // X<int> x;
2572 //
2573 // We are instantiating the member template "f" within X<int>, which means
2574 // substituting int for T, but leaving "f" as a member function template.
2575 // Build the function template itself.
2576 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2577 Method->getLocation(),
2578 Method->getDeclName(),
2579 TemplateParams, Method);
2580 if (isFriend) {
2581 FunctionTemplate->setLexicalDeclContext(Owner);
2582 FunctionTemplate->setObjectOfFriendDecl();
2583 } else if (D->isOutOfLine())
2584 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2585 Method->setDescribedFunctionTemplate(FunctionTemplate);
2586 } else if (FunctionTemplate) {
2587 // Record this function template specialization.
2588 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2589 Method->setFunctionTemplateSpecialization(FunctionTemplate,
2590 TemplateArgumentList::CreateCopy(SemaRef.Context,
2591 Innermost),
2592 /*InsertPos=*/nullptr);
2593 } else if (!isFriend) {
2594 // Record that this is an instantiation of a member function.
2595 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2596 }
2597
2598 // If we are instantiating a member function defined
2599 // out-of-line, the instantiation will have the same lexical
2600 // context (which will be a namespace scope) as the template.
2601 if (isFriend) {
2602 if (NumTempParamLists)
2603 Method->setTemplateParameterListsInfo(
2604 SemaRef.Context,
2605 llvm::ArrayRef(TempParamLists.data(), NumTempParamLists));
2606
2607 Method->setLexicalDeclContext(Owner);
2608 Method->setObjectOfFriendDecl();
2609 } else if (D->isOutOfLine())
2610 Method->setLexicalDeclContext(D->getLexicalDeclContext());
2611
2612 // Attach the parameters
2613 for (unsigned P = 0; P < Params.size(); ++P)
2614 Params[P]->setOwningFunction(Method);
2615 Method->setParams(Params);
2616
2617 if (InitMethodInstantiation(Method, D))
2618 Method->setInvalidDecl();
2619
2620 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2621 Sema::ForExternalRedeclaration);
2622
2623 bool IsExplicitSpecialization = false;
2624
2625 // If the name of this function was written as a template-id, instantiate
2626 // the explicit template arguments.
2627 if (DependentFunctionTemplateSpecializationInfo *Info
2628 = D->getDependentSpecializationInfo()) {
2629 assert(isFriend && "non-friend has dependent specialization info?")(static_cast <bool> (isFriend && "non-friend has dependent specialization info?"
) ? void (0) : __assert_fail ("isFriend && \"non-friend has dependent specialization info?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 2629, __extension__
__PRETTY_FUNCTION__))
;
2630
2631 // Instantiate the explicit template arguments.
2632 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2633 Info->getRAngleLoc());
2634 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2635 ExplicitArgs))
2636 return nullptr;
2637
2638 // Map the candidate templates to their instantiations.
2639 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2640 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2641 Info->getTemplate(I),
2642 TemplateArgs);
2643 if (!Temp) return nullptr;
2644
2645 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2646 }
2647
2648 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2649 &ExplicitArgs,
2650 Previous))
2651 Method->setInvalidDecl();
2652
2653 IsExplicitSpecialization = true;
2654 } else if (const ASTTemplateArgumentListInfo *Info =
2655 ClassScopeSpecializationArgs.value_or(
2656 D->getTemplateSpecializationArgsAsWritten())) {
2657 SemaRef.LookupQualifiedName(Previous, DC);
2658
2659 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2660 Info->getRAngleLoc());
2661 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2662 ExplicitArgs))
2663 return nullptr;
2664
2665 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2666 &ExplicitArgs,
2667 Previous))
2668 Method->setInvalidDecl();
2669
2670 IsExplicitSpecialization = true;
2671 } else if (ClassScopeSpecializationArgs) {
2672 // Class-scope explicit specialization written without explicit template
2673 // arguments.
2674 SemaRef.LookupQualifiedName(Previous, DC);
2675 if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
2676 Method->setInvalidDecl();
2677
2678 IsExplicitSpecialization = true;
2679 } else if (!FunctionTemplate || TemplateParams || isFriend) {
2680 SemaRef.LookupQualifiedName(Previous, Record);
2681
2682 // In C++, the previous declaration we find might be a tag type
2683 // (class or enum). In this case, the new declaration will hide the
2684 // tag type. Note that this does not apply if we're declaring a
2685 // typedef (C++ [dcl.typedef]p4).
2686 if (Previous.isSingleTagDecl())
2687 Previous.clear();
2688 }
2689
2690 // Per [temp.inst], default arguments in member functions of local classes
2691 // are instantiated along with the member function declaration. For example:
2692 //
2693 // template<typename T>
2694 // void ft() {
2695 // struct lc {
2696 // int operator()(int p = []{ return T::value; }());
2697 // };
2698 // }
2699 // template void ft<int>(); // error: type 'int' cannot be used prior
2700 // to '::'because it has no members
2701 //
2702 // The error is issued during instantiation of ft<int>()::lc::operator()
2703 // because substitution into the default argument fails; the default argument
2704 // is instantiated even though it is never used.
2705 if (D->isInLocalScopeForInstantiation()) {
2706 for (unsigned P = 0; P < Params.size(); ++P) {
2707 if (!Params[P]->hasDefaultArg())
2708 continue;
2709 if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
2710 // If substitution fails, the default argument is set to a
2711 // RecoveryExpr that wraps the uninstantiated default argument so
2712 // that downstream diagnostics are omitted.
2713 Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
2714 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2715 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2716 { UninstExpr }, UninstExpr->getType());
2717 if (ErrorResult.isUsable())
2718 Params[P]->setDefaultArg(ErrorResult.get());
2719 }
2720 }
2721 }
2722
2723 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2724 IsExplicitSpecialization,
2725 Method->isThisDeclarationADefinition());
2726
2727 if (D->isPure())
2728 SemaRef.CheckPureMethod(Method, SourceRange());
2729
2730 // Propagate access. For a non-friend declaration, the access is
2731 // whatever we're propagating from. For a friend, it should be the
2732 // previous declaration we just found.
2733 if (isFriend && Method->getPreviousDecl())
2734 Method->setAccess(Method->getPreviousDecl()->getAccess());
2735 else
2736 Method->setAccess(D->getAccess());
2737 if (FunctionTemplate)
2738 FunctionTemplate->setAccess(Method->getAccess());
2739
2740 SemaRef.CheckOverrideControl(Method);
2741
2742 // If a function is defined as defaulted or deleted, mark it as such now.
2743 if (D->isExplicitlyDefaulted()) {
2744 if (SubstDefaultedFunction(Method, D))
2745 return nullptr;
2746 }
2747 if (D->isDeletedAsWritten())
2748 SemaRef.SetDeclDeleted(Method, Method->getLocation());
2749
2750 // If this is an explicit specialization, mark the implicitly-instantiated
2751 // template specialization as being an explicit specialization too.
2752 // FIXME: Is this necessary?
2753 if (IsExplicitSpecialization && !isFriend)
2754 SemaRef.CompleteMemberSpecialization(Method, Previous);
2755
2756 // If there's a function template, let our caller handle it.
2757 if (FunctionTemplate) {
2758 // do nothing
2759
2760 // Don't hide a (potentially) valid declaration with an invalid one.
2761 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2762 // do nothing
2763
2764 // Otherwise, check access to friends and make them visible.
2765 } else if (isFriend) {
2766 // We only need to re-check access for methods which we didn't
2767 // manage to match during parsing.
2768 if (!D->getPreviousDecl())
2769 SemaRef.CheckFriendAccess(Method);
2770
2771 Record->makeDeclVisibleInContext(Method);
2772
2773 // Otherwise, add the declaration. We don't need to do this for
2774 // class-scope specializations because we'll have matched them with
2775 // the appropriate template.
2776 } else {
2777 Owner->addDecl(Method);
2778 }
2779
2780 // PR17480: Honor the used attribute to instantiate member function
2781 // definitions
2782 if (Method->hasAttr<UsedAttr>()) {
2783 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2784 SourceLocation Loc;
2785 if (const MemberSpecializationInfo *MSInfo =
2786 A->getMemberSpecializationInfo())
2787 Loc = MSInfo->getPointOfInstantiation();
2788 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2789 Loc = Spec->getPointOfInstantiation();
2790 SemaRef.MarkFunctionReferenced(Loc, Method);
2791 }
2792 }
2793
2794 return Method;
2795}
2796
2797Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2798 return VisitCXXMethodDecl(D);
2799}
2800
2801Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2802 return VisitCXXMethodDecl(D);
2803}
2804
2805Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2806 return VisitCXXMethodDecl(D);
2807}
2808
2809Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2810 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
2811 std::nullopt,
2812 /*ExpectParameterPack=*/false);
2813}
2814
2815Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2816 TemplateTypeParmDecl *D) {
2817 assert(D->getTypeForDecl()->isTemplateTypeParmType())(static_cast <bool> (D->getTypeForDecl()->isTemplateTypeParmType
()) ? void (0) : __assert_fail ("D->getTypeForDecl()->isTemplateTypeParmType()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 2817, __extension__
__PRETTY_FUNCTION__))
;
2818
2819 std::optional<unsigned> NumExpanded;
2820
2821 if (const TypeConstraint *TC = D->getTypeConstraint()) {
2822 if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
2823 assert(TC->getTemplateArgsAsWritten() &&(static_cast <bool> (TC->getTemplateArgsAsWritten() &&
"type parameter can only be an expansion when explicit arguments "
"are specified") ? void (0) : __assert_fail ("TC->getTemplateArgsAsWritten() && \"type parameter can only be an expansion when explicit arguments \" \"are specified\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 2825, __extension__
__PRETTY_FUNCTION__))
2824 "type parameter can only be an expansion when explicit arguments "(static_cast <bool> (TC->getTemplateArgsAsWritten() &&
"type parameter can only be an expansion when explicit arguments "
"are specified") ? void (0) : __assert_fail ("TC->getTemplateArgsAsWritten() && \"type parameter can only be an expansion when explicit arguments \" \"are specified\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 2825, __extension__
__PRETTY_FUNCTION__))
2825 "are specified")(static_cast <bool> (TC->getTemplateArgsAsWritten() &&
"type parameter can only be an expansion when explicit arguments "
"are specified") ? void (0) : __assert_fail ("TC->getTemplateArgsAsWritten() && \"type parameter can only be an expansion when explicit arguments \" \"are specified\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 2825, __extension__
__PRETTY_FUNCTION__))
;
2826 // The template type parameter pack's type is a pack expansion of types.
2827 // Determine whether we need to expand this parameter pack into separate
2828 // types.
2829 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2830 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2831 SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2832
2833 // Determine whether the set of unexpanded parameter packs can and should
2834 // be expanded.
2835 bool Expand = true;
2836 bool RetainExpansion = false;
2837 if (SemaRef.CheckParameterPacksForExpansion(
2838 cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2839 ->getEllipsisLoc(),
2840 SourceRange(TC->getConceptNameLoc(),
2841 TC->hasExplicitTemplateArgs() ?
2842 TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2843 TC->getConceptNameInfo().getEndLoc()),
2844 Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2845 return nullptr;
2846 }
2847 }
2848
2849 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2850 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2851 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2852 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
2853 D->hasTypeConstraint(), NumExpanded);
2854
2855 Inst->setAccess(AS_public);
2856 Inst->setImplicit(D->isImplicit());
2857 if (auto *TC = D->getTypeConstraint()) {
2858 if (!D->isImplicit()) {
2859 // Invented template parameter type constraints will be instantiated
2860 // with the corresponding auto-typed parameter as it might reference
2861 // other parameters.
2862 if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
2863 EvaluateConstraints))
2864 return nullptr;
2865 }
2866 }
2867 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2868 TypeSourceInfo *InstantiatedDefaultArg =
2869 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2870 D->getDefaultArgumentLoc(), D->getDeclName());
2871 if (InstantiatedDefaultArg)
2872 Inst->setDefaultArgument(InstantiatedDefaultArg);
2873 }
2874
2875 // Introduce this template parameter's instantiation into the instantiation
2876 // scope.
2877 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2878
2879 return Inst;
2880}
2881
2882Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2883 NonTypeTemplateParmDecl *D) {
2884 // Substitute into the type of the non-type template parameter.
2885 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2886 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2887 SmallVector<QualType, 4> ExpandedParameterPackTypes;
2888 bool IsExpandedParameterPack = false;
2889 TypeSourceInfo *DI;
2890 QualType T;
2891 bool Invalid = false;
2892
2893 if (D->isExpandedParameterPack()) {
2894 // The non-type template parameter pack is an already-expanded pack
2895 // expansion of types. Substitute into each of the expanded types.
2896 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2897 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2898 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2899 TypeSourceInfo *NewDI =
2900 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2901 D->getLocation(), D->getDeclName());
2902 if (!NewDI)
2903 return nullptr;
2904
2905 QualType NewT =
2906 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2907 if (NewT.isNull())
2908 return nullptr;
2909
2910 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2911 ExpandedParameterPackTypes.push_back(NewT);
2912 }
2913
2914 IsExpandedParameterPack = true;
2915 DI = D->getTypeSourceInfo();
2916 T = DI->getType();
2917 } else if (D->isPackExpansion()) {
2918 // The non-type template parameter pack's type is a pack expansion of types.
2919 // Determine whether we need to expand this parameter pack into separate
2920 // types.
2921 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2922 TypeLoc Pattern = Expansion.getPatternLoc();
2923 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2924 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2925
2926 // Determine whether the set of unexpanded parameter packs can and should
2927 // be expanded.
2928 bool Expand = true;
2929 bool RetainExpansion = false;
2930 std::optional<unsigned> OrigNumExpansions =
2931 Expansion.getTypePtr()->getNumExpansions();
2932 std::optional<unsigned> NumExpansions = OrigNumExpansions;
2933 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2934 Pattern.getSourceRange(),
2935 Unexpanded,
2936 TemplateArgs,
2937 Expand, RetainExpansion,
2938 NumExpansions))
2939 return nullptr;
2940
2941 if (Expand) {
2942 for (unsigned I = 0; I != *NumExpansions; ++I) {
2943 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2944 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2945 D->getLocation(),
2946 D->getDeclName());
2947 if (!NewDI)
2948 return nullptr;
2949
2950 QualType NewT =
2951 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2952 if (NewT.isNull())
2953 return nullptr;
2954
2955 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2956 ExpandedParameterPackTypes.push_back(NewT);
2957 }
2958
2959 // Note that we have an expanded parameter pack. The "type" of this
2960 // expanded parameter pack is the original expansion type, but callers
2961 // will end up using the expanded parameter pack types for type-checking.
2962 IsExpandedParameterPack = true;
2963 DI = D->getTypeSourceInfo();
2964 T = DI->getType();
2965 } else {
2966 // We cannot fully expand the pack expansion now, so substitute into the
2967 // pattern and create a new pack expansion type.
2968 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2969 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2970 D->getLocation(),
2971 D->getDeclName());
2972 if (!NewPattern)
2973 return nullptr;
2974
2975 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
2976 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2977 NumExpansions);
2978 if (!DI)
2979 return nullptr;
2980
2981 T = DI->getType();
2982 }
2983 } else {
2984 // Simple case: substitution into a parameter that is not a parameter pack.
2985 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2986 D->getLocation(), D->getDeclName());
2987 if (!DI)
2988 return nullptr;
2989
2990 // Check that this type is acceptable for a non-type template parameter.
2991 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
2992 if (T.isNull()) {
2993 T = SemaRef.Context.IntTy;
2994 Invalid = true;
2995 }
2996 }
2997
2998 NonTypeTemplateParmDecl *Param;
2999 if (IsExpandedParameterPack)
3000 Param = NonTypeTemplateParmDecl::Create(
3001 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3002 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3003 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
3004 ExpandedParameterPackTypesAsWritten);
3005 else
3006 Param = NonTypeTemplateParmDecl::Create(
3007 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3008 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3009 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
3010
3011 if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
3012 if (AutoLoc.isConstrained())
3013 // Note: We attach the uninstantiated constriant here, so that it can be
3014 // instantiated relative to the top level, like all our other constraints.
3015 if (SemaRef.AttachTypeConstraint(
3016 AutoLoc, Param, D,
3017 IsExpandedParameterPack
3018 ? DI->getTypeLoc().getAs<PackExpansionTypeLoc>()
3019 .getEllipsisLoc()
3020 : SourceLocation()))
3021 Invalid = true;
3022
3023 Param->setAccess(AS_public);
3024 Param->setImplicit(D->isImplicit());
3025 if (Invalid)
3026 Param->setInvalidDecl();
3027
3028 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3029 EnterExpressionEvaluationContext ConstantEvaluated(
3030 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3031 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
3032 if (!Value.isInvalid())
3033 Param->setDefaultArgument(Value.get());
3034 }
3035
3036 // Introduce this template parameter's instantiation into the instantiation
3037 // scope.
3038 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3039 return Param;
3040}
3041
3042static void collectUnexpandedParameterPacks(
3043 Sema &S,
3044 TemplateParameterList *Params,
3045 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
3046 for (const auto &P : *Params) {
3047 if (P->isTemplateParameterPack())
3048 continue;
3049 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3050 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3051 Unexpanded);
3052 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3053 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3054 Unexpanded);
3055 }
3056}
3057
3058Decl *
3059TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3060 TemplateTemplateParmDecl *D) {
3061 // Instantiate the template parameter list of the template template parameter.
3062 TemplateParameterList *TempParams = D->getTemplateParameters();
3063 TemplateParameterList *InstParams;
3064 SmallVector<TemplateParameterList*, 8> ExpandedParams;
3065
3066 bool IsExpandedParameterPack = false;
3067
3068 if (D->isExpandedParameterPack()) {
3069 // The template template parameter pack is an already-expanded pack
3070 // expansion of template parameters. Substitute into each of the expanded
3071 // parameters.
3072 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3073 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3074 I != N; ++I) {
3075 LocalInstantiationScope Scope(SemaRef);
3076 TemplateParameterList *Expansion =
3077 SubstTemplateParams(D->getExpansionTemplateParameters(I));
3078 if (!Expansion)
3079 return nullptr;
3080 ExpandedParams.push_back(Expansion);
3081 }
3082
3083 IsExpandedParameterPack = true;
3084 InstParams = TempParams;
3085 } else if (D->isPackExpansion()) {
3086 // The template template parameter pack expands to a pack of template
3087 // template parameters. Determine whether we need to expand this parameter
3088 // pack into separate parameters.
3089 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3090 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
3091 Unexpanded);
3092
3093 // Determine whether the set of unexpanded parameter packs can and should
3094 // be expanded.
3095 bool Expand = true;
3096 bool RetainExpansion = false;
3097 std::optional<unsigned> NumExpansions;
3098 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
3099 TempParams->getSourceRange(),
3100 Unexpanded,
3101 TemplateArgs,
3102 Expand, RetainExpansion,
3103 NumExpansions))
3104 return nullptr;
3105
3106 if (Expand) {
3107 for (unsigned I = 0; I != *NumExpansions; ++I) {
3108 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3109 LocalInstantiationScope Scope(SemaRef);
3110 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3111 if (!Expansion)
3112 return nullptr;
3113 ExpandedParams.push_back(Expansion);
3114 }
3115
3116 // Note that we have an expanded parameter pack. The "type" of this
3117 // expanded parameter pack is the original expansion type, but callers
3118 // will end up using the expanded parameter pack types for type-checking.
3119 IsExpandedParameterPack = true;
3120 InstParams = TempParams;
3121 } else {
3122 // We cannot fully expand the pack expansion now, so just substitute
3123 // into the pattern.
3124 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3125
3126 LocalInstantiationScope Scope(SemaRef);
3127 InstParams = SubstTemplateParams(TempParams);
3128 if (!InstParams)
3129 return nullptr;
3130 }
3131 } else {
3132 // Perform the actual substitution of template parameters within a new,
3133 // local instantiation scope.
3134 LocalInstantiationScope Scope(SemaRef);
3135 InstParams = SubstTemplateParams(TempParams);
3136 if (!InstParams)
3137 return nullptr;
3138 }
3139
3140 // Build the template template parameter.
3141 TemplateTemplateParmDecl *Param;
3142 if (IsExpandedParameterPack)
3143 Param = TemplateTemplateParmDecl::Create(
3144 SemaRef.Context, Owner, D->getLocation(),
3145 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3146 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
3147 else
3148 Param = TemplateTemplateParmDecl::Create(
3149 SemaRef.Context, Owner, D->getLocation(),
3150 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3151 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
3152 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3153 NestedNameSpecifierLoc QualifierLoc =
3154 D->getDefaultArgument().getTemplateQualifierLoc();
3155 QualifierLoc =
3156 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3157 TemplateName TName = SemaRef.SubstTemplateName(
3158 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3159 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3160 if (!TName.isNull())
3161 Param->setDefaultArgument(
3162 SemaRef.Context,
3163 TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
3164 D->getDefaultArgument().getTemplateQualifierLoc(),
3165 D->getDefaultArgument().getTemplateNameLoc()));
3166 }
3167 Param->setAccess(AS_public);
3168 Param->setImplicit(D->isImplicit());
3169
3170 // Introduce this template parameter's instantiation into the instantiation
3171 // scope.
3172 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3173
3174 return Param;
3175}
3176
3177Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3178 // Using directives are never dependent (and never contain any types or
3179 // expressions), so they require no explicit instantiation work.
3180
3181 UsingDirectiveDecl *Inst
3182 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3183 D->getNamespaceKeyLocation(),
3184 D->getQualifierLoc(),
3185 D->getIdentLocation(),
3186 D->getNominatedNamespace(),
3187 D->getCommonAncestor());
3188
3189 // Add the using directive to its declaration context
3190 // only if this is not a function or method.
3191 if (!Owner->isFunctionOrMethod())
3192 Owner->addDecl(Inst);
3193
3194 return Inst;
3195}
3196
3197Decl *TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl *D,
3198 BaseUsingDecl *Inst,
3199 LookupResult *Lookup) {
3200
3201 bool isFunctionScope = Owner->isFunctionOrMethod();
3202
3203 for (auto *Shadow : D->shadows()) {
3204 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3205 // reconstruct it in the case where it matters. Hm, can we extract it from
3206 // the DeclSpec when parsing and save it in the UsingDecl itself?
3207 NamedDecl *OldTarget = Shadow->getTargetDecl();
3208 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3209 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3210 OldTarget = BaseShadow;
3211
3212 NamedDecl *InstTarget = nullptr;
3213 if (auto *EmptyD =
3214 dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3215 InstTarget = UnresolvedUsingIfExistsDecl::Create(
3216 SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3217 } else {
3218 InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3219 Shadow->getLocation(), OldTarget, TemplateArgs));
3220 }
3221 if (!InstTarget)
3222 return nullptr;
3223
3224 UsingShadowDecl *PrevDecl = nullptr;
3225 if (Lookup &&
3226 SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3227 continue;
3228
3229 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3230 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3231 Shadow->getLocation(), OldPrev, TemplateArgs));
3232
3233 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3234 /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3235 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3236
3237 if (isFunctionScope)
3238 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3239 }
3240
3241 return Inst;
3242}
3243
3244Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3245
3246 // The nested name specifier may be dependent, for example
3247 // template <typename T> struct t {
3248 // struct s1 { T f1(); };
3249 // struct s2 : s1 { using s1::f1; };
3250 // };
3251 // template struct t<int>;
3252 // Here, in using s1::f1, s1 refers to t<T>::s1;
3253 // we need to substitute for t<int>::s1.
3254 NestedNameSpecifierLoc QualifierLoc
3255 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3256 TemplateArgs);
3257 if (!QualifierLoc)
3258 return nullptr;
3259
3260 // For an inheriting constructor declaration, the name of the using
3261 // declaration is the name of a constructor in this class, not in the
3262 // base class.
3263 DeclarationNameInfo NameInfo = D->getNameInfo();
3264 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3265 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3266 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
3267 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3268
3269 // We only need to do redeclaration lookups if we're in a class scope (in
3270 // fact, it's not really even possible in non-class scopes).
3271 bool CheckRedeclaration = Owner->isRecord();
3272 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3273 Sema::ForVisibleRedeclaration);
3274
3275 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3276 D->getUsingLoc(),
3277 QualifierLoc,
3278 NameInfo,
3279 D->hasTypename());
3280
3281 CXXScopeSpec SS;
3282 SS.Adopt(QualifierLoc);
3283 if (CheckRedeclaration) {
3284 Prev.setHideTags(false);
3285 SemaRef.LookupQualifiedName(Prev, Owner);
3286
3287 // Check for invalid redeclarations.
3288 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3289 D->hasTypename(), SS,
3290 D->getLocation(), Prev))
3291 NewUD->setInvalidDecl();
3292 }
3293
3294 if (!NewUD->isInvalidDecl() &&
3295 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3296 NameInfo, D->getLocation(), nullptr, D))
3297 NewUD->setInvalidDecl();
3298
3299 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3300 NewUD->setAccess(D->getAccess());
3301 Owner->addDecl(NewUD);
3302
3303 // Don't process the shadow decls for an invalid decl.
3304 if (NewUD->isInvalidDecl())
3305 return NewUD;
3306
3307 // If the using scope was dependent, or we had dependent bases, we need to
3308 // recheck the inheritance
3309 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3310 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
3311
3312 return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3313}
3314
3315Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3316 // Cannot be a dependent type, but still could be an instantiation
3317 EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3318 D->getLocation(), D->getEnumDecl(), TemplateArgs));
3319
3320 if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3321 return nullptr;
3322
3323 TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
3324 D->getLocation(), D->getDeclName());
3325 UsingEnumDecl *NewUD =
3326 UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3327 D->getEnumLoc(), D->getLocation(), TSI);
3328
3329 SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
3330 NewUD->setAccess(D->getAccess());
3331 Owner->addDecl(NewUD);
3332
3333 // Don't process the shadow decls for an invalid decl.
3334 if (NewUD->isInvalidDecl())
3335 return NewUD;
3336
3337 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3338 // cannot be dependent, and will therefore have been checked during template
3339 // definition.
3340
3341 return VisitBaseUsingDecls(D, NewUD, nullptr);
3342}
3343
3344Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3345 // Ignore these; we handle them in bulk when processing the UsingDecl.
3346 return nullptr;
3347}
3348
3349Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3350 ConstructorUsingShadowDecl *D) {
3351 // Ignore these; we handle them in bulk when processing the UsingDecl.
3352 return nullptr;
3353}
3354
3355template <typename T>
3356Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3357 T *D, bool InstantiatingPackElement) {
3358 // If this is a pack expansion, expand it now.
3359 if (D->isPackExpansion() && !InstantiatingPackElement) {
3360 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3361 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3362 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3363
3364 // Determine whether the set of unexpanded parameter packs can and should
3365 // be expanded.
3366 bool Expand = true;
3367 bool RetainExpansion = false;
3368 std::optional<unsigned> NumExpansions;
3369 if (SemaRef.CheckParameterPacksForExpansion(
3370 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3371 Expand, RetainExpansion, NumExpansions))
3372 return nullptr;
3373
3374 // This declaration cannot appear within a function template signature,
3375 // so we can't have a partial argument list for a parameter pack.
3376 assert(!RetainExpansion &&(static_cast <bool> (!RetainExpansion && "should never need to retain an expansion for UsingPackDecl"
) ? void (0) : __assert_fail ("!RetainExpansion && \"should never need to retain an expansion for UsingPackDecl\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3377, __extension__
__PRETTY_FUNCTION__))
3377 "should never need to retain an expansion for UsingPackDecl")(static_cast <bool> (!RetainExpansion && "should never need to retain an expansion for UsingPackDecl"
) ? void (0) : __assert_fail ("!RetainExpansion && \"should never need to retain an expansion for UsingPackDecl\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3377, __extension__
__PRETTY_FUNCTION__))
;
3378
3379 if (!Expand) {
3380 // We cannot fully expand the pack expansion now, so substitute into the
3381 // pattern and create a new pack expansion.
3382 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3383 return instantiateUnresolvedUsingDecl(D, true);
3384 }
3385
3386 // Within a function, we don't have any normal way to check for conflicts
3387 // between shadow declarations from different using declarations in the
3388 // same pack expansion, but this is always ill-formed because all expansions
3389 // must produce (conflicting) enumerators.
3390 //
3391 // Sadly we can't just reject this in the template definition because it
3392 // could be valid if the pack is empty or has exactly one expansion.
3393 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
3394 SemaRef.Diag(D->getEllipsisLoc(),
3395 diag::err_using_decl_redeclaration_expansion);
3396 return nullptr;
3397 }
3398
3399 // Instantiate the slices of this pack and build a UsingPackDecl.
3400 SmallVector<NamedDecl*, 8> Expansions;
3401 for (unsigned I = 0; I != *NumExpansions; ++I) {
3402 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3403 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3404 if (!Slice)
3405 return nullptr;
3406 // Note that we can still get unresolved using declarations here, if we
3407 // had arguments for all packs but the pattern also contained other
3408 // template arguments (this only happens during partial substitution, eg
3409 // into the body of a generic lambda in a function template).
3410 Expansions.push_back(cast<NamedDecl>(Slice));
3411 }
3412
3413 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3414 if (isDeclWithinFunction(D))
3415 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3416 return NewD;
3417 }
3418
3419 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3420 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
3421
3422 NestedNameSpecifierLoc QualifierLoc
3423 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3424 TemplateArgs);
3425 if (!QualifierLoc)
3426 return nullptr;
3427
3428 CXXScopeSpec SS;
3429 SS.Adopt(QualifierLoc);
3430
3431 DeclarationNameInfo NameInfo
3432 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3433
3434 // Produce a pack expansion only if we're not instantiating a particular
3435 // slice of a pack expansion.
3436 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3437 SemaRef.ArgumentPackSubstitutionIndex != -1;
3438 SourceLocation EllipsisLoc =
3439 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
3440
3441 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3442 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3443 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3444 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3445 ParsedAttributesView(),
3446 /*IsInstantiation*/ true, IsUsingIfExists);
3447 if (UD) {
3448 SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3449 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3450 }
3451
3452 return UD;
3453}
3454
3455Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3456 UnresolvedUsingTypenameDecl *D) {
3457 return instantiateUnresolvedUsingDecl(D);
3458}
3459
3460Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3461 UnresolvedUsingValueDecl *D) {
3462 return instantiateUnresolvedUsingDecl(D);
3463}
3464
3465Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3466 UnresolvedUsingIfExistsDecl *D) {
3467 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl")::llvm::llvm_unreachable_internal("referring to unresolved decl out of UsingShadowDecl"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3467)
;
3468}
3469
3470Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3471 SmallVector<NamedDecl*, 8> Expansions;
3472 for (auto *UD : D->expansions()) {
3473 if (NamedDecl *NewUD =
3474 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3475 Expansions.push_back(NewUD);
3476 else
3477 return nullptr;
3478 }
3479
3480 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3481 if (isDeclWithinFunction(D))
3482 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3483 return NewD;
3484}
3485
3486Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
3487 ClassScopeFunctionSpecializationDecl *Decl) {
3488 CXXMethodDecl *OldFD = Decl->getSpecialization();
3489 return cast_or_null<CXXMethodDecl>(
3490 VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
3491}
3492
3493Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3494 OMPThreadPrivateDecl *D) {
3495 SmallVector<Expr *, 5> Vars;
3496 for (auto *I : D->varlists()) {
3497 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3498 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr")(static_cast <bool> (isa<DeclRefExpr>(Var) &&
"threadprivate arg is not a DeclRefExpr") ? void (0) : __assert_fail
("isa<DeclRefExpr>(Var) && \"threadprivate arg is not a DeclRefExpr\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3498, __extension__
__PRETTY_FUNCTION__))
;
3499 Vars.push_back(Var);
3500 }
3501
3502 OMPThreadPrivateDecl *TD =
3503 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3504
3505 TD->setAccess(AS_public);
3506 Owner->addDecl(TD);
3507
3508 return TD;
3509}
3510
3511Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3512 SmallVector<Expr *, 5> Vars;
3513 for (auto *I : D->varlists()) {
3514 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3515 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr")(static_cast <bool> (isa<DeclRefExpr>(Var) &&
"allocate arg is not a DeclRefExpr") ? void (0) : __assert_fail
("isa<DeclRefExpr>(Var) && \"allocate arg is not a DeclRefExpr\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3515, __extension__
__PRETTY_FUNCTION__))
;
3516 Vars.push_back(Var);
3517 }
3518 SmallVector<OMPClause *, 4> Clauses;
3519 // Copy map clauses from the original mapper.
3520 for (OMPClause *C : D->clauselists()) {
3521 OMPClause *IC = nullptr;
3522 if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
3523 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3524 if (!NewE.isUsable())
3525 continue;
3526 IC = SemaRef.ActOnOpenMPAllocatorClause(
3527 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3528 } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
3529 ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
3530 if (!NewE.isUsable())
3531 continue;
3532 IC = SemaRef.ActOnOpenMPAlignClause(NewE.get(), AC->getBeginLoc(),
3533 AC->getLParenLoc(), AC->getEndLoc());
3534 // If align clause value ends up being invalid, this can end up null.
3535 if (!IC)
3536 continue;
3537 }
3538 Clauses.push_back(IC);
3539 }
3540
3541 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
3542 D->getLocation(), Vars, Clauses, Owner);
3543 if (Res.get().isNull())
3544 return nullptr;
3545 return Res.get().getSingleDecl();
3546}
3547
3548Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3549 llvm_unreachable(::llvm::llvm_unreachable_internal("Requires directive cannot be instantiated within a dependent context"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3550)
3550 "Requires directive cannot be instantiated within a dependent context")::llvm::llvm_unreachable_internal("Requires directive cannot be instantiated within a dependent context"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3550)
;
3551}
3552
3553Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3554 OMPDeclareReductionDecl *D) {
3555 // Instantiate type and check if it is allowed.
3556 const bool RequiresInstantiation =
3557 D->getType()->isDependentType() ||
3558 D->getType()->isInstantiationDependentType() ||
3559 D->getType()->containsUnexpandedParameterPack();
3560 QualType SubstReductionType;
3561 if (RequiresInstantiation) {
3562 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
3563 D->getLocation(),
3564 ParsedType::make(SemaRef.SubstType(
3565 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3566 } else {
3567 SubstReductionType = D->getType();
3568 }
3569 if (SubstReductionType.isNull())
3570 return nullptr;
3571 Expr *Combiner = D->getCombiner();
3572 Expr *Init = D->getInitializer();
3573 bool IsCorrect = true;
3574 // Create instantiated copy.
3575 std::pair<QualType, SourceLocation> ReductionTypes[] = {
3576 std::make_pair(SubstReductionType, D->getLocation())};
3577 auto *PrevDeclInScope = D->getPrevDeclInScope();
3578 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3579 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3580 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3581 ->get<Decl *>());
3582 }
3583 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
3584 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3585 PrevDeclInScope);
3586 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3587 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
3588 Expr *SubstCombiner = nullptr;
3589 Expr *SubstInitializer = nullptr;
3590 // Combiners instantiation sequence.
3591 if (Combiner) {
3592 SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
3593 /*S=*/nullptr, NewDRD);
3594 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3595 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3596 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3597 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3598 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3599 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3600 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3601 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3602 ThisContext);
3603 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3604 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3605 }
3606 // Initializers instantiation sequence.
3607 if (Init) {
3608 VarDecl *OmpPrivParm = SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
3609 /*S=*/nullptr, NewDRD);
3610 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3611 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3612 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3613 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3614 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3615 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3616 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
3617 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3618 } else {
3619 auto *OldPrivParm =
3620 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3621 IsCorrect = IsCorrect && OldPrivParm->hasInit();
3622 if (IsCorrect)
3623 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3624 TemplateArgs);
3625 }
3626 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD, SubstInitializer,
3627 OmpPrivParm);
3628 }
3629 IsCorrect = IsCorrect && SubstCombiner &&
3630 (!Init ||
3631 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
3632 SubstInitializer) ||
3633 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
3634 !SubstInitializer));
3635
3636 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
3637 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3638
3639 return NewDRD;
3640}
3641
3642Decl *
3643TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3644 // Instantiate type and check if it is allowed.
3645 const bool RequiresInstantiation =
3646 D->getType()->isDependentType() ||
3647 D->getType()->isInstantiationDependentType() ||
3648 D->getType()->containsUnexpandedParameterPack();
3649 QualType SubstMapperTy;
3650 DeclarationName VN = D->getVarName();
3651 if (RequiresInstantiation) {
3652 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
3653 D->getLocation(),
3654 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3655 D->getLocation(), VN)));
3656 } else {
3657 SubstMapperTy = D->getType();
3658 }
3659 if (SubstMapperTy.isNull())
3660 return nullptr;
3661 // Create an instantiated copy of mapper.
3662 auto *PrevDeclInScope = D->getPrevDeclInScope();
3663 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3664 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3665 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3666 ->get<Decl *>());
3667 }
3668 bool IsCorrect = true;
3669 SmallVector<OMPClause *, 6> Clauses;
3670 // Instantiate the mapper variable.
3671 DeclarationNameInfo DirName;
3672 SemaRef.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3673 /*S=*/nullptr,
3674 (*D->clauselist_begin())->getBeginLoc());
3675 ExprResult MapperVarRef = SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3676 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3677 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3678 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3679 cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3680 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3681 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3682 ThisContext);
3683 // Instantiate map clauses.
3684 for (OMPClause *C : D->clauselists()) {
3685 auto *OldC = cast<OMPMapClause>(C);
3686 SmallVector<Expr *, 4> NewVars;
3687 for (Expr *OE : OldC->varlists()) {
3688 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3689 if (!NE) {
3690 IsCorrect = false;
3691 break;
3692 }
3693 NewVars.push_back(NE);
3694 }
3695 if (!IsCorrect)
3696 break;
3697 NestedNameSpecifierLoc NewQualifierLoc =
3698 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3699 TemplateArgs);
3700 CXXScopeSpec SS;
3701 SS.Adopt(NewQualifierLoc);
3702 DeclarationNameInfo NewNameInfo =
3703 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3704 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3705 OldC->getEndLoc());
3706 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
3707 OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
3708 OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
3709 OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
3710 NewVars, Locs);
3711 Clauses.push_back(NewC);
3712 }
3713 SemaRef.EndOpenMPDSABlock(nullptr);
3714 if (!IsCorrect)
3715 return nullptr;
3716 Sema::DeclGroupPtrTy DG = SemaRef.ActOnOpenMPDeclareMapperDirective(
3717 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3718 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3719 Decl *NewDMD = DG.get().getSingleDecl();
3720 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3721 return NewDMD;
3722}
3723
3724Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3725 OMPCapturedExprDecl * /*D*/) {
3726 llvm_unreachable("Should not be met in templates")::llvm::llvm_unreachable_internal("Should not be met in templates"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3726)
;
3727}
3728
3729Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
3730 return VisitFunctionDecl(D, nullptr);
3731}
3732
3733Decl *
3734TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3735 Decl *Inst = VisitFunctionDecl(D, nullptr);
3736 if (Inst && !D->getDescribedFunctionTemplate())
3737 Owner->addDecl(Inst);
3738 return Inst;
3739}
3740
3741Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
3742 return VisitCXXMethodDecl(D, nullptr);
3743}
3744
3745Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3746 llvm_unreachable("There are only CXXRecordDecls in C++")::llvm::llvm_unreachable_internal("There are only CXXRecordDecls in C++"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3746)
;
3747}
3748
3749Decl *
3750TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3751 ClassTemplateSpecializationDecl *D) {
3752 // As a MS extension, we permit class-scope explicit specialization
3753 // of member class templates.
3754 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3755 assert(ClassTemplate->getDeclContext()->isRecord() &&(static_cast <bool> (ClassTemplate->getDeclContext()
->isRecord() && D->getTemplateSpecializationKind
() == TSK_ExplicitSpecialization && "can only instantiate an explicit specialization "
"for a member class template") ? void (0) : __assert_fail ("ClassTemplate->getDeclContext()->isRecord() && D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && \"can only instantiate an explicit specialization \" \"for a member class template\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3758, __extension__
__PRETTY_FUNCTION__))
3756 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&(static_cast <bool> (ClassTemplate->getDeclContext()
->isRecord() && D->getTemplateSpecializationKind
() == TSK_ExplicitSpecialization && "can only instantiate an explicit specialization "
"for a member class template") ? void (0) : __assert_fail ("ClassTemplate->getDeclContext()->isRecord() && D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && \"can only instantiate an explicit specialization \" \"for a member class template\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3758, __extension__
__PRETTY_FUNCTION__))
3757 "can only instantiate an explicit specialization "(static_cast <bool> (ClassTemplate->getDeclContext()
->isRecord() && D->getTemplateSpecializationKind
() == TSK_ExplicitSpecialization && "can only instantiate an explicit specialization "
"for a member class template") ? void (0) : __assert_fail ("ClassTemplate->getDeclContext()->isRecord() && D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && \"can only instantiate an explicit specialization \" \"for a member class template\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3758, __extension__
__PRETTY_FUNCTION__))
3758 "for a member class template")(static_cast <bool> (ClassTemplate->getDeclContext()
->isRecord() && D->getTemplateSpecializationKind
() == TSK_ExplicitSpecialization && "can only instantiate an explicit specialization "
"for a member class template") ? void (0) : __assert_fail ("ClassTemplate->getDeclContext()->isRecord() && D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && \"can only instantiate an explicit specialization \" \"for a member class template\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3758, __extension__
__PRETTY_FUNCTION__))
;
3759
3760 // Lookup the already-instantiated declaration in the instantiation
3761 // of the class template.
3762 ClassTemplateDecl *InstClassTemplate =
3763 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3764 D->getLocation(), ClassTemplate, TemplateArgs));
3765 if (!InstClassTemplate)
3766 return nullptr;
3767
3768 // Substitute into the template arguments of the class template explicit
3769 // specialization.
3770 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
3771 castAs<TemplateSpecializationTypeLoc>();
3772 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3773 Loc.getRAngleLoc());
3774 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
3775 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
3776 ArgLocs.push_back(Loc.getArgLoc(I));
3777 if (SemaRef.SubstTemplateArguments(ArgLocs, TemplateArgs, InstTemplateArgs))
3778 return nullptr;
3779
3780 // Check that the template argument list is well-formed for this
3781 // class template.
3782 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3783 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, D->getLocation(),
3784 InstTemplateArgs, false,
3785 SugaredConverted, CanonicalConverted,
3786 /*UpdateArgsWithConversions=*/true))
3787 return nullptr;
3788
3789 // Figure out where to insert this class template explicit specialization
3790 // in the member template's set of class template explicit specializations.
3791 void *InsertPos = nullptr;
3792 ClassTemplateSpecializationDecl *PrevDecl =
3793 InstClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3794
3795 // Check whether we've already seen a conflicting instantiation of this
3796 // declaration (for instance, if there was a prior implicit instantiation).
3797 bool Ignored;
3798 if (PrevDecl &&
3799 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3800 D->getSpecializationKind(),
3801 PrevDecl,
3802 PrevDecl->getSpecializationKind(),
3803 PrevDecl->getPointOfInstantiation(),
3804 Ignored))
3805 return nullptr;
3806
3807 // If PrevDecl was a definition and D is also a definition, diagnose.
3808 // This happens in cases like:
3809 //
3810 // template<typename T, typename U>
3811 // struct Outer {
3812 // template<typename X> struct Inner;
3813 // template<> struct Inner<T> {};
3814 // template<> struct Inner<U> {};
3815 // };
3816 //
3817 // Outer<int, int> outer; // error: the explicit specializations of Inner
3818 // // have the same signature.
3819 if (PrevDecl && PrevDecl->getDefinition() &&
3820 D->isThisDeclarationADefinition()) {
3821 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3822 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3823 diag::note_previous_definition);
3824 return nullptr;
3825 }
3826
3827 // Create the class template partial specialization declaration.
3828 ClassTemplateSpecializationDecl *InstD =
3829 ClassTemplateSpecializationDecl::Create(
3830 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3831 D->getLocation(), InstClassTemplate, CanonicalConverted, PrevDecl);
3832
3833 // Add this partial specialization to the set of class template partial
3834 // specializations.
3835 if (!PrevDecl)
3836 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3837
3838 // Substitute the nested name specifier, if any.
3839 if (SubstQualifier(D, InstD))
3840 return nullptr;
3841
3842 // Build the canonical type that describes the converted template
3843 // arguments of the class template explicit specialization.
3844 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3845 TemplateName(InstClassTemplate), CanonicalConverted,
3846 SemaRef.Context.getRecordType(InstD));
3847
3848 // Build the fully-sugared type for this class template
3849 // specialization as the user wrote in the specialization
3850 // itself. This means that we'll pretty-print the type retrieved
3851 // from the specialization's declaration the way that the user
3852 // actually wrote the specialization, rather than formatting the
3853 // name based on the "canonical" representation used to store the
3854 // template arguments in the specialization.
3855 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3856 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3857 CanonType);
3858
3859 InstD->setAccess(D->getAccess());
3860 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3861 InstD->setSpecializationKind(D->getSpecializationKind());
3862 InstD->setTypeAsWritten(WrittenTy);
3863 InstD->setExternLoc(D->getExternLoc());
3864 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3865
3866 Owner->addDecl(InstD);
3867
3868 // Instantiate the members of the class-scope explicit specialization eagerly.
3869 // We don't have support for lazy instantiation of an explicit specialization
3870 // yet, and MSVC eagerly instantiates in this case.
3871 // FIXME: This is wrong in standard C++.
3872 if (D->isThisDeclarationADefinition() &&
3873 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3874 TSK_ImplicitInstantiation,
3875 /*Complain=*/true))
3876 return nullptr;
3877
3878 return InstD;
3879}
3880
3881Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3882 VarTemplateSpecializationDecl *D) {
3883
3884 TemplateArgumentListInfo VarTemplateArgsInfo;
3885 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3886 assert(VarTemplate &&(static_cast <bool> (VarTemplate && "A template specialization without specialized template?"
) ? void (0) : __assert_fail ("VarTemplate && \"A template specialization without specialized template?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3887, __extension__
__PRETTY_FUNCTION__))
3887 "A template specialization without specialized template?")(static_cast <bool> (VarTemplate && "A template specialization without specialized template?"
) ? void (0) : __assert_fail ("VarTemplate && \"A template specialization without specialized template?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3887, __extension__
__PRETTY_FUNCTION__))
;
3888
3889 VarTemplateDecl *InstVarTemplate =
3890 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3891 D->getLocation(), VarTemplate, TemplateArgs));
3892 if (!InstVarTemplate)
3893 return nullptr;
3894
3895 // Substitute the current template arguments.
3896 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3897 D->getTemplateArgsInfo()) {
3898 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3899 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3900
3901 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3902 TemplateArgs, VarTemplateArgsInfo))
3903 return nullptr;
3904 }
3905
3906 // Check that the template argument list is well-formed for this template.
3907 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3908 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3909 VarTemplateArgsInfo, false,
3910 SugaredConverted, CanonicalConverted,
3911 /*UpdateArgsWithConversions=*/true))
3912 return nullptr;
3913
3914 // Check whether we've already seen a declaration of this specialization.
3915 void *InsertPos = nullptr;
3916 VarTemplateSpecializationDecl *PrevDecl =
3917 InstVarTemplate->findSpecialization(CanonicalConverted, InsertPos);
3918
3919 // Check whether we've already seen a conflicting instantiation of this
3920 // declaration (for instance, if there was a prior implicit instantiation).
3921 bool Ignored;
3922 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
3923 D->getLocation(), D->getSpecializationKind(), PrevDecl,
3924 PrevDecl->getSpecializationKind(),
3925 PrevDecl->getPointOfInstantiation(), Ignored))
3926 return nullptr;
3927
3928 return VisitVarTemplateSpecializationDecl(
3929 InstVarTemplate, D, VarTemplateArgsInfo, CanonicalConverted, PrevDecl);
3930}
3931
3932Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3933 VarTemplateDecl *VarTemplate, VarDecl *D,
3934 const TemplateArgumentListInfo &TemplateArgsInfo,
3935 ArrayRef<TemplateArgument> Converted,
3936 VarTemplateSpecializationDecl *PrevDecl) {
3937
3938 // Do substitution on the type of the declaration
3939 TypeSourceInfo *DI =
3940 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3941 D->getTypeSpecStartLoc(), D->getDeclName());
3942 if (!DI)
3943 return nullptr;
3944
3945 if (DI->getType()->isFunctionType()) {
3946 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3947 << D->isStaticDataMember() << DI->getType();
3948 return nullptr;
3949 }
3950
3951 // Build the instantiated declaration
3952 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3953 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3954 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
3955 Var->setTemplateArgsInfo(TemplateArgsInfo);
3956 if (!PrevDecl) {
3957 void *InsertPos = nullptr;
3958 VarTemplate->findSpecialization(Converted, InsertPos);
3959 VarTemplate->AddSpecialization(Var, InsertPos);
3960 }
3961
3962 if (SemaRef.getLangOpts().OpenCL)
3963 SemaRef.deduceOpenCLAddressSpace(Var);
3964
3965 // Substitute the nested name specifier, if any.
3966 if (SubstQualifier(D, Var))
3967 return nullptr;
3968
3969 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
3970 StartingScope, false, PrevDecl);
3971
3972 return Var;
3973}
3974
3975Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3976 llvm_unreachable("@defs is not supported in Objective-C++")::llvm::llvm_unreachable_internal("@defs is not supported in Objective-C++"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3976)
;
3977}
3978
3979Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3980 // FIXME: We need to be able to instantiate FriendTemplateDecls.
3981 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3982 DiagnosticsEngine::Error,
3983 "cannot instantiate %0 yet");
3984 SemaRef.Diag(D->getLocation(), DiagID)
3985 << D->getDeclKindName();
3986
3987 return nullptr;
3988}
3989
3990Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
3991 llvm_unreachable("Concept definitions cannot reside inside a template")::llvm::llvm_unreachable_internal("Concept definitions cannot reside inside a template"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3991)
;
3992}
3993
3994Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
3995 ImplicitConceptSpecializationDecl *D) {
3996 llvm_unreachable("Concept specializations cannot reside inside a template")::llvm::llvm_unreachable_internal("Concept specializations cannot reside inside a template"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3996)
;
3997}
3998
3999Decl *
4000TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4001 return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
4002 D->getBeginLoc());
4003}
4004
4005Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
4006 llvm_unreachable("Unexpected decl")::llvm::llvm_unreachable_internal("Unexpected decl", "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4006)
;
4007}
4008
4009Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
4010 const MultiLevelTemplateArgumentList &TemplateArgs) {
4011 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4012 if (D->isInvalidDecl())
4013 return nullptr;
4014
4015 Decl *SubstD;
4016 runWithSufficientStackSpace(D->getLocation(), [&] {
4017 SubstD = Instantiator.Visit(D);
4018 });
4019 return SubstD;
4020}
4021
4022void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK,
4023 FunctionDecl *Orig, QualType &T,
4024 TypeSourceInfo *&TInfo,
4025 DeclarationNameInfo &NameInfo) {
4026 assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual)(static_cast <bool> (RK == RewriteKind::RewriteSpaceshipAsEqualEqual
) ? void (0) : __assert_fail ("RK == RewriteKind::RewriteSpaceshipAsEqualEqual"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4026, __extension__
__PRETTY_FUNCTION__))
;
4027
4028 // C++2a [class.compare.default]p3:
4029 // the return type is replaced with bool
4030 auto *FPT = T->castAs<FunctionProtoType>();
4031 T = SemaRef.Context.getFunctionType(
4032 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4033
4034 // Update the return type in the source info too. The most straightforward
4035 // way is to create new TypeSourceInfo for the new type. Use the location of
4036 // the '= default' as the location of the new type.
4037 //
4038 // FIXME: Set the correct return type when we initially transform the type,
4039 // rather than delaying it to now.
4040 TypeSourceInfo *NewTInfo =
4041 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4042 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4043 assert(OldLoc && "type of function is not a function type?")(static_cast <bool> (OldLoc && "type of function is not a function type?"
) ? void (0) : __assert_fail ("OldLoc && \"type of function is not a function type?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4043, __extension__
__PRETTY_FUNCTION__))
;
4044 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4045 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4046 NewLoc.setParam(I, OldLoc.getParam(I));
4047 TInfo = NewTInfo;
4048
4049 // and the declarator-id is replaced with operator==
4050 NameInfo.setName(
4051 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4052}
4053
4054FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
4055 FunctionDecl *Spaceship) {
4056 if (Spaceship->isInvalidDecl())
4057 return nullptr;
4058
4059 // C++2a [class.compare.default]p3:
4060 // an == operator function is declared implicitly [...] with the same
4061 // access and function-definition and in the same class scope as the
4062 // three-way comparison operator function
4063 MultiLevelTemplateArgumentList NoTemplateArgs;
4064 NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite);
4065 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4066 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4067 Decl *R;
4068 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4069 R = Instantiator.VisitCXXMethodDecl(
4070 MD, nullptr, std::nullopt,
4071 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
4072 } else {
4073 assert(Spaceship->getFriendObjectKind() &&(static_cast <bool> (Spaceship->getFriendObjectKind(
) && "defaulted spaceship is neither a member nor a friend"
) ? void (0) : __assert_fail ("Spaceship->getFriendObjectKind() && \"defaulted spaceship is neither a member nor a friend\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4074, __extension__
__PRETTY_FUNCTION__))
4074 "defaulted spaceship is neither a member nor a friend")(static_cast <bool> (Spaceship->getFriendObjectKind(
) && "defaulted spaceship is neither a member nor a friend"
) ? void (0) : __assert_fail ("Spaceship->getFriendObjectKind() && \"defaulted spaceship is neither a member nor a friend\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4074, __extension__
__PRETTY_FUNCTION__))
;
4075
4076 R = Instantiator.VisitFunctionDecl(
4077 Spaceship, nullptr,
4078 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
4079 if (!R)
4080 return nullptr;
4081
4082 FriendDecl *FD =
4083 FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4084 cast<NamedDecl>(R), Spaceship->getBeginLoc());
4085 FD->setAccess(AS_public);
4086 RD->addDecl(FD);
4087 }
4088 return cast_or_null<FunctionDecl>(R);
4089}
4090
4091/// Instantiates a nested template parameter list in the current
4092/// instantiation context.
4093///
4094/// \param L The parameter list to instantiate
4095///
4096/// \returns NULL if there was an error
4097TemplateParameterList *
4098TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
4099 // Get errors for all the parameters before bailing out.
4100 bool Invalid = false;
4101
4102 unsigned N = L->size();
4103 typedef SmallVector<NamedDecl *, 8> ParamVector;
4104 ParamVector Params;
4105 Params.reserve(N);
4106 for (auto &P : *L) {
4107 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4108 Params.push_back(D);
4109 Invalid = Invalid || !D || D->isInvalidDecl();
4110 }
4111
4112 // Clean up if we had an error.
4113 if (Invalid)
4114 return nullptr;
4115
4116 Expr *InstRequiresClause = L->getRequiresClause();
4117
4118 TemplateParameterList *InstL
4119 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
4120 L->getLAngleLoc(), Params,
4121 L->getRAngleLoc(), InstRequiresClause);
4122 return InstL;
4123}
4124
4125TemplateParameterList *
4126Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
4127 const MultiLevelTemplateArgumentList &TemplateArgs,
4128 bool EvaluateConstraints) {
4129 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4130 Instantiator.setEvaluateConstraints(EvaluateConstraints);
4131 return Instantiator.SubstTemplateParams(Params);
4132}
4133
4134/// Instantiate the declaration of a class template partial
4135/// specialization.
4136///
4137/// \param ClassTemplate the (instantiated) class template that is partially
4138// specialized by the instantiation of \p PartialSpec.
4139///
4140/// \param PartialSpec the (uninstantiated) class template partial
4141/// specialization that we are instantiating.
4142///
4143/// \returns The instantiated partial specialization, if successful; otherwise,
4144/// NULL to indicate an error.
4145ClassTemplatePartialSpecializationDecl *
4146TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
4147 ClassTemplateDecl *ClassTemplate,
4148 ClassTemplatePartialSpecializationDecl *PartialSpec) {
4149 // Create a local instantiation scope for this class template partial
4150 // specialization, which will contain the instantiations of the template
4151 // parameters.
4152 LocalInstantiationScope Scope(SemaRef);
4153
4154 // Substitute into the template parameters of the class template partial
4155 // specialization.
4156 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4157 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4158 if (!InstParams)
4159 return nullptr;
4160
4161 // Substitute into the template arguments of the class template partial
4162 // specialization.
4163 const ASTTemplateArgumentListInfo *TemplArgInfo
4164 = PartialSpec->getTemplateArgsAsWritten();
4165 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4166 TemplArgInfo->RAngleLoc);
4167 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4168 InstTemplateArgs))
4169 return nullptr;
4170
4171 // Check that the template argument list is well-formed for this
4172 // class template.
4173 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4174 if (SemaRef.CheckTemplateArgumentList(
4175 ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4176 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4177 return nullptr;
4178
4179 // Check these arguments are valid for a template partial specialization.
4180 if (SemaRef.CheckTemplatePartialSpecializationArgs(
4181 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4182 CanonicalConverted))
4183 return nullptr;
4184
4185 // Figure out where to insert this class template partial specialization
4186 // in the member template's set of class template partial specializations.
4187 void *InsertPos = nullptr;
4188 ClassTemplateSpecializationDecl *PrevDecl =
4189 ClassTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4190 InsertPos);
4191
4192 // Build the canonical type that describes the converted template
4193 // arguments of the class template partial specialization.
4194 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4195 TemplateName(ClassTemplate), CanonicalConverted);
4196
4197 // Build the fully-sugared type for this class template
4198 // specialization as the user wrote in the specialization
4199 // itself. This means that we'll pretty-print the type retrieved
4200 // from the specialization's declaration the way that the user
4201 // actually wrote the specialization, rather than formatting the
4202 // name based on the "canonical" representation used to store the
4203 // template arguments in the specialization.
4204 TypeSourceInfo *WrittenTy
4205 = SemaRef.Context.getTemplateSpecializationTypeInfo(
4206 TemplateName(ClassTemplate),
4207 PartialSpec->getLocation(),
4208 InstTemplateArgs,
4209 CanonType);
4210
4211 if (PrevDecl) {
4212 // We've already seen a partial specialization with the same template
4213 // parameters and template arguments. This can happen, for example, when
4214 // substituting the outer template arguments ends up causing two
4215 // class template partial specializations of a member class template
4216 // to have identical forms, e.g.,
4217 //
4218 // template<typename T, typename U>
4219 // struct Outer {
4220 // template<typename X, typename Y> struct Inner;
4221 // template<typename Y> struct Inner<T, Y>;
4222 // template<typename Y> struct Inner<U, Y>;
4223 // };
4224 //
4225 // Outer<int, int> outer; // error: the partial specializations of Inner
4226 // // have the same signature.
4227 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
4228 << WrittenTy->getType();
4229 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4230 << SemaRef.Context.getTypeDeclType(PrevDecl);
4231 return nullptr;
4232 }
4233
4234
4235 // Create the class template partial specialization declaration.
4236 ClassTemplatePartialSpecializationDecl *InstPartialSpec =
4237 ClassTemplatePartialSpecializationDecl::Create(
4238 SemaRef.Context, PartialSpec->getTagKind(), Owner,
4239 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4240 ClassTemplate, CanonicalConverted, InstTemplateArgs, CanonType,
4241 nullptr);
4242 // Substitute the nested name specifier, if any.
4243 if (SubstQualifier(PartialSpec, InstPartialSpec))
4244 return nullptr;
4245
4246 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4247 InstPartialSpec->setTypeAsWritten(WrittenTy);
4248
4249 // Check the completed partial specialization.
4250 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4251
4252 // Add this partial specialization to the set of class template partial
4253 // specializations.
4254 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4255 /*InsertPos=*/nullptr);
4256 return InstPartialSpec;
4257}
4258
4259/// Instantiate the declaration of a variable template partial
4260/// specialization.
4261///
4262/// \param VarTemplate the (instantiated) variable template that is partially
4263/// specialized by the instantiation of \p PartialSpec.
4264///
4265/// \param PartialSpec the (uninstantiated) variable template partial
4266/// specialization that we are instantiating.
4267///
4268/// \returns The instantiated partial specialization, if successful; otherwise,
4269/// NULL to indicate an error.
4270VarTemplatePartialSpecializationDecl *
4271TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
4272 VarTemplateDecl *VarTemplate,
4273 VarTemplatePartialSpecializationDecl *PartialSpec) {
4274 // Create a local instantiation scope for this variable template partial
4275 // specialization, which will contain the instantiations of the template
4276 // parameters.
4277 LocalInstantiationScope Scope(SemaRef);
4278
4279 // Substitute into the template parameters of the variable template partial
4280 // specialization.
4281 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4282 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4283 if (!InstParams)
4284 return nullptr;
4285
4286 // Substitute into the template arguments of the variable template partial
4287 // specialization.
4288 const ASTTemplateArgumentListInfo *TemplArgInfo
4289 = PartialSpec->getTemplateArgsAsWritten();
4290 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4291 TemplArgInfo->RAngleLoc);
4292 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4293 InstTemplateArgs))
4294 return nullptr;
4295
4296 // Check that the template argument list is well-formed for this
4297 // class template.
4298 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4299 if (SemaRef.CheckTemplateArgumentList(
4300 VarTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4301 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4302 return nullptr;
4303
4304 // Check these arguments are valid for a template partial specialization.
4305 if (SemaRef.CheckTemplatePartialSpecializationArgs(
4306 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4307 CanonicalConverted))
4308 return nullptr;
4309
4310 // Figure out where to insert this variable template partial specialization
4311 // in the member template's set of variable template partial specializations.
4312 void *InsertPos = nullptr;
4313 VarTemplateSpecializationDecl *PrevDecl =
4314 VarTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4315 InsertPos);
4316
4317 // Build the canonical type that describes the converted template
4318 // arguments of the variable template partial specialization.
4319 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4320 TemplateName(VarTemplate), CanonicalConverted);
4321
4322 // Build the fully-sugared type for this variable template
4323 // specialization as the user wrote in the specialization
4324 // itself. This means that we'll pretty-print the type retrieved
4325 // from the specialization's declaration the way that the user
4326 // actually wrote the specialization, rather than formatting the
4327 // name based on the "canonical" representation used to store the
4328 // template arguments in the specialization.
4329 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
4330 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
4331 CanonType);
4332
4333 if (PrevDecl) {
4334 // We've already seen a partial specialization with the same template
4335 // parameters and template arguments. This can happen, for example, when
4336 // substituting the outer template arguments ends up causing two
4337 // variable template partial specializations of a member variable template
4338 // to have identical forms, e.g.,
4339 //
4340 // template<typename T, typename U>
4341 // struct Outer {
4342 // template<typename X, typename Y> pair<X,Y> p;
4343 // template<typename Y> pair<T, Y> p;
4344 // template<typename Y> pair<U, Y> p;
4345 // };
4346 //
4347 // Outer<int, int> outer; // error: the partial specializations of Inner
4348 // // have the same signature.
4349 SemaRef.Diag(PartialSpec->getLocation(),
4350 diag::err_var_partial_spec_redeclared)
4351 << WrittenTy->getType();
4352 SemaRef.Diag(PrevDecl->getLocation(),
4353 diag::note_var_prev_partial_spec_here);
4354 return nullptr;
4355 }
4356
4357 // Do substitution on the type of the declaration
4358 TypeSourceInfo *DI = SemaRef.SubstType(
4359 PartialSpec->getTypeSourceInfo(), TemplateArgs,
4360 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4361 if (!DI)
4362 return nullptr;
4363
4364 if (DI->getType()->isFunctionType()) {
4365 SemaRef.Diag(PartialSpec->getLocation(),
4366 diag::err_variable_instantiates_to_function)
4367 << PartialSpec->isStaticDataMember() << DI->getType();
4368 return nullptr;
4369 }
4370
4371 // Create the variable template partial specialization declaration.
4372 VarTemplatePartialSpecializationDecl *InstPartialSpec =
4373 VarTemplatePartialSpecializationDecl::Create(
4374 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4375 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4376 DI, PartialSpec->getStorageClass(), CanonicalConverted,
4377 InstTemplateArgs);
4378
4379 // Substitute the nested name specifier, if any.
4380 if (SubstQualifier(PartialSpec, InstPartialSpec))
4381 return nullptr;
4382
4383 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4384 InstPartialSpec->setTypeAsWritten(WrittenTy);
4385
4386 // Check the completed partial specialization.
4387 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4388
4389 // Add this partial specialization to the set of variable template partial
4390 // specializations. The instantiation of the initializer is not necessary.
4391 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4392
4393 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4394 LateAttrs, Owner, StartingScope);
4395
4396 return InstPartialSpec;
4397}
4398
4399TypeSourceInfo*
4400TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
4401 SmallVectorImpl<ParmVarDecl *> &Params) {
4402 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4403 assert(OldTInfo && "substituting function without type source info")(static_cast <bool> (OldTInfo && "substituting function without type source info"
) ? void (0) : __assert_fail ("OldTInfo && \"substituting function without type source info\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4403, __extension__
__PRETTY_FUNCTION__))
;
4404 assert(Params.empty() && "parameter vector is non-empty at start")(static_cast <bool> (Params.empty() && "parameter vector is non-empty at start"
) ? void (0) : __assert_fail ("Params.empty() && \"parameter vector is non-empty at start\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4404, __extension__
__PRETTY_FUNCTION__))
;
4405
4406 CXXRecordDecl *ThisContext = nullptr;
4407 Qualifiers ThisTypeQuals;
4408 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4409 ThisContext = cast<CXXRecordDecl>(Owner);
4410 ThisTypeQuals = Method->getMethodQualifiers();
4411 }
4412
4413 TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
4414 OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
4415 ThisContext, ThisTypeQuals, EvaluateConstraints);
4416 if (!NewTInfo)
4417 return nullptr;
4418
4419 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4420 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4421 if (NewTInfo != OldTInfo) {
4422 // Get parameters from the new type info.
4423 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4424 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4425 unsigned NewIdx = 0;
4426 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4427 OldIdx != NumOldParams; ++OldIdx) {
4428 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4429 if (!OldParam)
4430 return nullptr;
4431
4432 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
4433
4434 std::optional<unsigned> NumArgumentsInExpansion;
4435 if (OldParam->isParameterPack())
4436 NumArgumentsInExpansion =
4437 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4438 TemplateArgs);
4439 if (!NumArgumentsInExpansion) {
4440 // Simple case: normal parameter, or a parameter pack that's
4441 // instantiated to a (still-dependent) parameter pack.
4442 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4443 Params.push_back(NewParam);
4444 Scope->InstantiatedLocal(OldParam, NewParam);
4445 } else {
4446 // Parameter pack expansion: make the instantiation an argument pack.
4447 Scope->MakeInstantiatedLocalArgPack(OldParam);
4448 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
4449 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4450 Params.push_back(NewParam);
4451 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4452 }
4453 }
4454 }
4455 } else {
4456 // The function type itself was not dependent and therefore no
4457 // substitution occurred. However, we still need to instantiate
4458 // the function parameters themselves.
4459 const FunctionProtoType *OldProto =
4460 cast<FunctionProtoType>(OldProtoLoc.getType());
4461 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4462 ++i) {
4463 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4464 if (!OldParam) {
4465 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4466 D, D->getLocation(), OldProto->getParamType(i)));
4467 continue;
4468 }
4469
4470 ParmVarDecl *Parm =
4471 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4472 if (!Parm)
4473 return nullptr;
4474 Params.push_back(Parm);
4475 }
4476 }
4477 } else {
4478 // If the type of this function, after ignoring parentheses, is not
4479 // *directly* a function type, then we're instantiating a function that
4480 // was declared via a typedef or with attributes, e.g.,
4481 //
4482 // typedef int functype(int, int);
4483 // functype func;
4484 // int __cdecl meth(int, int);
4485 //
4486 // In this case, we'll just go instantiate the ParmVarDecls that we
4487 // synthesized in the method declaration.
4488 SmallVector<QualType, 4> ParamTypes;
4489 Sema::ExtParameterInfoBuilder ExtParamInfos;
4490 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4491 TemplateArgs, ParamTypes, &Params,
4492 ExtParamInfos))
4493 return nullptr;
4494 }
4495
4496 return NewTInfo;
4497}
4498
4499/// Introduce the instantiated function parameters into the local
4500/// instantiation scope, and set the parameter names to those used
4501/// in the template.
4502bool Sema::addInstantiatedParametersToScope(
4503 FunctionDecl *Function, const FunctionDecl *PatternDecl,
4504 LocalInstantiationScope &Scope,
4505 const MultiLevelTemplateArgumentList &TemplateArgs) {
4506 unsigned FParamIdx = 0;
4507 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4508 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4509 if (!PatternParam->isParameterPack()) {
4510 // Simple case: not a parameter pack.
4511 assert(FParamIdx < Function->getNumParams())(static_cast <bool> (FParamIdx < Function->getNumParams
()) ? void (0) : __assert_fail ("FParamIdx < Function->getNumParams()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4511, __extension__
__PRETTY_FUNCTION__))
;
4512 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4513 FunctionParam->setDeclName(PatternParam->getDeclName());
4514 // If the parameter's type is not dependent, update it to match the type
4515 // in the pattern. They can differ in top-level cv-qualifiers, and we want
4516 // the pattern's type here. If the type is dependent, they can't differ,
4517 // per core issue 1668. Substitute into the type from the pattern, in case
4518 // it's instantiation-dependent.
4519 // FIXME: Updating the type to work around this is at best fragile.
4520 if (!PatternDecl->getType()->isDependentType()) {
4521 QualType T = SubstType(PatternParam->getType(), TemplateArgs,
4522 FunctionParam->getLocation(),
4523 FunctionParam->getDeclName());
4524 if (T.isNull())
4525 return true;
4526 FunctionParam->setType(T);
4527 }
4528
4529 Scope.InstantiatedLocal(PatternParam, FunctionParam);
4530 ++FParamIdx;
4531 continue;
4532 }
4533
4534 // Expand the parameter pack.
4535 Scope.MakeInstantiatedLocalArgPack(PatternParam);
4536 std::optional<unsigned> NumArgumentsInExpansion =
4537 getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4538 if (NumArgumentsInExpansion) {
4539 QualType PatternType =
4540 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4541 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4542 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4543 FunctionParam->setDeclName(PatternParam->getDeclName());
4544 if (!PatternDecl->getType()->isDependentType()) {
4545 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
4546 QualType T =
4547 SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
4548 FunctionParam->getDeclName());
4549 if (T.isNull())
4550 return true;
4551 FunctionParam->setType(T);
4552 }
4553
4554 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4555 ++FParamIdx;
4556 }
4557 }
4558 }
4559
4560 return false;
4561}
4562
4563bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
4564 ParmVarDecl *Param) {
4565 assert(Param->hasUninstantiatedDefaultArg())(static_cast <bool> (Param->hasUninstantiatedDefaultArg
()) ? void (0) : __assert_fail ("Param->hasUninstantiatedDefaultArg()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4565, __extension__
__PRETTY_FUNCTION__))
;
4566
4567 // Instantiate the expression.
4568 //
4569 // FIXME: Pass in a correct Pattern argument, otherwise
4570 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4571 //
4572 // template<typename T>
4573 // struct A {
4574 // static int FooImpl();
4575 //
4576 // template<typename Tp>
4577 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4578 // // template argument list [[T], [Tp]], should be [[Tp]].
4579 // friend A<Tp> Foo(int a);
4580 // };
4581 //
4582 // template<typename T>
4583 // A<T> Foo(int a = A<T>::FooImpl());
4584 MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
4585 FD, /*Final=*/false, nullptr, /*RelativeToPrimary=*/true);
4586
4587 if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
4588 return true;
4589
4590 if (ASTMutationListener *L = getASTMutationListener())
4591 L->DefaultArgumentInstantiated(Param);
4592
4593 return false;
4594}
4595
4596void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
4597 FunctionDecl *Decl) {
4598 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4599 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
4600 return;
4601
4602 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4603 InstantiatingTemplate::ExceptionSpecification());
4604 if (Inst.isInvalid()) {
4605 // We hit the instantiation depth limit. Clear the exception specification
4606 // so that our callers don't have to cope with EST_Uninstantiated.
4607 UpdateExceptionSpec(Decl, EST_None);
4608 return;
4609 }
4610 if (Inst.isAlreadyInstantiating()) {
4611 // This exception specification indirectly depends on itself. Reject.
4612 // FIXME: Corresponding rule in the standard?
4613 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4614 UpdateExceptionSpec(Decl, EST_None);
4615 return;
4616 }
4617
4618 // Enter the scope of this instantiation. We don't use
4619 // PushDeclContext because we don't have a scope.
4620 Sema::ContextRAII savedContext(*this, Decl);
4621 LocalInstantiationScope Scope(*this);
4622
4623 MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
4624 Decl, /*Final=*/false, nullptr, /*RelativeToPrimary*/ true);
4625
4626 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4627 // here, because for a non-defining friend declaration in a class template,
4628 // we don't store enough information to map back to the friend declaration in
4629 // the template.
4630 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4631 if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
4632 UpdateExceptionSpec(Decl, EST_None);
4633 return;
4634 }
4635
4636 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
4637 TemplateArgs);
4638}
4639
4640/// Initializes the common fields of an instantiation function
4641/// declaration (New) from the corresponding fields of its template (Tmpl).
4642///
4643/// \returns true if there was an error
4644bool
4645TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
4646 FunctionDecl *Tmpl) {
4647 New->setImplicit(Tmpl->isImplicit());
4648
4649 // Forward the mangling number from the template to the instantiated decl.
4650 SemaRef.Context.setManglingNumber(New,
4651 SemaRef.Context.getManglingNumber(Tmpl));
4652
4653 // If we are performing substituting explicitly-specified template arguments
4654 // or deduced template arguments into a function template and we reach this
4655 // point, we are now past the point where SFINAE applies and have committed
4656 // to keeping the new function template specialization. We therefore
4657 // convert the active template instantiation for the function template
4658 // into a template instantiation for this specific function template
4659 // specialization, which is not a SFINAE context, so that we diagnose any
4660 // further errors in the declaration itself.
4661 //
4662 // FIXME: This is a hack.
4663 typedef Sema::CodeSynthesisContext ActiveInstType;
4664 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4665 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4666 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4667 if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
4668 SemaRef.InstantiatingSpecializations.erase(
4669 {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
4670 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4671 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4672 ActiveInst.Entity = New;
4673 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4674 }
4675 }
4676
4677 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4678 assert(Proto && "Function template without prototype?")(static_cast <bool> (Proto && "Function template without prototype?"
) ? void (0) : __assert_fail ("Proto && \"Function template without prototype?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4678, __extension__
__PRETTY_FUNCTION__))
;
4679
4680 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4681 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4682
4683 // DR1330: In C++11, defer instantiation of a non-trivial
4684 // exception specification.
4685 // DR1484: Local classes and their members are instantiated along with the
4686 // containing function.
4687 if (SemaRef.getLangOpts().CPlusPlus11 &&
4688 EPI.ExceptionSpec.Type != EST_None &&
4689 EPI.ExceptionSpec.Type != EST_DynamicNone &&
4690 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
4691 !Tmpl->isInLocalScopeForInstantiation()) {
4692 FunctionDecl *ExceptionSpecTemplate = Tmpl;
4693 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
4694 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4695 ExceptionSpecificationType NewEST = EST_Uninstantiated;
4696 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
4697 NewEST = EST_Unevaluated;
4698
4699 // Mark the function has having an uninstantiated exception specification.
4700 const FunctionProtoType *NewProto
4701 = New->getType()->getAs<FunctionProtoType>();
4702 assert(NewProto && "Template instantiation without function prototype?")(static_cast <bool> (NewProto && "Template instantiation without function prototype?"
) ? void (0) : __assert_fail ("NewProto && \"Template instantiation without function prototype?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4702, __extension__
__PRETTY_FUNCTION__))
;
4703 EPI = NewProto->getExtProtoInfo();
4704 EPI.ExceptionSpec.Type = NewEST;
4705 EPI.ExceptionSpec.SourceDecl = New;
4706 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4707 New->setType(SemaRef.Context.getFunctionType(
4708 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4709 } else {
4710 Sema::ContextRAII SwitchContext(SemaRef, New);
4711 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4712 }
4713 }
4714
4715 // Get the definition. Leaves the variable unchanged if undefined.
4716 const FunctionDecl *Definition = Tmpl;
4717 Tmpl->isDefined(Definition);
4718
4719 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4720 LateAttrs, StartingScope);
4721
4722 return false;
4723}
4724
4725/// Initializes common fields of an instantiated method
4726/// declaration (New) from the corresponding fields of its template
4727/// (Tmpl).
4728///
4729/// \returns true if there was an error
4730bool
4731TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4732 CXXMethodDecl *Tmpl) {
4733 if (InitFunctionInstantiation(New, Tmpl))
4734 return true;
4735
4736 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4737 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4738
4739 New->setAccess(Tmpl->getAccess());
4740 if (Tmpl->isVirtualAsWritten())
4741 New->setVirtualAsWritten(true);
4742
4743 // FIXME: New needs a pointer to Tmpl
4744 return false;
4745}
4746
4747bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
4748 FunctionDecl *Tmpl) {
4749 // Transfer across any unqualified lookups.
4750 if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) {
4751 SmallVector<DeclAccessPair, 32> Lookups;
4752 Lookups.reserve(DFI->getUnqualifiedLookups().size());
4753 bool AnyChanged = false;
4754 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4755 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4756 DA.getDecl(), TemplateArgs);
4757 if (!D)
4758 return true;
4759 AnyChanged |= (D != DA.getDecl());
4760 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4761 }
4762
4763 // It's unlikely that substitution will change any declarations. Don't
4764 // store an unnecessary copy in that case.
4765 New->setDefaultedFunctionInfo(
4766 AnyChanged ? FunctionDecl::DefaultedFunctionInfo::Create(
4767 SemaRef.Context, Lookups)
4768 : DFI);
4769 }
4770
4771 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4772 return false;
4773}
4774
4775/// Instantiate (or find existing instantiation of) a function template with a
4776/// given set of template arguments.
4777///
4778/// Usually this should not be used, and template argument deduction should be
4779/// used in its place.
4780FunctionDecl *
4781Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
4782 const TemplateArgumentList *Args,
4783 SourceLocation Loc) {
4784 FunctionDecl *FD = FTD->getTemplatedDecl();
4785
4786 sema::TemplateDeductionInfo Info(Loc);
4787 InstantiatingTemplate Inst(
4788 *this, Loc, FTD, Args->asArray(),
4789 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
4790 if (Inst.isInvalid())
4791 return nullptr;
4792
4793 ContextRAII SavedContext(*this, FD);
4794 MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
4795 /*Final=*/false);
4796
4797 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4798}
4799
4800/// Instantiate the definition of the given function from its
4801/// template.
4802///
4803/// \param PointOfInstantiation the point at which the instantiation was
4804/// required. Note that this is not precisely a "point of instantiation"
4805/// for the function, but it's close.
4806///
4807/// \param Function the already-instantiated declaration of a
4808/// function template specialization or member function of a class template
4809/// specialization.
4810///
4811/// \param Recursive if true, recursively instantiates any functions that
4812/// are required by this instantiation.
4813///
4814/// \param DefinitionRequired if true, then we are performing an explicit
4815/// instantiation where the body of the function is required. Complain if
4816/// there is no such body.
4817void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4818 FunctionDecl *Function,
4819 bool Recursive,
4820 bool DefinitionRequired,
4821 bool AtEndOfTU) {
4822 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
2
Assuming the condition is false
3
Assuming 'Function' is not a 'CXXDeductionGuideDecl'
4
Taking false branch
4823 return;
4824
4825 // Never instantiate an explicit specialization except if it is a class scope
4826 // explicit specialization.
4827 TemplateSpecializationKind TSK =
4828 Function->getTemplateSpecializationKindForInstantiation();
4829 if (TSK == TSK_ExplicitSpecialization)
5
Assuming 'TSK' is not equal to TSK_ExplicitSpecialization
4830 return;
4831
4832 // Never implicitly instantiate a builtin; we don't actually need a function
4833 // body.
4834 if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
6
Assuming the condition is false
4835 !DefinitionRequired)
4836 return;
4837
4838 // Don't instantiate a definition if we already have one.
4839 const FunctionDecl *ExistingDefn = nullptr;
4840 if (Function->isDefined(ExistingDefn,
7
Assuming the condition is false
8
Taking false branch
4841 /*CheckForPendingFriendDefinition=*/true)) {
4842 if (ExistingDefn->isThisDeclarationADefinition())
4843 return;
4844
4845 // If we're asked to instantiate a function whose body comes from an
4846 // instantiated friend declaration, attach the instantiated body to the
4847 // corresponding declaration of the function.
4848 assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition())(static_cast <bool> (ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition
()) ? void (0) : __assert_fail ("ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4848, __extension__
__PRETTY_FUNCTION__))
;
4849 Function = const_cast<FunctionDecl*>(ExistingDefn);
4850 }
4851
4852 // Find the function body that we'll be substituting.
4853 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4854 assert(PatternDecl && "instantiating a non-template")(static_cast <bool> (PatternDecl && "instantiating a non-template"
) ? void (0) : __assert_fail ("PatternDecl && \"instantiating a non-template\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4854, __extension__
__PRETTY_FUNCTION__))
;
9
Assuming 'PatternDecl' is non-null
10
'?' condition is true
4855
4856 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4857 Stmt *Pattern = nullptr;
4858 if (PatternDef
10.1
'PatternDef' is null
10.1
'PatternDef' is null
) {
11
Taking false branch
4859 Pattern = PatternDef->getBody(PatternDef);
4860 PatternDecl = PatternDef;
4861 if (PatternDef->willHaveBody())
4862 PatternDef = nullptr;
4863 }
4864
4865 // FIXME: We need to track the instantiation stack in order to know which
4866 // definitions should be visible within this instantiation.
4867 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
12
Assuming the condition is false
4868 Function->getInstantiatedFromMemberFunction(),
4869 PatternDecl, PatternDef, TSK,
4870 /*Complain*/DefinitionRequired)) {
4871 if (DefinitionRequired)
4872 Function->setInvalidDecl();
4873 else if (TSK == TSK_ExplicitInstantiationDefinition ||
4874 (Function->isConstexpr() && !Recursive)) {
4875 // Try again at the end of the translation unit (at which point a
4876 // definition will be required).
4877 assert(!Recursive)(static_cast <bool> (!Recursive) ? void (0) : __assert_fail
("!Recursive", "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4877, __extension__ __PRETTY_FUNCTION__))
;
4878 Function->setInstantiationIsPending(true);
4879 PendingInstantiations.push_back(
4880 std::make_pair(Function, PointOfInstantiation));
4881 } else if (TSK == TSK_ImplicitInstantiation) {
4882 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4883 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4884 Diag(PointOfInstantiation, diag::warn_func_template_missing)
4885 << Function;
4886 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4887 if (getLangOpts().CPlusPlus11)
4888 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4889 << Function;
4890 }
4891 }
4892
4893 return;
4894 }
4895
4896 // Postpone late parsed template instantiations.
4897 if (PatternDecl->isLateTemplateParsed() &&
13
Assuming the condition is false
4898 !LateTemplateParser) {
4899 Function->setInstantiationIsPending(true);
4900 LateParsedInstantiations.push_back(
4901 std::make_pair(Function, PointOfInstantiation));
4902 return;
4903 }
4904
4905 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
4906 std::string Name;
4907 llvm::raw_string_ostream OS(Name);
4908 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4909 /*Qualified=*/true);
4910 return Name;
4911 });
4912
4913 // If we're performing recursive template instantiation, create our own
4914 // queue of pending implicit instantiations that we will instantiate later,
4915 // while we're still within our own instantiation context.
4916 // This has to happen before LateTemplateParser below is called, so that
4917 // it marks vtables used in late parsed templates as used.
4918 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4919 /*Enabled=*/Recursive);
4920 LocalEagerInstantiationScope LocalInstantiations(*this);
4921
4922 // Call the LateTemplateParser callback if there is a need to late parse
4923 // a templated function definition.
4924 if (!Pattern
13.1
'Pattern' is null
13.1
'Pattern' is null
&& PatternDecl->isLateTemplateParsed() &&
4925 LateTemplateParser) {
4926 // FIXME: Optimize to allow individual templates to be deserialized.
4927 if (PatternDecl->isFromASTFile())
4928 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
4929
4930 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
4931 assert(LPTIter != LateParsedTemplateMap.end() &&(static_cast <bool> (LPTIter != LateParsedTemplateMap.end
() && "missing LateParsedTemplate") ? void (0) : __assert_fail
("LPTIter != LateParsedTemplateMap.end() && \"missing LateParsedTemplate\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4932, __extension__
__PRETTY_FUNCTION__))
4932 "missing LateParsedTemplate")(static_cast <bool> (LPTIter != LateParsedTemplateMap.end
() && "missing LateParsedTemplate") ? void (0) : __assert_fail
("LPTIter != LateParsedTemplateMap.end() && \"missing LateParsedTemplate\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4932, __extension__
__PRETTY_FUNCTION__))
;
4933 LateTemplateParser(OpaqueParser, *LPTIter->second);
4934 Pattern = PatternDecl->getBody(PatternDecl);
4935 updateAttrsForLateParsedTemplate(PatternDecl, Function);
4936 }
4937
4938 // Note, we should never try to instantiate a deleted function template.
4939 assert((Pattern || PatternDecl->isDefaulted() ||(static_cast <bool> ((Pattern || PatternDecl->isDefaulted
() || PatternDecl->hasSkippedBody()) && "unexpected kind of function template definition"
) ? void (0) : __assert_fail ("(Pattern || PatternDecl->isDefaulted() || PatternDecl->hasSkippedBody()) && \"unexpected kind of function template definition\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4941, __extension__
__PRETTY_FUNCTION__))
14
Assuming the condition is false
15
Assuming the condition is true
16
'?' condition is true
4940 PatternDecl->hasSkippedBody()) &&(static_cast <bool> ((Pattern || PatternDecl->isDefaulted
() || PatternDecl->hasSkippedBody()) && "unexpected kind of function template definition"
) ? void (0) : __assert_fail ("(Pattern || PatternDecl->isDefaulted() || PatternDecl->hasSkippedBody()) && \"unexpected kind of function template definition\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4941, __extension__
__PRETTY_FUNCTION__))
4941 "unexpected kind of function template definition")(static_cast <bool> ((Pattern || PatternDecl->isDefaulted
() || PatternDecl->hasSkippedBody()) && "unexpected kind of function template definition"
) ? void (0) : __assert_fail ("(Pattern || PatternDecl->isDefaulted() || PatternDecl->hasSkippedBody()) && \"unexpected kind of function template definition\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4941, __extension__
__PRETTY_FUNCTION__))
;
4942
4943 // C++1y [temp.explicit]p10:
4944 // Except for inline functions, declarations with types deduced from their
4945 // initializer or return value, and class template specializations, other
4946 // explicit instantiation declarations have the effect of suppressing the
4947 // implicit instantiation of the entity to which they refer.
4948 if (TSK == TSK_ExplicitInstantiationDeclaration &&
17
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDeclaration
18
Taking false branch
4949 !PatternDecl->isInlined() &&
4950 !PatternDecl->getReturnType()->getContainedAutoType())
4951 return;
4952
4953 if (PatternDecl->isInlined()) {
19
Assuming the condition is false
20
Taking false branch
4954 // Function, and all later redeclarations of it (from imported modules,
4955 // for instance), are now implicitly inline.
4956 for (auto *D = Function->getMostRecentDecl(); /**/;
4957 D = D->getPreviousDecl()) {
4958 D->setImplicitlyInline();
4959 if (D == Function)
4960 break;
4961 }
4962 }
4963
4964 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
4965 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
21
Assuming the condition is false
22
Assuming the condition is false
23
Taking false branch
4966 return;
4967 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
4968 "instantiating function definition");
4969
4970 // The instantiation is visible here, even if it was first declared in an
4971 // unimported module.
4972 Function->setVisibleDespiteOwningModule();
4973
4974 // Copy the inner loc start from the pattern.
4975 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
4976
4977 EnterExpressionEvaluationContext EvalContext(
4978 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4979
4980 // Introduce a new scope where local variable instantiations will be
4981 // recorded, unless we're actually a member function within a local
4982 // class, in which case we need to merge our results with the parent
4983 // scope (of the enclosing function). The exception is instantiating
4984 // a function template specialization, since the template to be
4985 // instantiated already has references to locals properly substituted.
4986 bool MergeWithParentScope = false;
4987 if (CXXRecordDecl *Rec
24.1
'Rec' is null
24.1
'Rec' is null
= dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
24
Assuming the object is not a 'CastReturnType'
25
Taking false branch
4988 MergeWithParentScope =
4989 Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
4990
4991 LocalInstantiationScope Scope(*this, MergeWithParentScope);
4992 auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
4993 // Special members might get their TypeSourceInfo set up w.r.t the
4994 // PatternDecl context, in which case parameters could still be pointing
4995 // back to the original class, make sure arguments are bound to the
4996 // instantiated record instead.
4997 assert(PatternDecl->isDefaulted() &&(static_cast <bool> (PatternDecl->isDefaulted() &&
"Special member needs to be defaulted") ? void (0) : __assert_fail
("PatternDecl->isDefaulted() && \"Special member needs to be defaulted\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4998, __extension__
__PRETTY_FUNCTION__))
4998 "Special member needs to be defaulted")(static_cast <bool> (PatternDecl->isDefaulted() &&
"Special member needs to be defaulted") ? void (0) : __assert_fail
("PatternDecl->isDefaulted() && \"Special member needs to be defaulted\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4998, __extension__
__PRETTY_FUNCTION__))
;
4999 auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
5000 if (!(PatternSM == Sema::CXXCopyConstructor ||
5001 PatternSM == Sema::CXXCopyAssignment ||
5002 PatternSM == Sema::CXXMoveConstructor ||
5003 PatternSM == Sema::CXXMoveAssignment))
5004 return;
5005
5006 auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
5007 const auto *PatternRec =
5008 dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
5009 if (!NewRec || !PatternRec)
5010 return;
5011 if (!PatternRec->isLambda())
5012 return;
5013
5014 struct SpecialMemberTypeInfoRebuilder
5015 : TreeTransform<SpecialMemberTypeInfoRebuilder> {
5016 using Base = TreeTransform<SpecialMemberTypeInfoRebuilder>;
5017 const CXXRecordDecl *OldDecl;
5018 CXXRecordDecl *NewDecl;
5019
5020 SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5021 CXXRecordDecl *N)
5022 : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5023
5024 bool TransformExceptionSpec(SourceLocation Loc,
5025 FunctionProtoType::ExceptionSpecInfo &ESI,
5026 SmallVectorImpl<QualType> &Exceptions,
5027 bool &Changed) {
5028 return false;
5029 }
5030
5031 QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5032 const RecordType *T = TL.getTypePtr();
5033 RecordDecl *Record = cast_or_null<RecordDecl>(
5034 getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
5035 if (Record != OldDecl)
5036 return Base::TransformRecordType(TLB, TL);
5037
5038 QualType Result = getDerived().RebuildRecordType(NewDecl);
5039 if (Result.isNull())
5040 return QualType();
5041
5042 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5043 NewTL.setNameLoc(TL.getNameLoc());
5044 return Result;
5045 }
5046 } IR{*this, PatternRec, NewRec};
5047
5048 TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5049 Function->setType(NewSI->getType());
5050 Function->setTypeSourceInfo(NewSI);
5051
5052 ParmVarDecl *Parm = Function->getParamDecl(0);
5053 TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5054 Parm->setType(NewParmSI->getType());
5055 Parm->setTypeSourceInfo(NewParmSI);
5056 };
5057
5058 if (PatternDecl->isDefaulted()) {
26
Taking false branch
5059 RebuildTypeSourceInfoForDefaultSpecialMembers();
5060 SetDeclDefaulted(Function, PatternDecl->getLocation());
5061 } else {
5062 MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
5063 Function, /*Final=*/false, nullptr, false, PatternDecl);
5064
5065 // Substitute into the qualifier; we can get a substitution failure here
5066 // through evil use of alias templates.
5067 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5068 // of the) lexical context of the pattern?
5069 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5070
5071 ActOnStartOfFunctionDef(nullptr, Function);
5072
5073 // Enter the scope of this instantiation. We don't use
5074 // PushDeclContext because we don't have a scope.
5075 Sema::ContextRAII savedContext(*this, Function);
5076
5077 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
27
Assuming the condition is false
28
Taking false branch
5078 TemplateArgs))
5079 return;
5080
5081 StmtResult Body;
5082 if (PatternDecl->hasSkippedBody()) {
29
Taking true branch
5083 ActOnSkippedFunctionBody(Function);
5084 Body = nullptr;
5085 } else {
5086 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5087 // If this is a constructor, instantiate the member initializers.
5088 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
5089 TemplateArgs);
5090
5091 // If this is an MS ABI dllexport default constructor, instantiate any
5092 // default arguments.
5093 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5094 Ctor->isDefaultConstructor()) {
5095 InstantiateDefaultCtorDefaultArgs(Ctor);
5096 }
5097 }
5098
5099 // Instantiate the function body.
5100 Body = SubstStmt(Pattern, TemplateArgs);
5101
5102 if (Body.isInvalid())
5103 Function->setInvalidDecl();
5104 }
5105 // FIXME: finishing the function body while in an expression evaluation
5106 // context seems wrong. Investigate more.
5107 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5108
5109 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5110
5111 if (auto *Listener = getASTMutationListener())
30
Assuming 'Listener' is null
31
Taking false branch
5112 Listener->FunctionDefinitionInstantiated(Function);
5113
5114 savedContext.pop();
5115 }
5116
5117 DeclGroupRef DG(Function);
5118 Consumer.HandleTopLevelDecl(DG);
5119
5120 // This class may have local implicit instantiations that need to be
5121 // instantiation within this scope.
5122 LocalInstantiations.perform();
5123 Scope.Exit();
5124 GlobalInstantiations.perform();
32
Calling 'GlobalEagerInstantiationScope::perform'
5125}
5126
5127VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
5128 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
5129 const TemplateArgumentList &TemplateArgList,
5130 const TemplateArgumentListInfo &TemplateArgsInfo,
5131 SmallVectorImpl<TemplateArgument> &Converted,
5132 SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
5133 LocalInstantiationScope *StartingScope) {
5134 if (FromVar->isInvalidDecl())
5135 return nullptr;
5136
5137 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
5138 if (Inst.isInvalid())
5139 return nullptr;
5140
5141 // Instantiate the first declaration of the variable template: for a partial
5142 // specialization of a static data member template, the first declaration may
5143 // or may not be the declaration in the class; if it's in the class, we want
5144 // to instantiate a member in the class (a declaration), and if it's outside,
5145 // we want to instantiate a definition.
5146 //
5147 // If we're instantiating an explicitly-specialized member template or member
5148 // partial specialization, don't do this. The member specialization completely
5149 // replaces the original declaration in this case.
5150 bool IsMemberSpec = false;
5151 MultiLevelTemplateArgumentList MultiLevelList;
5152 if (auto *PartialSpec =
5153 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
5154 IsMemberSpec = PartialSpec->isMemberSpecialization();
5155 MultiLevelList.addOuterTemplateArguments(
5156 PartialSpec, TemplateArgList.asArray(), /*Final=*/false);
5157 } else {
5158 assert(VarTemplate == FromVar->getDescribedVarTemplate())(static_cast <bool> (VarTemplate == FromVar->getDescribedVarTemplate
()) ? void (0) : __assert_fail ("VarTemplate == FromVar->getDescribedVarTemplate()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5158, __extension__
__PRETTY_FUNCTION__))
;
5159 IsMemberSpec = VarTemplate->isMemberSpecialization();
5160 MultiLevelList.addOuterTemplateArguments(
5161 VarTemplate, TemplateArgList.asArray(), /*Final=*/false);
5162 }
5163 if (!IsMemberSpec)
5164 FromVar = FromVar->getFirstDecl();
5165
5166 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
5167 MultiLevelList);
5168
5169 // TODO: Set LateAttrs and StartingScope ...
5170
5171 return cast_or_null<VarTemplateSpecializationDecl>(
5172 Instantiator.VisitVarTemplateSpecializationDecl(
5173 VarTemplate, FromVar, TemplateArgsInfo, Converted));
5174}
5175
5176/// Instantiates a variable template specialization by completing it
5177/// with appropriate type information and initializer.
5178VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
5179 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
5180 const MultiLevelTemplateArgumentList &TemplateArgs) {
5181 assert(PatternDecl->isThisDeclarationADefinition() &&(static_cast <bool> (PatternDecl->isThisDeclarationADefinition
() && "don't have a definition to instantiate from") ?
void (0) : __assert_fail ("PatternDecl->isThisDeclarationADefinition() && \"don't have a definition to instantiate from\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5182, __extension__
__PRETTY_FUNCTION__))
5182 "don't have a definition to instantiate from")(static_cast <bool> (PatternDecl->isThisDeclarationADefinition
() && "don't have a definition to instantiate from") ?
void (0) : __assert_fail ("PatternDecl->isThisDeclarationADefinition() && \"don't have a definition to instantiate from\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5182, __extension__
__PRETTY_FUNCTION__))
;
5183
5184 // Do substitution on the type of the declaration
5185 TypeSourceInfo *DI =
5186 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
5187 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
5188 if (!DI)
5189 return nullptr;
5190
5191 // Update the type of this variable template specialization.
5192 VarSpec->setType(DI->getType());
5193
5194 // Convert the declaration into a definition now.
5195 VarSpec->setCompleteDefinition();
5196
5197 // Instantiate the initializer.
5198 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
5199
5200 if (getLangOpts().OpenCL)
5201 deduceOpenCLAddressSpace(VarSpec);
5202
5203 return VarSpec;
5204}
5205
5206/// BuildVariableInstantiation - Used after a new variable has been created.
5207/// Sets basic variable data and decides whether to postpone the
5208/// variable instantiation.
5209void Sema::BuildVariableInstantiation(
5210 VarDecl *NewVar, VarDecl *OldVar,
5211 const MultiLevelTemplateArgumentList &TemplateArgs,
5212 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
5213 LocalInstantiationScope *StartingScope,
5214 bool InstantiatingVarTemplate,
5215 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
5216 // Instantiating a partial specialization to produce a partial
5217 // specialization.
5218 bool InstantiatingVarTemplatePartialSpec =
5219 isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
5220 isa<VarTemplatePartialSpecializationDecl>(NewVar);
5221 // Instantiating from a variable template (or partial specialization) to
5222 // produce a variable template specialization.
5223 bool InstantiatingSpecFromTemplate =
5224 isa<VarTemplateSpecializationDecl>(NewVar) &&
5225 (OldVar->getDescribedVarTemplate() ||
5226 isa<VarTemplatePartialSpecializationDecl>(OldVar));
5227
5228 // If we are instantiating a local extern declaration, the
5229 // instantiation belongs lexically to the containing function.
5230 // If we are instantiating a static data member defined
5231 // out-of-line, the instantiation will have the same lexical
5232 // context (which will be a namespace scope) as the template.
5233 if (OldVar->isLocalExternDecl()) {
5234 NewVar->setLocalExternDecl();
5235 NewVar->setLexicalDeclContext(Owner);
5236 } else if (OldVar->isOutOfLine())
5237 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
5238 NewVar->setTSCSpec(OldVar->getTSCSpec());
5239 NewVar->setInitStyle(OldVar->getInitStyle());
5240 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
5241 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
5242 NewVar->setConstexpr(OldVar->isConstexpr());
5243 NewVar->setInitCapture(OldVar->isInitCapture());
5244 NewVar->setPreviousDeclInSameBlockScope(
5245 OldVar->isPreviousDeclInSameBlockScope());
5246 NewVar->setAccess(OldVar->getAccess());
5247
5248 if (!OldVar->isStaticDataMember()) {
5249 if (OldVar->isUsed(false))
5250 NewVar->setIsUsed();
5251 NewVar->setReferenced(OldVar->isReferenced());
5252 }
5253
5254 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
5255
5256 LookupResult Previous(
5257 *this, NewVar->getDeclName(), NewVar->getLocation(),
5258 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
5259 : Sema::LookupOrdinaryName,
5260 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
5261 : forRedeclarationInCurContext());
5262
5263 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
5264 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
5265 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
5266 // We have a previous declaration. Use that one, so we merge with the
5267 // right type.
5268 if (NamedDecl *NewPrev = FindInstantiatedDecl(
5269 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
5270 Previous.addDecl(NewPrev);
5271 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
5272 OldVar->hasLinkage()) {
5273 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
5274 } else if (PrevDeclForVarTemplateSpecialization) {
5275 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
5276 }
5277 CheckVariableDeclaration(NewVar, Previous);
5278
5279 if (!InstantiatingVarTemplate) {
5280 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
5281 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
5282 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
5283 }
5284
5285 if (!OldVar->isOutOfLine()) {
5286 if (NewVar->getDeclContext()->isFunctionOrMethod())
5287 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
5288 }
5289
5290 // Link instantiations of static data members back to the template from
5291 // which they were instantiated.
5292 //
5293 // Don't do this when instantiating a template (we link the template itself
5294 // back in that case) nor when instantiating a static data member template
5295 // (that's not a member specialization).
5296 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
5297 !InstantiatingSpecFromTemplate)
5298 NewVar->setInstantiationOfStaticDataMember(OldVar,
5299 TSK_ImplicitInstantiation);
5300
5301 // If the pattern is an (in-class) explicit specialization, then the result
5302 // is also an explicit specialization.
5303 if (VarTemplateSpecializationDecl *OldVTSD =
5304 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
5305 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
5306 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
5307 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
5308 TSK_ExplicitSpecialization);
5309 }
5310
5311 // Forward the mangling number from the template to the instantiated decl.
5312 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
5313 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
5314
5315 // Figure out whether to eagerly instantiate the initializer.
5316 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
5317 // We're producing a template. Don't instantiate the initializer yet.
5318 } else if (NewVar->getType()->isUndeducedType()) {
5319 // We need the type to complete the declaration of the variable.
5320 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5321 } else if (InstantiatingSpecFromTemplate ||
5322 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
5323 !NewVar->isThisDeclarationADefinition())) {
5324 // Delay instantiation of the initializer for variable template
5325 // specializations or inline static data members until a definition of the
5326 // variable is needed.
5327 } else {
5328 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5329 }
5330
5331 // Diagnose unused local variables with dependent types, where the diagnostic
5332 // will have been deferred.
5333 if (!NewVar->isInvalidDecl() &&
5334 NewVar->getDeclContext()->isFunctionOrMethod() &&
5335 OldVar->getType()->isDependentType())
5336 DiagnoseUnusedDecl(NewVar);
5337}
5338
5339/// Instantiate the initializer of a variable.
5340void Sema::InstantiateVariableInitializer(
5341 VarDecl *Var, VarDecl *OldVar,
5342 const MultiLevelTemplateArgumentList &TemplateArgs) {
5343 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
5344 L->VariableDefinitionInstantiated(Var);
5345
5346 // We propagate the 'inline' flag with the initializer, because it
5347 // would otherwise imply that the variable is a definition for a
5348 // non-static data member.
5349 if (OldVar->isInlineSpecified())
5350 Var->setInlineSpecified();
5351 else if (OldVar->isInline())
5352 Var->setImplicitlyInline();
5353
5354 if (OldVar->getInit()) {
5355 EnterExpressionEvaluationContext Evaluated(
5356 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
5357
5358 // Instantiate the initializer.
5359 ExprResult Init;
5360
5361 {
5362 ContextRAII SwitchContext(*this, Var->getDeclContext());
5363 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
5364 OldVar->getInitStyle() == VarDecl::CallInit);
5365 }
5366
5367 if (!Init.isInvalid()) {
5368 Expr *InitExpr = Init.get();
5369
5370 if (Var->hasAttr<DLLImportAttr>() &&
5371 (!InitExpr ||
5372 !InitExpr->isConstantInitializer(getASTContext(), false))) {
5373 // Do not dynamically initialize dllimport variables.
5374 } else if (InitExpr) {
5375 bool DirectInit = OldVar->isDirectInit();
5376 AddInitializerToDecl(Var, InitExpr, DirectInit);
5377 } else
5378 ActOnUninitializedDecl(Var);
5379 } else {
5380 // FIXME: Not too happy about invalidating the declaration
5381 // because of a bogus initializer.
5382 Var->setInvalidDecl();
5383 }
5384 } else {
5385 // `inline` variables are a definition and declaration all in one; we won't
5386 // pick up an initializer from anywhere else.
5387 if (Var->isStaticDataMember() && !Var->isInline()) {
5388 if (!Var->isOutOfLine())
5389 return;
5390
5391 // If the declaration inside the class had an initializer, don't add
5392 // another one to the out-of-line definition.
5393 if (OldVar->getFirstDecl()->hasInit())
5394 return;
5395 }
5396
5397 // We'll add an initializer to a for-range declaration later.
5398 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
5399 return;
5400
5401 ActOnUninitializedDecl(Var);
5402 }
5403
5404 if (getLangOpts().CUDA)
5405 checkAllowedCUDAInitializer(Var);
5406}
5407
5408/// Instantiate the definition of the given variable from its
5409/// template.
5410///
5411/// \param PointOfInstantiation the point at which the instantiation was
5412/// required. Note that this is not precisely a "point of instantiation"
5413/// for the variable, but it's close.
5414///
5415/// \param Var the already-instantiated declaration of a templated variable.
5416///
5417/// \param Recursive if true, recursively instantiates any functions that
5418/// are required by this instantiation.
5419///
5420/// \param DefinitionRequired if true, then we are performing an explicit
5421/// instantiation where a definition of the variable is required. Complain
5422/// if there is no such definition.
5423void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
5424 VarDecl *Var, bool Recursive,
5425 bool DefinitionRequired, bool AtEndOfTU) {
5426 if (Var->isInvalidDecl())
51
Assuming the condition is false
52
Taking false branch
5427 return;
5428
5429 // Never instantiate an explicitly-specialized entity.
5430 TemplateSpecializationKind TSK =
5431 Var->getTemplateSpecializationKindForInstantiation();
5432 if (TSK == TSK_ExplicitSpecialization)
53
Assuming 'TSK' is not equal to TSK_ExplicitSpecialization
54
Taking false branch
5433 return;
5434
5435 // Find the pattern and the arguments to substitute into it.
5436 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
5437 assert(PatternDecl && "no pattern for templated variable")(static_cast <bool> (PatternDecl && "no pattern for templated variable"
) ? void (0) : __assert_fail ("PatternDecl && \"no pattern for templated variable\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5437, __extension__
__PRETTY_FUNCTION__))
;
55
Assuming 'PatternDecl' is non-null
56
'?' condition is true
5438 MultiLevelTemplateArgumentList TemplateArgs =
5439 getTemplateInstantiationArgs(Var);
5440
5441 VarTemplateSpecializationDecl *VarSpec =
5442 dyn_cast<VarTemplateSpecializationDecl>(Var);
57
'Var' is a 'VarTemplateSpecializationDecl'
5443 if (VarSpec
57.1
'VarSpec' is non-null
57.1
'VarSpec' is non-null
) {
5444 // If this is a static data member template, there might be an
5445 // uninstantiated initializer on the declaration. If so, instantiate
5446 // it now.
5447 //
5448 // FIXME: This largely duplicates what we would do below. The difference
5449 // is that along this path we may instantiate an initializer from an
5450 // in-class declaration of the template and instantiate the definition
5451 // from a separate out-of-class definition.
5452 if (PatternDecl->isStaticDataMember() &&
58
Assuming the condition is false
5453 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
5454 !Var->hasInit()) {
5455 // FIXME: Factor out the duplicated instantiation context setup/tear down
5456 // code here.
5457 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5458 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5459 return;
5460 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5461 "instantiating variable initializer");
5462
5463 // The instantiation is visible here, even if it was first declared in an
5464 // unimported module.
5465 Var->setVisibleDespiteOwningModule();
5466
5467 // If we're performing recursive template instantiation, create our own
5468 // queue of pending implicit instantiations that we will instantiate
5469 // later, while we're still within our own instantiation context.
5470 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5471 /*Enabled=*/Recursive);
5472 LocalInstantiationScope Local(*this);
5473 LocalEagerInstantiationScope LocalInstantiations(*this);
5474
5475 // Enter the scope of this instantiation. We don't use
5476 // PushDeclContext because we don't have a scope.
5477 ContextRAII PreviousContext(*this, Var->getDeclContext());
5478 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
5479 PreviousContext.pop();
5480
5481 // This variable may have local implicit instantiations that need to be
5482 // instantiated within this scope.
5483 LocalInstantiations.perform();
5484 Local.Exit();
5485 GlobalInstantiations.perform();
5486 }
5487 } else {
5488 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&(static_cast <bool> (Var->isStaticDataMember() &&
PatternDecl->isStaticDataMember() && "not a static data member?"
) ? void (0) : __assert_fail ("Var->isStaticDataMember() && PatternDecl->isStaticDataMember() && \"not a static data member?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5489, __extension__
__PRETTY_FUNCTION__))
5489 "not a static data member?")(static_cast <bool> (Var->isStaticDataMember() &&
PatternDecl->isStaticDataMember() && "not a static data member?"
) ? void (0) : __assert_fail ("Var->isStaticDataMember() && PatternDecl->isStaticDataMember() && \"not a static data member?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5489, __extension__
__PRETTY_FUNCTION__))
;
5490 }
5491
5492 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
59
'Def' initialized here
5493
5494 // If we don't have a definition of the variable template, we won't perform
5495 // any instantiation. Rather, we rely on the user to instantiate this
5496 // definition (or provide a specialization for it) in another translation
5497 // unit.
5498 if (!Def && !DefinitionRequired
61.1
'DefinitionRequired' is false
61.1
'DefinitionRequired' is false
) {
60
Assuming 'Def' is null
61
Assuming pointer value is null
62
Taking true branch
5499 if (TSK == TSK_ExplicitInstantiationDefinition) {
63
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDefinition
64
Taking false branch
5500 PendingInstantiations.push_back(
5501 std::make_pair(Var, PointOfInstantiation));
5502 } else if (TSK == TSK_ImplicitInstantiation) {
65
Assuming 'TSK' is not equal to TSK_ImplicitInstantiation
66
Taking false branch
5503 // Warn about missing definition at the end of translation unit.
5504 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5505 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5506 Diag(PointOfInstantiation, diag::warn_var_template_missing)
5507 << Var;
5508 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5509 if (getLangOpts().CPlusPlus11)
5510 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
5511 }
5512 return;
5513 }
5514 }
5515
5516 // FIXME: We need to track the instantiation stack in order to know which
5517 // definitions should be visible within this instantiation.
5518 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
5519 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
67
Assuming the condition is false
5520 /*InstantiatedFromMember*/false,
5521 PatternDecl, Def, TSK,
5522 /*Complain*/DefinitionRequired))
5523 return;
5524
5525 // C++11 [temp.explicit]p10:
5526 // Except for inline functions, const variables of literal types, variables
5527 // of reference types, [...] explicit instantiation declarations
5528 // have the effect of suppressing the implicit instantiation of the entity
5529 // to which they refer.
5530 //
5531 // FIXME: That's not exactly the same as "might be usable in constant
5532 // expressions", which only allows constexpr variables and const integral
5533 // types, not arbitrary const literal types.
5534 if (TSK == TSK_ExplicitInstantiationDeclaration &&
68
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDeclaration
5535 !Var->mightBeUsableInConstantExpressions(getASTContext()))
5536 return;
5537
5538 // Make sure to pass the instantiated variable to the consumer at the end.
5539 struct PassToConsumerRAII {
5540 ASTConsumer &Consumer;
5541 VarDecl *Var;
5542
5543 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
5544 : Consumer(Consumer), Var(Var) { }
5545
5546 ~PassToConsumerRAII() {
5547 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
5548 }
5549 } PassToConsumerRAII(Consumer, Var);
5550
5551 // If we already have a definition, we're done.
5552 if (VarDecl *Def = Var->getDefinition()) {
69
Assuming 'Def' is null
70
Taking false branch
5553 // We may be explicitly instantiating something we've already implicitly
5554 // instantiated.
5555 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
5556 PointOfInstantiation);
5557 return;
5558 }
5559
5560 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5561 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
71
Assuming the condition is false
72
Assuming the condition is false
73
Taking false branch
5562 return;
5563 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5564 "instantiating variable definition");
5565
5566 // If we're performing recursive template instantiation, create our own
5567 // queue of pending implicit instantiations that we will instantiate later,
5568 // while we're still within our own instantiation context.
5569 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5570 /*Enabled=*/Recursive);
5571
5572 // Enter the scope of this instantiation. We don't use
5573 // PushDeclContext because we don't have a scope.
5574 ContextRAII PreviousContext(*this, Var->getDeclContext());
5575 LocalInstantiationScope Local(*this);
5576
5577 LocalEagerInstantiationScope LocalInstantiations(*this);
5578
5579 VarDecl *OldVar = Var;
5580 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
74
Called C++ object pointer is null
5581 // We're instantiating an inline static data member whose definition was
5582 // provided inside the class.
5583 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5584 } else if (!VarSpec) {
5585 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
5586 TemplateArgs));
5587 } else if (Var->isStaticDataMember() &&
5588 Var->getLexicalDeclContext()->isRecord()) {
5589 // We need to instantiate the definition of a static data member template,
5590 // and all we have is the in-class declaration of it. Instantiate a separate
5591 // declaration of the definition.
5592 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
5593 TemplateArgs);
5594
5595 TemplateArgumentListInfo TemplateArgInfo;
5596 if (const ASTTemplateArgumentListInfo *ArgInfo =
5597 VarSpec->getTemplateArgsInfo()) {
5598 TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
5599 TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
5600 for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
5601 TemplateArgInfo.addArgument(Arg);
5602 }
5603
5604 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
5605 VarSpec->getSpecializedTemplate(), Def, TemplateArgInfo,
5606 VarSpec->getTemplateArgs().asArray(), VarSpec));
5607 if (Var) {
5608 llvm::PointerUnion<VarTemplateDecl *,
5609 VarTemplatePartialSpecializationDecl *> PatternPtr =
5610 VarSpec->getSpecializedTemplateOrPartial();
5611 if (VarTemplatePartialSpecializationDecl *Partial =
5612 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
5613 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
5614 Partial, &VarSpec->getTemplateInstantiationArgs());
5615
5616 // Attach the initializer.
5617 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5618 }
5619 } else
5620 // Complete the existing variable's definition with an appropriately
5621 // substituted type and initializer.
5622 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
5623
5624 PreviousContext.pop();
5625
5626 if (Var) {
5627 PassToConsumerRAII.Var = Var;
5628 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
5629 OldVar->getPointOfInstantiation());
5630 }
5631
5632 // This variable may have local implicit instantiations that need to be
5633 // instantiated within this scope.
5634 LocalInstantiations.perform();
5635 Local.Exit();
5636 GlobalInstantiations.perform();
5637}
5638
5639void
5640Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
5641 const CXXConstructorDecl *Tmpl,
5642 const MultiLevelTemplateArgumentList &TemplateArgs) {
5643
5644 SmallVector<CXXCtorInitializer*, 4> NewInits;
5645 bool AnyErrors = Tmpl->isInvalidDecl();
5646
5647 // Instantiate all the initializers.
5648 for (const auto *Init : Tmpl->inits()) {
5649 // Only instantiate written initializers, let Sema re-construct implicit
5650 // ones.
5651 if (!Init->isWritten())
5652 continue;
5653
5654 SourceLocation EllipsisLoc;
5655
5656 if (Init->isPackExpansion()) {
5657 // This is a pack expansion. We should expand it now.
5658 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
5659 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5660 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
5661 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
5662 bool ShouldExpand = false;
5663 bool RetainExpansion = false;
5664 std::optional<unsigned> NumExpansions;
5665 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
5666 BaseTL.getSourceRange(),
5667 Unexpanded,
5668 TemplateArgs, ShouldExpand,
5669 RetainExpansion,
5670 NumExpansions)) {
5671 AnyErrors = true;
5672 New->setInvalidDecl();
5673 continue;
5674 }
5675 assert(ShouldExpand && "Partial instantiation of base initializer?")(static_cast <bool> (ShouldExpand && "Partial instantiation of base initializer?"
) ? void (0) : __assert_fail ("ShouldExpand && \"Partial instantiation of base initializer?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5675, __extension__
__PRETTY_FUNCTION__))
;
5676
5677 // Loop over all of the arguments in the argument pack(s),
5678 for (unsigned I = 0; I != *NumExpansions; ++I) {
5679 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
5680
5681 // Instantiate the initializer.
5682 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5683 /*CXXDirectInit=*/true);
5684 if (TempInit.isInvalid()) {
5685 AnyErrors = true;
5686 break;
5687 }
5688
5689 // Instantiate the base type.
5690 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
5691 TemplateArgs,
5692 Init->getSourceLocation(),
5693 New->getDeclName());
5694 if (!BaseTInfo) {
5695 AnyErrors = true;
5696 break;
5697 }
5698
5699 // Build the initializer.
5700 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
5701 BaseTInfo, TempInit.get(),
5702 New->getParent(),
5703 SourceLocation());
5704 if (NewInit.isInvalid()) {
5705 AnyErrors = true;
5706 break;
5707 }
5708
5709 NewInits.push_back(NewInit.get());
5710 }
5711
5712 continue;
5713 }
5714
5715 // Instantiate the initializer.
5716 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5717 /*CXXDirectInit=*/true);
5718 if (TempInit.isInvalid()) {
5719 AnyErrors = true;
5720 continue;
5721 }
5722
5723 MemInitResult NewInit;
5724 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
5725 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
5726 TemplateArgs,
5727 Init->getSourceLocation(),
5728 New->getDeclName());
5729 if (!TInfo) {
5730 AnyErrors = true;
5731 New->setInvalidDecl();
5732 continue;
5733 }
5734
5735 if (Init->isBaseInitializer())
5736 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
5737 New->getParent(), EllipsisLoc);
5738 else
5739 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
5740 cast<CXXRecordDecl>(CurContext->getParent()));
5741 } else if (Init->isMemberInitializer()) {
5742 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
5743 Init->getMemberLocation(),
5744 Init->getMember(),
5745 TemplateArgs));
5746 if (!Member) {
5747 AnyErrors = true;
5748 New->setInvalidDecl();
5749 continue;
5750 }
5751
5752 NewInit = BuildMemberInitializer(Member, TempInit.get(),
5753 Init->getSourceLocation());
5754 } else if (Init->isIndirectMemberInitializer()) {
5755 IndirectFieldDecl *IndirectMember =
5756 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
5757 Init->getMemberLocation(),
5758 Init->getIndirectMember(), TemplateArgs));
5759
5760 if (!IndirectMember) {
5761 AnyErrors = true;
5762 New->setInvalidDecl();
5763 continue;
5764 }
5765
5766 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
5767 Init->getSourceLocation());
5768 }
5769
5770 if (NewInit.isInvalid()) {
5771 AnyErrors = true;
5772 New->setInvalidDecl();
5773 } else {
5774 NewInits.push_back(NewInit.get());
5775 }
5776 }
5777
5778 // Assign all the initializers to the new constructor.
5779 ActOnMemInitializers(New,
5780 /*FIXME: ColonLoc */
5781 SourceLocation(),
5782 NewInits,
5783 AnyErrors);
5784}
5785
5786// TODO: this could be templated if the various decl types used the
5787// same method name.
5788static bool isInstantiationOf(ClassTemplateDecl *Pattern,
5789 ClassTemplateDecl *Instance) {
5790 Pattern = Pattern->getCanonicalDecl();
5791
5792 do {
5793 Instance = Instance->getCanonicalDecl();
5794 if (Pattern == Instance) return true;
5795 Instance = Instance->getInstantiatedFromMemberTemplate();
5796 } while (Instance);
5797
5798 return false;
5799}
5800
5801static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
5802 FunctionTemplateDecl *Instance) {
5803 Pattern = Pattern->getCanonicalDecl();
5804
5805 do {
5806 Instance = Instance->getCanonicalDecl();
5807 if (Pattern == Instance) return true;
5808 Instance = Instance->getInstantiatedFromMemberTemplate();
5809 } while (Instance);
5810
5811 return false;
5812}
5813
5814static bool
5815isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
5816 ClassTemplatePartialSpecializationDecl *Instance) {
5817 Pattern
5818 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
5819 do {
5820 Instance = cast<ClassTemplatePartialSpecializationDecl>(
5821 Instance->getCanonicalDecl());
5822 if (Pattern == Instance)
5823 return true;
5824 Instance = Instance->getInstantiatedFromMember();
5825 } while (Instance);
5826
5827 return false;
5828}
5829
5830static bool isInstantiationOf(CXXRecordDecl *Pattern,
5831 CXXRecordDecl *Instance) {
5832 Pattern = Pattern->getCanonicalDecl();
5833
5834 do {
5835 Instance = Instance->getCanonicalDecl();
5836 if (Pattern == Instance) return true;
5837 Instance = Instance->getInstantiatedFromMemberClass();
5838 } while (Instance);
5839
5840 return false;
5841}
5842
5843static bool isInstantiationOf(FunctionDecl *Pattern,
5844 FunctionDecl *Instance) {
5845 Pattern = Pattern->getCanonicalDecl();
5846
5847 do {
5848 Instance = Instance->getCanonicalDecl();
5849 if (Pattern == Instance) return true;
5850 Instance = Instance->getInstantiatedFromMemberFunction();
5851 } while (Instance);
5852
5853 return false;
5854}
5855
5856static bool isInstantiationOf(EnumDecl *Pattern,
5857 EnumDecl *Instance) {
5858 Pattern = Pattern->getCanonicalDecl();
5859
5860 do {
5861 Instance = Instance->getCanonicalDecl();
5862 if (Pattern == Instance) return true;
5863 Instance = Instance->getInstantiatedFromMemberEnum();
5864 } while (Instance);
5865
5866 return false;
5867}
5868
5869static bool isInstantiationOf(UsingShadowDecl *Pattern,
5870 UsingShadowDecl *Instance,
5871 ASTContext &C) {
5872 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
5873 Pattern);
5874}
5875
5876static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
5877 ASTContext &C) {
5878 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
5879}
5880
5881template<typename T>
5882static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
5883 ASTContext &Ctx) {
5884 // An unresolved using declaration can instantiate to an unresolved using
5885 // declaration, or to a using declaration or a using declaration pack.
5886 //
5887 // Multiple declarations can claim to be instantiated from an unresolved
5888 // using declaration if it's a pack expansion. We want the UsingPackDecl
5889 // in that case, not the individual UsingDecls within the pack.
5890 bool OtherIsPackExpansion;
5891 NamedDecl *OtherFrom;
5892 if (auto *OtherUUD = dyn_cast<T>(Other)) {
5893 OtherIsPackExpansion = OtherUUD->isPackExpansion();
5894 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
5895 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
5896 OtherIsPackExpansion = true;
5897 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
5898 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
5899 OtherIsPackExpansion = false;
5900 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
5901 } else {
5902 return false;
5903 }
5904 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
5905 declaresSameEntity(OtherFrom, Pattern);
5906}
5907
5908static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
5909 VarDecl *Instance) {
5910 assert(Instance->isStaticDataMember())(static_cast <bool> (Instance->isStaticDataMember())
? void (0) : __assert_fail ("Instance->isStaticDataMember()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5910, __extension__
__PRETTY_FUNCTION__))
;
5911
5912 Pattern = Pattern->getCanonicalDecl();
5913
5914 do {
5915 Instance = Instance->getCanonicalDecl();
5916 if (Pattern == Instance) return true;
5917 Instance = Instance->getInstantiatedFromStaticDataMember();
5918 } while (Instance);
5919
5920 return false;
5921}
5922
5923// Other is the prospective instantiation
5924// D is the prospective pattern
5925static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
5926 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
5927 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5928
5929 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
5930 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5931
5932 if (D->getKind() != Other->getKind())
5933 return false;
5934
5935 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
5936 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
5937
5938 if (auto *Function = dyn_cast<FunctionDecl>(Other))
5939 return isInstantiationOf(cast<FunctionDecl>(D), Function);
5940
5941 if (auto *Enum = dyn_cast<EnumDecl>(Other))
5942 return isInstantiationOf(cast<EnumDecl>(D), Enum);
5943
5944 if (auto *Var = dyn_cast<VarDecl>(Other))
5945 if (Var->isStaticDataMember())
5946 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
5947
5948 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
5949 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
5950
5951 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
5952 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
5953
5954 if (auto *PartialSpec =
5955 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
5956 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
5957 PartialSpec);
5958
5959 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
5960 if (!Field->getDeclName()) {
5961 // This is an unnamed field.
5962 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
5963 cast<FieldDecl>(D));
5964 }
5965 }
5966
5967 if (auto *Using = dyn_cast<UsingDecl>(Other))
5968 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
5969
5970 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
5971 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
5972
5973 return D->getDeclName() &&
5974 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
5975}
5976
5977template<typename ForwardIterator>
5978static NamedDecl *findInstantiationOf(ASTContext &Ctx,
5979 NamedDecl *D,
5980 ForwardIterator first,
5981 ForwardIterator last) {
5982 for (; first != last; ++first)
5983 if (isInstantiationOf(Ctx, D, *first))
5984 return cast<NamedDecl>(*first);
5985
5986 return nullptr;
5987}
5988
5989/// Finds the instantiation of the given declaration context
5990/// within the current instantiation.
5991///
5992/// \returns NULL if there was an error
5993DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
5994 const MultiLevelTemplateArgumentList &TemplateArgs) {
5995 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
5996 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
5997 return cast_or_null<DeclContext>(ID);
5998 } else return DC;
5999}
6000
6001/// Determine whether the given context is dependent on template parameters at
6002/// level \p Level or below.
6003///
6004/// Sometimes we only substitute an inner set of template arguments and leave
6005/// the outer templates alone. In such cases, contexts dependent only on the
6006/// outer levels are not effectively dependent.
6007static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
6008 if (!DC->isDependentContext())
6009 return false;
6010 if (!Level)
6011 return true;
6012 return cast<Decl>(DC)->getTemplateDepth() > Level;
6013}
6014
6015/// Find the instantiation of the given declaration within the
6016/// current instantiation.
6017///
6018/// This routine is intended to be used when \p D is a declaration
6019/// referenced from within a template, that needs to mapped into the
6020/// corresponding declaration within an instantiation. For example,
6021/// given:
6022///
6023/// \code
6024/// template<typename T>
6025/// struct X {
6026/// enum Kind {
6027/// KnownValue = sizeof(T)
6028/// };
6029///
6030/// bool getKind() const { return KnownValue; }
6031/// };
6032///
6033/// template struct X<int>;
6034/// \endcode
6035///
6036/// In the instantiation of X<int>::getKind(), we need to map the \p
6037/// EnumConstantDecl for \p KnownValue (which refers to
6038/// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
6039/// \p FindInstantiatedDecl performs this mapping from within the instantiation
6040/// of X<int>.
6041NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6042 const MultiLevelTemplateArgumentList &TemplateArgs,
6043 bool FindingInstantiatedContext) {
6044 DeclContext *ParentDC = D->getDeclContext();
6045 // Determine whether our parent context depends on any of the template
6046 // arguments we're currently substituting.
6047 bool ParentDependsOnArgs = isDependentContextAtLevel(
6048 ParentDC, TemplateArgs.getNumRetainedOuterLevels());
6049 // FIXME: Parameters of pointer to functions (y below) that are themselves
6050 // parameters (p below) can have their ParentDC set to the translation-unit
6051 // - thus we can not consistently check if the ParentDC of such a parameter
6052 // is Dependent or/and a FunctionOrMethod.
6053 // For e.g. this code, during Template argument deduction tries to
6054 // find an instantiated decl for (T y) when the ParentDC for y is
6055 // the translation unit.
6056 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6057 // float baz(float(*)()) { return 0.0; }
6058 // Foo(baz);
6059 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6060 // it gets here, always has a FunctionOrMethod as its ParentDC??
6061 // For now:
6062 // - as long as we have a ParmVarDecl whose parent is non-dependent and
6063 // whose type is not instantiation dependent, do nothing to the decl
6064 // - otherwise find its instantiated decl.
6065 if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
6066 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
6067 return D;
6068 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
6069 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
6070 (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
6071 isa<OMPDeclareReductionDecl>(ParentDC) ||
6072 isa<OMPDeclareMapperDecl>(ParentDC))) ||
6073 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
6074 cast<CXXRecordDecl>(D)->getTemplateDepth() >
6075 TemplateArgs.getNumRetainedOuterLevels())) {
6076 // D is a local of some kind. Look into the map of local
6077 // declarations to their instantiations.
6078 if (CurrentInstantiationScope) {
6079 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
6080 if (Decl *FD = Found->dyn_cast<Decl *>())
6081 return cast<NamedDecl>(FD);
6082
6083 int PackIdx = ArgumentPackSubstitutionIndex;
6084 assert(PackIdx != -1 &&(static_cast <bool> (PackIdx != -1 && "found declaration pack but not pack expanding"
) ? void (0) : __assert_fail ("PackIdx != -1 && \"found declaration pack but not pack expanding\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6085, __extension__
__PRETTY_FUNCTION__))
6085 "found declaration pack but not pack expanding")(static_cast <bool> (PackIdx != -1 && "found declaration pack but not pack expanding"
) ? void (0) : __assert_fail ("PackIdx != -1 && \"found declaration pack but not pack expanding\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6085, __extension__
__PRETTY_FUNCTION__))
;
6086 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
6087 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
6088 }
6089 }
6090
6091 // If we're performing a partial substitution during template argument
6092 // deduction, we may not have values for template parameters yet. They
6093 // just map to themselves.
6094 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
6095 isa<TemplateTemplateParmDecl>(D))
6096 return D;
6097
6098 if (D->isInvalidDecl())
6099 return nullptr;
6100
6101 // Normally this function only searches for already instantiated declaration
6102 // however we have to make an exclusion for local types used before
6103 // definition as in the code:
6104 //
6105 // template<typename T> void f1() {
6106 // void g1(struct x1);
6107 // struct x1 {};
6108 // }
6109 //
6110 // In this case instantiation of the type of 'g1' requires definition of
6111 // 'x1', which is defined later. Error recovery may produce an enum used
6112 // before definition. In these cases we need to instantiate relevant
6113 // declarations here.
6114 bool NeedInstantiate = false;
6115 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6116 NeedInstantiate = RD->isLocalClass();
6117 else if (isa<TypedefNameDecl>(D) &&
6118 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
6119 NeedInstantiate = true;
6120 else
6121 NeedInstantiate = isa<EnumDecl>(D);
6122 if (NeedInstantiate) {
6123 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6124 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6125 return cast<TypeDecl>(Inst);
6126 }
6127
6128 // If we didn't find the decl, then we must have a label decl that hasn't
6129 // been found yet. Lazily instantiate it and return it now.
6130 assert(isa<LabelDecl>(D))(static_cast <bool> (isa<LabelDecl>(D)) ? void (0
) : __assert_fail ("isa<LabelDecl>(D)", "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 6130, __extension__ __PRETTY_FUNCTION__))
;
6131
6132 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6133 assert(Inst && "Failed to instantiate label??")(static_cast <bool> (Inst && "Failed to instantiate label??"
) ? void (0) : __assert_fail ("Inst && \"Failed to instantiate label??\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6133, __extension__
__PRETTY_FUNCTION__))
;
6134
6135 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6136 return cast<LabelDecl>(Inst);
6137 }
6138
6139 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
6140 if (!Record->isDependentContext())
6141 return D;
6142
6143 // Determine whether this record is the "templated" declaration describing
6144 // a class template or class template partial specialization.
6145 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
6146 if (ClassTemplate)
6147 ClassTemplate = ClassTemplate->getCanonicalDecl();
6148 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
6149 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
6150 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
6151
6152 // Walk the current context to find either the record or an instantiation of
6153 // it.
6154 DeclContext *DC = CurContext;
6155 while (!DC->isFileContext()) {
6156 // If we're performing substitution while we're inside the template
6157 // definition, we'll find our own context. We're done.
6158 if (DC->Equals(Record))
6159 return Record;
6160
6161 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
6162 // Check whether we're in the process of instantiating a class template
6163 // specialization of the template we're mapping.
6164 if (ClassTemplateSpecializationDecl *InstSpec
6165 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
6166 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
6167 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
6168 return InstRecord;
6169 }
6170
6171 // Check whether we're in the process of instantiating a member class.
6172 if (isInstantiationOf(Record, InstRecord))
6173 return InstRecord;
6174 }
6175
6176 // Move to the outer template scope.
6177 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
6178 if (FD->getFriendObjectKind() &&
6179 FD->getNonTransparentDeclContext()->isFileContext()) {
6180 DC = FD->getLexicalDeclContext();
6181 continue;
6182 }
6183 // An implicit deduction guide acts as if it's within the class template
6184 // specialization described by its name and first N template params.
6185 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
6186 if (Guide && Guide->isImplicit()) {
6187 TemplateDecl *TD = Guide->getDeducedTemplate();
6188 // Convert the arguments to an "as-written" list.
6189 TemplateArgumentListInfo Args(Loc, Loc);
6190 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
6191 TD->getTemplateParameters()->size())) {
6192 ArrayRef<TemplateArgument> Unpacked(Arg);
6193 if (Arg.getKind() == TemplateArgument::Pack)
6194 Unpacked = Arg.pack_elements();
6195 for (TemplateArgument UnpackedArg : Unpacked)
6196 Args.addArgument(
6197 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
6198 }
6199 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
6200 if (T.isNull())
6201 return nullptr;
6202 auto *SubstRecord = T->getAsCXXRecordDecl();
6203 assert(SubstRecord && "class template id not a class type?")(static_cast <bool> (SubstRecord && "class template id not a class type?"
) ? void (0) : __assert_fail ("SubstRecord && \"class template id not a class type?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6203, __extension__
__PRETTY_FUNCTION__))
;
6204 // Check that this template-id names the primary template and not a
6205 // partial or explicit specialization. (In the latter cases, it's
6206 // meaningless to attempt to find an instantiation of D within the
6207 // specialization.)
6208 // FIXME: The standard doesn't say what should happen here.
6209 if (FindingInstantiatedContext &&
6210 usesPartialOrExplicitSpecialization(
6211 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
6212 Diag(Loc, diag::err_specialization_not_primary_template)
6213 << T << (SubstRecord->getTemplateSpecializationKind() ==
6214 TSK_ExplicitSpecialization);
6215 return nullptr;
6216 }
6217 DC = SubstRecord;
6218 continue;
6219 }
6220 }
6221
6222 DC = DC->getParent();
6223 }
6224
6225 // Fall through to deal with other dependent record types (e.g.,
6226 // anonymous unions in class templates).
6227 }
6228
6229 if (!ParentDependsOnArgs)
6230 return D;
6231
6232 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
6233 if (!ParentDC)
6234 return nullptr;
6235
6236 if (ParentDC != D->getDeclContext()) {
6237 // We performed some kind of instantiation in the parent context,
6238 // so now we need to look into the instantiated parent context to
6239 // find the instantiation of the declaration D.
6240
6241 // If our context used to be dependent, we may need to instantiate
6242 // it before performing lookup into that context.
6243 bool IsBeingInstantiated = false;
6244 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
6245 if (!Spec->isDependentContext()) {
6246 QualType T = Context.getTypeDeclType(Spec);
6247 const RecordType *Tag = T->getAs<RecordType>();
6248 assert(Tag && "type of non-dependent record is not a RecordType")(static_cast <bool> (Tag && "type of non-dependent record is not a RecordType"
) ? void (0) : __assert_fail ("Tag && \"type of non-dependent record is not a RecordType\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6248, __extension__
__PRETTY_FUNCTION__))
;
6249 if (Tag->isBeingDefined())
6250 IsBeingInstantiated = true;
6251 if (!Tag->isBeingDefined() &&
6252 RequireCompleteType(Loc, T, diag::err_incomplete_type))
6253 return nullptr;
6254
6255 ParentDC = Tag->getDecl();
6256 }
6257 }
6258
6259 NamedDecl *Result = nullptr;
6260 // FIXME: If the name is a dependent name, this lookup won't necessarily
6261 // find it. Does that ever matter?
6262 if (auto Name = D->getDeclName()) {
6263 DeclarationNameInfo NameInfo(Name, D->getLocation());
6264 DeclarationNameInfo NewNameInfo =
6265 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
6266 Name = NewNameInfo.getName();
6267 if (!Name)
6268 return nullptr;
6269 DeclContext::lookup_result Found = ParentDC->lookup(Name);
6270
6271 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
6272 } else {
6273 // Since we don't have a name for the entity we're looking for,
6274 // our only option is to walk through all of the declarations to
6275 // find that name. This will occur in a few cases:
6276 //
6277 // - anonymous struct/union within a template
6278 // - unnamed class/struct/union/enum within a template
6279 //
6280 // FIXME: Find a better way to find these instantiations!
6281 Result = findInstantiationOf(Context, D,
6282 ParentDC->decls_begin(),
6283 ParentDC->decls_end());
6284 }
6285
6286 if (!Result) {
6287 if (isa<UsingShadowDecl>(D)) {
6288 // UsingShadowDecls can instantiate to nothing because of using hiding.
6289 } else if (hasUncompilableErrorOccurred()) {
6290 // We've already complained about some ill-formed code, so most likely
6291 // this declaration failed to instantiate. There's no point in
6292 // complaining further, since this is normal in invalid code.
6293 // FIXME: Use more fine-grained 'invalid' tracking for this.
6294 } else if (IsBeingInstantiated) {
6295 // The class in which this member exists is currently being
6296 // instantiated, and we haven't gotten around to instantiating this
6297 // member yet. This can happen when the code uses forward declarations
6298 // of member classes, and introduces ordering dependencies via
6299 // template instantiation.
6300 Diag(Loc, diag::err_member_not_yet_instantiated)
6301 << D->getDeclName()
6302 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
6303 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
6304 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
6305 // This enumeration constant was found when the template was defined,
6306 // but can't be found in the instantiation. This can happen if an
6307 // unscoped enumeration member is explicitly specialized.
6308 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
6309 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
6310 TemplateArgs));
6311 assert(Spec->getTemplateSpecializationKind() ==(static_cast <bool> (Spec->getTemplateSpecializationKind
() == TSK_ExplicitSpecialization) ? void (0) : __assert_fail (
"Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6312, __extension__
__PRETTY_FUNCTION__))
6312 TSK_ExplicitSpecialization)(static_cast <bool> (Spec->getTemplateSpecializationKind
() == TSK_ExplicitSpecialization) ? void (0) : __assert_fail (
"Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6312, __extension__
__PRETTY_FUNCTION__))
;
6313 Diag(Loc, diag::err_enumerator_does_not_exist)
6314 << D->getDeclName()
6315 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
6316 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
6317 << Context.getTypeDeclType(Spec);
6318 } else {
6319 // We should have found something, but didn't.
6320 llvm_unreachable("Unable to find instantiation of declaration!")::llvm::llvm_unreachable_internal("Unable to find instantiation of declaration!"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6320)
;
6321 }
6322 }
6323
6324 D = Result;
6325 }
6326
6327 return D;
6328}
6329
6330/// Performs template instantiation for all implicit template
6331/// instantiations we have seen until this point.
6332void Sema::PerformPendingInstantiations(bool LocalOnly) {
6333 std::deque<PendingImplicitInstantiation> delayedPCHInstantiations;
6334 while (!PendingLocalImplicitInstantiations.empty() ||
35
Assuming the condition is false
37
Loop condition is true. Entering loop body
6335 (!LocalOnly
35.1
'LocalOnly' is false
35.1
'LocalOnly' is false
&& !PendingInstantiations.empty())) {
36
Assuming the condition is true
6336 PendingImplicitInstantiation Inst;
6337
6338 if (PendingLocalImplicitInstantiations.empty()) {
38
Assuming the condition is false
39
Taking false branch
6339 Inst = PendingInstantiations.front();
6340 PendingInstantiations.pop_front();
6341 } else {
6342 Inst = PendingLocalImplicitInstantiations.front();
6343 PendingLocalImplicitInstantiations.pop_front();
6344 }
6345
6346 // Instantiate function definitions
6347 if (FunctionDecl *Function
40.1
'Function' is null
40.1
'Function' is null
= dyn_cast<FunctionDecl>(Inst.first)) {
40
Assuming field 'first' is not a 'CastReturnType'
41
Taking false branch
6348 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
6349 TSK_ExplicitInstantiationDefinition;
6350 if (Function->isMultiVersion()) {
6351 getASTContext().forEachMultiversionedFunctionVersion(
6352 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
6353 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
1
Calling 'Sema::InstantiateFunctionDefinition'
6354 DefinitionRequired, true);
6355 if (CurFD->isDefined())
6356 CurFD->setInstantiationIsPending(false);
6357 });
6358 } else {
6359 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
6360 DefinitionRequired, true);
6361 if (Function->isDefined())
6362 Function->setInstantiationIsPending(false);
6363 }
6364 // Definition of a PCH-ed template declaration may be available only in the TU.
6365 if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
6366 TUKind == TU_Prefix && Function->instantiationIsPending())
6367 delayedPCHInstantiations.push_back(Inst);
6368 continue;
6369 }
6370
6371 // Instantiate variable definitions
6372 VarDecl *Var = cast<VarDecl>(Inst.first);
42
Field 'first' is a 'CastReturnType'
6373
6374 assert((Var->isStaticDataMember() ||(static_cast <bool> ((Var->isStaticDataMember() || isa
<VarTemplateSpecializationDecl>(Var)) && "Not a static data member, nor a variable template"
" specialization?") ? void (0) : __assert_fail ("(Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl>(Var)) && \"Not a static data member, nor a variable template\" \" specialization?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6377, __extension__
__PRETTY_FUNCTION__))
43
Assuming 'Var' is a 'class clang::VarTemplateSpecializationDecl &'
44
'?' condition is true
6375 isa<VarTemplateSpecializationDecl>(Var)) &&(static_cast <bool> ((Var->isStaticDataMember() || isa
<VarTemplateSpecializationDecl>(Var)) && "Not a static data member, nor a variable template"
" specialization?") ? void (0) : __assert_fail ("(Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl>(Var)) && \"Not a static data member, nor a variable template\" \" specialization?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6377, __extension__
__PRETTY_FUNCTION__))
6376 "Not a static data member, nor a variable template"(static_cast <bool> ((Var->isStaticDataMember() || isa
<VarTemplateSpecializationDecl>(Var)) && "Not a static data member, nor a variable template"
" specialization?") ? void (0) : __assert_fail ("(Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl>(Var)) && \"Not a static data member, nor a variable template\" \" specialization?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6377, __extension__
__PRETTY_FUNCTION__))
6377 " specialization?")(static_cast <bool> ((Var->isStaticDataMember() || isa
<VarTemplateSpecializationDecl>(Var)) && "Not a static data member, nor a variable template"
" specialization?") ? void (0) : __assert_fail ("(Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl>(Var)) && \"Not a static data member, nor a variable template\" \" specialization?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6377, __extension__
__PRETTY_FUNCTION__))
;
6378
6379 // Don't try to instantiate declarations if the most recent redeclaration
6380 // is invalid.
6381 if (Var->getMostRecentDecl()->isInvalidDecl())
45
Assuming the condition is false
46
Taking false branch
6382 continue;
6383
6384 // Check if the most recent declaration has changed the specialization kind
6385 // and removed the need for implicit instantiation.
6386 switch (Var->getMostRecentDecl()
47
Control jumps to 'case TSK_ImplicitInstantiation:' at line 6399
6387 ->getTemplateSpecializationKindForInstantiation()) {
6388 case TSK_Undeclared:
6389 llvm_unreachable("Cannot instantitiate an undeclared specialization.")::llvm::llvm_unreachable_internal("Cannot instantitiate an undeclared specialization."
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6389)
;
6390 case TSK_ExplicitInstantiationDeclaration:
6391 case TSK_ExplicitSpecialization:
6392 continue; // No longer need to instantiate this type.
6393 case TSK_ExplicitInstantiationDefinition:
6394 // We only need an instantiation if the pending instantiation *is* the
6395 // explicit instantiation.
6396 if (Var != Var->getMostRecentDecl())
6397 continue;
6398 break;
6399 case TSK_ImplicitInstantiation:
6400 break;
6401 }
6402
6403 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
48
Execution continues on line 6403
6404 "instantiating variable definition");
6405 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
49
Assuming the condition is false
6406 TSK_ExplicitInstantiationDefinition;
6407
6408 // Instantiate static data member definitions or variable template
6409 // specializations.
6410 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
50
Calling 'Sema::InstantiateVariableDefinition'
6411 DefinitionRequired, true);
6412 }
6413
6414 if (!LocalOnly && LangOpts.PCHInstantiateTemplates)
6415 PendingInstantiations.swap(delayedPCHInstantiations);
6416}
6417
6418void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
6419 const MultiLevelTemplateArgumentList &TemplateArgs) {
6420 for (auto *DD : Pattern->ddiags()) {
6421 switch (DD->getKind()) {
6422 case DependentDiagnostic::Access:
6423 HandleDependentAccessCheck(*DD, TemplateArgs);
6424 break;
6425 }
6426 }
6427}

/build/source/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Availability.h"
21#include "clang/AST/ComparisonCategories.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprConcepts.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/AST/LocInfoType.h"
31#include "clang/AST/MangleNumberingContext.h"
32#include "clang/AST/NSAPI.h"
33#include "clang/AST/PrettyPrinter.h"
34#include "clang/AST/StmtCXX.h"
35#include "clang/AST/StmtOpenMP.h"
36#include "clang/AST/TypeLoc.h"
37#include "clang/AST/TypeOrdering.h"
38#include "clang/Basic/BitmaskEnum.h"
39#include "clang/Basic/Builtins.h"
40#include "clang/Basic/DarwinSDKInfo.h"
41#include "clang/Basic/ExpressionTraits.h"
42#include "clang/Basic/Module.h"
43#include "clang/Basic/OpenCLOptions.h"
44#include "clang/Basic/OpenMPKinds.h"
45#include "clang/Basic/PragmaKinds.h"
46#include "clang/Basic/Specifiers.h"
47#include "clang/Basic/TemplateKinds.h"
48#include "clang/Basic/TypeTraits.h"
49#include "clang/Sema/AnalysisBasedWarnings.h"
50#include "clang/Sema/CleanupInfo.h"
51#include "clang/Sema/DeclSpec.h"
52#include "clang/Sema/ExternalSemaSource.h"
53#include "clang/Sema/IdentifierResolver.h"
54#include "clang/Sema/ObjCMethodList.h"
55#include "clang/Sema/Ownership.h"
56#include "clang/Sema/Scope.h"
57#include "clang/Sema/SemaConcept.h"
58#include "clang/Sema/TypoCorrection.h"
59#include "clang/Sema/Weak.h"
60#include "llvm/ADT/ArrayRef.h"
61#include "llvm/ADT/SetVector.h"
62#include "llvm/ADT/SmallBitVector.h"
63#include "llvm/ADT/SmallPtrSet.h"
64#include "llvm/ADT/SmallSet.h"
65#include "llvm/ADT/SmallVector.h"
66#include "llvm/ADT/TinyPtrVector.h"
67#include "llvm/Frontend/OpenMP/OMPConstants.h"
68#include <deque>
69#include <memory>
70#include <optional>
71#include <string>
72#include <tuple>
73#include <vector>
74
75namespace llvm {
76 class APSInt;
77 template <typename ValueT, typename ValueInfoT> class DenseSet;
78 class SmallBitVector;
79 struct InlineAsmIdentifierInfo;
80}
81
82namespace clang {
83 class ADLResult;
84 class ASTConsumer;
85 class ASTContext;
86 class ASTMutationListener;
87 class ASTReader;
88 class ASTWriter;
89 class ArrayType;
90 class ParsedAttr;
91 class BindingDecl;
92 class BlockDecl;
93 class CapturedDecl;
94 class CXXBasePath;
95 class CXXBasePaths;
96 class CXXBindTemporaryExpr;
97 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
98 class CXXConstructorDecl;
99 class CXXConversionDecl;
100 class CXXDeleteExpr;
101 class CXXDestructorDecl;
102 class CXXFieldCollector;
103 class CXXMemberCallExpr;
104 class CXXMethodDecl;
105 class CXXScopeSpec;
106 class CXXTemporary;
107 class CXXTryStmt;
108 class CallExpr;
109 class ClassTemplateDecl;
110 class ClassTemplatePartialSpecializationDecl;
111 class ClassTemplateSpecializationDecl;
112 class VarTemplatePartialSpecializationDecl;
113 class CodeCompleteConsumer;
114 class CodeCompletionAllocator;
115 class CodeCompletionTUInfo;
116 class CodeCompletionResult;
117 class CoroutineBodyStmt;
118 class Decl;
119 class DeclAccessPair;
120 class DeclContext;
121 class DeclRefExpr;
122 class DeclaratorDecl;
123 class DeducedTemplateArgument;
124 class DependentDiagnostic;
125 class DesignatedInitExpr;
126 class Designation;
127 class EnableIfAttr;
128 class EnumConstantDecl;
129 class Expr;
130 class ExtVectorType;
131 class FormatAttr;
132 class FriendDecl;
133 class FunctionDecl;
134 class FunctionProtoType;
135 class FunctionTemplateDecl;
136 class ImplicitConversionSequence;
137 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
138 class InitListExpr;
139 class InitializationKind;
140 class InitializationSequence;
141 class InitializedEntity;
142 class IntegerLiteral;
143 class LabelStmt;
144 class LambdaExpr;
145 class LangOptions;
146 class LocalInstantiationScope;
147 class LookupResult;
148 class MacroInfo;
149 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
150 class ModuleLoader;
151 class MultiLevelTemplateArgumentList;
152 class NamedDecl;
153 class ObjCCategoryDecl;
154 class ObjCCategoryImplDecl;
155 class ObjCCompatibleAliasDecl;
156 class ObjCContainerDecl;
157 class ObjCImplDecl;
158 class ObjCImplementationDecl;
159 class ObjCInterfaceDecl;
160 class ObjCIvarDecl;
161 template <class T> class ObjCList;
162 class ObjCMessageExpr;
163 class ObjCMethodDecl;
164 class ObjCPropertyDecl;
165 class ObjCProtocolDecl;
166 class OMPThreadPrivateDecl;
167 class OMPRequiresDecl;
168 class OMPDeclareReductionDecl;
169 class OMPDeclareSimdDecl;
170 class OMPClause;
171 struct OMPVarListLocTy;
172 struct OverloadCandidate;
173 enum class OverloadCandidateParamOrder : char;
174 enum OverloadCandidateRewriteKind : unsigned;
175 class OverloadCandidateSet;
176 class OverloadExpr;
177 class ParenListExpr;
178 class ParmVarDecl;
179 class Preprocessor;
180 class PseudoDestructorTypeStorage;
181 class PseudoObjectExpr;
182 class QualType;
183 class StandardConversionSequence;
184 class Stmt;
185 class StringLiteral;
186 class SwitchStmt;
187 class TemplateArgument;
188 class TemplateArgumentList;
189 class TemplateArgumentLoc;
190 class TemplateDecl;
191 class TemplateInstantiationCallback;
192 class TemplateParameterList;
193 class TemplatePartialOrderingContext;
194 class TemplateTemplateParmDecl;
195 class Token;
196 class TypeAliasDecl;
197 class TypedefDecl;
198 class TypedefNameDecl;
199 class TypeLoc;
200 class TypoCorrectionConsumer;
201 class UnqualifiedId;
202 class UnresolvedLookupExpr;
203 class UnresolvedMemberExpr;
204 class UnresolvedSetImpl;
205 class UnresolvedSetIterator;
206 class UsingDecl;
207 class UsingShadowDecl;
208 class ValueDecl;
209 class VarDecl;
210 class VarTemplateSpecializationDecl;
211 class VisibilityAttr;
212 class VisibleDeclConsumer;
213 class IndirectFieldDecl;
214 struct DeductionFailureInfo;
215 class TemplateSpecCandidateSet;
216
217namespace sema {
218 class AccessedEntity;
219 class BlockScopeInfo;
220 class Capture;
221 class CapturedRegionScopeInfo;
222 class CapturingScopeInfo;
223 class CompoundScopeInfo;
224 class DelayedDiagnostic;
225 class DelayedDiagnosticPool;
226 class FunctionScopeInfo;
227 class LambdaScopeInfo;
228 class PossiblyUnreachableDiag;
229 class RISCVIntrinsicManager;
230 class SemaPPCallbacks;
231 class TemplateDeductionInfo;
232}
233
234namespace threadSafety {
235 class BeforeSet;
236 void threadSafetyCleanup(BeforeSet* Cache);
237}
238
239// FIXME: No way to easily map from TemplateTypeParmTypes to
240// TemplateTypeParmDecls, so we have this horrible PointerUnion.
241typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *>,
242 SourceLocation>
243 UnexpandedParameterPack;
244
245/// Describes whether we've seen any nullability information for the given
246/// file.
247struct FileNullability {
248 /// The first pointer declarator (of any pointer kind) in the file that does
249 /// not have a corresponding nullability annotation.
250 SourceLocation PointerLoc;
251
252 /// The end location for the first pointer declarator in the file. Used for
253 /// placing fix-its.
254 SourceLocation PointerEndLoc;
255
256 /// Which kind of pointer declarator we saw.
257 uint8_t PointerKind;
258
259 /// Whether we saw any type nullability annotations in the given file.
260 bool SawTypeNullability = false;
261};
262
263/// A mapping from file IDs to a record of whether we've seen nullability
264/// information in that file.
265class FileNullabilityMap {
266 /// A mapping from file IDs to the nullability information for each file ID.
267 llvm::DenseMap<FileID, FileNullability> Map;
268
269 /// A single-element cache based on the file ID.
270 struct {
271 FileID File;
272 FileNullability Nullability;
273 } Cache;
274
275public:
276 FileNullability &operator[](FileID file) {
277 // Check the single-element cache.
278 if (file == Cache.File)
279 return Cache.Nullability;
280
281 // It's not in the single-element cache; flush the cache if we have one.
282 if (!Cache.File.isInvalid()) {
283 Map[Cache.File] = Cache.Nullability;
284 }
285
286 // Pull this entry into the cache.
287 Cache.File = file;
288 Cache.Nullability = Map[file];
289 return Cache.Nullability;
290 }
291};
292
293/// Tracks expected type during expression parsing, for use in code completion.
294/// The type is tied to a particular token, all functions that update or consume
295/// the type take a start location of the token they are looking at as a
296/// parameter. This avoids updating the type on hot paths in the parser.
297class PreferredTypeBuilder {
298public:
299 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
300
301 void enterCondition(Sema &S, SourceLocation Tok);
302 void enterReturn(Sema &S, SourceLocation Tok);
303 void enterVariableInit(SourceLocation Tok, Decl *D);
304 /// Handles e.g. BaseType{ .D = Tok...
305 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
306 const Designation &D);
307 /// Computing a type for the function argument may require running
308 /// overloading, so we postpone its computation until it is actually needed.
309 ///
310 /// Clients should be very careful when using this function, as it stores a
311 /// function_ref, clients should make sure all calls to get() with the same
312 /// location happen while function_ref is alive.
313 ///
314 /// The callback should also emit signature help as a side-effect, but only
315 /// if the completion point has been reached.
316 void enterFunctionArgument(SourceLocation Tok,
317 llvm::function_ref<QualType()> ComputeType);
318
319 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
320 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
321 SourceLocation OpLoc);
322 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
323 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
324 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
325 /// Handles all type casts, including C-style cast, C++ casts, etc.
326 void enterTypeCast(SourceLocation Tok, QualType CastType);
327
328 /// Get the expected type associated with this location, if any.
329 ///
330 /// If the location is a function argument, determining the expected type
331 /// involves considering all function overloads and the arguments so far.
332 /// In this case, signature help for these function overloads will be reported
333 /// as a side-effect (only if the completion point has been reached).
334 QualType get(SourceLocation Tok) const {
335 if (!Enabled || Tok != ExpectedLoc)
336 return QualType();
337 if (!Type.isNull())
338 return Type;
339 if (ComputeType)
340 return ComputeType();
341 return QualType();
342 }
343
344private:
345 bool Enabled;
346 /// Start position of a token for which we store expected type.
347 SourceLocation ExpectedLoc;
348 /// Expected type for a token starting at ExpectedLoc.
349 QualType Type;
350 /// A function to compute expected type at ExpectedLoc. It is only considered
351 /// if Type is null.
352 llvm::function_ref<QualType()> ComputeType;
353};
354
355/// Sema - This implements semantic analysis and AST building for C.
356class Sema final {
357 Sema(const Sema &) = delete;
358 void operator=(const Sema &) = delete;
359
360 ///Source of additional semantic information.
361 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
362
363 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
364
365 /// Determine whether two declarations should be linked together, given that
366 /// the old declaration might not be visible and the new declaration might
367 /// not have external linkage.
368 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
369 const NamedDecl *New) {
370 if (isVisible(Old))
371 return true;
372 // See comment in below overload for why it's safe to compute the linkage
373 // of the new declaration here.
374 if (New->isExternallyDeclarable()) {
375 assert(Old->isExternallyDeclarable() &&(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "clang/include/clang/Sema/Sema.h", 376, __extension__ __PRETTY_FUNCTION__
))
376 "should not have found a non-externally-declarable previous decl")(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "clang/include/clang/Sema/Sema.h", 376, __extension__ __PRETTY_FUNCTION__
))
;
377 return true;
378 }
379 return false;
380 }
381 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
382
383 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
384 QualType ResultTy,
385 ArrayRef<QualType> Args);
386
387public:
388 /// The maximum alignment, same as in llvm::Value. We duplicate them here
389 /// because that allows us not to duplicate the constants in clang code,
390 /// which we must to since we can't directly use the llvm constants.
391 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
392 ///
393 /// This is the greatest alignment value supported by load, store, and alloca
394 /// instructions, and global values.
395 static const unsigned MaxAlignmentExponent = 32;
396 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
397
398 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
399 typedef OpaquePtr<TemplateName> TemplateTy;
400 typedef OpaquePtr<QualType> TypeTy;
401
402 OpenCLOptions OpenCLFeatures;
403 FPOptions CurFPFeatures;
404
405 const LangOptions &LangOpts;
406 Preprocessor &PP;
407 ASTContext &Context;
408 ASTConsumer &Consumer;
409 DiagnosticsEngine &Diags;
410 SourceManager &SourceMgr;
411
412 /// Flag indicating whether or not to collect detailed statistics.
413 bool CollectStats;
414
415 /// Code-completion consumer.
416 CodeCompleteConsumer *CodeCompleter;
417
418 /// CurContext - This is the current declaration context of parsing.
419 DeclContext *CurContext;
420
421 /// Generally null except when we temporarily switch decl contexts,
422 /// like in \see ActOnObjCTemporaryExitContainerContext.
423 DeclContext *OriginalLexicalContext;
424
425 /// VAListTagName - The declaration name corresponding to __va_list_tag.
426 /// This is used as part of a hack to omit that class from ADL results.
427 DeclarationName VAListTagName;
428
429 bool MSStructPragmaOn; // True when \#pragma ms_struct on
430
431 /// Controls member pointer representation format under the MS ABI.
432 LangOptions::PragmaMSPointersToMembersKind
433 MSPointerToMemberRepresentationMethod;
434
435 /// Stack of active SEH __finally scopes. Can be empty.
436 SmallVector<Scope*, 2> CurrentSEHFinally;
437
438 /// Source location for newly created implicit MSInheritanceAttrs
439 SourceLocation ImplicitMSInheritanceAttrLoc;
440
441 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
442 /// `TransformTypos` in order to keep track of any TypoExprs that are created
443 /// recursively during typo correction and wipe them away if the correction
444 /// fails.
445 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
446
447 /// pragma clang section kind
448 enum PragmaClangSectionKind {
449 PCSK_Invalid = 0,
450 PCSK_BSS = 1,
451 PCSK_Data = 2,
452 PCSK_Rodata = 3,
453 PCSK_Text = 4,
454 PCSK_Relro = 5
455 };
456
457 enum PragmaClangSectionAction {
458 PCSA_Set = 0,
459 PCSA_Clear = 1
460 };
461
462 struct PragmaClangSection {
463 std::string SectionName;
464 bool Valid = false;
465 SourceLocation PragmaLocation;
466 };
467
468 PragmaClangSection PragmaClangBSSSection;
469 PragmaClangSection PragmaClangDataSection;
470 PragmaClangSection PragmaClangRodataSection;
471 PragmaClangSection PragmaClangRelroSection;
472 PragmaClangSection PragmaClangTextSection;
473
474 enum PragmaMsStackAction {
475 PSK_Reset = 0x0, // #pragma ()
476 PSK_Set = 0x1, // #pragma (value)
477 PSK_Push = 0x2, // #pragma (push[, id])
478 PSK_Pop = 0x4, // #pragma (pop[, id])
479 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
480 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
481 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
482 };
483
484 struct PragmaPackInfo {
485 PragmaMsStackAction Action;
486 StringRef SlotLabel;
487 Token Alignment;
488 };
489
490 // #pragma pack and align.
491 class AlignPackInfo {
492 public:
493 // `Native` represents default align mode, which may vary based on the
494 // platform.
495 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
496
497 // #pragma pack info constructor
498 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
499 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
500 assert(Num == PackNumber && "The pack number has been truncated.")(static_cast <bool> (Num == PackNumber && "The pack number has been truncated."
) ? void (0) : __assert_fail ("Num == PackNumber && \"The pack number has been truncated.\""
, "clang/include/clang/Sema/Sema.h", 500, __extension__ __PRETTY_FUNCTION__
))
;
501 }
502
503 // #pragma align info constructor
504 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
505 : PackAttr(false), AlignMode(M),
506 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
507
508 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
509
510 AlignPackInfo() : AlignPackInfo(Native, false) {}
511
512 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
513 // integer encoding for it. This should only be passed to
514 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
515 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
516 std::uint32_t Encoding{};
517 if (Info.IsXLStack())
518 Encoding |= IsXLMask;
519
520 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
521
522 if (Info.IsPackAttr())
523 Encoding |= PackAttrMask;
524
525 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
526
527 return Encoding;
528 }
529
530 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
531 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
532 AlignPackInfo::Mode M =
533 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
534 int PackNumber = (Encoding & PackNumMask) >> 4;
535
536 if (Encoding & PackAttrMask)
537 return AlignPackInfo(M, PackNumber, IsXL);
538
539 return AlignPackInfo(M, IsXL);
540 }
541
542 bool IsPackAttr() const { return PackAttr; }
543
544 bool IsAlignAttr() const { return !PackAttr; }
545
546 Mode getAlignMode() const { return AlignMode; }
547
548 unsigned getPackNumber() const { return PackNumber; }
549
550 bool IsPackSet() const {
551 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
552 // attriute on a decl.
553 return PackNumber != UninitPackVal && PackNumber != 0;
554 }
555
556 bool IsXLStack() const { return XLStack; }
557
558 bool operator==(const AlignPackInfo &Info) const {
559 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
560 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
561 Info.XLStack);
562 }
563
564 bool operator!=(const AlignPackInfo &Info) const {
565 return !(*this == Info);
566 }
567
568 private:
569 /// \brief True if this is a pragma pack attribute,
570 /// not a pragma align attribute.
571 bool PackAttr;
572
573 /// \brief The alignment mode that is in effect.
574 Mode AlignMode;
575
576 /// \brief The pack number of the stack.
577 unsigned char PackNumber;
578
579 /// \brief True if it is a XL #pragma align/pack stack.
580 bool XLStack;
581
582 /// \brief Uninitialized pack value.
583 static constexpr unsigned char UninitPackVal = -1;
584
585 // Masks to encode and decode an AlignPackInfo.
586 static constexpr uint32_t IsXLMask{0x0000'0001};
587 static constexpr uint32_t AlignModeMask{0x0000'0006};
588 static constexpr uint32_t PackAttrMask{0x00000'0008};
589 static constexpr uint32_t PackNumMask{0x0000'01F0};
590 };
591
592 template<typename ValueType>
593 struct PragmaStack {
594 struct Slot {
595 llvm::StringRef StackSlotLabel;
596 ValueType Value;
597 SourceLocation PragmaLocation;
598 SourceLocation PragmaPushLocation;
599 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
600 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
601 : StackSlotLabel(StackSlotLabel), Value(Value),
602 PragmaLocation(PragmaLocation),
603 PragmaPushLocation(PragmaPushLocation) {}
604 };
605
606 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
607 llvm::StringRef StackSlotLabel, ValueType Value) {
608 if (Action == PSK_Reset) {
609 CurrentValue = DefaultValue;
610 CurrentPragmaLocation = PragmaLocation;
611 return;
612 }
613 if (Action & PSK_Push)
614 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
615 PragmaLocation);
616 else if (Action & PSK_Pop) {
617 if (!StackSlotLabel.empty()) {
618 // If we've got a label, try to find it and jump there.
619 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
620 return x.StackSlotLabel == StackSlotLabel;
621 });
622 // If we found the label so pop from there.
623 if (I != Stack.rend()) {
624 CurrentValue = I->Value;
625 CurrentPragmaLocation = I->PragmaLocation;
626 Stack.erase(std::prev(I.base()), Stack.end());
627 }
628 } else if (!Stack.empty()) {
629 // We do not have a label, just pop the last entry.
630 CurrentValue = Stack.back().Value;
631 CurrentPragmaLocation = Stack.back().PragmaLocation;
632 Stack.pop_back();
633 }
634 }
635 if (Action & PSK_Set) {
636 CurrentValue = Value;
637 CurrentPragmaLocation = PragmaLocation;
638 }
639 }
640
641 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
642 // method body to restore the stacks on exit, so it works like this:
643 //
644 // struct S {
645 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
646 // void Method {}
647 // #pragma <name>(pop, InternalPragmaSlot)
648 // };
649 //
650 // It works even with #pragma vtordisp, although MSVC doesn't support
651 // #pragma vtordisp(push [, id], n)
652 // syntax.
653 //
654 // Push / pop a named sentinel slot.
655 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
656 assert((Action == PSK_Push || Action == PSK_Pop) &&(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "clang/include/clang/Sema/Sema.h", 657, __extension__ __PRETTY_FUNCTION__
))
657 "Can only push / pop #pragma stack sentinels!")(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "clang/include/clang/Sema/Sema.h", 657, __extension__ __PRETTY_FUNCTION__
))
;
658 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
659 }
660
661 // Constructors.
662 explicit PragmaStack(const ValueType &Default)
663 : DefaultValue(Default), CurrentValue(Default) {}
664
665 bool hasValue() const { return CurrentValue != DefaultValue; }
666
667 SmallVector<Slot, 2> Stack;
668 ValueType DefaultValue; // Value used for PSK_Reset action.
669 ValueType CurrentValue;
670 SourceLocation CurrentPragmaLocation;
671 };
672 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
673 // we shouldn't do so if they're in a module).
674
675 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
676 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
677 ///
678 /// 0: Suppress all vtordisps
679 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
680 /// structors
681 /// 2: Always insert vtordisps to support RTTI on partially constructed
682 /// objects
683 PragmaStack<MSVtorDispMode> VtorDispStack;
684 PragmaStack<AlignPackInfo> AlignPackStack;
685 // The current #pragma align/pack values and locations at each #include.
686 struct AlignPackIncludeState {
687 AlignPackInfo CurrentValue;
688 SourceLocation CurrentPragmaLocation;
689 bool HasNonDefaultValue, ShouldWarnOnInclude;
690 };
691 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
692 // Segment #pragmas.
693 PragmaStack<StringLiteral *> DataSegStack;
694 PragmaStack<StringLiteral *> BSSSegStack;
695 PragmaStack<StringLiteral *> ConstSegStack;
696 PragmaStack<StringLiteral *> CodeSegStack;
697
698 // #pragma strict_gs_check.
699 PragmaStack<bool> StrictGuardStackCheckStack;
700
701 // This stack tracks the current state of Sema.CurFPFeatures.
702 PragmaStack<FPOptionsOverride> FpPragmaStack;
703 FPOptionsOverride CurFPFeatureOverrides() {
704 FPOptionsOverride result;
705 if (!FpPragmaStack.hasValue()) {
706 result = FPOptionsOverride();
707 } else {
708 result = FpPragmaStack.CurrentValue;
709 }
710 return result;
711 }
712
713 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
714 // Actions should be performed only if we enter / exit a C++ method body.
715 class PragmaStackSentinelRAII {
716 public:
717 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
718 ~PragmaStackSentinelRAII();
719
720 private:
721 Sema &S;
722 StringRef SlotLabel;
723 bool ShouldAct;
724 };
725
726 /// A mapping that describes the nullability we've seen in each header file.
727 FileNullabilityMap NullabilityMap;
728
729 /// Last section used with #pragma init_seg.
730 StringLiteral *CurInitSeg;
731 SourceLocation CurInitSegLoc;
732
733 /// Sections used with #pragma alloc_text.
734 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
735
736 /// VisContext - Manages the stack for \#pragma GCC visibility.
737 void *VisContext; // Really a "PragmaVisStack*"
738
739 /// This an attribute introduced by \#pragma clang attribute.
740 struct PragmaAttributeEntry {
741 SourceLocation Loc;
742 ParsedAttr *Attribute;
743 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
744 bool IsUsed;
745 };
746
747 /// A push'd group of PragmaAttributeEntries.
748 struct PragmaAttributeGroup {
749 /// The location of the push attribute.
750 SourceLocation Loc;
751 /// The namespace of this push group.
752 const IdentifierInfo *Namespace;
753 SmallVector<PragmaAttributeEntry, 2> Entries;
754 };
755
756 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
757
758 /// The declaration that is currently receiving an attribute from the
759 /// #pragma attribute stack.
760 const Decl *PragmaAttributeCurrentTargetDecl;
761
762 /// This represents the last location of a "#pragma clang optimize off"
763 /// directive if such a directive has not been closed by an "on" yet. If
764 /// optimizations are currently "on", this is set to an invalid location.
765 SourceLocation OptimizeOffPragmaLocation;
766
767 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
768 /// whether the optimizations in the list passed to the pragma should be
769 /// turned off or on. This boolean is true by default because command line
770 /// options are honored when `#pragma optimize("", on)`.
771 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
772 bool MSPragmaOptimizeIsOn = true;
773
774 /// Set of no-builtin functions listed by \#pragma function.
775 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
776
777 /// Flag indicating if Sema is building a recovery call expression.
778 ///
779 /// This flag is used to avoid building recovery call expressions
780 /// if Sema is already doing so, which would cause infinite recursions.
781 bool IsBuildingRecoveryCallExpr;
782
783 /// Used to control the generation of ExprWithCleanups.
784 CleanupInfo Cleanup;
785
786 /// ExprCleanupObjects - This is the stack of objects requiring
787 /// cleanup that are created by the current full expression.
788 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
789
790 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
791 /// to a variable (constant) that may or may not be odr-used in this Expr, and
792 /// we won't know until all lvalue-to-rvalue and discarded value conversions
793 /// have been applied to all subexpressions of the enclosing full expression.
794 /// This is cleared at the end of each full expression.
795 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
796 llvm::SmallPtrSet<Expr *, 4>>;
797 MaybeODRUseExprSet MaybeODRUseExprs;
798
799 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
800
801 /// Stack containing information about each of the nested
802 /// function, block, and method scopes that are currently active.
803 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
804
805 /// The index of the first FunctionScope that corresponds to the current
806 /// context.
807 unsigned FunctionScopesStart = 0;
808
809 /// Track the number of currently active capturing scopes.
810 unsigned CapturingFunctionScopes = 0;
811
812 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
813 return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart,
814 FunctionScopes.end());
815 }
816
817 /// Stack containing information needed when in C++2a an 'auto' is encountered
818 /// in a function declaration parameter type specifier in order to invent a
819 /// corresponding template parameter in the enclosing abbreviated function
820 /// template. This information is also present in LambdaScopeInfo, stored in
821 /// the FunctionScopes stack.
822 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
823
824 /// The index of the first InventedParameterInfo that refers to the current
825 /// context.
826 unsigned InventedParameterInfosStart = 0;
827
828 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
829 return llvm::ArrayRef(InventedParameterInfos.begin() +
830 InventedParameterInfosStart,
831 InventedParameterInfos.end());
832 }
833
834 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
835 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
836 ExtVectorDeclsType;
837
838 /// ExtVectorDecls - This is a list all the extended vector types. This allows
839 /// us to associate a raw vector type with one of the ext_vector type names.
840 /// This is only necessary for issuing pretty diagnostics.
841 ExtVectorDeclsType ExtVectorDecls;
842
843 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
844 std::unique_ptr<CXXFieldCollector> FieldCollector;
845
846 typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType;
847
848 /// Set containing all declared private fields that are not used.
849 NamedDeclSetType UnusedPrivateFields;
850
851 /// Set containing all typedefs that are likely unused.
852 llvm::SmallSetVector<const TypedefNameDecl *, 4>
853 UnusedLocalTypedefNameCandidates;
854
855 /// Delete-expressions to be analyzed at the end of translation unit
856 ///
857 /// This list contains class members, and locations of delete-expressions
858 /// that could not be proven as to whether they mismatch with new-expression
859 /// used in initializer of the field.
860 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
861 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
862 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
863
864 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
865
866 /// PureVirtualClassDiagSet - a set of class declarations which we have
867 /// emitted a list of pure virtual functions. Used to prevent emitting the
868 /// same list more than once.
869 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
870
871 /// ParsingInitForAutoVars - a set of declarations with auto types for which
872 /// we are currently parsing the initializer.
873 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
874
875 /// Look for a locally scoped extern "C" declaration by the given name.
876 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
877
878 typedef LazyVector<VarDecl *, ExternalSemaSource,
879 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
880 TentativeDefinitionsType;
881
882 /// All the tentative definitions encountered in the TU.
883 TentativeDefinitionsType TentativeDefinitions;
884
885 /// All the external declarations encoutered and used in the TU.
886 SmallVector<VarDecl *, 4> ExternalDeclarations;
887
888 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
889 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
890 UnusedFileScopedDeclsType;
891
892 /// The set of file scoped decls seen so far that have not been used
893 /// and must warn if not used. Only contains the first declaration.
894 UnusedFileScopedDeclsType UnusedFileScopedDecls;
895
896 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
897 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
898 DelegatingCtorDeclsType;
899
900 /// All the delegating constructors seen so far in the file, used for
901 /// cycle detection at the end of the TU.
902 DelegatingCtorDeclsType DelegatingCtorDecls;
903
904 /// All the overriding functions seen during a class definition
905 /// that had their exception spec checks delayed, plus the overridden
906 /// function.
907 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
908 DelayedOverridingExceptionSpecChecks;
909
910 /// All the function redeclarations seen during a class definition that had
911 /// their exception spec checks delayed, plus the prior declaration they
912 /// should be checked against. Except during error recovery, the new decl
913 /// should always be a friend declaration, as that's the only valid way to
914 /// redeclare a special member before its class is complete.
915 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
916 DelayedEquivalentExceptionSpecChecks;
917
918 typedef llvm::MapVector<const FunctionDecl *,
919 std::unique_ptr<LateParsedTemplate>>
920 LateParsedTemplateMapT;
921 LateParsedTemplateMapT LateParsedTemplateMap;
922
923 /// Callback to the parser to parse templated functions when needed.
924 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
925 typedef void LateTemplateParserCleanupCB(void *P);
926 LateTemplateParserCB *LateTemplateParser;
927 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
928 void *OpaqueParser;
929
930 void SetLateTemplateParser(LateTemplateParserCB *LTP,
931 LateTemplateParserCleanupCB *LTPCleanup,
932 void *P) {
933 LateTemplateParser = LTP;
934 LateTemplateParserCleanup = LTPCleanup;
935 OpaqueParser = P;
936 }
937
938 class DelayedDiagnostics;
939
940 class DelayedDiagnosticsState {
941 sema::DelayedDiagnosticPool *SavedPool;
942 friend class Sema::DelayedDiagnostics;
943 };
944 typedef DelayedDiagnosticsState ParsingDeclState;
945 typedef DelayedDiagnosticsState ProcessingContextState;
946
947 /// A class which encapsulates the logic for delaying diagnostics
948 /// during parsing and other processing.
949 class DelayedDiagnostics {
950 /// The current pool of diagnostics into which delayed
951 /// diagnostics should go.
952 sema::DelayedDiagnosticPool *CurPool = nullptr;
953
954 public:
955 DelayedDiagnostics() = default;
956
957 /// Adds a delayed diagnostic.
958 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
959
960 /// Determines whether diagnostics should be delayed.
961 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
962
963 /// Returns the current delayed-diagnostics pool.
964 sema::DelayedDiagnosticPool *getCurrentPool() const {
965 return CurPool;
966 }
967
968 /// Enter a new scope. Access and deprecation diagnostics will be
969 /// collected in this pool.
970 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
971 DelayedDiagnosticsState state;
972 state.SavedPool = CurPool;
973 CurPool = &pool;
974 return state;
975 }
976
977 /// Leave a delayed-diagnostic state that was previously pushed.
978 /// Do not emit any of the diagnostics. This is performed as part
979 /// of the bookkeeping of popping a pool "properly".
980 void popWithoutEmitting(DelayedDiagnosticsState state) {
981 CurPool = state.SavedPool;
982 }
983
984 /// Enter a new scope where access and deprecation diagnostics are
985 /// not delayed.
986 DelayedDiagnosticsState pushUndelayed() {
987 DelayedDiagnosticsState state;
988 state.SavedPool = CurPool;
989 CurPool = nullptr;
990 return state;
991 }
992
993 /// Undo a previous pushUndelayed().
994 void popUndelayed(DelayedDiagnosticsState state) {
995 assert(CurPool == nullptr)(static_cast <bool> (CurPool == nullptr) ? void (0) : __assert_fail
("CurPool == nullptr", "clang/include/clang/Sema/Sema.h", 995
, __extension__ __PRETTY_FUNCTION__))
;
996 CurPool = state.SavedPool;
997 }
998 } DelayedDiagnostics;
999
1000 /// A RAII object to temporarily push a declaration context.
1001 class ContextRAII {
1002 private:
1003 Sema &S;
1004 DeclContext *SavedContext;
1005 ProcessingContextState SavedContextState;
1006 QualType SavedCXXThisTypeOverride;
1007 unsigned SavedFunctionScopesStart;
1008 unsigned SavedInventedParameterInfosStart;
1009
1010 public:
1011 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
1012 : S(S), SavedContext(S.CurContext),
1013 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
1014 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
1015 SavedFunctionScopesStart(S.FunctionScopesStart),
1016 SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1017 {
1018 assert(ContextToPush && "pushing null context")(static_cast <bool> (ContextToPush && "pushing null context"
) ? void (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "clang/include/clang/Sema/Sema.h", 1018, __extension__ __PRETTY_FUNCTION__
))
;
1019 S.CurContext = ContextToPush;
1020 if (NewThisContext)
1021 S.CXXThisTypeOverride = QualType();
1022 // Any saved FunctionScopes do not refer to this context.
1023 S.FunctionScopesStart = S.FunctionScopes.size();
1024 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1025 }
1026
1027 void pop() {
1028 if (!SavedContext) return;
1029 S.CurContext = SavedContext;
1030 S.DelayedDiagnostics.popUndelayed(SavedContextState);
1031 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1032 S.FunctionScopesStart = SavedFunctionScopesStart;
1033 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1034 SavedContext = nullptr;
1035 }
1036
1037 ~ContextRAII() {
1038 pop();
1039 }
1040 };
1041
1042 /// Whether the AST is currently being rebuilt to correct immediate
1043 /// invocations. Immediate invocation candidates and references to consteval
1044 /// functions aren't tracked when this is set.
1045 bool RebuildingImmediateInvocation = false;
1046
1047 /// Used to change context to isConstantEvaluated without pushing a heavy
1048 /// ExpressionEvaluationContextRecord object.
1049 bool isConstantEvaluatedOverride;
1050
1051 bool isConstantEvaluated() const {
1052 return ExprEvalContexts.back().isConstantEvaluated() ||
1053 isConstantEvaluatedOverride;
1054 }
1055
1056 /// RAII object to handle the state changes required to synthesize
1057 /// a function body.
1058 class SynthesizedFunctionScope {
1059 Sema &S;
1060 Sema::ContextRAII SavedContext;
1061 bool PushedCodeSynthesisContext = false;
1062
1063 public:
1064 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
1065 : S(S), SavedContext(S, DC) {
1066 S.PushFunctionScope();
1067 S.PushExpressionEvaluationContext(
1068 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1069 if (auto *FD = dyn_cast<FunctionDecl>(DC))
1070 FD->setWillHaveBody(true);
1071 else
1072 assert(isa<ObjCMethodDecl>(DC))(static_cast <bool> (isa<ObjCMethodDecl>(DC)) ? void
(0) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "clang/include/clang/Sema/Sema.h"
, 1072, __extension__ __PRETTY_FUNCTION__))
;
1073 }
1074
1075 void addContextNote(SourceLocation UseLoc) {
1076 assert(!PushedCodeSynthesisContext)(static_cast <bool> (!PushedCodeSynthesisContext) ? void
(0) : __assert_fail ("!PushedCodeSynthesisContext", "clang/include/clang/Sema/Sema.h"
, 1076, __extension__ __PRETTY_FUNCTION__))
;
1077
1078 Sema::CodeSynthesisContext Ctx;
1079 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
1080 Ctx.PointOfInstantiation = UseLoc;
1081 Ctx.Entity = cast<Decl>(S.CurContext);
1082 S.pushCodeSynthesisContext(Ctx);
1083
1084 PushedCodeSynthesisContext = true;
1085 }
1086
1087 ~SynthesizedFunctionScope() {
1088 if (PushedCodeSynthesisContext)
1089 S.popCodeSynthesisContext();
1090 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1091 FD->setWillHaveBody(false);
1092 S.PopExpressionEvaluationContext();
1093 S.PopFunctionScopeInfo();
1094 }
1095 };
1096
1097 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
1098 /// declared. Rare. May alias another identifier, declared or undeclared.
1099 ///
1100 /// For aliases, the target identifier is used as a key for eventual
1101 /// processing when the target is declared. For the single-identifier form,
1102 /// the sole identifier is used as the key. Each entry is a `SetVector`
1103 /// (ordered by parse order) of aliases (identified by the alias name) in case
1104 /// of multiple aliases to the same undeclared identifier.
1105 llvm::MapVector<
1106 IdentifierInfo *,
1107 llvm::SetVector<
1108 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
1109 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
1110 WeakUndeclaredIdentifiers;
1111
1112 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1113 /// \#pragma redefine_extname before declared. Used in Solaris system headers
1114 /// to define functions that occur in multiple standards to call the version
1115 /// in the currently selected standard.
1116 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1117
1118
1119 /// Load weak undeclared identifiers from the external source.
1120 void LoadExternalWeakUndeclaredIdentifiers();
1121
1122 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1123 /// \#pragma weak during processing of other Decls.
1124 /// I couldn't figure out a clean way to generate these in-line, so
1125 /// we store them here and handle separately -- which is a hack.
1126 /// It would be best to refactor this.
1127 SmallVector<Decl*,2> WeakTopLevelDecl;
1128
1129 IdentifierResolver IdResolver;
1130
1131 /// Translation Unit Scope - useful to Objective-C actions that need
1132 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1133 /// For example, user-defined classes, built-in "id" type, etc.
1134 Scope *TUScope;
1135
1136 /// The C++ "std" namespace, where the standard library resides.
1137 LazyDeclPtr StdNamespace;
1138
1139 /// The C++ "std::bad_alloc" class, which is defined by the C++
1140 /// standard library.
1141 LazyDeclPtr StdBadAlloc;
1142
1143 /// The C++ "std::align_val_t" enum class, which is defined by the C++
1144 /// standard library.
1145 LazyDeclPtr StdAlignValT;
1146
1147 /// The C++ "std::initializer_list" template, which is defined in
1148 /// \<initializer_list>.
1149 ClassTemplateDecl *StdInitializerList;
1150
1151 /// The C++ "std::coroutine_traits" template, which is defined in
1152 /// \<coroutine_traits>
1153 ClassTemplateDecl *StdCoroutineTraitsCache;
1154
1155 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1156 RecordDecl *CXXTypeInfoDecl;
1157
1158 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1159 RecordDecl *MSVCGuidDecl;
1160
1161 /// The C++ "std::source_location::__impl" struct, defined in
1162 /// \<source_location>.
1163 RecordDecl *StdSourceLocationImplDecl;
1164
1165 /// Caches identifiers/selectors for NSFoundation APIs.
1166 std::unique_ptr<NSAPI> NSAPIObj;
1167
1168 /// The declaration of the Objective-C NSNumber class.
1169 ObjCInterfaceDecl *NSNumberDecl;
1170
1171 /// The declaration of the Objective-C NSValue class.
1172 ObjCInterfaceDecl *NSValueDecl;
1173
1174 /// Pointer to NSNumber type (NSNumber *).
1175 QualType NSNumberPointer;
1176
1177 /// Pointer to NSValue type (NSValue *).
1178 QualType NSValuePointer;
1179
1180 /// The Objective-C NSNumber methods used to create NSNumber literals.
1181 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1182
1183 /// The declaration of the Objective-C NSString class.
1184 ObjCInterfaceDecl *NSStringDecl;
1185
1186 /// Pointer to NSString type (NSString *).
1187 QualType NSStringPointer;
1188
1189 /// The declaration of the stringWithUTF8String: method.
1190 ObjCMethodDecl *StringWithUTF8StringMethod;
1191
1192 /// The declaration of the valueWithBytes:objCType: method.
1193 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1194
1195 /// The declaration of the Objective-C NSArray class.
1196 ObjCInterfaceDecl *NSArrayDecl;
1197
1198 /// The declaration of the arrayWithObjects:count: method.
1199 ObjCMethodDecl *ArrayWithObjectsMethod;
1200
1201 /// The declaration of the Objective-C NSDictionary class.
1202 ObjCInterfaceDecl *NSDictionaryDecl;
1203
1204 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1205 ObjCMethodDecl *DictionaryWithObjectsMethod;
1206
1207 /// id<NSCopying> type.
1208 QualType QIDNSCopying;
1209
1210 /// will hold 'respondsToSelector:'
1211 Selector RespondsToSelectorSel;
1212
1213 /// A flag to remember whether the implicit forms of operator new and delete
1214 /// have been declared.
1215 bool GlobalNewDeleteDeclared;
1216
1217 /// Describes how the expressions currently being parsed are
1218 /// evaluated at run-time, if at all.
1219 enum class ExpressionEvaluationContext {
1220 /// The current expression and its subexpressions occur within an
1221 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1222 /// \c sizeof, where the type of the expression may be significant but
1223 /// no code will be generated to evaluate the value of the expression at
1224 /// run time.
1225 Unevaluated,
1226
1227 /// The current expression occurs within a braced-init-list within
1228 /// an unevaluated operand. This is mostly like a regular unevaluated
1229 /// context, except that we still instantiate constexpr functions that are
1230 /// referenced here so that we can perform narrowing checks correctly.
1231 UnevaluatedList,
1232
1233 /// The current expression occurs within a discarded statement.
1234 /// This behaves largely similarly to an unevaluated operand in preventing
1235 /// definitions from being required, but not in other ways.
1236 DiscardedStatement,
1237
1238 /// The current expression occurs within an unevaluated
1239 /// operand that unconditionally permits abstract references to
1240 /// fields, such as a SIZE operator in MS-style inline assembly.
1241 UnevaluatedAbstract,
1242
1243 /// The current context is "potentially evaluated" in C++11 terms,
1244 /// but the expression is evaluated at compile-time (like the values of
1245 /// cases in a switch statement).
1246 ConstantEvaluated,
1247
1248 /// In addition of being constant evaluated, the current expression
1249 /// occurs in an immediate function context - either a consteval function
1250 /// or a consteval if function.
1251 ImmediateFunctionContext,
1252
1253 /// The current expression is potentially evaluated at run time,
1254 /// which means that code may be generated to evaluate the value of the
1255 /// expression at run time.
1256 PotentiallyEvaluated,
1257
1258 /// The current expression is potentially evaluated, but any
1259 /// declarations referenced inside that expression are only used if
1260 /// in fact the current expression is used.
1261 ///
1262 /// This value is used when parsing default function arguments, for which
1263 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1264 /// through varargs) but do not want to mark declarations as "referenced"
1265 /// until the default argument is used.
1266 PotentiallyEvaluatedIfUsed
1267 };
1268
1269 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1270
1271 /// Data structure used to record current or nested
1272 /// expression evaluation contexts.
1273 struct ExpressionEvaluationContextRecord {
1274 /// The expression evaluation context.
1275 ExpressionEvaluationContext Context;
1276
1277 /// Whether the enclosing context needed a cleanup.
1278 CleanupInfo ParentCleanup;
1279
1280 /// The number of active cleanup objects when we entered
1281 /// this expression evaluation context.
1282 unsigned NumCleanupObjects;
1283
1284 /// The number of typos encountered during this expression evaluation
1285 /// context (i.e. the number of TypoExprs created).
1286 unsigned NumTypos;
1287
1288 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1289
1290 /// The lambdas that are present within this context, if it
1291 /// is indeed an unevaluated context.
1292 SmallVector<LambdaExpr *, 2> Lambdas;
1293
1294 /// The declaration that provides context for lambda expressions
1295 /// and block literals if the normal declaration context does not
1296 /// suffice, e.g., in a default function argument.
1297 Decl *ManglingContextDecl;
1298
1299 /// If we are processing a decltype type, a set of call expressions
1300 /// for which we have deferred checking the completeness of the return type.
1301 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1302
1303 /// If we are processing a decltype type, a set of temporary binding
1304 /// expressions for which we have deferred checking the destructor.
1305 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1306
1307 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1308
1309 /// Expressions appearing as the LHS of a volatile assignment in this
1310 /// context. We produce a warning for these when popping the context if
1311 /// they are not discarded-value expressions nor unevaluated operands.
1312 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1313
1314 /// Set of candidates for starting an immediate invocation.
1315 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1316
1317 /// Set of DeclRefExprs referencing a consteval function when used in a
1318 /// context not already known to be immediately invoked.
1319 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1320
1321 /// \brief Describes whether we are in an expression constext which we have
1322 /// to handle differently.
1323 enum ExpressionKind {
1324 EK_Decltype, EK_TemplateArgument, EK_Other
1325 } ExprContext;
1326
1327 // A context can be nested in both a discarded statement context and
1328 // an immediate function context, so they need to be tracked independently.
1329 bool InDiscardedStatement;
1330 bool InImmediateFunctionContext;
1331
1332 bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false;
1333
1334 // When evaluating immediate functions in the initializer of a default
1335 // argument or default member initializer, this is the declaration whose
1336 // default initializer is being evaluated and the location of the call
1337 // or constructor definition.
1338 struct InitializationContext {
1339 InitializationContext(SourceLocation Loc, ValueDecl *Decl,
1340 DeclContext *Context)
1341 : Loc(Loc), Decl(Decl), Context(Context) {
1342 assert(Decl && Context && "invalid initialization context")(static_cast <bool> (Decl && Context &&
"invalid initialization context") ? void (0) : __assert_fail
("Decl && Context && \"invalid initialization context\""
, "clang/include/clang/Sema/Sema.h", 1342, __extension__ __PRETTY_FUNCTION__
))
;
1343 }
1344
1345 SourceLocation Loc;
1346 ValueDecl *Decl = nullptr;
1347 DeclContext *Context = nullptr;
1348 };
1349 std::optional<InitializationContext> DelayedDefaultInitializationContext;
1350
1351 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1352 unsigned NumCleanupObjects,
1353 CleanupInfo ParentCleanup,
1354 Decl *ManglingContextDecl,
1355 ExpressionKind ExprContext)
1356 : Context(Context), ParentCleanup(ParentCleanup),
1357 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1358 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
1359 InDiscardedStatement(false), InImmediateFunctionContext(false) {}
1360
1361 bool isUnevaluated() const {
1362 return Context == ExpressionEvaluationContext::Unevaluated ||
1363 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1364 Context == ExpressionEvaluationContext::UnevaluatedList;
1365 }
1366
1367 bool isConstantEvaluated() const {
1368 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
1369 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
1370 }
1371
1372 bool isImmediateFunctionContext() const {
1373 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
1374 (Context == ExpressionEvaluationContext::DiscardedStatement &&
1375 InImmediateFunctionContext) ||
1376 // C++23 [expr.const]p14:
1377 // An expression or conversion is in an immediate function
1378 // context if it is potentially evaluated and either:
1379 // * its innermost enclosing non-block scope is a function
1380 // parameter scope of an immediate function, or
1381 // * its enclosing statement is enclosed by the compound-
1382 // statement of a consteval if statement.
1383 (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
1384 InImmediateFunctionContext);
1385 }
1386
1387 bool isDiscardedStatementContext() const {
1388 return Context == ExpressionEvaluationContext::DiscardedStatement ||
1389 (Context ==
1390 ExpressionEvaluationContext::ImmediateFunctionContext &&
1391 InDiscardedStatement);
1392 }
1393 };
1394
1395 /// A stack of expression evaluation contexts.
1396 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1397
1398 // Set of failed immediate invocations to avoid double diagnosing.
1399 llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations;
1400
1401 /// Emit a warning for all pending noderef expressions that we recorded.
1402 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1403
1404 /// Compute the mangling number context for a lambda expression or
1405 /// block literal. Also return the extra mangling decl if any.
1406 ///
1407 /// \param DC - The DeclContext containing the lambda expression or
1408 /// block literal.
1409 std::tuple<MangleNumberingContext *, Decl *>
1410 getCurrentMangleNumberContext(const DeclContext *DC);
1411
1412
1413 /// SpecialMemberOverloadResult - The overloading result for a special member
1414 /// function.
1415 ///
1416 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1417 /// integer are used to determine whether overload resolution succeeded.
1418 class SpecialMemberOverloadResult {
1419 public:
1420 enum Kind {
1421 NoMemberOrDeleted,
1422 Ambiguous,
1423 Success
1424 };
1425
1426 private:
1427 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1428
1429 public:
1430 SpecialMemberOverloadResult() {}
1431 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1432 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1433
1434 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1435 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1436
1437 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1438 void setKind(Kind K) { Pair.setInt(K); }
1439 };
1440
1441 class SpecialMemberOverloadResultEntry
1442 : public llvm::FastFoldingSetNode,
1443 public SpecialMemberOverloadResult {
1444 public:
1445 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1446 : FastFoldingSetNode(ID)
1447 {}
1448 };
1449
1450 /// A cache of special member function overload resolution results
1451 /// for C++ records.
1452 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1453
1454 /// A cache of the flags available in enumerations with the flag_bits
1455 /// attribute.
1456 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1457
1458 /// The kind of translation unit we are processing.
1459 ///
1460 /// When we're processing a complete translation unit, Sema will perform
1461 /// end-of-translation-unit semantic tasks (such as creating
1462 /// initializers for tentative definitions in C) once parsing has
1463 /// completed. Modules and precompiled headers perform different kinds of
1464 /// checks.
1465 const TranslationUnitKind TUKind;
1466
1467 llvm::BumpPtrAllocator BumpAlloc;
1468
1469 /// The number of SFINAE diagnostics that have been trapped.
1470 unsigned NumSFINAEErrors;
1471
1472 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1473 UnparsedDefaultArgInstantiationsMap;
1474
1475 /// A mapping from parameters with unparsed default arguments to the
1476 /// set of instantiations of each parameter.
1477 ///
1478 /// This mapping is a temporary data structure used when parsing
1479 /// nested class templates or nested classes of class templates,
1480 /// where we might end up instantiating an inner class before the
1481 /// default arguments of its methods have been parsed.
1482 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1483
1484 // Contains the locations of the beginning of unparsed default
1485 // argument locations.
1486 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1487
1488 /// UndefinedInternals - all the used, undefined objects which require a
1489 /// definition in this translation unit.
1490 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1491
1492 /// Determine if VD, which must be a variable or function, is an external
1493 /// symbol that nonetheless can't be referenced from outside this translation
1494 /// unit because its type has no linkage and it's not extern "C".
1495 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
1496
1497 /// Obtain a sorted list of functions that are undefined but ODR-used.
1498 void getUndefinedButUsed(
1499 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1500
1501 /// Retrieves list of suspicious delete-expressions that will be checked at
1502 /// the end of translation unit.
1503 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1504 getMismatchingDeleteExpressions() const;
1505
1506 class GlobalMethodPool {
1507 public:
1508 using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1509 using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1510 iterator begin() { return Methods.begin(); }
1511 iterator end() { return Methods.end(); }
1512 iterator find(Selector Sel) { return Methods.find(Sel); }
1513 std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1514 return Methods.insert(Val);
1515 }
1516 int count(Selector Sel) const { return Methods.count(Sel); }
1517 bool empty() const { return Methods.empty(); }
1518
1519 private:
1520 llvm::DenseMap<Selector, Lists> Methods;
1521 };
1522
1523 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1524 /// We need to maintain a list, since selectors can have differing signatures
1525 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1526 /// of selectors are "overloaded").
1527 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1528 /// methods inside categories with a particular selector.
1529 GlobalMethodPool MethodPool;
1530
1531 /// Method selectors used in a \@selector expression. Used for implementation
1532 /// of -Wselector.
1533 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1534
1535 /// List of SourceLocations where 'self' is implicitly retained inside a
1536 /// block.
1537 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1538 ImplicitlyRetainedSelfLocs;
1539
1540 /// Kinds of C++ special members.
1541 enum CXXSpecialMember {
1542 CXXDefaultConstructor,
1543 CXXCopyConstructor,
1544 CXXMoveConstructor,
1545 CXXCopyAssignment,
1546 CXXMoveAssignment,
1547 CXXDestructor,
1548 CXXInvalid
1549 };
1550
1551 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1552 SpecialMemberDecl;
1553
1554 /// The C++ special members which we are currently in the process of
1555 /// declaring. If this process recursively triggers the declaration of the
1556 /// same special member, we should act as if it is not yet declared.
1557 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1558
1559 /// Kinds of defaulted comparison operator functions.
1560 enum class DefaultedComparisonKind : unsigned char {
1561 /// This is not a defaultable comparison operator.
1562 None,
1563 /// This is an operator== that should be implemented as a series of
1564 /// subobject comparisons.
1565 Equal,
1566 /// This is an operator<=> that should be implemented as a series of
1567 /// subobject comparisons.
1568 ThreeWay,
1569 /// This is an operator!= that should be implemented as a rewrite in terms
1570 /// of a == comparison.
1571 NotEqual,
1572 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1573 /// terms of a <=> comparison.
1574 Relational,
1575 };
1576
1577 /// The function definitions which were renamed as part of typo-correction
1578 /// to match their respective declarations. We want to keep track of them
1579 /// to ensure that we don't emit a "redefinition" error if we encounter a
1580 /// correctly named definition after the renamed definition.
1581 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1582
1583 /// Stack of types that correspond to the parameter entities that are
1584 /// currently being copy-initialized. Can be empty.
1585 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1586
1587 void ReadMethodPool(Selector Sel);
1588 void updateOutOfDateSelector(Selector Sel);
1589
1590 /// Private Helper predicate to check for 'self'.
1591 bool isSelfExpr(Expr *RExpr);
1592 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1593
1594 /// Cause the active diagnostic on the DiagosticsEngine to be
1595 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1596 /// should not be used elsewhere.
1597 void EmitCurrentDiagnostic(unsigned DiagID);
1598
1599 /// Records and restores the CurFPFeatures state on entry/exit of compound
1600 /// statements.
1601 class FPFeaturesStateRAII {
1602 public:
1603 FPFeaturesStateRAII(Sema &S);
1604 ~FPFeaturesStateRAII();
1605 FPOptionsOverride getOverrides() { return OldOverrides; }
1606
1607 private:
1608 Sema& S;
1609 FPOptions OldFPFeaturesState;
1610 FPOptionsOverride OldOverrides;
1611 LangOptions::FPEvalMethodKind OldEvalMethod;
1612 SourceLocation OldFPPragmaLocation;
1613 };
1614
1615 void addImplicitTypedef(StringRef Name, QualType T);
1616
1617 bool WarnedStackExhausted = false;
1618
1619 /// Increment when we find a reference; decrement when we find an ignored
1620 /// assignment. Ultimately the value is 0 if every reference is an ignored
1621 /// assignment.
1622 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1623
1624 /// Indicate RISC-V vector builtin functions enabled or not.
1625 bool DeclareRISCVVBuiltins = false;
1626
1627 /// Indicate RISC-V Sifive vector builtin functions enabled or not.
1628 bool DeclareRISCVVectorBuiltins = false;
1629
1630private:
1631 std::unique_ptr<sema::RISCVIntrinsicManager> RVIntrinsicManager;
1632
1633 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1634
1635 bool WarnedDarwinSDKInfoMissing = false;
1636
1637public:
1638 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1639 TranslationUnitKind TUKind = TU_Complete,
1640 CodeCompleteConsumer *CompletionConsumer = nullptr);
1641 ~Sema();
1642
1643 /// Perform initialization that occurs after the parser has been
1644 /// initialized but before it parses anything.
1645 void Initialize();
1646
1647 /// This virtual key function only exists to limit the emission of debug info
1648 /// describing the Sema class. GCC and Clang only emit debug info for a class
1649 /// with a vtable when the vtable is emitted. Sema is final and not
1650 /// polymorphic, but the debug info size savings are so significant that it is
1651 /// worth adding a vtable just to take advantage of this optimization.
1652 virtual void anchor();
1653
1654 const LangOptions &getLangOpts() const { return LangOpts; }
1655 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1656 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
1657
1658 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1659 SourceManager &getSourceManager() const { return SourceMgr; }
1660 Preprocessor &getPreprocessor() const { return PP; }
1661 ASTContext &getASTContext() const { return Context; }
1662 ASTConsumer &getASTConsumer() const { return Consumer; }
1663 ASTMutationListener *getASTMutationListener() const;
1664 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
1665
1666 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
1667 StringRef Platform);
1668 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
1669
1670 ///Registers an external source. If an external source already exists,
1671 /// creates a multiplex external source and appends to it.
1672 ///
1673 ///\param[in] E - A non-null external sema source.
1674 ///
1675 void addExternalSource(ExternalSemaSource *E);
1676
1677 void PrintStats() const;
1678
1679 /// Warn that the stack is nearly exhausted.
1680 void warnStackExhausted(SourceLocation Loc);
1681
1682 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1683 /// guaranteed). Produces a warning if we're low on stack space and allocates
1684 /// more in that case. Use this in code that may recurse deeply (for example,
1685 /// in template instantiation) to avoid stack overflow.
1686 void runWithSufficientStackSpace(SourceLocation Loc,
1687 llvm::function_ref<void()> Fn);
1688
1689 /// Helper class that creates diagnostics with optional
1690 /// template instantiation stacks.
1691 ///
1692 /// This class provides a wrapper around the basic DiagnosticBuilder
1693 /// class that emits diagnostics. ImmediateDiagBuilder is
1694 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1695 /// does) and, if the diagnostic comes from inside a template
1696 /// instantiation, printing the template instantiation stack as
1697 /// well.
1698 class ImmediateDiagBuilder : public DiagnosticBuilder {
1699 Sema &SemaRef;
1700 unsigned DiagID;
1701
1702 public:
1703 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1704 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1705 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1706 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1707
1708 // This is a cunning lie. DiagnosticBuilder actually performs move
1709 // construction in its copy constructor (but due to varied uses, it's not
1710 // possible to conveniently express this as actual move construction). So
1711 // the default copy ctor here is fine, because the base class disables the
1712 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1713 // in that case anwyay.
1714 ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1715
1716 ~ImmediateDiagBuilder() {
1717 // If we aren't active, there is nothing to do.
1718 if (!isActive()) return;
1719
1720 // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1721 // builder itself so it won't emit the diagnostic in its own destructor.
1722 //
1723 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1724 // do its own needless checks to see if the diagnostic needs to be
1725 // emitted. However, because we take care to ensure that the builder
1726 // objects never escape, a sufficiently smart compiler will be able to
1727 // eliminate that code.
1728 Clear();
1729
1730 // Dispatch to Sema to emit the diagnostic.
1731 SemaRef.EmitCurrentDiagnostic(DiagID);
1732 }
1733
1734 /// Teach operator<< to produce an object of the correct type.
1735 template <typename T>
1736 friend const ImmediateDiagBuilder &
1737 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1738 const DiagnosticBuilder &BaseDiag = Diag;
1739 BaseDiag << Value;
1740 return Diag;
1741 }
1742
1743 // It is necessary to limit this to rvalue reference to avoid calling this
1744 // function with a bitfield lvalue argument since non-const reference to
1745 // bitfield is not allowed.
1746 template <typename T,
1747 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1748 const ImmediateDiagBuilder &operator<<(T &&V) const {
1749 const DiagnosticBuilder &BaseDiag = *this;
1750 BaseDiag << std::move(V);
1751 return *this;
1752 }
1753 };
1754
1755 /// A generic diagnostic builder for errors which may or may not be deferred.
1756 ///
1757 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1758 /// which are not allowed to appear inside __device__ functions and are
1759 /// allowed to appear in __host__ __device__ functions only if the host+device
1760 /// function is never codegen'ed.
1761 ///
1762 /// To handle this, we use the notion of "deferred diagnostics", where we
1763 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1764 ///
1765 /// This class lets you emit either a regular diagnostic, a deferred
1766 /// diagnostic, or no diagnostic at all, according to an argument you pass to
1767 /// its constructor, thus simplifying the process of creating these "maybe
1768 /// deferred" diagnostics.
1769 class SemaDiagnosticBuilder {
1770 public:
1771 enum Kind {
1772 /// Emit no diagnostics.
1773 K_Nop,
1774 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1775 K_Immediate,
1776 /// Emit the diagnostic immediately, and, if it's a warning or error, also
1777 /// emit a call stack showing how this function can be reached by an a
1778 /// priori known-emitted function.
1779 K_ImmediateWithCallStack,
1780 /// Create a deferred diagnostic, which is emitted only if the function
1781 /// it's attached to is codegen'ed. Also emit a call stack as with
1782 /// K_ImmediateWithCallStack.
1783 K_Deferred
1784 };
1785
1786 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1787 const FunctionDecl *Fn, Sema &S);
1788 SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1789 SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1790 ~SemaDiagnosticBuilder();
1791
1792 bool isImmediate() const { return ImmediateDiag.has_value(); }
1793
1794 /// Convertible to bool: True if we immediately emitted an error, false if
1795 /// we didn't emit an error or we created a deferred error.
1796 ///
1797 /// Example usage:
1798 ///
1799 /// if (SemaDiagnosticBuilder(...) << foo << bar)
1800 /// return ExprError();
1801 ///
1802 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1803 /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1804 operator bool() const { return isImmediate(); }
1805
1806 template <typename T>
1807 friend const SemaDiagnosticBuilder &
1808 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1809 if (Diag.ImmediateDiag)
1810 *Diag.ImmediateDiag << Value;
1811 else if (Diag.PartialDiagId)
1812 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1813 << Value;
1814 return Diag;
1815 }
1816
1817 // It is necessary to limit this to rvalue reference to avoid calling this
1818 // function with a bitfield lvalue argument since non-const reference to
1819 // bitfield is not allowed.
1820 template <typename T,
1821 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1822 const SemaDiagnosticBuilder &operator<<(T &&V) const {
1823 if (ImmediateDiag)
1824 *ImmediateDiag << std::move(V);
1825 else if (PartialDiagId)
1826 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1827 return *this;
1828 }
1829
1830 friend const SemaDiagnosticBuilder &
1831 operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1832 if (Diag.ImmediateDiag)
1833 PD.Emit(*Diag.ImmediateDiag);
1834 else if (Diag.PartialDiagId)
1835 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1836 return Diag;
1837 }
1838
1839 void AddFixItHint(const FixItHint &Hint) const {
1840 if (ImmediateDiag)
1841 ImmediateDiag->AddFixItHint(Hint);
1842 else if (PartialDiagId)
1843 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1844 }
1845
1846 friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1847 return ExprError();
1848 }
1849 friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1850 return StmtError();
1851 }
1852 operator ExprResult() const { return ExprError(); }
1853 operator StmtResult() const { return StmtError(); }
1854 operator TypeResult() const { return TypeError(); }
1855 operator DeclResult() const { return DeclResult(true); }
1856 operator MemInitResult() const { return MemInitResult(true); }
1857
1858 private:
1859 Sema &S;
1860 SourceLocation Loc;
1861 unsigned DiagID;
1862 const FunctionDecl *Fn;
1863 bool ShowCallStack;
1864
1865 // Invariant: At most one of these Optionals has a value.
1866 // FIXME: Switch these to a Variant once that exists.
1867 std::optional<ImmediateDiagBuilder> ImmediateDiag;
1868 std::optional<unsigned> PartialDiagId;
1869 };
1870
1871 /// Is the last error level diagnostic immediate. This is used to determined
1872 /// whether the next info diagnostic should be immediate.
1873 bool IsLastErrorImmediate = true;
1874
1875 /// Emit a diagnostic.
1876 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1877 bool DeferHint = false);
1878
1879 /// Emit a partial diagnostic.
1880 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1881 bool DeferHint = false);
1882
1883 /// Build a partial diagnostic.
1884 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1885
1886 /// Whether deferrable diagnostics should be deferred.
1887 bool DeferDiags = false;
1888
1889 /// RAII class to control scope of DeferDiags.
1890 class DeferDiagsRAII {
1891 Sema &S;
1892 bool SavedDeferDiags = false;
1893
1894 public:
1895 DeferDiagsRAII(Sema &S, bool DeferDiags)
1896 : S(S), SavedDeferDiags(S.DeferDiags) {
1897 S.DeferDiags = DeferDiags;
1898 }
1899 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1900 };
1901
1902 /// Whether uncompilable error has occurred. This includes error happens
1903 /// in deferred diagnostics.
1904 bool hasUncompilableErrorOccurred() const;
1905
1906 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1907
1908 /// Get a string to suggest for zero-initialization of a type.
1909 std::string
1910 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1911 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1912
1913 /// Calls \c Lexer::getLocForEndOfToken()
1914 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1915
1916 /// Retrieve the module loader associated with the preprocessor.
1917 ModuleLoader &getModuleLoader() const;
1918
1919 /// Invent a new identifier for parameters of abbreviated templates.
1920 IdentifierInfo *
1921 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1922 unsigned Index);
1923
1924 void emitAndClearUnusedLocalTypedefWarnings();
1925
1926 private:
1927 /// Function or variable declarations to be checked for whether the deferred
1928 /// diagnostics should be emitted.
1929 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1930
1931 public:
1932 // Emit all deferred diagnostics.
1933 void emitDeferredDiags();
1934
1935 enum TUFragmentKind {
1936 /// The global module fragment, between 'module;' and a module-declaration.
1937 Global,
1938 /// A normal translation unit fragment. For a non-module unit, this is the
1939 /// entire translation unit. Otherwise, it runs from the module-declaration
1940 /// to the private-module-fragment (if any) or the end of the TU (if not).
1941 Normal,
1942 /// The private module fragment, between 'module :private;' and the end of
1943 /// the translation unit.
1944 Private
1945 };
1946
1947 void ActOnStartOfTranslationUnit();
1948 void ActOnEndOfTranslationUnit();
1949 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1950
1951 void CheckDelegatingCtorCycles();
1952
1953 Scope *getScopeForContext(DeclContext *Ctx);
1954
1955 void PushFunctionScope();
1956 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1957 sema::LambdaScopeInfo *PushLambdaScope();
1958
1959 /// This is used to inform Sema what the current TemplateParameterDepth
1960 /// is during Parsing. Currently it is used to pass on the depth
1961 /// when parsing generic lambda 'auto' parameters.
1962 void RecordParsingTemplateParameterDepth(unsigned Depth);
1963
1964 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1965 RecordDecl *RD, CapturedRegionKind K,
1966 unsigned OpenMPCaptureLevel = 0);
1967
1968 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1969 /// time after they've been popped.
1970 class PoppedFunctionScopeDeleter {
1971 Sema *Self;
1972
1973 public:
1974 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1975 void operator()(sema::FunctionScopeInfo *Scope) const;
1976 };
1977
1978 using PoppedFunctionScopePtr =
1979 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1980
1981 PoppedFunctionScopePtr
1982 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1983 const Decl *D = nullptr,
1984 QualType BlockType = QualType());
1985
1986 sema::FunctionScopeInfo *getCurFunction() const {
1987 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1988 }
1989
1990 sema::FunctionScopeInfo *getEnclosingFunction() const;
1991
1992 void setFunctionHasBranchIntoScope();
1993 void setFunctionHasBranchProtectedScope();
1994 void setFunctionHasIndirectGoto();
1995 void setFunctionHasMustTail();
1996
1997 void PushCompoundScope(bool IsStmtExpr);
1998 void PopCompoundScope();
1999
2000 sema::CompoundScopeInfo &getCurCompoundScope() const;
2001
2002 bool hasAnyUnrecoverableErrorsInThisFunction() const;
2003
2004 /// Retrieve the current block, if any.
2005 sema::BlockScopeInfo *getCurBlock();
2006
2007 /// Get the innermost lambda enclosing the current location, if any. This
2008 /// looks through intervening non-lambda scopes such as local functions and
2009 /// blocks.
2010 sema::LambdaScopeInfo *getEnclosingLambda() const;
2011
2012 /// Retrieve the current lambda scope info, if any.
2013 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
2014 /// lambda scope info ignoring all inner capturing scopes that are not
2015 /// lambda scopes.
2016 sema::LambdaScopeInfo *
2017 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
2018
2019 /// Retrieve the current generic lambda info, if any.
2020 sema::LambdaScopeInfo *getCurGenericLambda();
2021
2022 /// Retrieve the current captured region, if any.
2023 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
2024
2025 /// Retrieve the current function, if any, that should be analyzed for
2026 /// potential availability violations.
2027 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2028
2029 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
2030 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
2031
2032 /// Called before parsing a function declarator belonging to a function
2033 /// declaration.
2034 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
2035 unsigned TemplateParameterDepth);
2036
2037 /// Called after parsing a function declarator belonging to a function
2038 /// declaration.
2039 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
2040
2041 void ActOnComment(SourceRange Comment);
2042
2043 //===--------------------------------------------------------------------===//
2044 // Type Analysis / Processing: SemaType.cpp.
2045 //
2046
2047 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
2048 const DeclSpec *DS = nullptr);
2049 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
2050 const DeclSpec *DS = nullptr);
2051 QualType BuildPointerType(QualType T,
2052 SourceLocation Loc, DeclarationName Entity);
2053 QualType BuildReferenceType(QualType T, bool LValueRef,
2054 SourceLocation Loc, DeclarationName Entity);
2055 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2056 Expr *ArraySize, unsigned Quals,
2057 SourceRange Brackets, DeclarationName Entity);
2058 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
2059 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
2060 SourceLocation AttrLoc);
2061 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
2062 SourceLocation AttrLoc);
2063
2064 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2065 SourceLocation AttrLoc);
2066
2067 /// Same as above, but constructs the AddressSpace index if not provided.
2068 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
2069 SourceLocation AttrLoc);
2070
2071 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
2072
2073 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
2074
2075 /// Build a function type.
2076 ///
2077 /// This routine checks the function type according to C++ rules and
2078 /// under the assumption that the result type and parameter types have
2079 /// just been instantiated from a template. It therefore duplicates
2080 /// some of the behavior of GetTypeForDeclarator, but in a much
2081 /// simpler form that is only suitable for this narrow use case.
2082 ///
2083 /// \param T The return type of the function.
2084 ///
2085 /// \param ParamTypes The parameter types of the function. This array
2086 /// will be modified to account for adjustments to the types of the
2087 /// function parameters.
2088 ///
2089 /// \param Loc The location of the entity whose type involves this
2090 /// function type or, if there is no such entity, the location of the
2091 /// type that will have function type.
2092 ///
2093 /// \param Entity The name of the entity that involves the function
2094 /// type, if known.
2095 ///
2096 /// \param EPI Extra information about the function type. Usually this will
2097 /// be taken from an existing function with the same prototype.
2098 ///
2099 /// \returns A suitable function type, if there are no errors. The
2100 /// unqualified type will always be a FunctionProtoType.
2101 /// Otherwise, returns a NULL type.
2102 QualType BuildFunctionType(QualType T,
2103 MutableArrayRef<QualType> ParamTypes,
2104 SourceLocation Loc, DeclarationName Entity,
2105 const FunctionProtoType::ExtProtoInfo &EPI);
2106
2107 QualType BuildMemberPointerType(QualType T, QualType Class,
2108 SourceLocation Loc,
2109 DeclarationName Entity);
2110 QualType BuildBlockPointerType(QualType T,
2111 SourceLocation Loc, DeclarationName Entity);
2112 QualType BuildParenType(QualType T);
2113 QualType BuildAtomicType(QualType T, SourceLocation Loc);
2114 QualType BuildReadPipeType(QualType T,
2115 SourceLocation Loc);
2116 QualType BuildWritePipeType(QualType T,
2117 SourceLocation Loc);
2118 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2119
2120 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
2121 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
2122
2123 /// Package the given type and TSI into a ParsedType.
2124 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
2125 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
2126 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
2127 static QualType GetTypeFromParser(ParsedType Ty,
2128 TypeSourceInfo **TInfo = nullptr);
2129 CanThrowResult canThrow(const Stmt *E);
2130 /// Determine whether the callee of a particular function call can throw.
2131 /// E, D and Loc are all optional.
2132 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2133 SourceLocation Loc = SourceLocation());
2134 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
2135 const FunctionProtoType *FPT);
2136 void UpdateExceptionSpec(FunctionDecl *FD,
2137 const FunctionProtoType::ExceptionSpecInfo &ESI);
2138 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
2139 bool CheckDistantExceptionSpec(QualType T);
2140 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
2141 bool CheckEquivalentExceptionSpec(
2142 const FunctionProtoType *Old, SourceLocation OldLoc,
2143 const FunctionProtoType *New, SourceLocation NewLoc);
2144 bool CheckEquivalentExceptionSpec(
2145 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2146 const FunctionProtoType *Old, SourceLocation OldLoc,
2147 const FunctionProtoType *New, SourceLocation NewLoc);
2148 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2149 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2150 const PartialDiagnostic &NestedDiagID,
2151 const PartialDiagnostic &NoteID,
2152 const PartialDiagnostic &NoThrowDiagID,
2153 const FunctionProtoType *Superset,
2154 SourceLocation SuperLoc,
2155 const FunctionProtoType *Subset,
2156 SourceLocation SubLoc);
2157 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2158 const PartialDiagnostic &NoteID,
2159 const FunctionProtoType *Target,
2160 SourceLocation TargetLoc,
2161 const FunctionProtoType *Source,
2162 SourceLocation SourceLoc);
2163
2164 TypeResult ActOnTypeName(Scope *S, Declarator &D);
2165
2166 /// The parser has parsed the context-sensitive type 'instancetype'
2167 /// in an Objective-C message declaration. Return the appropriate type.
2168 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
2169
2170 /// Abstract class used to diagnose incomplete types.
2171 struct TypeDiagnoser {
2172 TypeDiagnoser() {}
2173
2174 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2175 virtual ~TypeDiagnoser() {}
2176 };
2177
2178 static int getPrintable(int I) { return I; }
2179 static unsigned getPrintable(unsigned I) { return I; }
2180 static bool getPrintable(bool B) { return B; }
2181 static const char * getPrintable(const char *S) { return S; }
2182 static StringRef getPrintable(StringRef S) { return S; }
2183 static const std::string &getPrintable(const std::string &S) { return S; }
2184 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2185 return II;
2186 }
2187 static DeclarationName getPrintable(DeclarationName N) { return N; }
2188 static QualType getPrintable(QualType T) { return T; }
2189 static SourceRange getPrintable(SourceRange R) { return R; }
2190 static SourceRange getPrintable(SourceLocation L) { return L; }
2191 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2192 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2193
2194 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2195 protected:
2196 unsigned DiagID;
2197 std::tuple<const Ts &...> Args;
2198
2199 template <std::size_t... Is>
2200 void emit(const SemaDiagnosticBuilder &DB,
2201 std::index_sequence<Is...>) const {
2202 // Apply all tuple elements to the builder in order.
2203 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2204 (void)Dummy;
2205 }
2206
2207 public:
2208 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2209 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2210 assert(DiagID != 0 && "no diagnostic for type diagnoser")(static_cast <bool> (DiagID != 0 && "no diagnostic for type diagnoser"
) ? void (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "clang/include/clang/Sema/Sema.h", 2210, __extension__ __PRETTY_FUNCTION__
))
;
2211 }
2212
2213 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2214 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2215 emit(DB, std::index_sequence_for<Ts...>());
2216 DB << T;
2217 }
2218 };
2219
2220 /// Do a check to make sure \p Name looks like a legal argument for the
2221 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2222 /// is invalid for the given declaration.
2223 ///
2224 /// \p AL is used to provide caret diagnostics in case of a malformed name.
2225 ///
2226 /// \returns true if the name is a valid swift name for \p D, false otherwise.
2227 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2228 const ParsedAttr &AL, bool IsAsync);
2229
2230 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2231 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2232 /// For example, a diagnostic with no other parameters would generally have
2233 /// the form "...%select{incomplete|sizeless}0 type %1...".
2234 template <typename... Ts>
2235 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
2236 public:
2237 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2238 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2239
2240 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2241 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2242 this->emit(DB, std::index_sequence_for<Ts...>());
2243 DB << T->isSizelessType() << T;
2244 }
2245 };
2246
2247 enum class CompleteTypeKind {
2248 /// Apply the normal rules for complete types. In particular,
2249 /// treat all sizeless types as incomplete.
2250 Normal,
2251
2252 /// Relax the normal rules for complete types so that they include
2253 /// sizeless built-in types.
2254 AcceptSizeless,
2255
2256 // FIXME: Eventually we should flip the default to Normal and opt in
2257 // to AcceptSizeless rather than opt out of it.
2258 Default = AcceptSizeless
2259 };
2260
2261 enum class AcceptableKind { Visible, Reachable };
2262
2263private:
2264 /// Methods for marking which expressions involve dereferencing a pointer
2265 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2266 /// they are parsed, meaning that a noderef pointer may not be accessed. For
2267 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2268 /// `*p`, but need to check that `address of` is called on it. This requires
2269 /// keeping a container of all pending expressions and checking if the address
2270 /// of them are eventually taken.
2271 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2272 void CheckAddressOfNoDeref(const Expr *E);
2273 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2274
2275 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2276 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2277
2278 struct ModuleScope {
2279 SourceLocation BeginLoc;
2280 clang::Module *Module = nullptr;
2281 bool ModuleInterface = false;
2282 VisibleModuleSet OuterVisibleModules;
2283 };
2284 /// The modules we're currently parsing.
2285 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
2286
2287 /// For an interface unit, this is the implicitly imported interface unit.
2288 clang::Module *ThePrimaryInterface = nullptr;
2289
2290 /// The explicit global module fragment of the current translation unit.
2291 /// The explicit Global Module Fragment, as specified in C++
2292 /// [module.global.frag].
2293 clang::Module *TheGlobalModuleFragment = nullptr;
2294
2295 /// The implicit global module fragments of the current translation unit.
2296 /// We would only create at most two implicit global module fragments to
2297 /// avoid performance penalties when there are many language linkage
2298 /// exports.
2299 ///
2300 /// The contents in the implicit global module fragment can't be discarded
2301 /// no matter if it is exported or not.
2302 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
2303 clang::Module *TheExportedImplicitGlobalModuleFragment = nullptr;
2304
2305 /// Namespace definitions that we will export when they finish.
2306 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2307
2308 /// In a C++ standard module, inline declarations require a definition to be
2309 /// present at the end of a definition domain. This set holds the decls to
2310 /// be checked at the end of the TU.
2311 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
2312
2313 /// Helper function to judge if we are in module purview.
2314 /// Return false if we are not in a module.
2315 bool isCurrentModulePurview() const {
2316 return getCurrentModule() ? getCurrentModule()->isModulePurview() : false;
2317 }
2318
2319 /// Enter the scope of the explicit global module fragment.
2320 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
2321 /// Leave the scope of the explicit global module fragment.
2322 void PopGlobalModuleFragment();
2323
2324 /// Enter the scope of an implicit global module fragment.
2325 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc,
2326 bool IsExported);
2327 /// Leave the scope of an implicit global module fragment.
2328 void PopImplicitGlobalModuleFragment();
2329
2330 VisibleModuleSet VisibleModules;
2331
2332 /// Cache for module units which is usable for current module.
2333 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
2334
2335 bool isUsableModule(const Module *M);
2336
2337 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
2338
2339public:
2340 /// Get the module unit whose scope we are currently within.
2341 Module *getCurrentModule() const {
2342 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2343 }
2344
2345 /// Is the module scope we are an interface?
2346 bool currentModuleIsInterface() const {
2347 return ModuleScopes.empty() ? false : ModuleScopes.back().ModuleInterface;
2348 }
2349
2350 /// Is the module scope we are in a C++ Header Unit?
2351 bool currentModuleIsHeaderUnit() const {
2352 return ModuleScopes.empty() ? false
2353 : ModuleScopes.back().Module->isHeaderUnit();
2354 }
2355
2356 /// Get the module owning an entity.
2357 Module *getOwningModule(const Decl *Entity) {
2358 return Entity->getOwningModule();
2359 }
2360
2361 /// Make a merged definition of an existing hidden definition \p ND
2362 /// visible at the specified location.
2363 void makeMergedDefinitionVisible(NamedDecl *ND);
2364
2365 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2366
2367 // When loading a non-modular PCH files, this is used to restore module
2368 // visibility.
2369 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2370 VisibleModules.setVisible(Mod, ImportLoc);
2371 }
2372
2373 /// Determine whether a declaration is visible to name lookup.
2374 bool isVisible(const NamedDecl *D) {
2375 return D->isUnconditionallyVisible() ||
2376 isAcceptableSlow(D, AcceptableKind::Visible);
2377 }
2378
2379 /// Determine whether a declaration is reachable.
2380 bool isReachable(const NamedDecl *D) {
2381 // All visible declarations are reachable.
2382 return D->isUnconditionallyVisible() ||
2383 isAcceptableSlow(D, AcceptableKind::Reachable);
2384 }
2385
2386 /// Determine whether a declaration is acceptable (visible/reachable).
2387 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
2388 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
2389 }
2390
2391 /// Determine whether any declaration of an entity is visible.
2392 bool
2393 hasVisibleDeclaration(const NamedDecl *D,
2394 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2395 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2396 }
2397
2398 bool hasVisibleDeclarationSlow(const NamedDecl *D,
2399 llvm::SmallVectorImpl<Module *> *Modules);
2400 /// Determine whether any declaration of an entity is reachable.
2401 bool
2402 hasReachableDeclaration(const NamedDecl *D,
2403 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2404 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
2405 }
2406 bool hasReachableDeclarationSlow(
2407 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2408
2409 bool hasVisibleMergedDefinition(const NamedDecl *Def);
2410 bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def);
2411
2412 /// Determine if \p D and \p Suggested have a structurally compatible
2413 /// layout as described in C11 6.2.7/1.
2414 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2415
2416 /// Determine if \p D has a visible definition. If not, suggest a declaration
2417 /// that should be made visible to expose the definition.
2418 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2419 bool OnlyNeedComplete = false);
2420 bool hasVisibleDefinition(const NamedDecl *D) {
2421 NamedDecl *Hidden;
2422 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2423 }
2424
2425 /// Determine if \p D has a reachable definition. If not, suggest a
2426 /// declaration that should be made reachable to expose the definition.
2427 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
2428 bool OnlyNeedComplete = false);
2429 bool hasReachableDefinition(NamedDecl *D) {
2430 NamedDecl *Hidden;
2431 return hasReachableDefinition(D, &Hidden);
2432 }
2433
2434 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
2435 AcceptableKind Kind,
2436 bool OnlyNeedComplete = false);
2437 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
2438 NamedDecl *Hidden;
2439 return hasAcceptableDefinition(D, &Hidden, Kind);
2440 }
2441
2442 /// Determine if the template parameter \p D has a visible default argument.
2443 bool
2444 hasVisibleDefaultArgument(const NamedDecl *D,
2445 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2446 /// Determine if the template parameter \p D has a reachable default argument.
2447 bool hasReachableDefaultArgument(
2448 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2449 /// Determine if the template parameter \p D has a reachable default argument.
2450 bool hasAcceptableDefaultArgument(const NamedDecl *D,
2451 llvm::SmallVectorImpl<Module *> *Modules,
2452 Sema::AcceptableKind Kind);
2453
2454 /// Determine if there is a visible declaration of \p D that is an explicit
2455 /// specialization declaration for a specialization of a template. (For a
2456 /// member specialization, use hasVisibleMemberSpecialization.)
2457 bool hasVisibleExplicitSpecialization(
2458 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2459 /// Determine if there is a reachable declaration of \p D that is an explicit
2460 /// specialization declaration for a specialization of a template. (For a
2461 /// member specialization, use hasReachableMemberSpecialization.)
2462 bool hasReachableExplicitSpecialization(
2463 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2464
2465 /// Determine if there is a visible declaration of \p D that is a member
2466 /// specialization declaration (as opposed to an instantiated declaration).
2467 bool hasVisibleMemberSpecialization(
2468 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2469 /// Determine if there is a reachable declaration of \p D that is a member
2470 /// specialization declaration (as opposed to an instantiated declaration).
2471 bool hasReachableMemberSpecialization(
2472 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2473
2474 /// Determine if \p A and \p B are equivalent internal linkage declarations
2475 /// from different modules, and thus an ambiguity error can be downgraded to
2476 /// an extension warning.
2477 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
2478 const NamedDecl *B);
2479 void diagnoseEquivalentInternalLinkageDeclarations(
2480 SourceLocation Loc, const NamedDecl *D,
2481 ArrayRef<const NamedDecl *> Equiv);
2482
2483 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
2484
2485 // Check whether the size of array element of type \p EltTy is a multiple of
2486 // its alignment and return false if it isn't.
2487 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
2488
2489 bool isCompleteType(SourceLocation Loc, QualType T,
2490 CompleteTypeKind Kind = CompleteTypeKind::Default) {
2491 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2492 }
2493 bool RequireCompleteType(SourceLocation Loc, QualType T,
2494 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2495 bool RequireCompleteType(SourceLocation Loc, QualType T,
2496 CompleteTypeKind Kind, unsigned DiagID);
2497
2498 bool RequireCompleteType(SourceLocation Loc, QualType T,
2499 TypeDiagnoser &Diagnoser) {
2500 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2501 }
2502 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2503 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2504 }
2505
2506 template <typename... Ts>
2507 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2508 const Ts &...Args) {
2509 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2510 return RequireCompleteType(Loc, T, Diagnoser);
2511 }
2512
2513 template <typename... Ts>
2514 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2515 const Ts &... Args) {
2516 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2517 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2518 }
2519
2520 /// Get the type of expression E, triggering instantiation to complete the
2521 /// type if necessary -- that is, if the expression refers to a templated
2522 /// static data member of incomplete array type.
2523 ///
2524 /// May still return an incomplete type if instantiation was not possible or
2525 /// if the type is incomplete for a different reason. Use
2526 /// RequireCompleteExprType instead if a diagnostic is expected for an
2527 /// incomplete expression type.
2528 QualType getCompletedType(Expr *E);
2529
2530 void completeExprArrayBound(Expr *E);
2531 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2532 TypeDiagnoser &Diagnoser);
2533 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2534
2535 template <typename... Ts>
2536 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2537 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2538 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2539 }
2540
2541 template <typename... Ts>
2542 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2543 const Ts &... Args) {
2544 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2545 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2546 }
2547
2548 bool RequireLiteralType(SourceLocation Loc, QualType T,
2549 TypeDiagnoser &Diagnoser);
2550 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2551
2552 template <typename... Ts>
2553 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2554 const Ts &...Args) {
2555 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2556 return RequireLiteralType(Loc, T, Diagnoser);
2557 }
2558
2559 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2560 const CXXScopeSpec &SS, QualType T,
2561 TagDecl *OwnedTagDecl = nullptr);
2562
2563 // Returns the underlying type of a decltype with the given expression.
2564 QualType getDecltypeForExpr(Expr *E);
2565
2566 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
2567 /// If AsUnevaluated is false, E is treated as though it were an evaluated
2568 /// context, such as when building a type for decltype(auto).
2569 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2570
2571 using UTTKind = UnaryTransformType::UTTKind;
2572 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
2573 SourceLocation Loc);
2574 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
2575 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
2576 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
2577 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
2578 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
2579 SourceLocation Loc);
2580 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
2581 SourceLocation Loc);
2582 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
2583 SourceLocation Loc);
2584 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
2585 SourceLocation Loc);
2586 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
2587 SourceLocation Loc);
2588
2589 //===--------------------------------------------------------------------===//
2590 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2591 //
2592
2593 struct SkipBodyInfo {
2594 SkipBodyInfo() = default;
2595 bool ShouldSkip = false;
2596 bool CheckSameAsPrevious = false;
2597 NamedDecl *Previous = nullptr;
2598 NamedDecl *New = nullptr;
2599 };
2600
2601 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2602
2603 void DiagnoseUseOfUnimplementedSelectors();
2604
2605 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2606
2607 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2608 Scope *S, CXXScopeSpec *SS = nullptr,
2609 bool isClassName = false, bool HasTrailingDot = false,
2610 ParsedType ObjectType = nullptr,
2611 bool IsCtorOrDtorName = false,
2612 bool WantNontrivialTypeSourceInfo = false,
2613 bool IsClassTemplateDeductionContext = true,
2614 ImplicitTypenameContext AllowImplicitTypename =
2615 ImplicitTypenameContext::No,
2616 IdentifierInfo **CorrectedII = nullptr);
2617 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2618 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2619 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2620 SourceLocation IILoc,
2621 Scope *S,
2622 CXXScopeSpec *SS,
2623 ParsedType &SuggestedType,
2624 bool IsTemplateName = false);
2625
2626 /// Attempt to behave like MSVC in situations where lookup of an unqualified
2627 /// type name has failed in a dependent context. In these situations, we
2628 /// automatically form a DependentTypeName that will retry lookup in a related
2629 /// scope during instantiation.
2630 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2631 SourceLocation NameLoc,
2632 bool IsTemplateTypeArg);
2633
2634 /// Describes the result of the name lookup and resolution performed
2635 /// by \c ClassifyName().
2636 enum NameClassificationKind {
2637 /// This name is not a type or template in this context, but might be
2638 /// something else.
2639 NC_Unknown,
2640 /// Classification failed; an error has been produced.
2641 NC_Error,
2642 /// The name has been typo-corrected to a keyword.
2643 NC_Keyword,
2644 /// The name was classified as a type.
2645 NC_Type,
2646 /// The name was classified as a specific non-type, non-template
2647 /// declaration. ActOnNameClassifiedAsNonType should be called to
2648 /// convert the declaration to an expression.
2649 NC_NonType,
2650 /// The name was classified as an ADL-only function name.
2651 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2652 /// result to an expression.
2653 NC_UndeclaredNonType,
2654 /// The name denotes a member of a dependent type that could not be
2655 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2656 /// convert the result to an expression.
2657 NC_DependentNonType,
2658 /// The name was classified as an overload set, and an expression
2659 /// representing that overload set has been formed.
2660 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2661 /// expression referencing the overload set.
2662 NC_OverloadSet,
2663 /// The name was classified as a template whose specializations are types.
2664 NC_TypeTemplate,
2665 /// The name was classified as a variable template name.
2666 NC_VarTemplate,
2667 /// The name was classified as a function template name.
2668 NC_FunctionTemplate,
2669 /// The name was classified as an ADL-only function template name.
2670 NC_UndeclaredTemplate,
2671 /// The name was classified as a concept name.
2672 NC_Concept,
2673 };
2674
2675 class NameClassification {
2676 NameClassificationKind Kind;
2677 union {
2678 ExprResult Expr;
2679 NamedDecl *NonTypeDecl;
2680 TemplateName Template;
2681 ParsedType Type;
2682 };
2683
2684 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2685
2686 public:
2687 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2688
2689 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2690
2691 static NameClassification Error() {
2692 return NameClassification(NC_Error);
2693 }
2694
2695 static NameClassification Unknown() {
2696 return NameClassification(NC_Unknown);
2697 }
2698
2699 static NameClassification OverloadSet(ExprResult E) {
2700 NameClassification Result(NC_OverloadSet);
2701 Result.Expr = E;
2702 return Result;
2703 }
2704
2705 static NameClassification NonType(NamedDecl *D) {
2706 NameClassification Result(NC_NonType);
2707 Result.NonTypeDecl = D;
2708 return Result;
2709 }
2710
2711 static NameClassification UndeclaredNonType() {
2712 return NameClassification(NC_UndeclaredNonType);
2713 }
2714
2715 static NameClassification DependentNonType() {
2716 return NameClassification(NC_DependentNonType);
2717 }
2718
2719 static NameClassification TypeTemplate(TemplateName Name) {
2720 NameClassification Result(NC_TypeTemplate);
2721 Result.Template = Name;
2722 return Result;
2723 }
2724
2725 static NameClassification VarTemplate(TemplateName Name) {
2726 NameClassification Result(NC_VarTemplate);
2727 Result.Template = Name;
2728 return Result;
2729 }
2730
2731 static NameClassification FunctionTemplate(TemplateName Name) {
2732 NameClassification Result(NC_FunctionTemplate);
2733 Result.Template = Name;
2734 return Result;
2735 }
2736
2737 static NameClassification Concept(TemplateName Name) {
2738 NameClassification Result(NC_Concept);
2739 Result.Template = Name;
2740 return Result;
2741 }
2742
2743 static NameClassification UndeclaredTemplate(TemplateName Name) {
2744 NameClassification Result(NC_UndeclaredTemplate);
2745 Result.Template = Name;
2746 return Result;
2747 }
2748
2749 NameClassificationKind getKind() const { return Kind; }
2750
2751 ExprResult getExpression() const {
2752 assert(Kind == NC_OverloadSet)(static_cast <bool> (Kind == NC_OverloadSet) ? void (0)
: __assert_fail ("Kind == NC_OverloadSet", "clang/include/clang/Sema/Sema.h"
, 2752, __extension__ __PRETTY_FUNCTION__))
;
2753 return Expr;
2754 }
2755
2756 ParsedType getType() const {
2757 assert(Kind == NC_Type)(static_cast <bool> (Kind == NC_Type) ? void (0) : __assert_fail
("Kind == NC_Type", "clang/include/clang/Sema/Sema.h", 2757,
__extension__ __PRETTY_FUNCTION__))
;
2758 return Type;
2759 }
2760
2761 NamedDecl *getNonTypeDecl() const {
2762 assert(Kind == NC_NonType)(static_cast <bool> (Kind == NC_NonType) ? void (0) : __assert_fail
("Kind == NC_NonType", "clang/include/clang/Sema/Sema.h", 2762
, __extension__ __PRETTY_FUNCTION__))
;
2763 return NonTypeDecl;
2764 }
2765
2766 TemplateName getTemplateName() const {
2767 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2769, __extension__ __PRETTY_FUNCTION__
))
2768 Kind == NC_VarTemplate || Kind == NC_Concept ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2769, __extension__ __PRETTY_FUNCTION__
))
2769 Kind == NC_UndeclaredTemplate)(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2769, __extension__ __PRETTY_FUNCTION__
))
;
2770 return Template;
2771 }
2772
2773 TemplateNameKind getTemplateNameKind() const {
2774 switch (Kind) {
2775 case NC_TypeTemplate:
2776 return TNK_Type_template;
2777 case NC_FunctionTemplate:
2778 return TNK_Function_template;
2779 case NC_VarTemplate:
2780 return TNK_Var_template;
2781 case NC_Concept:
2782 return TNK_Concept_template;
2783 case NC_UndeclaredTemplate:
2784 return TNK_Undeclared_template;
2785 default:
2786 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "clang/include/clang/Sema/Sema.h", 2786)
;
2787 }
2788 }
2789 };
2790
2791 /// Perform name lookup on the given name, classifying it based on
2792 /// the results of name lookup and the following token.
2793 ///
2794 /// This routine is used by the parser to resolve identifiers and help direct
2795 /// parsing. When the identifier cannot be found, this routine will attempt
2796 /// to correct the typo and classify based on the resulting name.
2797 ///
2798 /// \param S The scope in which we're performing name lookup.
2799 ///
2800 /// \param SS The nested-name-specifier that precedes the name.
2801 ///
2802 /// \param Name The identifier. If typo correction finds an alternative name,
2803 /// this pointer parameter will be updated accordingly.
2804 ///
2805 /// \param NameLoc The location of the identifier.
2806 ///
2807 /// \param NextToken The token following the identifier. Used to help
2808 /// disambiguate the name.
2809 ///
2810 /// \param CCC The correction callback, if typo correction is desired.
2811 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2812 IdentifierInfo *&Name, SourceLocation NameLoc,
2813 const Token &NextToken,
2814 CorrectionCandidateCallback *CCC = nullptr);
2815
2816 /// Act on the result of classifying a name as an undeclared (ADL-only)
2817 /// non-type declaration.
2818 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2819 SourceLocation NameLoc);
2820 /// Act on the result of classifying a name as an undeclared member of a
2821 /// dependent base class.
2822 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2823 IdentifierInfo *Name,
2824 SourceLocation NameLoc,
2825 bool IsAddressOfOperand);
2826 /// Act on the result of classifying a name as a specific non-type
2827 /// declaration.
2828 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2829 NamedDecl *Found,
2830 SourceLocation NameLoc,
2831 const Token &NextToken);
2832 /// Act on the result of classifying a name as an overload set.
2833 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2834
2835 /// Describes the detailed kind of a template name. Used in diagnostics.
2836 enum class TemplateNameKindForDiagnostics {
2837 ClassTemplate,
2838 FunctionTemplate,
2839 VarTemplate,
2840 AliasTemplate,
2841 TemplateTemplateParam,
2842 Concept,
2843 DependentTemplate
2844 };
2845 TemplateNameKindForDiagnostics
2846 getTemplateNameKindForDiagnostics(TemplateName Name);
2847
2848 /// Determine whether it's plausible that E was intended to be a
2849 /// template-name.
2850 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2851 if (!getLangOpts().CPlusPlus || E.isInvalid())
2852 return false;
2853 Dependent = false;
2854 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2855 return !DRE->hasExplicitTemplateArgs();
2856 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2857 return !ME->hasExplicitTemplateArgs();
2858 Dependent = true;
2859 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2860 return !DSDRE->hasExplicitTemplateArgs();
2861 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2862 return !DSME->hasExplicitTemplateArgs();
2863 // Any additional cases recognized here should also be handled by
2864 // diagnoseExprIntendedAsTemplateName.
2865 return false;
2866 }
2867 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2868 SourceLocation Less,
2869 SourceLocation Greater);
2870
2871 void warnOnReservedIdentifier(const NamedDecl *D);
2872
2873 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2874
2875 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2876 MultiTemplateParamsArg TemplateParameterLists);
2877 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
2878 QualType &T, SourceLocation Loc,
2879 unsigned FailedFoldDiagID);
2880 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2881 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2882 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2883 DeclarationName Name, SourceLocation Loc,
2884 bool IsTemplateId);
2885 void
2886 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2887 SourceLocation FallbackLoc,
2888 SourceLocation ConstQualLoc = SourceLocation(),
2889 SourceLocation VolatileQualLoc = SourceLocation(),
2890 SourceLocation RestrictQualLoc = SourceLocation(),
2891 SourceLocation AtomicQualLoc = SourceLocation(),
2892 SourceLocation UnalignedQualLoc = SourceLocation());
2893
2894 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2895 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2896 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2897 const LookupResult &R);
2898 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2899 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
2900 const LookupResult &R);
2901 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2902 const LookupResult &R);
2903 void CheckShadow(Scope *S, VarDecl *D);
2904
2905 /// Warn if 'E', which is an expression that is about to be modified, refers
2906 /// to a shadowing declaration.
2907 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2908
2909 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2910
2911private:
2912 /// Map of current shadowing declarations to shadowed declarations. Warn if
2913 /// it looks like the user is trying to modify the shadowing declaration.
2914 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2915
2916public:
2917 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2918 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2919 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2920 TypedefNameDecl *NewTD);
2921 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2922 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2923 TypeSourceInfo *TInfo,
2924 LookupResult &Previous);
2925 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2926 LookupResult &Previous, bool &Redeclaration);
2927 NamedDecl *ActOnVariableDeclarator(
2928 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
2929 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
2930 bool &AddToScope, ArrayRef<BindingDecl *> Bindings = std::nullopt);
2931 NamedDecl *
2932 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2933 MultiTemplateParamsArg TemplateParamLists);
2934 // Returns true if the variable declaration is a redeclaration
2935 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2936 void CheckVariableDeclarationType(VarDecl *NewVD);
2937 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2938 Expr *Init);
2939 void CheckCompleteVariableDeclaration(VarDecl *VD);
2940 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2941 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2942
2943 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2944 TypeSourceInfo *TInfo,
2945 LookupResult &Previous,
2946 MultiTemplateParamsArg TemplateParamLists,
2947 bool &AddToScope);
2948 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2949
2950 enum class CheckConstexprKind {
2951 /// Diagnose issues that are non-constant or that are extensions.
2952 Diagnose,
2953 /// Identify whether this function satisfies the formal rules for constexpr
2954 /// functions in the current lanugage mode (with no extensions).
2955 CheckValid
2956 };
2957
2958 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2959 CheckConstexprKind Kind);
2960
2961 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2962 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2963 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2964 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2965 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2966 // Returns true if the function declaration is a redeclaration
2967 bool CheckFunctionDeclaration(Scope *S,
2968 FunctionDecl *NewFD, LookupResult &Previous,
2969 bool IsMemberSpecialization, bool DeclIsDefn);
2970 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2971 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2972 QualType NewT, QualType OldT);
2973 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2974 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2975 void CheckHLSLEntryPoint(FunctionDecl *FD);
2976 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2977 bool IsDefinition);
2978 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2979 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2980 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2981 SourceLocation Loc,
2982 QualType T);
2983 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2984 SourceLocation NameLoc, IdentifierInfo *Name,
2985 QualType T, TypeSourceInfo *TSInfo,
2986 StorageClass SC);
2987 void ActOnParamDefaultArgument(Decl *param,
2988 SourceLocation EqualLoc,
2989 Expr *defarg);
2990 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2991 SourceLocation ArgLoc);
2992 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2993 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2994 SourceLocation EqualLoc);
2995 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2996 SourceLocation EqualLoc);
2997
2998 // Contexts where using non-trivial C union types can be disallowed. This is
2999 // passed to err_non_trivial_c_union_in_invalid_context.
3000 enum NonTrivialCUnionContext {
3001 // Function parameter.
3002 NTCUC_FunctionParam,
3003 // Function return.
3004 NTCUC_FunctionReturn,
3005 // Default-initialized object.
3006 NTCUC_DefaultInitializedObject,
3007 // Variable with automatic storage duration.
3008 NTCUC_AutoVar,
3009 // Initializer expression that might copy from another object.
3010 NTCUC_CopyInit,
3011 // Assignment.
3012 NTCUC_Assignment,
3013 // Compound literal.
3014 NTCUC_CompoundLiteral,
3015 // Block capture.
3016 NTCUC_BlockCapture,
3017 // lvalue-to-rvalue conversion of volatile type.
3018 NTCUC_LValueToRValueVolatile,
3019 };
3020
3021 /// Emit diagnostics if the initializer or any of its explicit or
3022 /// implicitly-generated subexpressions require copying or
3023 /// default-initializing a type that is or contains a C union type that is
3024 /// non-trivial to copy or default-initialize.
3025 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
3026
3027 // These flags are passed to checkNonTrivialCUnion.
3028 enum NonTrivialCUnionKind {
3029 NTCUK_Init = 0x1,
3030 NTCUK_Destruct = 0x2,
3031 NTCUK_Copy = 0x4,
3032 };
3033
3034 /// Emit diagnostics if a non-trivial C union type or a struct that contains
3035 /// a non-trivial C union is used in an invalid context.
3036 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
3037 NonTrivialCUnionContext UseContext,
3038 unsigned NonTrivialKind);
3039
3040 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
3041 void ActOnUninitializedDecl(Decl *dcl);
3042 void ActOnInitializerError(Decl *Dcl);
3043
3044 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
3045 void ActOnCXXForRangeDecl(Decl *D);
3046 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
3047 IdentifierInfo *Ident,
3048 ParsedAttributes &Attrs);
3049 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
3050 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
3051 void CheckStaticLocalForDllExport(VarDecl *VD);
3052 void CheckThreadLocalForLargeAlignment(VarDecl *VD);
3053 void FinalizeDeclaration(Decl *D);
3054 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3055 ArrayRef<Decl *> Group);
3056 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
3057
3058 /// Should be called on all declarations that might have attached
3059 /// documentation comments.
3060 void ActOnDocumentableDecl(Decl *D);
3061 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
3062
3063 enum class FnBodyKind {
3064 /// C++ [dcl.fct.def.general]p1
3065 /// function-body:
3066 /// ctor-initializer[opt] compound-statement
3067 /// function-try-block
3068 Other,
3069 /// = default ;
3070 Default,
3071 /// = delete ;
3072 Delete
3073 };
3074
3075 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
3076 SourceLocation LocAfterDecls);
3077 void CheckForFunctionRedefinition(
3078 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
3079 SkipBodyInfo *SkipBody = nullptr);
3080 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
3081 MultiTemplateParamsArg TemplateParamLists,
3082 SkipBodyInfo *SkipBody = nullptr,
3083 FnBodyKind BodyKind = FnBodyKind::Other);
3084 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
3085 SkipBodyInfo *SkipBody = nullptr,
3086 FnBodyKind BodyKind = FnBodyKind::Other);
3087 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind);
3088 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
3089 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
3090 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
3091 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
3092 bool isObjCMethodDecl(Decl *D) {
3093 return D && isa<ObjCMethodDecl>(D);
3094 }
3095
3096 /// Determine whether we can delay parsing the body of a function or
3097 /// function template until it is used, assuming we don't care about emitting
3098 /// code for that function.
3099 ///
3100 /// This will be \c false if we may need the body of the function in the
3101 /// middle of parsing an expression (where it's impractical to switch to
3102 /// parsing a different function), for instance, if it's constexpr in C++11
3103 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
3104 bool canDelayFunctionBody(const Declarator &D);
3105
3106 /// Determine whether we can skip parsing the body of a function
3107 /// definition, assuming we don't care about analyzing its body or emitting
3108 /// code for that function.
3109 ///
3110 /// This will be \c false only if we may need the body of the function in
3111 /// order to parse the rest of the program (for instance, if it is
3112 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
3113 bool canSkipFunctionBody(Decl *D);
3114
3115 /// Determine whether \param D is function like (function or function
3116 /// template) for parsing.
3117 bool isDeclaratorFunctionLike(Declarator &D);
3118
3119 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
3120 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
3121 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
3122 Decl *ActOnSkippedFunctionBody(Decl *Decl);
3123 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
3124
3125 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
3126 /// attribute for which parsing is delayed.
3127 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
3128
3129 /// Diagnose any unused parameters in the given sequence of
3130 /// ParmVarDecl pointers.
3131 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
3132
3133 /// Diagnose whether the size of parameters or return value of a
3134 /// function or obj-c method definition is pass-by-value and larger than a
3135 /// specified threshold.
3136 void
3137 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
3138 QualType ReturnTy, NamedDecl *D);
3139
3140 void DiagnoseInvalidJumps(Stmt *Body);
3141 Decl *ActOnFileScopeAsmDecl(Expr *expr,
3142 SourceLocation AsmLoc,
3143 SourceLocation RParenLoc);
3144
3145 Decl *ActOnTopLevelStmtDecl(Stmt *Statement);
3146
3147 /// Handle a C++11 empty-declaration and attribute-declaration.
3148 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
3149 SourceLocation SemiLoc);
3150
3151 enum class ModuleDeclKind {
3152 Interface, ///< 'export module X;'
3153 Implementation, ///< 'module X;'
3154 PartitionInterface, ///< 'export module X:Y;'
3155 PartitionImplementation, ///< 'module X:Y;'
3156 };
3157
3158 /// An enumeration to represent the transition of states in parsing module
3159 /// fragments and imports. If we are not parsing a C++20 TU, or we find
3160 /// an error in state transition, the state is set to NotACXX20Module.
3161 enum class ModuleImportState {
3162 FirstDecl, ///< Parsing the first decl in a TU.
3163 GlobalFragment, ///< after 'module;' but before 'module X;'
3164 ImportAllowed, ///< after 'module X;' but before any non-import decl.
3165 ImportFinished, ///< after any non-import decl.
3166 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
3167 ///< non-import decl.
3168 PrivateFragmentImportFinished, ///< after 'module :private;' but a
3169 ///< non-import decl has already been seen.
3170 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
3171 };
3172
3173private:
3174 /// The parser has begun a translation unit to be compiled as a C++20
3175 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
3176 void HandleStartOfHeaderUnit();
3177
3178public:
3179 /// The parser has processed a module-declaration that begins the definition
3180 /// of a module interface or implementation.
3181 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
3182 SourceLocation ModuleLoc, ModuleDeclKind MDK,
3183 ModuleIdPath Path, ModuleIdPath Partition,
3184 ModuleImportState &ImportState);
3185
3186 /// The parser has processed a global-module-fragment declaration that begins
3187 /// the definition of the global module fragment of the current module unit.
3188 /// \param ModuleLoc The location of the 'module' keyword.
3189 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
3190
3191 /// The parser has processed a private-module-fragment declaration that begins
3192 /// the definition of the private module fragment of the current module unit.
3193 /// \param ModuleLoc The location of the 'module' keyword.
3194 /// \param PrivateLoc The location of the 'private' keyword.
3195 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
3196 SourceLocation PrivateLoc);
3197
3198 /// The parser has processed a module import declaration.
3199 ///
3200 /// \param StartLoc The location of the first token in the declaration. This
3201 /// could be the location of an '@', 'export', or 'import'.
3202 /// \param ExportLoc The location of the 'export' keyword, if any.
3203 /// \param ImportLoc The location of the 'import' keyword.
3204 /// \param Path The module toplevel name as an access path.
3205 /// \param IsPartition If the name is for a partition.
3206 DeclResult ActOnModuleImport(SourceLocation StartLoc,
3207 SourceLocation ExportLoc,
3208 SourceLocation ImportLoc, ModuleIdPath Path,
3209 bool IsPartition = false);
3210 DeclResult ActOnModuleImport(SourceLocation StartLoc,
3211 SourceLocation ExportLoc,
3212 SourceLocation ImportLoc, Module *M,
3213 ModuleIdPath Path = {});
3214
3215 /// The parser has processed a module import translated from a
3216 /// #include or similar preprocessing directive.
3217 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3218 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3219
3220 /// The parsed has entered a submodule.
3221 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
3222 /// The parser has left a submodule.
3223 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
3224
3225 /// Create an implicit import of the given module at the given
3226 /// source location, for error recovery, if possible.
3227 ///
3228 /// This routine is typically used when an entity found by name lookup
3229 /// is actually hidden within a module that we know about but the user
3230 /// has forgotten to import.
3231 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3232 Module *Mod);
3233
3234 /// Kinds of missing import. Note, the values of these enumerators correspond
3235 /// to %select values in diagnostics.
3236 enum class MissingImportKind {
3237 Declaration,
3238 Definition,
3239 DefaultArgument,
3240 ExplicitSpecialization,
3241 PartialSpecialization
3242 };
3243
3244 /// Diagnose that the specified declaration needs to be visible but
3245 /// isn't, and suggest a module import that would resolve the problem.
3246 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
3247 MissingImportKind MIK, bool Recover = true);
3248 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
3249 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3250 MissingImportKind MIK, bool Recover);
3251
3252 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
3253 SourceLocation LBraceLoc);
3254 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
3255 SourceLocation RBraceLoc);
3256
3257 /// We've found a use of a templated declaration that would trigger an
3258 /// implicit instantiation. Check that any relevant explicit specializations
3259 /// and partial specializations are visible/reachable, and diagnose if not.
3260 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
3261 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
3262
3263 /// Retrieve a suitable printing policy for diagnostics.
3264 PrintingPolicy getPrintingPolicy() const {
3265 return getPrintingPolicy(Context, PP);
3266 }
3267
3268 /// Retrieve a suitable printing policy for diagnostics.
3269 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
3270 const Preprocessor &PP);
3271
3272 /// Scope actions.
3273 void ActOnPopScope(SourceLocation Loc, Scope *S);
3274 void ActOnTranslationUnitScope(Scope *S);
3275
3276 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3277 const ParsedAttributesView &DeclAttrs,
3278 RecordDecl *&AnonRecord);
3279 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3280 const ParsedAttributesView &DeclAttrs,
3281 MultiTemplateParamsArg TemplateParams,
3282 bool IsExplicitInstantiation,
3283 RecordDecl *&AnonRecord);
3284
3285 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3286 AccessSpecifier AS,
3287 RecordDecl *Record,
3288 const PrintingPolicy &Policy);
3289
3290 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3291 RecordDecl *Record);
3292
3293 /// Common ways to introduce type names without a tag for use in diagnostics.
3294 /// Keep in sync with err_tag_reference_non_tag.
3295 enum NonTagKind {
3296 NTK_NonStruct,
3297 NTK_NonClass,
3298 NTK_NonUnion,
3299 NTK_NonEnum,
3300 NTK_Typedef,
3301 NTK_TypeAlias,
3302 NTK_Template,
3303 NTK_TypeAliasTemplate,
3304 NTK_TemplateTemplateArgument,
3305 };
3306
3307 /// Given a non-tag type declaration, returns an enum useful for indicating
3308 /// what kind of non-tag type this is.
3309 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
3310
3311 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
3312 TagTypeKind NewTag, bool isDefinition,
3313 SourceLocation NewTagLoc,
3314 const IdentifierInfo *Name);
3315
3316 enum TagUseKind {
3317 TUK_Reference, // Reference to a tag: 'struct foo *X;'
3318 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
3319 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
3320 TUK_Friend // Friend declaration: 'friend struct foo;'
3321 };
3322
3323 enum OffsetOfKind {
3324 // Not parsing a type within __builtin_offsetof.
3325 OOK_Outside,
3326 // Parsing a type within __builtin_offsetof.
3327 OOK_Builtin,
3328 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
3329 // To improve our diagnostic message.
3330 OOK_Macro,
3331 };
3332
3333 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3334 SourceLocation KWLoc, CXXScopeSpec &SS,
3335 IdentifierInfo *Name, SourceLocation NameLoc,
3336 const ParsedAttributesView &Attr, AccessSpecifier AS,
3337 SourceLocation ModulePrivateLoc,
3338 MultiTemplateParamsArg TemplateParameterLists,
3339 bool &OwnedDecl, bool &IsDependent,
3340 SourceLocation ScopedEnumKWLoc,
3341 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3342 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3343 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
3344
3345 DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
3346 unsigned TagSpec, SourceLocation TagLoc,
3347 CXXScopeSpec &SS, IdentifierInfo *Name,
3348 SourceLocation NameLoc,
3349 const ParsedAttributesView &Attr,
3350 MultiTemplateParamsArg TempParamLists);
3351
3352 TypeResult ActOnDependentTag(Scope *S,
3353 unsigned TagSpec,
3354 TagUseKind TUK,
3355 const CXXScopeSpec &SS,
3356 IdentifierInfo *Name,
3357 SourceLocation TagLoc,
3358 SourceLocation NameLoc);
3359
3360 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3361 IdentifierInfo *ClassName,
3362 SmallVectorImpl<Decl *> &Decls);
3363 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3364 Declarator &D, Expr *BitfieldWidth);
3365
3366 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3367 Declarator &D, Expr *BitfieldWidth,
3368 InClassInitStyle InitStyle,
3369 AccessSpecifier AS);
3370 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
3371 SourceLocation DeclStart, Declarator &D,
3372 Expr *BitfieldWidth,
3373 InClassInitStyle InitStyle,
3374 AccessSpecifier AS,
3375 const ParsedAttr &MSPropertyAttr);
3376
3377 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
3378 TypeSourceInfo *TInfo,
3379 RecordDecl *Record, SourceLocation Loc,
3380 bool Mutable, Expr *BitfieldWidth,
3381 InClassInitStyle InitStyle,
3382 SourceLocation TSSL,
3383 AccessSpecifier AS, NamedDecl *PrevDecl,
3384 Declarator *D = nullptr);
3385
3386 bool CheckNontrivialField(FieldDecl *FD);
3387 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3388
3389 enum TrivialABIHandling {
3390 /// The triviality of a method unaffected by "trivial_abi".
3391 TAH_IgnoreTrivialABI,
3392
3393 /// The triviality of a method affected by "trivial_abi".
3394 TAH_ConsiderTrivialABI
3395 };
3396
3397 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
3398 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
3399 bool Diagnose = false);
3400
3401 /// For a defaulted function, the kind of defaulted function that it is.
3402 class DefaultedFunctionKind {
3403 CXXSpecialMember SpecialMember : 8;
3404 DefaultedComparisonKind Comparison : 8;
3405
3406 public:
3407 DefaultedFunctionKind()
3408 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3409 }
3410 DefaultedFunctionKind(CXXSpecialMember CSM)
3411 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3412 DefaultedFunctionKind(DefaultedComparisonKind Comp)
3413 : SpecialMember(CXXInvalid), Comparison(Comp) {}
3414
3415 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3416 bool isComparison() const {
3417 return Comparison != DefaultedComparisonKind::None;
3418 }
3419
3420 explicit operator bool() const {
3421 return isSpecialMember() || isComparison();
3422 }
3423
3424 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3425 DefaultedComparisonKind asComparison() const { return Comparison; }
3426
3427 /// Get the index of this function kind for use in diagnostics.
3428 unsigned getDiagnosticIndex() const {
3429 static_assert(CXXInvalid > CXXDestructor,
3430 "invalid should have highest index");
3431 static_assert((unsigned)DefaultedComparisonKind::None == 0,
3432 "none should be equal to zero");
3433 return SpecialMember + (unsigned)Comparison;
3434 }
3435 };
3436
3437 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3438
3439 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
3440 return getDefaultedFunctionKind(MD).asSpecialMember();
3441 }
3442 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
3443 return getDefaultedFunctionKind(FD).asComparison();
3444 }
3445
3446 void ActOnLastBitfield(SourceLocation DeclStart,
3447 SmallVectorImpl<Decl *> &AllIvarDecls);
3448 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3449 Declarator &D, Expr *BitfieldWidth,
3450 tok::ObjCKeywordKind visibility);
3451
3452 // This is used for both record definitions and ObjC interface declarations.
3453 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3454 ArrayRef<Decl *> Fields, SourceLocation LBrac,
3455 SourceLocation RBrac, const ParsedAttributesView &AttrList);
3456
3457 /// ActOnTagStartDefinition - Invoked when we have entered the
3458 /// scope of a tag's definition (e.g., for an enumeration, class,
3459 /// struct, or union).
3460 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
3461
3462 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3463 /// Differently from C++, actually parse the body and reject / error out
3464 /// in case of a structural mismatch.
3465 bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3466
3467 /// Check ODR hashes for C/ObjC when merging types from modules.
3468 /// Differently from C++, actually parse the body and reject in case
3469 /// of a mismatch.
3470 template <typename T,
3471 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
3472 bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) {
3473 if (Duplicate->getODRHash() != Previous->getODRHash())
3474 return false;
3475
3476 // Make the previous decl visible.
3477 makeMergedDefinitionVisible(Previous);
3478 return true;
3479 }
3480
3481 typedef void *SkippedDefinitionContext;
3482
3483 /// Invoked when we enter a tag definition that we're skipping.
3484 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
3485
3486 void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl);
3487
3488 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3489 /// C++ record definition's base-specifiers clause and are starting its
3490 /// member declarations.
3491 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
3492 SourceLocation FinalLoc,
3493 bool IsFinalSpelledSealed,
3494 bool IsAbstract,
3495 SourceLocation LBraceLoc);
3496
3497 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3498 /// the definition of a tag (enumeration, class, struct, or union).
3499 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
3500 SourceRange BraceRange);
3501
3502 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
3503
3504 void ActOnObjCContainerFinishDefinition();
3505
3506 /// Invoked when we must temporarily exit the objective-c container
3507 /// scope for parsing/looking-up C constructs.
3508 ///
3509 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3510 void ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx);
3511 void ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx);
3512
3513 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3514 /// error parsing the definition of a tag.
3515 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
3516
3517 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
3518 EnumConstantDecl *LastEnumConst,
3519 SourceLocation IdLoc,
3520 IdentifierInfo *Id,
3521 Expr *val);
3522 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
3523 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3524 QualType EnumUnderlyingTy, bool IsFixed,
3525 const EnumDecl *Prev);
3526
3527 /// Determine whether the body of an anonymous enumeration should be skipped.
3528 /// \param II The name of the first enumerator.
3529 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
3530 SourceLocation IILoc);
3531
3532 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3533 SourceLocation IdLoc, IdentifierInfo *Id,
3534 const ParsedAttributesView &Attrs,
3535 SourceLocation EqualLoc, Expr *Val);
3536 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3537 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3538 const ParsedAttributesView &Attr);
3539
3540 /// Set the current declaration context until it gets popped.
3541 void PushDeclContext(Scope *S, DeclContext *DC);
3542 void PopDeclContext();
3543
3544 /// EnterDeclaratorContext - Used when we must lookup names in the context
3545 /// of a declarator's nested name specifier.
3546 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
3547 void ExitDeclaratorContext(Scope *S);
3548
3549 /// Enter a template parameter scope, after it's been associated with a particular
3550 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3551 /// in the correct order.
3552 void EnterTemplatedContext(Scope *S, DeclContext *DC);
3553
3554 /// Push the parameters of D, which must be a function, into scope.
3555 void ActOnReenterFunctionContext(Scope* S, Decl* D);
3556 void ActOnExitFunctionContext();
3557
3558 /// If \p AllowLambda is true, treat lambda as function.
3559 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
3560
3561 /// Returns a pointer to the innermost enclosing function, or nullptr if the
3562 /// current context is not inside a function. If \p AllowLambda is true,
3563 /// this can return the call operator of an enclosing lambda, otherwise
3564 /// lambdas are skipped when looking for an enclosing function.
3565 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
3566
3567 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3568 /// the method decl for the method being parsed. If we're currently
3569 /// in a 'block', this returns the containing context.
3570 ObjCMethodDecl *getCurMethodDecl();
3571
3572 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3573 /// or C function we're in, otherwise return null. If we're currently
3574 /// in a 'block', this returns the containing context.
3575 NamedDecl *getCurFunctionOrMethodDecl() const;
3576
3577 /// Add this decl to the scope shadowed decl chains.
3578 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3579
3580 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3581 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3582 /// true if 'D' belongs to the given declaration context.
3583 ///
3584 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3585 /// enclosing namespace set of the context, rather than contained
3586 /// directly within it.
3587 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3588 bool AllowInlineNamespace = false) const;
3589
3590 /// Finds the scope corresponding to the given decl context, if it
3591 /// happens to be an enclosing scope. Otherwise return NULL.
3592 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3593
3594 /// Subroutines of ActOnDeclarator().
3595 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
3596 TypeSourceInfo *TInfo);
3597 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
3598
3599 /// Describes the kind of merge to perform for availability
3600 /// attributes (including "deprecated", "unavailable", and "availability").
3601 enum AvailabilityMergeKind {
3602 /// Don't merge availability attributes at all.
3603 AMK_None,
3604 /// Merge availability attributes for a redeclaration, which requires
3605 /// an exact match.
3606 AMK_Redeclaration,
3607 /// Merge availability attributes for an override, which requires
3608 /// an exact match or a weakening of constraints.
3609 AMK_Override,
3610 /// Merge availability attributes for an implementation of
3611 /// a protocol requirement.
3612 AMK_ProtocolImplementation,
3613 /// Merge availability attributes for an implementation of
3614 /// an optional protocol requirement.
3615 AMK_OptionalProtocolImplementation
3616 };
3617
3618 /// Describes the kind of priority given to an availability attribute.
3619 ///
3620 /// The sum of priorities deteremines the final priority of the attribute.
3621 /// The final priority determines how the attribute will be merged.
3622 /// An attribute with a lower priority will always remove higher priority
3623 /// attributes for the specified platform when it is being applied. An
3624 /// attribute with a higher priority will not be applied if the declaration
3625 /// already has an availability attribute with a lower priority for the
3626 /// specified platform. The final prirority values are not expected to match
3627 /// the values in this enumeration, but instead should be treated as a plain
3628 /// integer value. This enumeration just names the priority weights that are
3629 /// used to calculate that final vaue.
3630 enum AvailabilityPriority : int {
3631 /// The availability attribute was specified explicitly next to the
3632 /// declaration.
3633 AP_Explicit = 0,
3634
3635 /// The availability attribute was applied using '#pragma clang attribute'.
3636 AP_PragmaClangAttribute = 1,
3637
3638 /// The availability attribute for a specific platform was inferred from
3639 /// an availability attribute for another platform.
3640 AP_InferredFromOtherPlatform = 2
3641 };
3642
3643 /// Attribute merging methods. Return true if a new attribute was added.
3644 AvailabilityAttr *
3645 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3646 IdentifierInfo *Platform, bool Implicit,
3647 VersionTuple Introduced, VersionTuple Deprecated,
3648 VersionTuple Obsoleted, bool IsUnavailable,
3649 StringRef Message, bool IsStrict, StringRef Replacement,
3650 AvailabilityMergeKind AMK, int Priority);
3651 TypeVisibilityAttr *
3652 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3653 TypeVisibilityAttr::VisibilityType Vis);
3654 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3655 VisibilityAttr::VisibilityType Vis);
3656 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3657 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3658 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3659 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3660 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3661 const AttributeCommonInfo &CI,
3662 bool BestCase,
3663 MSInheritanceModel Model);
3664 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3665 StringRef NewUserDiagnostic);
3666 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3667 IdentifierInfo *Format, int FormatIdx,
3668 int FirstArg);
3669 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3670 StringRef Name);
3671 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3672 StringRef Name);
3673 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3674 const AttributeCommonInfo &CI,
3675 const IdentifierInfo *Ident);
3676 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3677 SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3678 StringRef Name);
3679 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3680 const AttributeCommonInfo &CI);
3681 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3682 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3683 const InternalLinkageAttr &AL);
3684 WebAssemblyImportNameAttr *mergeImportNameAttr(
3685 Decl *D, const WebAssemblyImportNameAttr &AL);
3686 WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3687 Decl *D, const WebAssemblyImportModuleAttr &AL);
3688 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3689 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3690 const EnforceTCBLeafAttr &AL);
3691 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3692 HLSLNumThreadsAttr *mergeHLSLNumThreadsAttr(Decl *D,
3693 const AttributeCommonInfo &AL,
3694 int X, int Y, int Z);
3695 HLSLShaderAttr *mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL,
3696 HLSLShaderAttr::ShaderType ShaderType);
3697
3698 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3699 AvailabilityMergeKind AMK = AMK_Redeclaration);
3700 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
3701 LookupResult &OldDecls);
3702 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3703 bool MergeTypeWithOld, bool NewDeclIsDefn);
3704 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3705 Scope *S, bool MergeTypeWithOld);
3706 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
3707 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
3708 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3709 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3710 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3711 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3712 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3713
3714 // AssignmentAction - This is used by all the assignment diagnostic functions
3715 // to represent what is actually causing the operation
3716 enum AssignmentAction {
3717 AA_Assigning,
3718 AA_Passing,
3719 AA_Returning,
3720 AA_Converting,
3721 AA_Initializing,
3722 AA_Sending,
3723 AA_Casting,
3724 AA_Passing_CFAudited
3725 };
3726
3727 /// C++ Overloading.
3728 enum OverloadKind {
3729 /// This is a legitimate overload: the existing declarations are
3730 /// functions or function templates with different signatures.
3731 Ovl_Overload,
3732
3733 /// This is not an overload because the signature exactly matches
3734 /// an existing declaration.
3735 Ovl_Match,
3736
3737 /// This is not an overload because the lookup results contain a
3738 /// non-function.
3739 Ovl_NonFunction
3740 };
3741 OverloadKind CheckOverload(Scope *S,
3742 FunctionDecl *New,
3743 const LookupResult &OldDecls,
3744 NamedDecl *&OldDecl,
3745 bool UseMemberUsingDeclRules);
3746 bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
3747 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true,
3748 bool ConsiderRequiresClauses = true);
3749
3750 // Calculates whether the expression Constraint depends on an enclosing
3751 // template, for the purposes of [temp.friend] p9.
3752 // TemplateDepth is the 'depth' of the friend function, which is used to
3753 // compare whether a declaration reference is referring to a containing
3754 // template, or just the current friend function. A 'lower' TemplateDepth in
3755 // the AST refers to a 'containing' template. As the constraint is
3756 // uninstantiated, this is relative to the 'top' of the TU.
3757 bool
3758 ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
3759 unsigned TemplateDepth,
3760 const Expr *Constraint);
3761
3762 // Calculates whether the friend function depends on an enclosing template for
3763 // the purposes of [temp.friend] p9.
3764 bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD);
3765
3766 // Calculates whether two constraint expressions are equal irrespective of a
3767 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
3768 // 'New', which are the "source" of the constraint, since this is necessary
3769 // for figuring out the relative 'depth' of the constraint. The depth of the
3770 // 'primary template' and the 'instantiated from' templates aren't necessarily
3771 // the same, such as a case when one is a 'friend' defined in a class.
3772 bool AreConstraintExpressionsEqual(const NamedDecl *Old,
3773 const Expr *OldConstr,
3774 const NamedDecl *New,
3775 const Expr *NewConstr);
3776
3777 enum class AllowedExplicit {
3778 /// Allow no explicit functions to be used.
3779 None,
3780 /// Allow explicit conversion functions but not explicit constructors.
3781 Conversions,
3782 /// Allow both explicit conversion functions and explicit constructors.
3783 All
3784 };
3785
3786 ImplicitConversionSequence
3787 TryImplicitConversion(Expr *From, QualType ToType,
3788 bool SuppressUserConversions,
3789 AllowedExplicit AllowExplicit,
3790 bool InOverloadResolution,
3791 bool CStyle,
3792 bool AllowObjCWritebackConversion);
3793
3794 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3795 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3796 bool IsComplexPromotion(QualType FromType, QualType ToType);
3797 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3798 bool InOverloadResolution,
3799 QualType& ConvertedType, bool &IncompatibleObjC);
3800 bool isObjCPointerConversion(QualType FromType, QualType ToType,
3801 QualType& ConvertedType, bool &IncompatibleObjC);
3802 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3803 QualType &ConvertedType);
3804 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3805 QualType& ConvertedType);
3806 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3807 const FunctionProtoType *NewType,
3808 unsigned *ArgPos = nullptr,
3809 bool Reversed = false);
3810 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3811 QualType FromType, QualType ToType);
3812
3813 void maybeExtendBlockObject(ExprResult &E);
3814 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
3815 bool CheckPointerConversion(Expr *From, QualType ToType,
3816 CastKind &Kind,
3817 CXXCastPath& BasePath,
3818 bool IgnoreBaseAccess,
3819 bool Diagnose = true);
3820 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3821 bool InOverloadResolution,
3822 QualType &ConvertedType);
3823 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3824 CastKind &Kind,
3825 CXXCastPath &BasePath,
3826 bool IgnoreBaseAccess);
3827 bool IsQualificationConversion(QualType FromType, QualType ToType,
3828 bool CStyle, bool &ObjCLifetimeConversion);
3829 bool IsFunctionConversion(QualType FromType, QualType ToType,
3830 QualType &ResultTy);
3831 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3832 bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
3833
3834 bool CanPerformAggregateInitializationForOverloadResolution(
3835 const InitializedEntity &Entity, InitListExpr *From);
3836
3837 bool IsStringInit(Expr *Init, const ArrayType *AT);
3838
3839 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3840 ExprResult Init);
3841 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3842 SourceLocation EqualLoc,
3843 ExprResult Init,
3844 bool TopLevelOfInitList = false,
3845 bool AllowExplicit = false);
3846 ExprResult PerformObjectArgumentInitialization(Expr *From,
3847 NestedNameSpecifier *Qualifier,
3848 NamedDecl *FoundDecl,
3849 CXXMethodDecl *Method);
3850
3851 /// Check that the lifetime of the initializer (and its subobjects) is
3852 /// sufficient for initializing the entity, and perform lifetime extension
3853 /// (when permitted) if not.
3854 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3855
3856 ExprResult PerformContextuallyConvertToBool(Expr *From);
3857 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3858
3859 /// Contexts in which a converted constant expression is required.
3860 enum CCEKind {
3861 CCEK_CaseValue, ///< Expression in a case label.
3862 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
3863 CCEK_TemplateArg, ///< Value of a non-type template parameter.
3864 CCEK_ArrayBound, ///< Array bound in array declarator or new-expression.
3865 CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier.
3866 CCEK_Noexcept ///< Condition in a noexcept(bool) specifier.
3867 };
3868 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3869 llvm::APSInt &Value, CCEKind CCE);
3870 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3871 APValue &Value, CCEKind CCE,
3872 NamedDecl *Dest = nullptr);
3873
3874 /// Abstract base class used to perform a contextual implicit
3875 /// conversion from an expression to any type passing a filter.
3876 class ContextualImplicitConverter {
3877 public:
3878 bool Suppress;
3879 bool SuppressConversion;
3880
3881 ContextualImplicitConverter(bool Suppress = false,
3882 bool SuppressConversion = false)
3883 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3884
3885 /// Determine whether the specified type is a valid destination type
3886 /// for this conversion.
3887 virtual bool match(QualType T) = 0;
3888
3889 /// Emits a diagnostic complaining that the expression does not have
3890 /// integral or enumeration type.
3891 virtual SemaDiagnosticBuilder
3892 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3893
3894 /// Emits a diagnostic when the expression has incomplete class type.
3895 virtual SemaDiagnosticBuilder
3896 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3897
3898 /// Emits a diagnostic when the only matching conversion function
3899 /// is explicit.
3900 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3901 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3902
3903 /// Emits a note for the explicit conversion function.
3904 virtual SemaDiagnosticBuilder
3905 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3906
3907 /// Emits a diagnostic when there are multiple possible conversion
3908 /// functions.
3909 virtual SemaDiagnosticBuilder
3910 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3911
3912 /// Emits a note for one of the candidate conversions.
3913 virtual SemaDiagnosticBuilder
3914 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3915
3916 /// Emits a diagnostic when we picked a conversion function
3917 /// (for cases when we are not allowed to pick a conversion function).
3918 virtual SemaDiagnosticBuilder diagnoseConversion(
3919 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3920
3921 virtual ~ContextualImplicitConverter() {}
3922 };
3923
3924 class ICEConvertDiagnoser : public ContextualImplicitConverter {
3925 bool AllowScopedEnumerations;
3926
3927 public:
3928 ICEConvertDiagnoser(bool AllowScopedEnumerations,
3929 bool Suppress, bool SuppressConversion)
3930 : ContextualImplicitConverter(Suppress, SuppressConversion),
3931 AllowScopedEnumerations(AllowScopedEnumerations) {}
3932
3933 /// Match an integral or (possibly scoped) enumeration type.
3934 bool match(QualType T) override;
3935
3936 SemaDiagnosticBuilder
3937 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3938 return diagnoseNotInt(S, Loc, T);
3939 }
3940
3941 /// Emits a diagnostic complaining that the expression does not have
3942 /// integral or enumeration type.
3943 virtual SemaDiagnosticBuilder
3944 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3945 };
3946
3947 /// Perform a contextual implicit conversion.
3948 ExprResult PerformContextualImplicitConversion(
3949 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3950
3951
3952 enum ObjCSubscriptKind {
3953 OS_Array,
3954 OS_Dictionary,
3955 OS_Error
3956 };
3957 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3958
3959 // Note that LK_String is intentionally after the other literals, as
3960 // this is used for diagnostics logic.
3961 enum ObjCLiteralKind {
3962 LK_Array,
3963 LK_Dictionary,
3964 LK_Numeric,
3965 LK_Boxed,
3966 LK_String,
3967 LK_Block,
3968 LK_None
3969 };
3970 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3971
3972 ExprResult PerformObjectMemberConversion(Expr *From,
3973 NestedNameSpecifier *Qualifier,
3974 NamedDecl *FoundDecl,
3975 NamedDecl *Member);
3976
3977 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3978 // TODO: make this is a typesafe union.
3979 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
3980 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3981
3982 using ADLCallKind = CallExpr::ADLCallKind;
3983
3984 void AddOverloadCandidate(
3985 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
3986 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3987 bool PartialOverloading = false, bool AllowExplicit = true,
3988 bool AllowExplicitConversion = false,
3989 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3990 ConversionSequenceList EarlyConversions = std::nullopt,
3991 OverloadCandidateParamOrder PO = {});
3992 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3993 ArrayRef<Expr *> Args,
3994 OverloadCandidateSet &CandidateSet,
3995 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3996 bool SuppressUserConversions = false,
3997 bool PartialOverloading = false,
3998 bool FirstArgumentIsBase = false);
3999 void AddMethodCandidate(DeclAccessPair FoundDecl,
4000 QualType ObjectType,
4001 Expr::Classification ObjectClassification,
4002 ArrayRef<Expr *> Args,
4003 OverloadCandidateSet& CandidateSet,
4004 bool SuppressUserConversion = false,
4005 OverloadCandidateParamOrder PO = {});
4006 void
4007 AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
4008 CXXRecordDecl *ActingContext, QualType ObjectType,
4009 Expr::Classification ObjectClassification,
4010 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
4011 bool SuppressUserConversions = false,
4012 bool PartialOverloading = false,
4013 ConversionSequenceList EarlyConversions = std::nullopt,
4014 OverloadCandidateParamOrder PO = {});
4015 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
4016 DeclAccessPair FoundDecl,
4017 CXXRecordDecl *ActingContext,
4018 TemplateArgumentListInfo *ExplicitTemplateArgs,
4019 QualType ObjectType,
4020 Expr::Classification ObjectClassification,
4021 ArrayRef<Expr *> Args,
4022 OverloadCandidateSet& CandidateSet,
4023 bool SuppressUserConversions = false,
4024 bool PartialOverloading = false,
4025 OverloadCandidateParamOrder PO = {});
4026 void AddTemplateOverloadCandidate(
4027 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
4028 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4029 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
4030 bool PartialOverloading = false, bool AllowExplicit = true,
4031 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
4032 OverloadCandidateParamOrder PO = {});
4033 bool CheckNonDependentConversions(
4034 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
4035 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
4036 ConversionSequenceList &Conversions, bool SuppressUserConversions,
4037 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
4038 Expr::Classification ObjectClassification = {},
4039 OverloadCandidateParamOrder PO = {});
4040 void AddConversionCandidate(
4041 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
4042 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
4043 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
4044 bool AllowExplicit, bool AllowResultConversion = true);
4045 void AddTemplateConversionCandidate(
4046 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
4047 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
4048 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
4049 bool AllowExplicit, bool AllowResultConversion = true);
4050 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
4051 DeclAccessPair FoundDecl,
4052 CXXRecordDecl *ActingContext,
4053 const FunctionProtoType *Proto,
4054 Expr *Object, ArrayRef<Expr *> Args,
4055 OverloadCandidateSet& CandidateSet);
4056 void AddNonMemberOperatorCandidates(
4057 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
4058 OverloadCandidateSet &CandidateSet,
4059 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4060 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4061 SourceLocation OpLoc, ArrayRef<Expr *> Args,
4062 OverloadCandidateSet &CandidateSet,
4063 OverloadCandidateParamOrder PO = {});
4064 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
4065 OverloadCandidateSet& CandidateSet,
4066 bool IsAssignmentOperator = false,
4067 unsigned NumContextualBoolArguments = 0);
4068 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
4069 SourceLocation OpLoc, ArrayRef<Expr *> Args,
4070 OverloadCandidateSet& CandidateSet);
4071 void AddArgumentDependentLookupCandidates(DeclarationName Name,
4072 SourceLocation Loc,
4073 ArrayRef<Expr *> Args,
4074 TemplateArgumentListInfo *ExplicitTemplateArgs,
4075 OverloadCandidateSet& CandidateSet,
4076 bool PartialOverloading = false);
4077
4078 // Emit as a 'note' the specific overload candidate
4079 void NoteOverloadCandidate(
4080 const NamedDecl *Found, const FunctionDecl *Fn,
4081 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
4082 QualType DestType = QualType(), bool TakingAddress = false);
4083
4084 // Emit as a series of 'note's all template and non-templates identified by
4085 // the expression Expr
4086 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
4087 bool TakingAddress = false);
4088
4089 /// Check the enable_if expressions on the given function. Returns the first
4090 /// failing attribute, or NULL if they were all successful.
4091 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
4092 ArrayRef<Expr *> Args,
4093 bool MissingImplicitThis = false);
4094
4095 /// Find the failed Boolean condition within a given Boolean
4096 /// constant expression, and describe it with a string.
4097 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
4098
4099 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
4100 /// non-ArgDependent DiagnoseIfAttrs.
4101 ///
4102 /// Argument-dependent diagnose_if attributes should be checked each time a
4103 /// function is used as a direct callee of a function call.
4104 ///
4105 /// Returns true if any errors were emitted.
4106 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
4107 const Expr *ThisArg,
4108 ArrayRef<const Expr *> Args,
4109 SourceLocation Loc);
4110
4111 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
4112 /// ArgDependent DiagnoseIfAttrs.
4113 ///
4114 /// Argument-independent diagnose_if attributes should be checked on every use
4115 /// of a function.
4116 ///
4117 /// Returns true if any errors were emitted.
4118 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
4119 SourceLocation Loc);
4120
4121 /// Returns whether the given function's address can be taken or not,
4122 /// optionally emitting a diagnostic if the address can't be taken.
4123 ///
4124 /// Returns false if taking the address of the function is illegal.
4125 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
4126 bool Complain = false,
4127 SourceLocation Loc = SourceLocation());
4128
4129 // [PossiblyAFunctionType] --> [Return]
4130 // NonFunctionType --> NonFunctionType
4131 // R (A) --> R(A)
4132 // R (*)(A) --> R (A)
4133 // R (&)(A) --> R (A)
4134 // R (S::*)(A) --> R (A)
4135 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
4136
4137 FunctionDecl *
4138 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
4139 QualType TargetType,
4140 bool Complain,
4141 DeclAccessPair &Found,
4142 bool *pHadMultipleCandidates = nullptr);
4143
4144 FunctionDecl *
4145 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
4146
4147 bool resolveAndFixAddressOfSingleOverloadCandidate(
4148 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
4149
4150 FunctionDecl *
4151 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
4152 bool Complain = false,
4153 DeclAccessPair *Found = nullptr);
4154
4155 bool ResolveAndFixSingleFunctionTemplateSpecialization(
4156 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
4157 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
4158 QualType DestTypeForComplaining = QualType(),
4159 unsigned DiagIDForComplaining = 0);
4160
4161 Expr *FixOverloadedFunctionReference(Expr *E,
4162 DeclAccessPair FoundDecl,
4163 FunctionDecl *Fn);
4164 ExprResult FixOverloadedFunctionReference(ExprResult,
4165 DeclAccessPair FoundDecl,
4166 FunctionDecl *Fn);
4167
4168 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
4169 ArrayRef<Expr *> Args,
4170 OverloadCandidateSet &CandidateSet,
4171 bool PartialOverloading = false);
4172 void AddOverloadedCallCandidates(
4173 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
4174 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
4175
4176 // An enum used to represent the different possible results of building a
4177 // range-based for loop.
4178 enum ForRangeStatus {
4179 FRS_Success,
4180 FRS_NoViableFunction,
4181 FRS_DiagnosticIssued
4182 };
4183
4184 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
4185 SourceLocation RangeLoc,
4186 const DeclarationNameInfo &NameInfo,
4187 LookupResult &MemberLookup,
4188 OverloadCandidateSet *CandidateSet,
4189 Expr *Range, ExprResult *CallExpr);
4190
4191 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
4192 UnresolvedLookupExpr *ULE,
4193 SourceLocation LParenLoc,
4194 MultiExprArg Args,
4195 SourceLocation RParenLoc,
4196 Expr *ExecConfig,
4197 bool AllowTypoCorrection=true,
4198 bool CalleesAddressIsTaken=false);
4199
4200 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
4201 MultiExprArg Args, SourceLocation RParenLoc,
4202 OverloadCandidateSet *CandidateSet,
4203 ExprResult *Result);
4204
4205 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
4206 NestedNameSpecifierLoc NNSLoc,
4207 DeclarationNameInfo DNI,
4208 const UnresolvedSetImpl &Fns,
4209 bool PerformADL = true);
4210
4211 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
4212 UnaryOperatorKind Opc,
4213 const UnresolvedSetImpl &Fns,
4214 Expr *input, bool RequiresADL = true);
4215
4216 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
4217 OverloadedOperatorKind Op,
4218 const UnresolvedSetImpl &Fns,
4219 ArrayRef<Expr *> Args, bool RequiresADL = true);
4220 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
4221 BinaryOperatorKind Opc,
4222 const UnresolvedSetImpl &Fns,
4223 Expr *LHS, Expr *RHS,
4224 bool RequiresADL = true,
4225 bool AllowRewrittenCandidates = true,
4226 FunctionDecl *DefaultedFn = nullptr);
4227 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
4228 const UnresolvedSetImpl &Fns,
4229 Expr *LHS, Expr *RHS,
4230 FunctionDecl *DefaultedFn);
4231
4232 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
4233 SourceLocation RLoc, Expr *Base,
4234 MultiExprArg Args);
4235
4236 ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
4237 SourceLocation LParenLoc,
4238 MultiExprArg Args,
4239 SourceLocation RParenLoc,
4240 Expr *ExecConfig = nullptr,
4241 bool IsExecConfig = false,
4242 bool AllowRecovery = false);
4243 ExprResult
4244 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
4245 MultiExprArg Args,
4246 SourceLocation RParenLoc);
4247
4248 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
4249 SourceLocation OpLoc,
4250 bool *NoArrowOperatorFound = nullptr);
4251
4252 /// CheckCallReturnType - Checks that a call expression's return type is
4253 /// complete. Returns true on failure. The location passed in is the location
4254 /// that best represents the call.
4255 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
4256 CallExpr *CE, FunctionDecl *FD);
4257
4258 /// Helpers for dealing with blocks and functions.
4259 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
4260 bool CheckParameterNames);
4261 void CheckCXXDefaultArguments(FunctionDecl *FD);
4262 void CheckExtraCXXDefaultArguments(Declarator &D);
4263 Scope *getNonFieldDeclScope(Scope *S);
4264
4265 /// \name Name lookup
4266 ///
4267 /// These routines provide name lookup that is used during semantic
4268 /// analysis to resolve the various kinds of names (identifiers,
4269 /// overloaded operator names, constructor names, etc.) into zero or
4270 /// more declarations within a particular scope. The major entry
4271 /// points are LookupName, which performs unqualified name lookup,
4272 /// and LookupQualifiedName, which performs qualified name lookup.
4273 ///
4274 /// All name lookup is performed based on some specific criteria,
4275 /// which specify what names will be visible to name lookup and how
4276 /// far name lookup should work. These criteria are important both
4277 /// for capturing language semantics (certain lookups will ignore
4278 /// certain names, for example) and for performance, since name
4279 /// lookup is often a bottleneck in the compilation of C++. Name
4280 /// lookup criteria is specified via the LookupCriteria enumeration.
4281 ///
4282 /// The results of name lookup can vary based on the kind of name
4283 /// lookup performed, the current language, and the translation
4284 /// unit. In C, for example, name lookup will either return nothing
4285 /// (no entity found) or a single declaration. In C++, name lookup
4286 /// can additionally refer to a set of overloaded functions or
4287 /// result in an ambiguity. All of the possible results of name
4288 /// lookup are captured by the LookupResult class, which provides
4289 /// the ability to distinguish among them.
4290 //@{
4291
4292 /// Describes the kind of name lookup to perform.
4293 enum LookupNameKind {
4294 /// Ordinary name lookup, which finds ordinary names (functions,
4295 /// variables, typedefs, etc.) in C and most kinds of names
4296 /// (functions, variables, members, types, etc.) in C++.
4297 LookupOrdinaryName = 0,
4298 /// Tag name lookup, which finds the names of enums, classes,
4299 /// structs, and unions.
4300 LookupTagName,
4301 /// Label name lookup.
4302 LookupLabel,
4303 /// Member name lookup, which finds the names of
4304 /// class/struct/union members.
4305 LookupMemberName,
4306 /// Look up of an operator name (e.g., operator+) for use with
4307 /// operator overloading. This lookup is similar to ordinary name
4308 /// lookup, but will ignore any declarations that are class members.
4309 LookupOperatorName,
4310 /// Look up a name following ~ in a destructor name. This is an ordinary
4311 /// lookup, but prefers tags to typedefs.
4312 LookupDestructorName,
4313 /// Look up of a name that precedes the '::' scope resolution
4314 /// operator in C++. This lookup completely ignores operator, object,
4315 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
4316 LookupNestedNameSpecifierName,
4317 /// Look up a namespace name within a C++ using directive or
4318 /// namespace alias definition, ignoring non-namespace names (C++
4319 /// [basic.lookup.udir]p1).
4320 LookupNamespaceName,
4321 /// Look up all declarations in a scope with the given name,
4322 /// including resolved using declarations. This is appropriate
4323 /// for checking redeclarations for a using declaration.
4324 LookupUsingDeclName,
4325 /// Look up an ordinary name that is going to be redeclared as a
4326 /// name with linkage. This lookup ignores any declarations that
4327 /// are outside of the current scope unless they have linkage. See
4328 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
4329 LookupRedeclarationWithLinkage,
4330 /// Look up a friend of a local class. This lookup does not look
4331 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
4332 LookupLocalFriendName,
4333 /// Look up the name of an Objective-C protocol.
4334 LookupObjCProtocolName,
4335 /// Look up implicit 'self' parameter of an objective-c method.
4336 LookupObjCImplicitSelfParam,
4337 /// Look up the name of an OpenMP user-defined reduction operation.
4338 LookupOMPReductionName,
4339 /// Look up the name of an OpenMP user-defined mapper.
4340 LookupOMPMapperName,
4341 /// Look up any declaration with any name.
4342 LookupAnyName
4343 };
4344
4345 /// Specifies whether (or how) name lookup is being performed for a
4346 /// redeclaration (vs. a reference).
4347 enum RedeclarationKind {
4348 /// The lookup is a reference to this name that is not for the
4349 /// purpose of redeclaring the name.
4350 NotForRedeclaration = 0,
4351 /// The lookup results will be used for redeclaration of a name,
4352 /// if an entity by that name already exists and is visible.
4353 ForVisibleRedeclaration,
4354 /// The lookup results will be used for redeclaration of a name
4355 /// with external linkage; non-visible lookup results with external linkage
4356 /// may also be found.
4357 ForExternalRedeclaration
4358 };
4359
4360 RedeclarationKind forRedeclarationInCurContext() const {
4361 // A declaration with an owning module for linkage can never link against
4362 // anything that is not visible. We don't need to check linkage here; if
4363 // the context has internal linkage, redeclaration lookup won't find things
4364 // from other TUs, and we can't safely compute linkage yet in general.
4365 if (cast<Decl>(CurContext)
4366 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
4367 return ForVisibleRedeclaration;
4368 return ForExternalRedeclaration;
4369 }
4370
4371 /// The possible outcomes of name lookup for a literal operator.
4372 enum LiteralOperatorLookupResult {
4373 /// The lookup resulted in an error.
4374 LOLR_Error,
4375 /// The lookup found no match but no diagnostic was issued.
4376 LOLR_ErrorNoDiagnostic,
4377 /// The lookup found a single 'cooked' literal operator, which
4378 /// expects a normal literal to be built and passed to it.
4379 LOLR_Cooked,
4380 /// The lookup found a single 'raw' literal operator, which expects
4381 /// a string literal containing the spelling of the literal token.
4382 LOLR_Raw,
4383 /// The lookup found an overload set of literal operator templates,
4384 /// which expect the characters of the spelling of the literal token to be
4385 /// passed as a non-type template argument pack.
4386 LOLR_Template,
4387 /// The lookup found an overload set of literal operator templates,
4388 /// which expect the character type and characters of the spelling of the
4389 /// string literal token to be passed as template arguments.
4390 LOLR_StringTemplatePack,
4391 };
4392
4393 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
4394 CXXSpecialMember SM,
4395 bool ConstArg,
4396 bool VolatileArg,
4397 bool RValueThis,
4398 bool ConstThis,
4399 bool VolatileThis);
4400
4401 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
4402 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
4403 TypoRecoveryCallback;
4404
4405private:
4406 bool CppLookupName(LookupResult &R, Scope *S);
4407
4408 struct TypoExprState {
4409 std::unique_ptr<TypoCorrectionConsumer> Consumer;
4410 TypoDiagnosticGenerator DiagHandler;
4411 TypoRecoveryCallback RecoveryHandler;
4412 TypoExprState();
4413 TypoExprState(TypoExprState &&other) noexcept;
4414 TypoExprState &operator=(TypoExprState &&other) noexcept;
4415 };
4416
4417 /// The set of unhandled TypoExprs and their associated state.
4418 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
4419
4420 /// Creates a new TypoExpr AST node.
4421 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4422 TypoDiagnosticGenerator TDG,
4423 TypoRecoveryCallback TRC, SourceLocation TypoLoc);
4424
4425 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
4426 //
4427 // The boolean value will be true to indicate that the namespace was loaded
4428 // from an AST/PCH file, or false otherwise.
4429 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
4430
4431 /// Whether we have already loaded known namespaces from an extenal
4432 /// source.
4433 bool LoadedExternalKnownNamespaces;
4434
4435 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
4436 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
4437 /// should be skipped entirely.
4438 std::unique_ptr<TypoCorrectionConsumer>
4439 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
4440 Sema::LookupNameKind LookupKind, Scope *S,
4441 CXXScopeSpec *SS,
4442 CorrectionCandidateCallback &CCC,
4443 DeclContext *MemberContext, bool EnteringContext,
4444 const ObjCObjectPointerType *OPT,
4445 bool ErrorRecovery);
4446
4447public:
4448 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
4449
4450 /// Clears the state of the given TypoExpr.
4451 void clearDelayedTypo(TypoExpr *TE);
4452
4453 /// Look up a name, looking for a single declaration. Return
4454 /// null if the results were absent, ambiguous, or overloaded.
4455 ///
4456 /// It is preferable to use the elaborated form and explicitly handle
4457 /// ambiguity and overloaded.
4458 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
4459 SourceLocation Loc,
4460 LookupNameKind NameKind,
4461 RedeclarationKind Redecl
4462 = NotForRedeclaration);
4463 bool LookupBuiltin(LookupResult &R);
4464 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
4465 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
4466 bool ForceNoCPlusPlus = false);
4467 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4468 bool InUnqualifiedLookup = false);
4469 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4470 CXXScopeSpec &SS);
4471 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
4472 bool AllowBuiltinCreation = false,
4473 bool EnteringContext = false);
4474 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
4475 RedeclarationKind Redecl
4476 = NotForRedeclaration);
4477 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
4478
4479 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
4480 UnresolvedSetImpl &Functions);
4481
4482 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
4483 SourceLocation GnuLabelLoc = SourceLocation());
4484
4485 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
4486 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
4487 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
4488 unsigned Quals);
4489 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
4490 bool RValueThis, unsigned ThisQuals);
4491 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
4492 unsigned Quals);
4493 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
4494 bool RValueThis, unsigned ThisQuals);
4495 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
4496
4497 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
4498 bool IsUDSuffix);
4499 LiteralOperatorLookupResult
4500 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
4501 bool AllowRaw, bool AllowTemplate,
4502 bool AllowStringTemplate, bool DiagnoseMissing,
4503 StringLiteral *StringLit = nullptr);
4504 bool isKnownName(StringRef name);
4505
4506 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4507 enum class FunctionEmissionStatus {
4508 Emitted,
4509 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4510 OMPDiscarded, // Discarded due to OpenMP hostness
4511 TemplateDiscarded, // Discarded due to uninstantiated templates
4512 Unknown,
4513 };
4514 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4515 bool Final = false);
4516
4517 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4518 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4519
4520 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
4521 ArrayRef<Expr *> Args, ADLResult &Functions);
4522
4523 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4524 VisibleDeclConsumer &Consumer,
4525 bool IncludeGlobalScope = true,
4526 bool LoadExternal = true);
4527 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4528 VisibleDeclConsumer &Consumer,
4529 bool IncludeGlobalScope = true,
4530 bool IncludeDependentBases = false,
4531 bool LoadExternal = true);
4532
4533 enum CorrectTypoKind {
4534 CTK_NonError, // CorrectTypo used in a non error recovery situation.
4535 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4536 };
4537
4538 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
4539 Sema::LookupNameKind LookupKind,
4540 Scope *S, CXXScopeSpec *SS,
4541 CorrectionCandidateCallback &CCC,
4542 CorrectTypoKind Mode,
4543 DeclContext *MemberContext = nullptr,
4544 bool EnteringContext = false,
4545 const ObjCObjectPointerType *OPT = nullptr,
4546 bool RecordFailure = true);
4547
4548 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
4549 Sema::LookupNameKind LookupKind, Scope *S,
4550 CXXScopeSpec *SS,
4551 CorrectionCandidateCallback &CCC,
4552 TypoDiagnosticGenerator TDG,
4553 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
4554 DeclContext *MemberContext = nullptr,
4555 bool EnteringContext = false,
4556 const ObjCObjectPointerType *OPT = nullptr);
4557
4558 /// Process any TypoExprs in the given Expr and its children,
4559 /// generating diagnostics as appropriate and returning a new Expr if there
4560 /// were typos that were all successfully corrected and ExprError if one or
4561 /// more typos could not be corrected.
4562 ///
4563 /// \param E The Expr to check for TypoExprs.
4564 ///
4565 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4566 /// initializer.
4567 ///
4568 /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4569 /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4570 ///
4571 /// \param Filter A function applied to a newly rebuilt Expr to determine if
4572 /// it is an acceptable/usable result from a single combination of typo
4573 /// corrections. As long as the filter returns ExprError, different
4574 /// combinations of corrections will be tried until all are exhausted.
4575 ExprResult CorrectDelayedTyposInExpr(
4576 Expr *E, VarDecl *InitDecl = nullptr,
4577 bool RecoverUncorrectedTypos = false,
4578 llvm::function_ref<ExprResult(Expr *)> Filter =
4579 [](Expr *E) -> ExprResult { return E; });
4580
4581 ExprResult CorrectDelayedTyposInExpr(
4582 ExprResult ER, VarDecl *InitDecl = nullptr,
4583 bool RecoverUncorrectedTypos = false,
4584 llvm::function_ref<ExprResult(Expr *)> Filter =
4585 [](Expr *E) -> ExprResult { return E; }) {
4586 return ER.isInvalid()
4587 ? ER
4588 : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4589 RecoverUncorrectedTypos, Filter);
4590 }
4591
4592 void diagnoseTypo(const TypoCorrection &Correction,
4593 const PartialDiagnostic &TypoDiag,
4594 bool ErrorRecovery = true);
4595
4596 void diagnoseTypo(const TypoCorrection &Correction,
4597 const PartialDiagnostic &TypoDiag,
4598 const PartialDiagnostic &PrevNote,
4599 bool ErrorRecovery = true);
4600
4601 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4602
4603 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4604 ArrayRef<Expr *> Args,
4605 AssociatedNamespaceSet &AssociatedNamespaces,
4606 AssociatedClassSet &AssociatedClasses);
4607
4608 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4609 bool ConsiderLinkage, bool AllowInlineNamespace);
4610
4611 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4612 bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4613 bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4614 bool IsRedefinitionInModule(const NamedDecl *New,
4615 const NamedDecl *Old) const;
4616
4617 void DiagnoseAmbiguousLookup(LookupResult &Result);
4618 //@}
4619
4620 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4621 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4622 ArrayRef<Expr *> SubExprs,
4623 QualType T = QualType());
4624
4625 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4626 SourceLocation IdLoc,
4627 bool TypoCorrection = false);
4628 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4629 SourceLocation Loc);
4630 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
4631 Scope *S, bool ForRedeclaration,
4632 SourceLocation Loc);
4633 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4634 Scope *S);
4635 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4636 FunctionDecl *FD);
4637 void AddKnownFunctionAttributes(FunctionDecl *FD);
4638
4639 // More parsing and symbol table subroutines.
4640
4641 void ProcessPragmaWeak(Scope *S, Decl *D);
4642 // Decl attributes - this routine is the top level dispatcher.
4643 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
4644 // Helper for delayed processing of attributes.
4645 void ProcessDeclAttributeDelayed(Decl *D,
4646 const ParsedAttributesView &AttrList);
4647
4648 // Options for ProcessDeclAttributeList().
4649 struct ProcessDeclAttributeOptions {
4650 ProcessDeclAttributeOptions()
4651 : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
4652
4653 ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) {
4654 ProcessDeclAttributeOptions Result = *this;
4655 Result.IncludeCXX11Attributes = Val;
4656 return Result;
4657 }
4658
4659 ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) {
4660 ProcessDeclAttributeOptions Result = *this;
4661 Result.IgnoreTypeAttributes = Val;
4662 return Result;
4663 }
4664
4665 // Should C++11 attributes be processed?
4666 bool IncludeCXX11Attributes;
4667
4668 // Should any type attributes encountered be ignored?
4669 // If this option is false, a diagnostic will be emitted for any type
4670 // attributes of a kind that does not "slide" from the declaration to
4671 // the decl-specifier-seq.
4672 bool IgnoreTypeAttributes;
4673 };
4674
4675 void ProcessDeclAttributeList(Scope *S, Decl *D,
4676 const ParsedAttributesView &AttrList,
4677 const ProcessDeclAttributeOptions &Options =
4678 ProcessDeclAttributeOptions());
4679 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4680 const ParsedAttributesView &AttrList);
4681
4682 void checkUnusedDeclAttributes(Declarator &D);
4683
4684 /// Handles semantic checking for features that are common to all attributes,
4685 /// such as checking whether a parameter was properly specified, or the
4686 /// correct number of arguments were passed, etc. Returns true if the
4687 /// attribute has been diagnosed.
4688 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
4689 bool SkipArgCountCheck = false);
4690 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
4691 bool SkipArgCountCheck = false);
4692
4693 /// Determine if type T is a valid subject for a nonnull and similar
4694 /// attributes. By default, we look through references (the behavior used by
4695 /// nonnull), but if the second parameter is true, then we treat a reference
4696 /// type as valid.
4697 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4698
4699 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4700 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
4701 const FunctionDecl *FD = nullptr);
4702 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4703 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4704 bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
4705 const Expr *E, StringRef &Str,
4706 SourceLocation *ArgLocation = nullptr);
4707 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4708 StringRef &Str,
4709 SourceLocation *ArgLocation = nullptr);
4710 llvm::Error isValidSectionSpecifier(StringRef Str);
4711 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4712 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4713 bool checkTargetVersionAttr(SourceLocation LiteralLoc, StringRef &Str,
4714 bool &isDefault);
4715 bool
4716 checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str,
4717 const StringLiteral *Literal, bool &HasDefault,
4718 bool &HasCommas, bool &HasNotDefault,
4719 SmallVectorImpl<SmallString<64>> &StringsBuffer);
4720 bool checkMSInheritanceAttrOnDefinition(
4721 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4722 MSInheritanceModel SemanticSpelling);
4723
4724 void CheckAlignasUnderalignment(Decl *D);
4725
4726 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
4727 const AttributeCommonInfo &A);
4728 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
4729 const AttributeCommonInfo &A);
4730
4731 /// Adjust the calling convention of a method to be the ABI default if it
4732 /// wasn't specified explicitly. This handles method types formed from
4733 /// function type typedefs and typename template arguments.
4734 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4735 SourceLocation Loc);
4736
4737 // Check if there is an explicit attribute, but only look through parens.
4738 // The intent is to look for an attribute on the current declarator, but not
4739 // one that came from a typedef.
4740 bool hasExplicitCallingConv(QualType T);
4741
4742 /// Get the outermost AttributedType node that sets a calling convention.
4743 /// Valid types should not have multiple attributes with different CCs.
4744 const AttributedType *getCallingConvAttributedType(QualType T) const;
4745
4746 /// Process the attributes before creating an attributed statement. Returns
4747 /// the semantic attributes that have been processed.
4748 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
4749 SmallVectorImpl<const Attr *> &OutAttrs);
4750
4751 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
4752 ObjCMethodDecl *MethodDecl,
4753 bool IsProtocolMethodDecl);
4754
4755 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
4756 ObjCMethodDecl *Overridden,
4757 bool IsProtocolMethodDecl);
4758
4759 /// WarnExactTypedMethods - This routine issues a warning if method
4760 /// implementation declaration matches exactly that of its declaration.
4761 void WarnExactTypedMethods(ObjCMethodDecl *Method,
4762 ObjCMethodDecl *MethodDecl,
4763 bool IsProtocolMethodDecl);
4764
4765 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
4766
4767 /// CheckImplementationIvars - This routine checks if the instance variables
4768 /// listed in the implelementation match those listed in the interface.
4769 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
4770 ObjCIvarDecl **Fields, unsigned nIvars,
4771 SourceLocation Loc);
4772
4773 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4774 /// remains unimplemented in the class or category \@implementation.
4775 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4776 ObjCContainerDecl* IDecl,
4777 bool IncompleteImpl = false);
4778
4779 /// DiagnoseUnimplementedProperties - This routine warns on those properties
4780 /// which must be implemented by this implementation.
4781 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
4782 ObjCContainerDecl *CDecl,
4783 bool SynthesizeProperties);
4784
4785 /// Diagnose any null-resettable synthesized setters.
4786 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
4787
4788 /// DefaultSynthesizeProperties - This routine default synthesizes all
4789 /// properties which must be synthesized in the class's \@implementation.
4790 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
4791 ObjCInterfaceDecl *IDecl,
4792 SourceLocation AtEnd);
4793 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
4794
4795 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4796 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4797 /// declared in class 'IFace'.
4798 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
4799 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4800
4801 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4802 /// backs the property is not used in the property's accessor.
4803 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4804 const ObjCImplementationDecl *ImplD);
4805
4806 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4807 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4808 /// It also returns ivar's property on success.
4809 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4810 const ObjCPropertyDecl *&PDecl) const;
4811
4812 /// Called by ActOnProperty to handle \@property declarations in
4813 /// class extensions.
4814 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
4815 SourceLocation AtLoc,
4816 SourceLocation LParenLoc,
4817 FieldDeclarator &FD,
4818 Selector GetterSel,
4819 SourceLocation GetterNameLoc,
4820 Selector SetterSel,
4821 SourceLocation SetterNameLoc,
4822 const bool isReadWrite,
4823 unsigned &Attributes,
4824 const unsigned AttributesAsWritten,
4825 QualType T,
4826 TypeSourceInfo *TSI,
4827 tok::ObjCKeywordKind MethodImplKind);
4828
4829 /// Called by ActOnProperty and HandlePropertyInClassExtension to
4830 /// handle creating the ObjcPropertyDecl for a category or \@interface.
4831 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
4832 ObjCContainerDecl *CDecl,
4833 SourceLocation AtLoc,
4834 SourceLocation LParenLoc,
4835 FieldDeclarator &FD,
4836 Selector GetterSel,
4837 SourceLocation GetterNameLoc,
4838 Selector SetterSel,
4839 SourceLocation SetterNameLoc,
4840 const bool isReadWrite,
4841 const unsigned Attributes,
4842 const unsigned AttributesAsWritten,
4843 QualType T,
4844 TypeSourceInfo *TSI,
4845 tok::ObjCKeywordKind MethodImplKind,
4846 DeclContext *lexicalDC = nullptr);
4847
4848 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4849 /// warning) when atomic property has one but not the other user-declared
4850 /// setter or getter.
4851 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
4852 ObjCInterfaceDecl* IDecl);
4853
4854 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
4855
4856 void DiagnoseMissingDesignatedInitOverrides(
4857 const ObjCImplementationDecl *ImplD,
4858 const ObjCInterfaceDecl *IFD);
4859
4860 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
4861
4862 enum MethodMatchStrategy {
4863 MMS_loose,
4864 MMS_strict
4865 };
4866
4867 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
4868 /// true, or false, accordingly.
4869 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
4870 const ObjCMethodDecl *PrevMethod,
4871 MethodMatchStrategy strategy = MMS_strict);
4872
4873 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
4874 /// or protocol against those declared in their implementations.
4875 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
4876 const SelectorSet &ClsMap,
4877 SelectorSet &InsMapSeen,
4878 SelectorSet &ClsMapSeen,
4879 ObjCImplDecl* IMPDecl,
4880 ObjCContainerDecl* IDecl,
4881 bool &IncompleteImpl,
4882 bool ImmediateClass,
4883 bool WarnCategoryMethodImpl=false);
4884
4885 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
4886 /// category matches with those implemented in its primary class and
4887 /// warns each time an exact match is found.
4888 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
4889
4890 /// Add the given method to the list of globally-known methods.
4891 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
4892
4893 /// Returns default addr space for method qualifiers.
4894 LangAS getDefaultCXXMethodAddrSpace() const;
4895
4896private:
4897 /// AddMethodToGlobalPool - Add an instance or factory method to the global
4898 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4899 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4900
4901 /// LookupMethodInGlobalPool - Returns the instance or factory method and
4902 /// optionally warns if there are multiple signatures.
4903 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4904 bool receiverIdOrClass,
4905 bool instance);
4906
4907public:
4908 /// - Returns instance or factory methods in global method pool for
4909 /// given selector. It checks the desired kind first, if none is found, and
4910 /// parameter checkTheOther is set, it then checks the other kind. If no such
4911 /// method or only one method is found, function returns false; otherwise, it
4912 /// returns true.
4913 bool
4914 CollectMultipleMethodsInGlobalPool(Selector Sel,
4915 SmallVectorImpl<ObjCMethodDecl*>& Methods,
4916 bool InstanceFirst, bool CheckTheOther,
4917 const ObjCObjectType *TypeBound = nullptr);
4918
4919 bool
4920 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4921 SourceRange R, bool receiverIdOrClass,
4922 SmallVectorImpl<ObjCMethodDecl*>& Methods);
4923
4924 void
4925 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4926 Selector Sel, SourceRange R,
4927 bool receiverIdOrClass);
4928
4929private:
4930 /// - Returns a selector which best matches given argument list or
4931 /// nullptr if none could be found
4932 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4933 bool IsInstance,
4934 SmallVectorImpl<ObjCMethodDecl*>& Methods);
4935
4936
4937 /// Record the typo correction failure and return an empty correction.
4938 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4939 bool RecordFailure = true) {
4940 if (RecordFailure)
4941 TypoCorrectionFailures[Typo].insert(TypoLoc);
4942 return TypoCorrection();
4943 }
4944
4945public:
4946 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4947 /// unit are added to a global pool. This allows us to efficiently associate
4948 /// a selector with a method declaraation for purposes of typechecking
4949 /// messages sent to "id" (where the class of the object is unknown).
4950 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4951 AddMethodToGlobalPool(Method, impl, /*instance*/true);
4952 }
4953
4954 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4955 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4956 AddMethodToGlobalPool(Method, impl, /*instance*/false);
4957 }
4958
4959 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4960 /// pool.
4961 void AddAnyMethodToGlobalPool(Decl *D);
4962
4963 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4964 /// there are multiple signatures.
4965 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4966 bool receiverIdOrClass=false) {
4967 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4968 /*instance*/true);
4969 }
4970
4971 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4972 /// there are multiple signatures.
4973 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4974 bool receiverIdOrClass=false) {
4975 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4976 /*instance*/false);
4977 }
4978
4979 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4980 QualType ObjectType=QualType());
4981 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4982 /// implementation.
4983 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4984
4985 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4986 /// initialization.
4987 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4988 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4989
4990 //===--------------------------------------------------------------------===//
4991 // Statement Parsing Callbacks: SemaStmt.cpp.
4992public:
4993 class FullExprArg {
4994 public:
4995 FullExprArg() : E(nullptr) { }
4996 FullExprArg(Sema &actions) : E(nullptr) { }
4997
4998 ExprResult release() {
4999 return E;
5000 }
5001
5002 Expr *get() const { return E; }
5003
5004 Expr *operator->() {
5005 return E;
5006 }
5007
5008 private:
5009 // FIXME: No need to make the entire Sema class a friend when it's just
5010 // Sema::MakeFullExpr that needs access to the constructor below.
5011 friend class Sema;
5012
5013 explicit FullExprArg(Expr *expr) : E(expr) {}
5014
5015 Expr *E;
5016 };
5017
5018 FullExprArg MakeFullExpr(Expr *Arg) {
5019 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
5020 }
5021 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
5022 return FullExprArg(
5023 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
5024 }
5025 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
5026 ExprResult FE =
5027 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
5028 /*DiscardedValue*/ true);
5029 return FullExprArg(FE.get());
5030 }
5031
5032 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
5033 StmtResult ActOnExprStmtError();
5034
5035 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
5036 bool HasLeadingEmptyMacro = false);
5037
5038 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
5039 void ActOnAfterCompoundStatementLeadingPragmas();
5040 void ActOnFinishOfCompoundStmt();
5041 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
5042 ArrayRef<Stmt *> Elts, bool isStmtExpr);
5043
5044 /// A RAII object to enter scope of a compound statement.
5045 class CompoundScopeRAII {
5046 public:
5047 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
5048 S.ActOnStartOfCompoundStmt(IsStmtExpr);
5049 }
5050
5051 ~CompoundScopeRAII() {
5052 S.ActOnFinishOfCompoundStmt();
5053 }
5054
5055 private:
5056 Sema &S;
5057 };
5058
5059 /// An RAII helper that pops function a function scope on exit.
5060 struct FunctionScopeRAII {
5061 Sema &S;
5062 bool Active;
5063 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
5064 ~FunctionScopeRAII() {
5065 if (Active)
5066 S.PopFunctionScopeInfo();
5067 }
5068 void disable() { Active = false; }
5069 };
5070
5071 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
5072 SourceLocation StartLoc,
5073 SourceLocation EndLoc);
5074 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
5075 StmtResult ActOnForEachLValueExpr(Expr *E);
5076 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
5077 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
5078 SourceLocation DotDotDotLoc, ExprResult RHS,
5079 SourceLocation ColonLoc);
5080 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
5081
5082 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
5083 SourceLocation ColonLoc,
5084 Stmt *SubStmt, Scope *CurScope);
5085 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
5086 SourceLocation ColonLoc, Stmt *SubStmt);
5087
5088 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
5089 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
5090 StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
5091 Stmt *SubStmt);
5092
5093 class ConditionResult;
5094
5095 StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
5096 SourceLocation LParenLoc, Stmt *InitStmt,
5097 ConditionResult Cond, SourceLocation RParenLoc,
5098 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
5099 StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
5100 SourceLocation LParenLoc, Stmt *InitStmt,
5101 ConditionResult Cond, SourceLocation RParenLoc,
5102 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
5103 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
5104 SourceLocation LParenLoc, Stmt *InitStmt,
5105 ConditionResult Cond,
5106 SourceLocation RParenLoc);
5107 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
5108 Stmt *Switch, Stmt *Body);
5109 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
5110 ConditionResult Cond, SourceLocation RParenLoc,
5111 Stmt *Body);
5112 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
5113 SourceLocation WhileLoc, SourceLocation CondLParen,
5114 Expr *Cond, SourceLocation CondRParen);
5115
5116 StmtResult ActOnForStmt(SourceLocation ForLoc,
5117 SourceLocation LParenLoc,
5118 Stmt *First,
5119 ConditionResult Second,
5120 FullExprArg Third,
5121 SourceLocation RParenLoc,
5122 Stmt *Body);
5123 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
5124 Expr *collection);
5125 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
5126 Stmt *First, Expr *collection,
5127 SourceLocation RParenLoc);
5128 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
5129
5130 enum BuildForRangeKind {
5131 /// Initial building of a for-range statement.
5132 BFRK_Build,
5133 /// Instantiation or recovery rebuild of a for-range statement. Don't
5134 /// attempt any typo-correction.
5135 BFRK_Rebuild,
5136 /// Determining whether a for-range statement could be built. Avoid any
5137 /// unnecessary or irreversible actions.
5138 BFRK_Check
5139 };
5140
5141 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
5142 SourceLocation CoawaitLoc,
5143 Stmt *InitStmt,
5144 Stmt *LoopVar,
5145 SourceLocation ColonLoc, Expr *Collection,
5146 SourceLocation RParenLoc,
5147 BuildForRangeKind Kind);
5148 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
5149 SourceLocation CoawaitLoc,
5150 Stmt *InitStmt,
5151 SourceLocation ColonLoc,
5152 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
5153 Expr *Cond, Expr *Inc,
5154 Stmt *LoopVarDecl,
5155 SourceLocation RParenLoc,
5156 BuildForRangeKind Kind);
5157 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
5158
5159 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
5160 SourceLocation LabelLoc,
5161 LabelDecl *TheDecl);
5162 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
5163 SourceLocation StarLoc,
5164 Expr *DestExp);
5165 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
5166 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
5167
5168 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
5169 CapturedRegionKind Kind, unsigned NumParams);
5170 typedef std::pair<StringRef, QualType> CapturedParamNameType;
5171 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
5172 CapturedRegionKind Kind,
5173 ArrayRef<CapturedParamNameType> Params,
5174 unsigned OpenMPCaptureLevel = 0);
5175 StmtResult ActOnCapturedRegionEnd(Stmt *S);
5176 void ActOnCapturedRegionError();
5177 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
5178 SourceLocation Loc,
5179 unsigned NumParams);
5180
5181 struct NamedReturnInfo {
5182 const VarDecl *Candidate;
5183
5184 enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
5185 Status S;
5186
5187 bool isMoveEligible() const { return S != None; };
5188 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
5189 };
5190 enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
5191 NamedReturnInfo getNamedReturnInfo(
5192 Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
5193 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
5194 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
5195 QualType ReturnType);
5196
5197 ExprResult
5198 PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
5199 const NamedReturnInfo &NRInfo, Expr *Value,
5200 bool SupressSimplerImplicitMoves = false);
5201
5202 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
5203 Scope *CurScope);
5204 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
5205 bool AllowRecovery = false);
5206 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
5207 NamedReturnInfo &NRInfo,
5208 bool SupressSimplerImplicitMoves);
5209
5210 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
5211 bool IsVolatile, unsigned NumOutputs,
5212 unsigned NumInputs, IdentifierInfo **Names,
5213 MultiExprArg Constraints, MultiExprArg Exprs,
5214 Expr *AsmString, MultiExprArg Clobbers,
5215 unsigned NumLabels,
5216 SourceLocation RParenLoc);
5217
5218 void FillInlineAsmIdentifierInfo(Expr *Res,
5219 llvm::InlineAsmIdentifierInfo &Info);
5220 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
5221 SourceLocation TemplateKWLoc,
5222 UnqualifiedId &Id,
5223 bool IsUnevaluatedContext);
5224 bool LookupInlineAsmField(StringRef Base, StringRef Member,
5225 unsigned &Offset, SourceLocation AsmLoc);
5226 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
5227 SourceLocation AsmLoc);
5228 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
5229 ArrayRef<Token> AsmToks,
5230 StringRef AsmString,
5231 unsigned NumOutputs, unsigned NumInputs,
5232 ArrayRef<StringRef> Constraints,
5233 ArrayRef<StringRef> Clobbers,
5234 ArrayRef<Expr*> Exprs,
5235 SourceLocation EndLoc);
5236 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
5237 SourceLocation Location,
5238 bool AlwaysCreate);
5239
5240 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
5241 SourceLocation StartLoc,
5242 SourceLocation IdLoc, IdentifierInfo *Id,
5243 bool Invalid = false);
5244
5245 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
5246
5247 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
5248 Decl *Parm, Stmt *Body);
5249
5250 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
5251
5252 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
5253 MultiStmtArg Catch, Stmt *Finally);
5254
5255 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
5256 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
5257 Scope *CurScope);
5258 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
5259 Expr *operand);
5260 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
5261 Expr *SynchExpr,
5262 Stmt *SynchBody);
5263
5264 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
5265
5266 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
5267 SourceLocation StartLoc,
5268 SourceLocation IdLoc,
5269 IdentifierInfo *Id);
5270
5271 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
5272
5273 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
5274 Decl *ExDecl, Stmt *HandlerBlock);
5275 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
5276 ArrayRef<Stmt *> Handlers);
5277
5278 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
5279 SourceLocation TryLoc, Stmt *TryBlock,
5280 Stmt *Handler);
5281 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
5282 Expr *FilterExpr,
5283 Stmt *Block);
5284 void ActOnStartSEHFinallyBlock();
5285 void ActOnAbortSEHFinallyBlock();
5286 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
5287 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
5288
5289 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
5290
5291 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
5292
5293 /// If it's a file scoped decl that must warn if not used, keep track
5294 /// of it.
5295 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
5296
5297 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
5298 DiagReceiverTy;
5299
5300 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
5301 /// whose result is unused, warn.
5302 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
5303 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
5304 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
5305 DiagReceiverTy DiagReceiver);
5306 void DiagnoseUnusedDecl(const NamedDecl *ND);
5307 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
5308
5309 /// If VD is set but not otherwise used, diagnose, for a parameter or a
5310 /// variable.
5311 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
5312
5313 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
5314 /// statement as a \p Body, and it is located on the same line.
5315 ///
5316 /// This helps prevent bugs due to typos, such as:
5317 /// if (condition);
5318 /// do_stuff();
5319 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5320 const Stmt *Body,
5321 unsigned DiagID);
5322
5323 /// Warn if a for/while loop statement \p S, which is followed by
5324 /// \p PossibleBody, has a suspicious null statement as a body.
5325 void DiagnoseEmptyLoopBody(const Stmt *S,
5326 const Stmt *PossibleBody);
5327
5328 /// Warn if a value is moved to itself.
5329 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
5330 SourceLocation OpLoc);
5331
5332 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
5333 /// SelfAssigned when inside a CXXMethodDecl.
5334 const FieldDecl *
5335 getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned);
5336
5337 /// Warn if we're implicitly casting from a _Nullable pointer type to a
5338 /// _Nonnull one.
5339 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
5340 SourceLocation Loc);
5341
5342 /// Warn when implicitly casting 0 to nullptr.
5343 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
5344
5345 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
5346 return DelayedDiagnostics.push(pool);
5347 }
5348 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5349
5350 typedef ProcessingContextState ParsingClassState;
5351 ParsingClassState PushParsingClass() {
5352 ParsingClassDepth++;
5353 return DelayedDiagnostics.pushUndelayed();
5354 }
5355 void PopParsingClass(ParsingClassState state) {
5356 ParsingClassDepth--;
5357 DelayedDiagnostics.popUndelayed(state);
5358 }
5359
5360 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5361
5362 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
5363 const ObjCInterfaceDecl *UnknownObjCClass,
5364 bool ObjCPropertyAccess,
5365 bool AvoidPartialAvailabilityChecks = false,
5366 ObjCInterfaceDecl *ClassReceiver = nullptr);
5367
5368 bool makeUnavailableInSystemHeader(SourceLocation loc,
5369 UnavailableAttr::ImplicitReason reason);
5370
5371 /// Issue any -Wunguarded-availability warnings in \c FD
5372 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
5373
5374 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5375
5376 //===--------------------------------------------------------------------===//
5377 // Expression Parsing Callbacks: SemaExpr.cpp.
5378
5379 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
5380 // A version of DiagnoseUseOfDecl that should be used if overload resolution
5381 // has been used to find this declaration, which means we don't have to bother
5382 // checking the trailing requires clause.
5383 bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) {
5384 return DiagnoseUseOfDecl(
5385 D, Loc, /*UnknownObjCClass=*/nullptr, /*ObjCPropertyAccess=*/false,
5386 /*AvoidPartialAvailabilityChecks=*/false, /*ClassReceiver=*/nullptr,
5387 /*SkipTrailingRequiresClause=*/true);
5388 }
5389
5390 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
5391 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
5392 bool ObjCPropertyAccess = false,
5393 bool AvoidPartialAvailabilityChecks = false,
5394 ObjCInterfaceDecl *ClassReciever = nullptr,
5395 bool SkipTrailingRequiresClause = false);
5396 void NoteDeletedFunction(FunctionDecl *FD);
5397 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
5398 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
5399 ObjCMethodDecl *Getter,
5400 SourceLocation Loc);
5401 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
5402 ArrayRef<Expr *> Args);
5403
5404 void PushExpressionEvaluationContext(
5405 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
5406 ExpressionEvaluationContextRecord::ExpressionKind Type =
5407 ExpressionEvaluationContextRecord::EK_Other);
5408 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
5409 void PushExpressionEvaluationContext(
5410 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
5411 ExpressionEvaluationContextRecord::ExpressionKind Type =
5412 ExpressionEvaluationContextRecord::EK_Other);
5413 void PopExpressionEvaluationContext();
5414
5415 void DiscardCleanupsInEvaluationContext();
5416
5417 ExprResult TransformToPotentiallyEvaluated(Expr *E);
5418 TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
5419 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
5420
5421 ExprResult CheckUnevaluatedOperand(Expr *E);
5422 void CheckUnusedVolatileAssignment(Expr *E);
5423
5424 ExprResult ActOnConstantExpression(ExprResult Res);
5425
5426 // Functions for marking a declaration referenced. These functions also
5427 // contain the relevant logic for marking if a reference to a function or
5428 // variable is an odr-use (in the C++11 sense). There are separate variants
5429 // for expressions referring to a decl; these exist because odr-use marking
5430 // needs to be delayed for some constant variables when we build one of the
5431 // named expressions.
5432 //
5433 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
5434 // should usually be true. This only needs to be set to false if the lack of
5435 // odr-use cannot be determined from the current context (for instance,
5436 // because the name denotes a virtual function and was written without an
5437 // explicit nested-name-specifier).
5438 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
5439 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
5440 bool MightBeOdrUse = true);
5441 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
5442 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
5443 void MarkMemberReferenced(MemberExpr *E);
5444 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
5445 void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc,
5446 unsigned CapturingScopeIndex);
5447
5448 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
5449 void CleanupVarDeclMarking();
5450
5451 enum TryCaptureKind {
5452 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
5453 };
5454
5455 /// Try to capture the given variable.
5456 ///
5457 /// \param Var The variable to capture.
5458 ///
5459 /// \param Loc The location at which the capture occurs.
5460 ///
5461 /// \param Kind The kind of capture, which may be implicit (for either a
5462 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
5463 ///
5464 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
5465 /// an explicit lambda capture.
5466 ///
5467 /// \param BuildAndDiagnose Whether we are actually supposed to add the
5468 /// captures or diagnose errors. If false, this routine merely check whether
5469 /// the capture can occur without performing the capture itself or complaining
5470 /// if the variable cannot be captured.
5471 ///
5472 /// \param CaptureType Will be set to the type of the field used to capture
5473 /// this variable in the innermost block or lambda. Only valid when the
5474 /// variable can be captured.
5475 ///
5476 /// \param DeclRefType Will be set to the type of a reference to the capture
5477 /// from within the current scope. Only valid when the variable can be
5478 /// captured.
5479 ///
5480 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5481 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5482 /// This is useful when enclosing lambdas must speculatively capture
5483 /// variables that may or may not be used in certain specializations of
5484 /// a nested generic lambda.
5485 ///
5486 /// \returns true if an error occurred (i.e., the variable cannot be
5487 /// captured) and false if the capture succeeded.
5488 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
5489 TryCaptureKind Kind, SourceLocation EllipsisLoc,
5490 bool BuildAndDiagnose, QualType &CaptureType,
5491 QualType &DeclRefType,
5492 const unsigned *const FunctionScopeIndexToStopAt);
5493
5494 /// Try to capture the given variable.
5495 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
5496 TryCaptureKind Kind = TryCapture_Implicit,
5497 SourceLocation EllipsisLoc = SourceLocation());
5498
5499 /// Checks if the variable must be captured.
5500 bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc);
5501
5502 /// Given a variable, determine the type that a reference to that
5503 /// variable will have in the given scope.
5504 QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc);
5505
5506 /// Mark all of the declarations referenced within a particular AST node as
5507 /// referenced. Used when template instantiation instantiates a non-dependent
5508 /// type -- entities referenced by the type are now referenced.
5509 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
5510 void MarkDeclarationsReferencedInExpr(
5511 Expr *E, bool SkipLocalVariables = false,
5512 ArrayRef<const Expr *> StopAt = std::nullopt);
5513
5514 /// Try to recover by turning the given expression into a
5515 /// call. Returns true if recovery was attempted or an error was
5516 /// emitted; this may also leave the ExprResult invalid.
5517 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
5518 bool ForceComplain = false,
5519 bool (*IsPlausibleResult)(QualType) = nullptr);
5520
5521 /// Figure out if an expression could be turned into a call.
5522 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
5523 UnresolvedSetImpl &NonTemplateOverloads);
5524
5525 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
5526 /// conversion.
5527 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
5528
5529 /// Conditionally issue a diagnostic based on the statements's reachability
5530 /// analysis.
5531 ///
5532 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
5533 /// the function body is parsed, and then do a basic reachability analysis to
5534 /// determine if the statement is reachable. If it is unreachable, the
5535 /// diagnostic will not be emitted.
5536 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
5537 const PartialDiagnostic &PD);
5538
5539 /// Conditionally issue a diagnostic based on the current
5540 /// evaluation context.
5541 ///
5542 /// \param Statement If Statement is non-null, delay reporting the
5543 /// diagnostic until the function body is parsed, and then do a basic
5544 /// reachability analysis to determine if the statement is reachable.
5545 /// If it is unreachable, the diagnostic will not be emitted.
5546 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
5547 const PartialDiagnostic &PD);
5548 /// Similar, but diagnostic is only produced if all the specified statements
5549 /// are reachable.
5550 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
5551 const PartialDiagnostic &PD);
5552
5553 // Primary Expressions.
5554 SourceRange getExprRange(Expr *E) const;
5555
5556 ExprResult ActOnIdExpression(
5557 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5558 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
5559 CorrectionCandidateCallback *CCC = nullptr,
5560 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
5561
5562 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
5563 TemplateArgumentListInfo &Buffer,
5564 DeclarationNameInfo &NameInfo,
5565 const TemplateArgumentListInfo *&TemplateArgs);
5566
5567 bool DiagnoseDependentMemberLookup(const LookupResult &R);
5568
5569 bool
5570 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
5571 CorrectionCandidateCallback &CCC,
5572 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
5573 ArrayRef<Expr *> Args = std::nullopt,
5574 TypoExpr **Out = nullptr);
5575
5576 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
5577 IdentifierInfo *II);
5578 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
5579
5580 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
5581 IdentifierInfo *II,
5582 bool AllowBuiltinCreation=false);
5583
5584 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
5585 SourceLocation TemplateKWLoc,
5586 const DeclarationNameInfo &NameInfo,
5587 bool isAddressOfOperand,
5588 const TemplateArgumentListInfo *TemplateArgs);
5589
5590 /// If \p D cannot be odr-used in the current expression evaluation context,
5591 /// return a reason explaining why. Otherwise, return NOUR_None.
5592 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
5593
5594 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5595 SourceLocation Loc,
5596 const CXXScopeSpec *SS = nullptr);
5597 DeclRefExpr *
5598 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5599 const DeclarationNameInfo &NameInfo,
5600 const CXXScopeSpec *SS = nullptr,
5601 NamedDecl *FoundD = nullptr,
5602 SourceLocation TemplateKWLoc = SourceLocation(),
5603 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5604 DeclRefExpr *
5605 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5606 const DeclarationNameInfo &NameInfo,
5607 NestedNameSpecifierLoc NNS,
5608 NamedDecl *FoundD = nullptr,
5609 SourceLocation TemplateKWLoc = SourceLocation(),
5610 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5611
5612 ExprResult
5613 BuildAnonymousStructUnionMemberReference(
5614 const CXXScopeSpec &SS,
5615 SourceLocation nameLoc,
5616 IndirectFieldDecl *indirectField,
5617 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
5618 Expr *baseObjectExpr = nullptr,
5619 SourceLocation opLoc = SourceLocation());
5620
5621 ExprResult BuildPossibleImplicitMemberExpr(
5622 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
5623 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
5624 UnresolvedLookupExpr *AsULE = nullptr);
5625 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
5626 SourceLocation TemplateKWLoc,
5627 LookupResult &R,
5628 const TemplateArgumentListInfo *TemplateArgs,
5629 bool IsDefiniteInstance,
5630 const Scope *S);
5631 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
5632 const LookupResult &R,
5633 bool HasTrailingLParen);
5634
5635 ExprResult
5636 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
5637 const DeclarationNameInfo &NameInfo,
5638 bool IsAddressOfOperand, const Scope *S,
5639 TypeSourceInfo **RecoveryTSI = nullptr);
5640
5641 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
5642 SourceLocation TemplateKWLoc,
5643 const DeclarationNameInfo &NameInfo,
5644 const TemplateArgumentListInfo *TemplateArgs);
5645
5646 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
5647 LookupResult &R,
5648 bool NeedsADL,
5649 bool AcceptInvalidDecl = false);
5650 ExprResult BuildDeclarationNameExpr(
5651 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
5652 NamedDecl *FoundD = nullptr,
5653 const TemplateArgumentListInfo *TemplateArgs = nullptr,
5654 bool AcceptInvalidDecl = false);
5655
5656 ExprResult BuildLiteralOperatorCall(LookupResult &R,
5657 DeclarationNameInfo &SuffixInfo,
5658 ArrayRef<Expr *> Args,
5659 SourceLocation LitEndLoc,
5660 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
5661
5662 ExprResult BuildPredefinedExpr(SourceLocation Loc,
5663 PredefinedExpr::IdentKind IK);
5664 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
5665 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
5666
5667 ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5668 SourceLocation LParen,
5669 SourceLocation RParen,
5670 TypeSourceInfo *TSI);
5671 ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5672 SourceLocation LParen,
5673 SourceLocation RParen,
5674 ParsedType ParsedTy);
5675
5676 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
5677
5678 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
5679 ExprResult ActOnCharacterConstant(const Token &Tok,
5680 Scope *UDLScope = nullptr);
5681 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
5682 ExprResult ActOnParenListExpr(SourceLocation L,
5683 SourceLocation R,
5684 MultiExprArg Val);
5685
5686 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
5687 /// fragments (e.g. "foo" "bar" L"baz").
5688 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
5689 Scope *UDLScope = nullptr);
5690
5691 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
5692 SourceLocation DefaultLoc,
5693 SourceLocation RParenLoc,
5694 Expr *ControllingExpr,
5695 ArrayRef<ParsedType> ArgTypes,
5696 ArrayRef<Expr *> ArgExprs);
5697 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
5698 SourceLocation DefaultLoc,
5699 SourceLocation RParenLoc,
5700 Expr *ControllingExpr,
5701 ArrayRef<TypeSourceInfo *> Types,
5702 ArrayRef<Expr *> Exprs);
5703
5704 // Binary/Unary Operators. 'Tok' is the token for the operator.
5705 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
5706 Expr *InputExpr, bool IsAfterAmp = false);
5707 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
5708 Expr *Input, bool IsAfterAmp = false);
5709 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
5710 Expr *Input, bool IsAfterAmp = false);
5711
5712 bool isQualifiedMemberAccess(Expr *E);
5713 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
5714
5715 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
5716
5717 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
5718 SourceLocation OpLoc,
5719 UnaryExprOrTypeTrait ExprKind,
5720 SourceRange R);
5721 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
5722 UnaryExprOrTypeTrait ExprKind);
5723 ExprResult
5724 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
5725 UnaryExprOrTypeTrait ExprKind,
5726 bool IsType, void *TyOrEx,
5727 SourceRange ArgRange);
5728
5729 ExprResult CheckPlaceholderExpr(Expr *E);
5730 bool CheckVecStepExpr(Expr *E);
5731
5732 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
5733 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
5734 SourceRange ExprRange,
5735 UnaryExprOrTypeTrait ExprKind);
5736 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
5737 SourceLocation OpLoc,
5738 IdentifierInfo &Name,
5739 SourceLocation NameLoc,
5740 SourceLocation RParenLoc);
5741 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
5742 tok::TokenKind Kind, Expr *Input);
5743
5744 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
5745 MultiExprArg ArgExprs,
5746 SourceLocation RLoc);
5747 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5748 Expr *Idx, SourceLocation RLoc);
5749
5750 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5751 Expr *ColumnIdx,
5752 SourceLocation RBLoc);
5753
5754 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5755 Expr *LowerBound,
5756 SourceLocation ColonLocFirst,
5757 SourceLocation ColonLocSecond,
5758 Expr *Length, Expr *Stride,
5759 SourceLocation RBLoc);
5760 ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5761 SourceLocation RParenLoc,
5762 ArrayRef<Expr *> Dims,
5763 ArrayRef<SourceRange> Brackets);
5764
5765 /// Data structure for iterator expression.
5766 struct OMPIteratorData {
5767 IdentifierInfo *DeclIdent = nullptr;
5768 SourceLocation DeclIdentLoc;
5769 ParsedType Type;
5770 OMPIteratorExpr::IteratorRange Range;
5771 SourceLocation AssignLoc;
5772 SourceLocation ColonLoc;
5773 SourceLocation SecColonLoc;
5774 };
5775
5776 ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5777 SourceLocation LLoc, SourceLocation RLoc,
5778 ArrayRef<OMPIteratorData> Data);
5779
5780 // This struct is for use by ActOnMemberAccess to allow
5781 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
5782 // changing the access operator from a '.' to a '->' (to see if that is the
5783 // change needed to fix an error about an unknown member, e.g. when the class
5784 // defines a custom operator->).
5785 struct ActOnMemberAccessExtraArgs {
5786 Scope *S;
5787 UnqualifiedId &Id;
5788 Decl *ObjCImpDecl;
5789 };
5790
5791 ExprResult BuildMemberReferenceExpr(
5792 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
5793 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5794 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
5795 const TemplateArgumentListInfo *TemplateArgs,
5796 const Scope *S,
5797 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5798
5799 ExprResult
5800 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
5801 bool IsArrow, const CXXScopeSpec &SS,
5802 SourceLocation TemplateKWLoc,
5803 NamedDecl *FirstQualifierInScope, LookupResult &R,
5804 const TemplateArgumentListInfo *TemplateArgs,
5805 const Scope *S,
5806 bool SuppressQualifierCheck = false,
5807 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5808
5809 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
5810 SourceLocation OpLoc,
5811 const CXXScopeSpec &SS, FieldDecl *Field,
5812 DeclAccessPair FoundDecl,
5813 const DeclarationNameInfo &MemberNameInfo);
5814
5815 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
5816
5817 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
5818 const CXXScopeSpec &SS,
5819 const LookupResult &R);
5820
5821 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
5822 bool IsArrow, SourceLocation OpLoc,
5823 const CXXScopeSpec &SS,
5824 SourceLocation TemplateKWLoc,
5825 NamedDecl *FirstQualifierInScope,
5826 const DeclarationNameInfo &NameInfo,
5827 const TemplateArgumentListInfo *TemplateArgs);
5828
5829 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
5830 SourceLocation OpLoc,
5831 tok::TokenKind OpKind,
5832 CXXScopeSpec &SS,
5833 SourceLocation TemplateKWLoc,
5834 UnqualifiedId &Member,
5835 Decl *ObjCImpDecl);
5836
5837 MemberExpr *
5838 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5839 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
5840 ValueDecl *Member, DeclAccessPair FoundDecl,
5841 bool HadMultipleCandidates,
5842 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5843 ExprValueKind VK, ExprObjectKind OK,
5844 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5845 MemberExpr *
5846 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5847 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
5848 ValueDecl *Member, DeclAccessPair FoundDecl,
5849 bool HadMultipleCandidates,
5850 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5851 ExprValueKind VK, ExprObjectKind OK,
5852 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5853
5854 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
5855 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5856 FunctionDecl *FDecl,
5857 const FunctionProtoType *Proto,
5858 ArrayRef<Expr *> Args,
5859 SourceLocation RParenLoc,
5860 bool ExecConfig = false);
5861 void CheckStaticArrayArgument(SourceLocation CallLoc,
5862 ParmVarDecl *Param,
5863 const Expr *ArgExpr);
5864
5865 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5866 /// This provides the location of the left/right parens and a list of comma
5867 /// locations.
5868 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5869 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5870 Expr *ExecConfig = nullptr);
5871 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5872 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5873 Expr *ExecConfig = nullptr,
5874 bool IsExecConfig = false,
5875 bool AllowRecovery = false);
5876 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
5877 MultiExprArg CallArgs);
5878 enum class AtomicArgumentOrder { API, AST };
5879 ExprResult
5880 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5881 SourceLocation RParenLoc, MultiExprArg Args,
5882 AtomicExpr::AtomicOp Op,
5883 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
5884 ExprResult
5885 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
5886 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
5887 Expr *Config = nullptr, bool IsExecConfig = false,
5888 ADLCallKind UsesADL = ADLCallKind::NotADL);
5889
5890 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5891 MultiExprArg ExecConfig,
5892 SourceLocation GGGLoc);
5893
5894 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5895 Declarator &D, ParsedType &Ty,
5896 SourceLocation RParenLoc, Expr *CastExpr);
5897 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
5898 TypeSourceInfo *Ty,
5899 SourceLocation RParenLoc,
5900 Expr *Op);
5901 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
5902
5903 /// Build an altivec or OpenCL literal.
5904 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
5905 SourceLocation RParenLoc, Expr *E,
5906 TypeSourceInfo *TInfo);
5907
5908 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
5909
5910 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
5911 ParsedType Ty,
5912 SourceLocation RParenLoc,
5913 Expr *InitExpr);
5914
5915 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
5916 TypeSourceInfo *TInfo,
5917 SourceLocation RParenLoc,
5918 Expr *LiteralExpr);
5919
5920 ExprResult ActOnInitList(SourceLocation LBraceLoc,
5921 MultiExprArg InitArgList,
5922 SourceLocation RBraceLoc);
5923
5924 ExprResult BuildInitList(SourceLocation LBraceLoc,
5925 MultiExprArg InitArgList,
5926 SourceLocation RBraceLoc);
5927
5928 ExprResult ActOnDesignatedInitializer(Designation &Desig,
5929 SourceLocation EqualOrColonLoc,
5930 bool GNUSyntax,
5931 ExprResult Init);
5932
5933private:
5934 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
5935
5936public:
5937 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
5938 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
5939 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
5940 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
5941 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
5942 Expr *LHSExpr, Expr *RHSExpr);
5943 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
5944 UnresolvedSetImpl &Functions);
5945
5946 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
5947
5948 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
5949 /// in the case of a the GNU conditional expr extension.
5950 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
5951 SourceLocation ColonLoc,
5952 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
5953
5954 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5955 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
5956 LabelDecl *TheDecl);
5957
5958 void ActOnStartStmtExpr();
5959 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
5960 SourceLocation RPLoc);
5961 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
5962 SourceLocation RPLoc, unsigned TemplateDepth);
5963 // Handle the final expression in a statement expression.
5964 ExprResult ActOnStmtExprResult(ExprResult E);
5965 void ActOnStmtExprError();
5966
5967 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
5968 struct OffsetOfComponent {
5969 SourceLocation LocStart, LocEnd;
5970 bool isBrackets; // true if [expr], false if .ident
5971 union {
5972 IdentifierInfo *IdentInfo;
5973 Expr *E;
5974 } U;
5975 };
5976
5977 /// __builtin_offsetof(type, a.b[123][456].c)
5978 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
5979 TypeSourceInfo *TInfo,
5980 ArrayRef<OffsetOfComponent> Components,
5981 SourceLocation RParenLoc);
5982 ExprResult ActOnBuiltinOffsetOf(Scope *S,
5983 SourceLocation BuiltinLoc,
5984 SourceLocation TypeLoc,
5985 ParsedType ParsedArgTy,
5986 ArrayRef<OffsetOfComponent> Components,
5987 SourceLocation RParenLoc);
5988
5989 // __builtin_choose_expr(constExpr, expr1, expr2)
5990 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
5991 Expr *CondExpr, Expr *LHSExpr,
5992 Expr *RHSExpr, SourceLocation RPLoc);
5993
5994 // __builtin_va_arg(expr, type)
5995 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
5996 SourceLocation RPLoc);
5997 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
5998 TypeSourceInfo *TInfo, SourceLocation RPLoc);
5999
6000 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
6001 // __builtin_COLUMN(), __builtin_source_location()
6002 ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
6003 SourceLocation BuiltinLoc,
6004 SourceLocation RPLoc);
6005
6006 // Build a potentially resolved SourceLocExpr.
6007 ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
6008 QualType ResultTy, SourceLocation BuiltinLoc,
6009 SourceLocation RPLoc,
6010 DeclContext *ParentContext);
6011
6012 // __null
6013 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
6014
6015 bool CheckCaseExpression(Expr *E);
6016
6017 /// Describes the result of an "if-exists" condition check.
6018 enum IfExistsResult {
6019 /// The symbol exists.
6020 IER_Exists,
6021
6022 /// The symbol does not exist.
6023 IER_DoesNotExist,
6024
6025 /// The name is a dependent name, so the results will differ
6026 /// from one instantiation to the next.
6027 IER_Dependent,
6028
6029 /// An error occurred.
6030 IER_Error
6031 };
6032
6033 IfExistsResult
6034 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
6035 const DeclarationNameInfo &TargetNameInfo);
6036
6037 IfExistsResult
6038 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
6039 bool IsIfExists, CXXScopeSpec &SS,
6040 UnqualifiedId &Name);
6041
6042 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
6043 bool IsIfExists,
6044 NestedNameSpecifierLoc QualifierLoc,
6045 DeclarationNameInfo NameInfo,
6046 Stmt *Nested);
6047 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
6048 bool IsIfExists,
6049 CXXScopeSpec &SS, UnqualifiedId &Name,
6050 Stmt *Nested);
6051
6052 //===------------------------- "Block" Extension ------------------------===//
6053
6054 /// ActOnBlockStart - This callback is invoked when a block literal is
6055 /// started.
6056 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
6057
6058 /// ActOnBlockArguments - This callback allows processing of block arguments.
6059 /// If there are no arguments, this is still invoked.
6060 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
6061 Scope *CurScope);
6062
6063 /// ActOnBlockError - If there is an error parsing a block, this callback
6064 /// is invoked to pop the information about the block from the action impl.
6065 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
6066
6067 /// ActOnBlockStmtExpr - This is called when the body of a block statement
6068 /// literal was successfully completed. ^(int x){...}
6069 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
6070 Scope *CurScope);
6071
6072 //===---------------------------- Clang Extensions ----------------------===//
6073
6074 /// __builtin_convertvector(...)
6075 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6076 SourceLocation BuiltinLoc,
6077 SourceLocation RParenLoc);
6078
6079 //===---------------------------- OpenCL Features -----------------------===//
6080
6081 /// __builtin_astype(...)
6082 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6083 SourceLocation BuiltinLoc,
6084 SourceLocation RParenLoc);
6085 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
6086 SourceLocation BuiltinLoc,
6087 SourceLocation RParenLoc);
6088
6089 //===---------------------------- HLSL Features -------------------------===//
6090 Decl *ActOnStartHLSLBuffer(Scope *BufferScope, bool CBuffer,
6091 SourceLocation KwLoc, IdentifierInfo *Ident,
6092 SourceLocation IdentLoc, SourceLocation LBrace);
6093 void ActOnFinishHLSLBuffer(Decl *Dcl, SourceLocation RBrace);
6094
6095 //===---------------------------- C++ Features --------------------------===//
6096
6097 // Act on C++ namespaces
6098 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
6099 SourceLocation NamespaceLoc,
6100 SourceLocation IdentLoc, IdentifierInfo *Ident,
6101 SourceLocation LBrace,
6102 const ParsedAttributesView &AttrList,
6103 UsingDirectiveDecl *&UsingDecl, bool IsNested);
6104 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
6105
6106 NamespaceDecl *getStdNamespace() const;
6107 NamespaceDecl *getOrCreateStdNamespace();
6108
6109 CXXRecordDecl *getStdBadAlloc() const;
6110 EnumDecl *getStdAlignValT() const;
6111
6112private:
6113 // A cache representing if we've fully checked the various comparison category
6114 // types stored in ASTContext. The bit-index corresponds to the integer value
6115 // of a ComparisonCategoryType enumerator.
6116 llvm::SmallBitVector FullyCheckedComparisonCategories;
6117
6118 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
6119 CXXScopeSpec &SS,
6120 ParsedType TemplateTypeTy,
6121 IdentifierInfo *MemberOrBase);
6122
6123public:
6124 enum class ComparisonCategoryUsage {
6125 /// The '<=>' operator was used in an expression and a builtin operator
6126 /// was selected.
6127 OperatorInExpression,
6128 /// A defaulted 'operator<=>' needed the comparison category. This
6129 /// typically only applies to 'std::strong_ordering', due to the implicit
6130 /// fallback return value.
6131 DefaultedOperator,
6132 };
6133
6134 /// Lookup the specified comparison category types in the standard
6135 /// library, an check the VarDecls possibly returned by the operator<=>
6136 /// builtins for that type.
6137 ///
6138 /// \return The type of the comparison category type corresponding to the
6139 /// specified Kind, or a null type if an error occurs
6140 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
6141 SourceLocation Loc,
6142 ComparisonCategoryUsage Usage);
6143
6144 /// Tests whether Ty is an instance of std::initializer_list and, if
6145 /// it is and Element is not NULL, assigns the element type to Element.
6146 bool isStdInitializerList(QualType Ty, QualType *Element);
6147
6148 /// Looks for the std::initializer_list template and instantiates it
6149 /// with Element, or emits an error if it's not found.
6150 ///
6151 /// \returns The instantiated template, or null on error.
6152 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
6153
6154 /// Determine whether Ctor is an initializer-list constructor, as
6155 /// defined in [dcl.init.list]p2.
6156 bool isInitListConstructor(const FunctionDecl *Ctor);
6157
6158 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
6159 SourceLocation NamespcLoc, CXXScopeSpec &SS,
6160 SourceLocation IdentLoc,
6161 IdentifierInfo *NamespcName,
6162 const ParsedAttributesView &AttrList);
6163
6164 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
6165
6166 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
6167 SourceLocation NamespaceLoc,
6168 SourceLocation AliasLoc,
6169 IdentifierInfo *Alias,
6170 CXXScopeSpec &SS,
6171 SourceLocation IdentLoc,
6172 IdentifierInfo *Ident);
6173
6174 void FilterUsingLookup(Scope *S, LookupResult &lookup);
6175 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
6176 bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
6177 const LookupResult &PreviousDecls,
6178 UsingShadowDecl *&PrevShadow);
6179 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
6180 NamedDecl *Target,
6181 UsingShadowDecl *PrevDecl);
6182
6183 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6184 bool HasTypenameKeyword,
6185 const CXXScopeSpec &SS,
6186 SourceLocation NameLoc,
6187 const LookupResult &Previous);
6188 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
6189 const CXXScopeSpec &SS,
6190 const DeclarationNameInfo &NameInfo,
6191 SourceLocation NameLoc,
6192 const LookupResult *R = nullptr,
6193 const UsingDecl *UD = nullptr);
6194
6195 NamedDecl *BuildUsingDeclaration(
6196 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
6197 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
6198 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
6199 const ParsedAttributesView &AttrList, bool IsInstantiation,
6200 bool IsUsingIfExists);
6201 NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
6202 SourceLocation UsingLoc,
6203 SourceLocation EnumLoc,
6204 SourceLocation NameLoc,
6205 TypeSourceInfo *EnumType, EnumDecl *ED);
6206 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
6207 ArrayRef<NamedDecl *> Expansions);
6208
6209 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
6210
6211 /// Given a derived-class using shadow declaration for a constructor and the
6212 /// correspnding base class constructor, find or create the implicit
6213 /// synthesized derived class constructor to use for this initialization.
6214 CXXConstructorDecl *
6215 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
6216 ConstructorUsingShadowDecl *DerivedShadow);
6217
6218 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
6219 SourceLocation UsingLoc,
6220 SourceLocation TypenameLoc, CXXScopeSpec &SS,
6221 UnqualifiedId &Name, SourceLocation EllipsisLoc,
6222 const ParsedAttributesView &AttrList);
6223 Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
6224 SourceLocation UsingLoc,
6225 SourceLocation EnumLoc,
6226 SourceLocation IdentLoc, IdentifierInfo &II,
6227 CXXScopeSpec *SS = nullptr);
6228 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
6229 MultiTemplateParamsArg TemplateParams,
6230 SourceLocation UsingLoc, UnqualifiedId &Name,
6231 const ParsedAttributesView &AttrList,
6232 TypeResult Type, Decl *DeclFromDeclSpec);
6233
6234 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
6235 /// including handling of its default argument expressions.
6236 ///
6237 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
6238 ExprResult
6239 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6240 NamedDecl *FoundDecl,
6241 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
6242 bool HadMultipleCandidates, bool IsListInitialization,
6243 bool IsStdInitListInitialization,
6244 bool RequiresZeroInit, unsigned ConstructKind,
6245 SourceRange ParenRange);
6246
6247 /// Build a CXXConstructExpr whose constructor has already been resolved if
6248 /// it denotes an inherited constructor.
6249 ExprResult
6250 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6251 CXXConstructorDecl *Constructor, bool Elidable,
6252 MultiExprArg Exprs,
6253 bool HadMultipleCandidates, bool IsListInitialization,
6254 bool IsStdInitListInitialization,
6255 bool RequiresZeroInit, unsigned ConstructKind,
6256 SourceRange ParenRange);
6257
6258 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
6259 // the constructor can be elidable?
6260 ExprResult
6261 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6262 NamedDecl *FoundDecl,
6263 CXXConstructorDecl *Constructor, bool Elidable,
6264 MultiExprArg Exprs, bool HadMultipleCandidates,
6265 bool IsListInitialization,
6266 bool IsStdInitListInitialization, bool RequiresZeroInit,
6267 unsigned ConstructKind, SourceRange ParenRange);
6268
6269 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr,
6270 SourceLocation InitLoc);
6271
6272 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
6273
6274
6275 /// Instantiate or parse a C++ default argument expression as necessary.
6276 /// Return true on error.
6277 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
6278 ParmVarDecl *Param, Expr *Init = nullptr,
6279 bool SkipImmediateInvocations = true);
6280
6281 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
6282 /// the default expr if needed.
6283 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
6284 ParmVarDecl *Param, Expr *Init = nullptr);
6285
6286 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
6287 /// constructed variable.
6288 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
6289
6290 /// Helper class that collects exception specifications for
6291 /// implicitly-declared special member functions.
6292 class ImplicitExceptionSpecification {
6293 // Pointer to allow copying
6294 Sema *Self;
6295 // We order exception specifications thus:
6296 // noexcept is the most restrictive, but is only used in C++11.
6297 // throw() comes next.
6298 // Then a throw(collected exceptions)
6299 // Finally no specification, which is expressed as noexcept(false).
6300 // throw(...) is used instead if any called function uses it.
6301 ExceptionSpecificationType ComputedEST;
6302 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
6303 SmallVector<QualType, 4> Exceptions;
6304
6305 void ClearExceptions() {
6306 ExceptionsSeen.clear();
6307 Exceptions.clear();
6308 }
6309
6310 public:
6311 explicit ImplicitExceptionSpecification(Sema &Self)
6312 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
6313 if (!Self.getLangOpts().CPlusPlus11)
6314 ComputedEST = EST_DynamicNone;
6315 }
6316
6317 /// Get the computed exception specification type.
6318 ExceptionSpecificationType getExceptionSpecType() const {
6319 assert(!isComputedNoexcept(ComputedEST) &&(static_cast <bool> (!isComputedNoexcept(ComputedEST) &&
"noexcept(expr) should not be a possible result") ? void (0)
: __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "clang/include/clang/Sema/Sema.h", 6320, __extension__ __PRETTY_FUNCTION__
))
6320 "noexcept(expr) should not be a possible result")(static_cast <bool> (!isComputedNoexcept(ComputedEST) &&
"noexcept(expr) should not be a possible result") ? void (0)
: __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "clang/include/clang/Sema/Sema.h", 6320, __extension__ __PRETTY_FUNCTION__
))
;
6321 return ComputedEST;
6322 }
6323
6324 /// The number of exceptions in the exception specification.
6325 unsigned size() const { return Exceptions.size(); }
6326
6327 /// The set of exceptions in the exception specification.
6328 const QualType *data() const { return Exceptions.data(); }
6329
6330 /// Integrate another called method into the collected data.
6331 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
6332
6333 /// Integrate an invoked expression into the collected data.
6334 void CalledExpr(Expr *E) { CalledStmt(E); }
6335
6336 /// Integrate an invoked statement into the collected data.
6337 void CalledStmt(Stmt *S);
6338
6339 /// Overwrite an EPI's exception specification with this
6340 /// computed exception specification.
6341 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
6342 FunctionProtoType::ExceptionSpecInfo ESI;
6343 ESI.Type = getExceptionSpecType();
6344 if (ESI.Type == EST_Dynamic) {
6345 ESI.Exceptions = Exceptions;
6346 } else if (ESI.Type == EST_None) {
6347 /// C++11 [except.spec]p14:
6348 /// The exception-specification is noexcept(false) if the set of
6349 /// potential exceptions of the special member function contains "any"
6350 ESI.Type = EST_NoexceptFalse;
6351 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
6352 tok::kw_false).get();
6353 }
6354 return ESI;
6355 }
6356 };
6357
6358 /// Evaluate the implicit exception specification for a defaulted
6359 /// special member function.
6360 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
6361
6362 /// Check the given noexcept-specifier, convert its expression, and compute
6363 /// the appropriate ExceptionSpecificationType.
6364 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6365 ExceptionSpecificationType &EST);
6366
6367 /// Check the given exception-specification and update the
6368 /// exception specification information with the results.
6369 void checkExceptionSpecification(bool IsTopLevel,
6370 ExceptionSpecificationType EST,
6371 ArrayRef<ParsedType> DynamicExceptions,
6372 ArrayRef<SourceRange> DynamicExceptionRanges,
6373 Expr *NoexceptExpr,
6374 SmallVectorImpl<QualType> &Exceptions,
6375 FunctionProtoType::ExceptionSpecInfo &ESI);
6376
6377 /// Determine if we're in a case where we need to (incorrectly) eagerly
6378 /// parse an exception specification to work around a libstdc++ bug.
6379 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6380
6381 /// Add an exception-specification to the given member function
6382 /// (or member function template). The exception-specification was parsed
6383 /// after the method itself was declared.
6384 void actOnDelayedExceptionSpecification(Decl *Method,
6385 ExceptionSpecificationType EST,
6386 SourceRange SpecificationRange,
6387 ArrayRef<ParsedType> DynamicExceptions,
6388 ArrayRef<SourceRange> DynamicExceptionRanges,
6389 Expr *NoexceptExpr);
6390
6391 class InheritedConstructorInfo;
6392
6393 /// Determine if a special member function should have a deleted
6394 /// definition when it is defaulted.
6395 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6396 InheritedConstructorInfo *ICI = nullptr,
6397 bool Diagnose = false);
6398
6399 /// Produce notes explaining why a defaulted function was defined as deleted.
6400 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
6401
6402 /// Declare the implicit default constructor for the given class.
6403 ///
6404 /// \param ClassDecl The class declaration into which the implicit
6405 /// default constructor will be added.
6406 ///
6407 /// \returns The implicitly-declared default constructor.
6408 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
6409 CXXRecordDecl *ClassDecl);
6410
6411 /// DefineImplicitDefaultConstructor - Checks for feasibility of
6412 /// defining this constructor as the default constructor.
6413 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6414 CXXConstructorDecl *Constructor);
6415
6416 /// Declare the implicit destructor for the given class.
6417 ///
6418 /// \param ClassDecl The class declaration into which the implicit
6419 /// destructor will be added.
6420 ///
6421 /// \returns The implicitly-declared destructor.
6422 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
6423
6424 /// DefineImplicitDestructor - Checks for feasibility of
6425 /// defining this destructor as the default destructor.
6426 void DefineImplicitDestructor(SourceLocation CurrentLocation,
6427 CXXDestructorDecl *Destructor);
6428
6429 /// Build an exception spec for destructors that don't have one.
6430 ///
6431 /// C++11 says that user-defined destructors with no exception spec get one
6432 /// that looks as if the destructor was implicitly declared.
6433 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
6434
6435 /// Define the specified inheriting constructor.
6436 void DefineInheritingConstructor(SourceLocation UseLoc,
6437 CXXConstructorDecl *Constructor);
6438
6439 /// Declare the implicit copy constructor for the given class.
6440 ///
6441 /// \param ClassDecl The class declaration into which the implicit
6442 /// copy constructor will be added.
6443 ///
6444 /// \returns The implicitly-declared copy constructor.
6445 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
6446
6447 /// DefineImplicitCopyConstructor - Checks for feasibility of
6448 /// defining this constructor as the copy constructor.
6449 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6450 CXXConstructorDecl *Constructor);
6451
6452 /// Declare the implicit move constructor for the given class.
6453 ///
6454 /// \param ClassDecl The Class declaration into which the implicit
6455 /// move constructor will be added.
6456 ///
6457 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
6458 /// declared.
6459 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
6460
6461 /// DefineImplicitMoveConstructor - Checks for feasibility of
6462 /// defining this constructor as the move constructor.
6463 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
6464 CXXConstructorDecl *Constructor);
6465
6466 /// Declare the implicit copy assignment operator for the given class.
6467 ///
6468 /// \param ClassDecl The class declaration into which the implicit
6469 /// copy assignment operator will be added.
6470 ///
6471 /// \returns The implicitly-declared copy assignment operator.
6472 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
6473
6474 /// Defines an implicitly-declared copy assignment operator.
6475 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6476 CXXMethodDecl *MethodDecl);
6477
6478 /// Declare the implicit move assignment operator for the given class.
6479 ///
6480 /// \param ClassDecl The Class declaration into which the implicit
6481 /// move assignment operator will be added.
6482 ///
6483 /// \returns The implicitly-declared move assignment operator, or NULL if it
6484 /// wasn't declared.
6485 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
6486
6487 /// Defines an implicitly-declared move assignment operator.
6488 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
6489 CXXMethodDecl *MethodDecl);
6490
6491 /// Force the declaration of any implicitly-declared members of this
6492 /// class.
6493 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
6494
6495 /// Check a completed declaration of an implicit special member.
6496 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
6497
6498 /// Determine whether the given function is an implicitly-deleted
6499 /// special member function.
6500 bool isImplicitlyDeleted(FunctionDecl *FD);
6501
6502 /// Check whether 'this' shows up in the type of a static member
6503 /// function after the (naturally empty) cv-qualifier-seq would be.
6504 ///
6505 /// \returns true if an error occurred.
6506 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
6507
6508 /// Whether this' shows up in the exception specification of a static
6509 /// member function.
6510 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
6511
6512 /// Check whether 'this' shows up in the attributes of the given
6513 /// static member function.
6514 ///
6515 /// \returns true if an error occurred.
6516 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
6517
6518 /// MaybeBindToTemporary - If the passed in expression has a record type with
6519 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
6520 /// it simply returns the passed in expression.
6521 ExprResult MaybeBindToTemporary(Expr *E);
6522
6523 /// Wrap the expression in a ConstantExpr if it is a potential immediate
6524 /// invocation.
6525 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
6526
6527 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
6528 QualType DeclInitType, MultiExprArg ArgsPtr,
6529 SourceLocation Loc,
6530 SmallVectorImpl<Expr *> &ConvertedArgs,
6531 bool AllowExplicit = false,
6532 bool IsListInitialization = false);
6533
6534 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
6535 SourceLocation NameLoc,
6536 IdentifierInfo &Name);
6537
6538 ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
6539 Scope *S, CXXScopeSpec &SS,
6540 bool EnteringContext);
6541 ParsedType getDestructorName(SourceLocation TildeLoc,
6542 IdentifierInfo &II, SourceLocation NameLoc,
6543 Scope *S, CXXScopeSpec &SS,
6544 ParsedType ObjectType,
6545 bool EnteringContext);
6546
6547 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
6548 ParsedType ObjectType);
6549
6550 // Checks that reinterpret casts don't have undefined behavior.
6551 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
6552 bool IsDereference, SourceRange Range);
6553
6554 // Checks that the vector type should be initialized from a scalar
6555 // by splatting the value rather than populating a single element.
6556 // This is the case for AltiVecVector types as well as with
6557 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
6558 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
6559
6560 // Checks if the -faltivec-src-compat=gcc option is specified.
6561 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
6562 // treated the same way as they are when trying to initialize
6563 // these vectors on gcc (an error is emitted).
6564 bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
6565 QualType SrcTy);
6566
6567 /// ActOnCXXNamedCast - Parse
6568 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
6569 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
6570 tok::TokenKind Kind,
6571 SourceLocation LAngleBracketLoc,
6572 Declarator &D,
6573 SourceLocation RAngleBracketLoc,
6574 SourceLocation LParenLoc,
6575 Expr *E,
6576 SourceLocation RParenLoc);
6577
6578 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
6579 tok::TokenKind Kind,
6580 TypeSourceInfo *Ty,
6581 Expr *E,
6582 SourceRange AngleBrackets,
6583 SourceRange Parens);
6584
6585 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
6586 ExprResult Operand,
6587 SourceLocation RParenLoc);
6588
6589 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
6590 Expr *Operand, SourceLocation RParenLoc);
6591
6592 ExprResult BuildCXXTypeId(QualType TypeInfoType,
6593 SourceLocation TypeidLoc,
6594 TypeSourceInfo *Operand,
6595 SourceLocation RParenLoc);
6596 ExprResult BuildCXXTypeId(QualType TypeInfoType,
6597 SourceLocation TypeidLoc,
6598 Expr *Operand,
6599 SourceLocation RParenLoc);
6600
6601 /// ActOnCXXTypeid - Parse typeid( something ).
6602 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
6603 SourceLocation LParenLoc, bool isType,
6604 void *TyOrExpr,
6605 SourceLocation RParenLoc);
6606
6607 ExprResult BuildCXXUuidof(QualType TypeInfoType,
6608 SourceLocation TypeidLoc,
6609 TypeSourceInfo *Operand,
6610 SourceLocation RParenLoc);
6611 ExprResult BuildCXXUuidof(QualType TypeInfoType,
6612 SourceLocation TypeidLoc,
6613 Expr *Operand,
6614 SourceLocation RParenLoc);
6615
6616 /// ActOnCXXUuidof - Parse __uuidof( something ).
6617 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
6618 SourceLocation LParenLoc, bool isType,
6619 void *TyOrExpr,
6620 SourceLocation RParenLoc);
6621
6622 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
6623 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
6624 tok::TokenKind Operator,
6625 SourceLocation EllipsisLoc, Expr *RHS,
6626 SourceLocation RParenLoc);
6627 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
6628 SourceLocation LParenLoc, Expr *LHS,
6629 BinaryOperatorKind Operator,
6630 SourceLocation EllipsisLoc, Expr *RHS,
6631 SourceLocation RParenLoc,
6632 std::optional<unsigned> NumExpansions);
6633 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
6634 BinaryOperatorKind Operator);
6635
6636 //// ActOnCXXThis - Parse 'this' pointer.
6637 ExprResult ActOnCXXThis(SourceLocation loc);
6638
6639 /// Build a CXXThisExpr and mark it referenced in the current context.
6640 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
6641 void MarkThisReferenced(CXXThisExpr *This);
6642
6643 /// Try to retrieve the type of the 'this' pointer.
6644 ///
6645 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
6646 QualType getCurrentThisType();
6647
6648 /// When non-NULL, the C++ 'this' expression is allowed despite the
6649 /// current context not being a non-static member function. In such cases,
6650 /// this provides the type used for 'this'.
6651 QualType CXXThisTypeOverride;
6652
6653 /// RAII object used to temporarily allow the C++ 'this' expression
6654 /// to be used, with the given qualifiers on the current class type.
6655 class CXXThisScopeRAII {
6656 Sema &S;
6657 QualType OldCXXThisTypeOverride;
6658 bool Enabled;
6659
6660 public:
6661 /// Introduce a new scope where 'this' may be allowed (when enabled),
6662 /// using the given declaration (which is either a class template or a
6663 /// class) along with the given qualifiers.
6664 /// along with the qualifiers placed on '*this'.
6665 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
6666 bool Enabled = true);
6667
6668 ~CXXThisScopeRAII();
6669 };
6670
6671 /// Make sure the value of 'this' is actually available in the current
6672 /// context, if it is a potentially evaluated context.
6673 ///
6674 /// \param Loc The location at which the capture of 'this' occurs.
6675 ///
6676 /// \param Explicit Whether 'this' is explicitly captured in a lambda
6677 /// capture list.
6678 ///
6679 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
6680 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
6681 /// This is useful when enclosing lambdas must speculatively capture
6682 /// 'this' that may or may not be used in certain specializations of
6683 /// a nested generic lambda (depending on whether the name resolves to
6684 /// a non-static member function or a static function).
6685 /// \return returns 'true' if failed, 'false' if success.
6686 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
6687 bool BuildAndDiagnose = true,
6688 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
6689 bool ByCopy = false);
6690
6691 /// Determine whether the given type is the type of *this that is used
6692 /// outside of the body of a member function for a type that is currently
6693 /// being defined.
6694 bool isThisOutsideMemberFunctionBody(QualType BaseType);
6695
6696 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
6697 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6698
6699
6700 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
6701 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6702
6703 ExprResult
6704 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
6705 SourceLocation AtLoc, SourceLocation RParen);
6706
6707 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
6708 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
6709
6710 //// ActOnCXXThrow - Parse throw expressions.
6711 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
6712 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
6713 bool IsThrownVarInScope);
6714 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
6715
6716 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
6717 /// Can be interpreted either as function-style casting ("int(x)")
6718 /// or class type construction ("ClassType(x,y,z)")
6719 /// or creation of a value-initialized type ("int()").
6720 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
6721 SourceLocation LParenOrBraceLoc,
6722 MultiExprArg Exprs,
6723 SourceLocation RParenOrBraceLoc,
6724 bool ListInitialization);
6725
6726 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
6727 SourceLocation LParenLoc,
6728 MultiExprArg Exprs,
6729 SourceLocation RParenLoc,
6730 bool ListInitialization);
6731
6732 /// ActOnCXXNew - Parsed a C++ 'new' expression.
6733 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
6734 SourceLocation PlacementLParen,
6735 MultiExprArg PlacementArgs,
6736 SourceLocation PlacementRParen,
6737 SourceRange TypeIdParens, Declarator &D,
6738 Expr *Initializer);
6739 ExprResult
6740 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
6741 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
6742 SourceRange TypeIdParens, QualType AllocType,
6743 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
6744 SourceRange DirectInitRange, Expr *Initializer);
6745
6746 /// Determine whether \p FD is an aligned allocation or deallocation
6747 /// function that is unavailable.
6748 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
6749
6750 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
6751 /// function that is unavailable.
6752 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
6753 SourceLocation Loc);
6754
6755 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
6756 SourceRange R);
6757
6758 /// The scope in which to find allocation functions.
6759 enum AllocationFunctionScope {
6760 /// Only look for allocation functions in the global scope.
6761 AFS_Global,
6762 /// Only look for allocation functions in the scope of the
6763 /// allocated class.
6764 AFS_Class,
6765 /// Look for allocation functions in both the global scope
6766 /// and in the scope of the allocated class.
6767 AFS_Both
6768 };
6769
6770 /// Finds the overloads of operator new and delete that are appropriate
6771 /// for the allocation.
6772 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
6773 AllocationFunctionScope NewScope,
6774 AllocationFunctionScope DeleteScope,
6775 QualType AllocType, bool IsArray,
6776 bool &PassAlignment, MultiExprArg PlaceArgs,
6777 FunctionDecl *&OperatorNew,
6778 FunctionDecl *&OperatorDelete,
6779 bool Diagnose = true);
6780 void DeclareGlobalNewDelete();
6781 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
6782 ArrayRef<QualType> Params);
6783
6784 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
6785 DeclarationName Name, FunctionDecl *&Operator,
6786 bool Diagnose = true, bool WantSize = false,
6787 bool WantAligned = false);
6788 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
6789 bool CanProvideSize,
6790 bool Overaligned,
6791 DeclarationName Name);
6792 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
6793 CXXRecordDecl *RD);
6794
6795 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
6796 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
6797 bool UseGlobal, bool ArrayForm,
6798 Expr *Operand);
6799 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
6800 bool IsDelete, bool CallCanBeVirtual,
6801 bool WarnOnNonAbstractTypes,
6802 SourceLocation DtorLoc);
6803
6804 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
6805 Expr *Operand, SourceLocation RParen);
6806 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6807 SourceLocation RParen);
6808
6809 /// Parsed one of the type trait support pseudo-functions.
6810 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6811 ArrayRef<ParsedType> Args,
6812 SourceLocation RParenLoc);
6813 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6814 ArrayRef<TypeSourceInfo *> Args,
6815 SourceLocation RParenLoc);
6816
6817 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
6818 /// pseudo-functions.
6819 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
6820 SourceLocation KWLoc,
6821 ParsedType LhsTy,
6822 Expr *DimExpr,
6823 SourceLocation RParen);
6824
6825 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
6826 SourceLocation KWLoc,
6827 TypeSourceInfo *TSInfo,
6828 Expr *DimExpr,
6829 SourceLocation RParen);
6830
6831 /// ActOnExpressionTrait - Parsed one of the unary type trait support
6832 /// pseudo-functions.
6833 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
6834 SourceLocation KWLoc,
6835 Expr *Queried,
6836 SourceLocation RParen);
6837
6838 ExprResult BuildExpressionTrait(ExpressionTrait OET,
6839 SourceLocation KWLoc,
6840 Expr *Queried,
6841 SourceLocation RParen);
6842
6843 ExprResult ActOnStartCXXMemberReference(Scope *S,
6844 Expr *Base,
6845 SourceLocation OpLoc,
6846 tok::TokenKind OpKind,
6847 ParsedType &ObjectType,
6848 bool &MayBePseudoDestructor);
6849
6850 ExprResult BuildPseudoDestructorExpr(Expr *Base,
6851 SourceLocation OpLoc,
6852 tok::TokenKind OpKind,
6853 const CXXScopeSpec &SS,
6854 TypeSourceInfo *ScopeType,
6855 SourceLocation CCLoc,
6856 SourceLocation TildeLoc,
6857 PseudoDestructorTypeStorage DestroyedType);
6858
6859 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6860 SourceLocation OpLoc,
6861 tok::TokenKind OpKind,
6862 CXXScopeSpec &SS,
6863 UnqualifiedId &FirstTypeName,
6864 SourceLocation CCLoc,
6865 SourceLocation TildeLoc,
6866 UnqualifiedId &SecondTypeName);
6867
6868 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6869 SourceLocation OpLoc,
6870 tok::TokenKind OpKind,
6871 SourceLocation TildeLoc,
6872 const DeclSpec& DS);
6873
6874 /// MaybeCreateExprWithCleanups - If the current full-expression
6875 /// requires any cleanups, surround it with a ExprWithCleanups node.
6876 /// Otherwise, just returns the passed-in expression.
6877 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
6878 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
6879 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
6880
6881 MaterializeTemporaryExpr *
6882 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6883 bool BoundToLvalueReference);
6884
6885 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
6886 return ActOnFinishFullExpr(
6887 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
6888 }
6889 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
6890 bool DiscardedValue, bool IsConstexpr = false,
6891 bool IsTemplateArgument = false);
6892 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
6893
6894 // Marks SS invalid if it represents an incomplete type.
6895 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
6896 // Complete an enum decl, maybe without a scope spec.
6897 bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
6898 CXXScopeSpec *SS = nullptr);
6899
6900 DeclContext *computeDeclContext(QualType T);
6901 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
6902 bool EnteringContext = false);
6903 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
6904 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
6905
6906 /// The parser has parsed a global nested-name-specifier '::'.
6907 ///
6908 /// \param CCLoc The location of the '::'.
6909 ///
6910 /// \param SS The nested-name-specifier, which will be updated in-place
6911 /// to reflect the parsed nested-name-specifier.
6912 ///
6913 /// \returns true if an error occurred, false otherwise.
6914 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
6915
6916 /// The parser has parsed a '__super' nested-name-specifier.
6917 ///
6918 /// \param SuperLoc The location of the '__super' keyword.
6919 ///
6920 /// \param ColonColonLoc The location of the '::'.
6921 ///
6922 /// \param SS The nested-name-specifier, which will be updated in-place
6923 /// to reflect the parsed nested-name-specifier.
6924 ///
6925 /// \returns true if an error occurred, false otherwise.
6926 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
6927 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
6928
6929 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
6930 bool *CanCorrect = nullptr);
6931 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
6932
6933 /// Keeps information about an identifier in a nested-name-spec.
6934 ///
6935 struct NestedNameSpecInfo {
6936 /// The type of the object, if we're parsing nested-name-specifier in
6937 /// a member access expression.
6938 ParsedType ObjectType;
6939
6940 /// The identifier preceding the '::'.
6941 IdentifierInfo *Identifier;
6942
6943 /// The location of the identifier.
6944 SourceLocation IdentifierLoc;
6945
6946 /// The location of the '::'.
6947 SourceLocation CCLoc;
6948
6949 /// Creates info object for the most typical case.
6950 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6951 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
6952 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
6953 CCLoc(ColonColonLoc) {
6954 }
6955
6956 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6957 SourceLocation ColonColonLoc, QualType ObjectType)
6958 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
6959 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
6960 }
6961 };
6962
6963 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
6964 NestedNameSpecInfo &IdInfo);
6965
6966 bool BuildCXXNestedNameSpecifier(Scope *S,
6967 NestedNameSpecInfo &IdInfo,
6968 bool EnteringContext,
6969 CXXScopeSpec &SS,
6970 NamedDecl *ScopeLookupResult,
6971 bool ErrorRecoveryLookup,
6972 bool *IsCorrectedToColon = nullptr,
6973 bool OnlyNamespace = false);
6974
6975 /// The parser has parsed a nested-name-specifier 'identifier::'.
6976 ///
6977 /// \param S The scope in which this nested-name-specifier occurs.
6978 ///
6979 /// \param IdInfo Parser information about an identifier in the
6980 /// nested-name-spec.
6981 ///
6982 /// \param EnteringContext Whether we're entering the context nominated by
6983 /// this nested-name-specifier.
6984 ///
6985 /// \param SS The nested-name-specifier, which is both an input
6986 /// parameter (the nested-name-specifier before this type) and an
6987 /// output parameter (containing the full nested-name-specifier,
6988 /// including this new type).
6989 ///
6990 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
6991 /// are allowed. The bool value pointed by this parameter is set to 'true'
6992 /// if the identifier is treated as if it was followed by ':', not '::'.
6993 ///
6994 /// \param OnlyNamespace If true, only considers namespaces in lookup.
6995 ///
6996 /// \returns true if an error occurred, false otherwise.
6997 bool ActOnCXXNestedNameSpecifier(Scope *S,
6998 NestedNameSpecInfo &IdInfo,
6999 bool EnteringContext,
7000 CXXScopeSpec &SS,
7001 bool *IsCorrectedToColon = nullptr,
7002 bool OnlyNamespace = false);
7003
7004 ExprResult ActOnDecltypeExpression(Expr *E);
7005
7006 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
7007 const DeclSpec &DS,
7008 SourceLocation ColonColonLoc);
7009
7010 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
7011 NestedNameSpecInfo &IdInfo,
7012 bool EnteringContext);
7013
7014 /// The parser has parsed a nested-name-specifier
7015 /// 'template[opt] template-name < template-args >::'.
7016 ///
7017 /// \param S The scope in which this nested-name-specifier occurs.
7018 ///
7019 /// \param SS The nested-name-specifier, which is both an input
7020 /// parameter (the nested-name-specifier before this type) and an
7021 /// output parameter (containing the full nested-name-specifier,
7022 /// including this new type).
7023 ///
7024 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
7025 /// \param TemplateName the template name.
7026 /// \param TemplateNameLoc The location of the template name.
7027 /// \param LAngleLoc The location of the opening angle bracket ('<').
7028 /// \param TemplateArgs The template arguments.
7029 /// \param RAngleLoc The location of the closing angle bracket ('>').
7030 /// \param CCLoc The location of the '::'.
7031 ///
7032 /// \param EnteringContext Whether we're entering the context of the
7033 /// nested-name-specifier.
7034 ///
7035 ///
7036 /// \returns true if an error occurred, false otherwise.
7037 bool ActOnCXXNestedNameSpecifier(Scope *S,
7038 CXXScopeSpec &SS,
7039 SourceLocation TemplateKWLoc,
7040 TemplateTy TemplateName,
7041 SourceLocation TemplateNameLoc,
7042 SourceLocation LAngleLoc,
7043 ASTTemplateArgsPtr TemplateArgs,
7044 SourceLocation RAngleLoc,
7045 SourceLocation CCLoc,
7046 bool EnteringContext);
7047
7048 /// Given a C++ nested-name-specifier, produce an annotation value
7049 /// that the parser can use later to reconstruct the given
7050 /// nested-name-specifier.
7051 ///
7052 /// \param SS A nested-name-specifier.
7053 ///
7054 /// \returns A pointer containing all of the information in the
7055 /// nested-name-specifier \p SS.
7056 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
7057
7058 /// Given an annotation pointer for a nested-name-specifier, restore
7059 /// the nested-name-specifier structure.
7060 ///
7061 /// \param Annotation The annotation pointer, produced by
7062 /// \c SaveNestedNameSpecifierAnnotation().
7063 ///
7064 /// \param AnnotationRange The source range corresponding to the annotation.
7065 ///
7066 /// \param SS The nested-name-specifier that will be updated with the contents
7067 /// of the annotation pointer.
7068 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
7069 SourceRange AnnotationRange,
7070 CXXScopeSpec &SS);
7071
7072 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
7073
7074 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
7075 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
7076 /// After this method is called, according to [C++ 3.4.3p3], names should be
7077 /// looked up in the declarator-id's scope, until the declarator is parsed and
7078 /// ActOnCXXExitDeclaratorScope is called.
7079 /// The 'SS' should be a non-empty valid CXXScopeSpec.
7080 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
7081
7082 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
7083 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
7084 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
7085 /// Used to indicate that names should revert to being looked up in the
7086 /// defining scope.
7087 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
7088
7089 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
7090 /// initializer for the declaration 'Dcl'.
7091 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7092 /// static data member of class X, names should be looked up in the scope of
7093 /// class X.
7094 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
7095
7096 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
7097 /// initializer for the declaration 'Dcl'.
7098 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
7099
7100 /// Create a new lambda closure type.
7101 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
7102 TypeSourceInfo *Info,
7103 unsigned LambdaDependencyKind,
7104 LambdaCaptureDefault CaptureDefault);
7105
7106 /// Start the definition of a lambda expression.
7107 CXXMethodDecl *
7108 startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange,
7109 TypeSourceInfo *MethodType, SourceLocation EndLoc,
7110 ArrayRef<ParmVarDecl *> Params,
7111 ConstexprSpecKind ConstexprKind, StorageClass SC,
7112 Expr *TrailingRequiresClause);
7113
7114 /// Number lambda for linkage purposes if necessary.
7115 void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method,
7116 std::optional<CXXRecordDecl::LambdaNumbering>
7117 NumberingOverride = std::nullopt);
7118
7119 /// Endow the lambda scope info with the relevant properties.
7120 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
7121 SourceRange IntroducerRange,
7122 LambdaCaptureDefault CaptureDefault,
7123 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
7124 bool Mutable);
7125
7126 CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange,
7127 CXXRecordDecl *Class);
7128 void CompleteLambdaCallOperator(
7129 CXXMethodDecl *Method, SourceLocation LambdaLoc,
7130 SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause,
7131 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,
7132 StorageClass SC, ArrayRef<ParmVarDecl *> Params,
7133 bool HasExplicitResultType);
7134
7135 /// Perform initialization analysis of the init-capture and perform
7136 /// any implicit conversions such as an lvalue-to-rvalue conversion if
7137 /// not being used to initialize a reference.
7138 ParsedType actOnLambdaInitCaptureInitialization(
7139 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
7140 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
7141 return ParsedType::make(buildLambdaInitCaptureInitialization(
7142 Loc, ByRef, EllipsisLoc, std::nullopt, Id,
7143 InitKind != LambdaCaptureInitKind::CopyInit, Init));
7144 }
7145 QualType buildLambdaInitCaptureInitialization(
7146 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
7147 std::optional<unsigned> NumExpansions, IdentifierInfo *Id,
7148 bool DirectInit, Expr *&Init);
7149
7150 /// Create a dummy variable within the declcontext of the lambda's
7151 /// call operator, for name lookup purposes for a lambda init capture.
7152 ///
7153 /// CodeGen handles emission of lambda captures, ignoring these dummy
7154 /// variables appropriately.
7155 VarDecl *createLambdaInitCaptureVarDecl(
7156 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
7157 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
7158
7159 /// Add an init-capture to a lambda scope.
7160 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var,
7161 bool isReferenceType);
7162
7163 /// Note that we have finished the explicit captures for the
7164 /// given lambda.
7165 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
7166
7167 /// Deduce a block or lambda's return type based on the return
7168 /// statements present in the body.
7169 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
7170
7171 /// Once the Lambdas capture are known, we can start to create the closure,
7172 /// call operator method, and keep track of the captures.
7173 /// We do the capture lookup here, but they are not actually captured until
7174 /// after we know what the qualifiers of the call operator are.
7175 void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
7176 Scope *CurContext);
7177
7178 /// This is called after parsing the explicit template parameter list
7179 /// on a lambda (if it exists) in C++2a.
7180 void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro,
7181 SourceLocation LAngleLoc,
7182 ArrayRef<NamedDecl *> TParams,
7183 SourceLocation RAngleLoc,
7184 ExprResult RequiresClause);
7185
7186 void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
7187 SourceLocation MutableLoc);
7188
7189 void ActOnLambdaClosureParameters(
7190 Scope *LambdaScope,
7191 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo);
7192
7193 /// ActOnStartOfLambdaDefinition - This is called just before we start
7194 /// parsing the body of a lambda; it analyzes the explicit captures and
7195 /// arguments, and sets up various data-structures for the body of the
7196 /// lambda.
7197 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
7198 Declarator &ParamInfo, const DeclSpec &DS);
7199
7200 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
7201 /// is invoked to pop the information about the lambda.
7202 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
7203 bool IsInstantiation = false);
7204
7205 /// ActOnLambdaExpr - This is called when the body of a lambda expression
7206 /// was successfully completed.
7207 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
7208 Scope *CurScope);
7209
7210 /// Does copying/destroying the captured variable have side effects?
7211 bool CaptureHasSideEffects(const sema::Capture &From);
7212
7213 /// Diagnose if an explicit lambda capture is unused. Returns true if a
7214 /// diagnostic is emitted.
7215 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
7216 const sema::Capture &From);
7217
7218 /// Build a FieldDecl suitable to hold the given capture.
7219 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
7220
7221 /// Initialize the given capture with a suitable expression.
7222 ExprResult BuildCaptureInit(const sema::Capture &Capture,
7223 SourceLocation ImplicitCaptureLoc,
7224 bool IsOpenMPMapping = false);
7225
7226 /// Complete a lambda-expression having processed and attached the
7227 /// lambda body.
7228 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
7229 sema::LambdaScopeInfo *LSI);
7230
7231 /// Get the return type to use for a lambda's conversion function(s) to
7232 /// function pointer type, given the type of the call operator.
7233 QualType
7234 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
7235 CallingConv CC);
7236
7237 /// Define the "body" of the conversion from a lambda object to a
7238 /// function pointer.
7239 ///
7240 /// This routine doesn't actually define a sensible body; rather, it fills
7241 /// in the initialization expression needed to copy the lambda object into
7242 /// the block, and IR generation actually generates the real body of the
7243 /// block pointer conversion.
7244 void DefineImplicitLambdaToFunctionPointerConversion(
7245 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
7246
7247 /// Define the "body" of the conversion from a lambda object to a
7248 /// block pointer.
7249 ///
7250 /// This routine doesn't actually define a sensible body; rather, it fills
7251 /// in the initialization expression needed to copy the lambda object into
7252 /// the block, and IR generation actually generates the real body of the
7253 /// block pointer conversion.
7254 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
7255 CXXConversionDecl *Conv);
7256
7257 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
7258 SourceLocation ConvLocation,
7259 CXXConversionDecl *Conv,
7260 Expr *Src);
7261
7262 /// Check whether the given expression is a valid constraint expression.
7263 /// A diagnostic is emitted if it is not, false is returned, and
7264 /// PossibleNonPrimary will be set to true if the failure might be due to a
7265 /// non-primary expression being used as an atomic constraint.
7266 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
7267 bool *PossibleNonPrimary = nullptr,
7268 bool IsTrailingRequiresClause = false);
7269
7270private:
7271 /// Caches pairs of template-like decls whose associated constraints were
7272 /// checked for subsumption and whether or not the first's constraints did in
7273 /// fact subsume the second's.
7274 llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
7275 /// Caches the normalized associated constraints of declarations (concepts or
7276 /// constrained declarations). If an error occurred while normalizing the
7277 /// associated constraints of the template or concept, nullptr will be cached
7278 /// here.
7279 llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
7280 NormalizationCache;
7281
7282 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
7283 SatisfactionCache;
7284
7285 /// Introduce the instantiated function parameters into the local
7286 /// instantiation scope, and set the parameter names to those used
7287 /// in the template.
7288 bool addInstantiatedParametersToScope(
7289 FunctionDecl *Function, const FunctionDecl *PatternDecl,
7290 LocalInstantiationScope &Scope,
7291 const MultiLevelTemplateArgumentList &TemplateArgs);
7292
7293 /// Introduce the instantiated captures of the lambda into the local
7294 /// instantiation scope.
7295 bool addInstantiatedCapturesToScope(
7296 FunctionDecl *Function, const FunctionDecl *PatternDecl,
7297 LocalInstantiationScope &Scope,
7298 const MultiLevelTemplateArgumentList &TemplateArgs);
7299
7300 /// used by SetupConstraintCheckingTemplateArgumentsAndScope to recursively(in
7301 /// the case of lambdas) set up the LocalInstantiationScope of the current
7302 /// function.
7303 bool SetupConstraintScope(
7304 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
7305 MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope);
7306
7307 /// Used during constraint checking, sets up the constraint template argument
7308 /// lists, and calls SetupConstraintScope to set up the
7309 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
7310 std::optional<MultiLevelTemplateArgumentList>
7311 SetupConstraintCheckingTemplateArgumentsAndScope(
7312 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
7313 LocalInstantiationScope &Scope);
7314
7315private:
7316 // The current stack of constraint satisfactions, so we can exit-early.
7317 using SatisfactionStackEntryTy =
7318 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
7319 llvm::SmallVector<SatisfactionStackEntryTy, 10>
7320 SatisfactionStack;
7321
7322public:
7323 void PushSatisfactionStackEntry(const NamedDecl *D,
7324 const llvm::FoldingSetNodeID &ID) {
7325 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
7326 SatisfactionStack.emplace_back(Can, ID);
7327 }
7328
7329 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
7330
7331 bool SatisfactionStackContains(const NamedDecl *D,
7332 const llvm::FoldingSetNodeID &ID) const {
7333 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
7334 return llvm::find(SatisfactionStack,
7335 SatisfactionStackEntryTy{Can, ID}) !=
7336 SatisfactionStack.end();
7337 }
7338
7339 // Resets the current SatisfactionStack for cases where we are instantiating
7340 // constraints as a 'side effect' of normal instantiation in a way that is not
7341 // indicative of recursive definition.
7342 class SatisfactionStackResetRAII {
7343 llvm::SmallVector<SatisfactionStackEntryTy, 10>
7344 BackupSatisfactionStack;
7345 Sema &SemaRef;
7346
7347 public:
7348 SatisfactionStackResetRAII(Sema &S) : SemaRef(S) {
7349 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
7350 }
7351
7352 ~SatisfactionStackResetRAII() {
7353 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
7354 }
7355 };
7356
7357 void SwapSatisfactionStack(
7358 llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) {
7359 SatisfactionStack.swap(NewSS);
7360 }
7361
7362 const NormalizedConstraint *
7363 getNormalizedAssociatedConstraints(
7364 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
7365
7366 /// \brief Check whether the given declaration's associated constraints are
7367 /// at least as constrained than another declaration's according to the
7368 /// partial ordering of constraints.
7369 ///
7370 /// \param Result If no error occurred, receives the result of true if D1 is
7371 /// at least constrained than D2, and false otherwise.
7372 ///
7373 /// \returns true if an error occurred, false otherwise.
7374 bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef<const Expr *> AC1,
7375 NamedDecl *D2, MutableArrayRef<const Expr *> AC2,
7376 bool &Result);
7377
7378 /// If D1 was not at least as constrained as D2, but would've been if a pair
7379 /// of atomic constraints involved had been declared in a concept and not
7380 /// repeated in two separate places in code.
7381 /// \returns true if such a diagnostic was emitted, false otherwise.
7382 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
7383 ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
7384
7385 /// \brief Check whether the given list of constraint expressions are
7386 /// satisfied (as if in a 'conjunction') given template arguments.
7387 /// \param Template the template-like entity that triggered the constraints
7388 /// check (either a concept or a constrained entity).
7389 /// \param ConstraintExprs a list of constraint expressions, treated as if
7390 /// they were 'AND'ed together.
7391 /// \param TemplateArgLists the list of template arguments to substitute into
7392 /// the constraint expression.
7393 /// \param TemplateIDRange The source range of the template id that
7394 /// caused the constraints check.
7395 /// \param Satisfaction if true is returned, will contain details of the
7396 /// satisfaction, with enough information to diagnose an unsatisfied
7397 /// expression.
7398 /// \returns true if an error occurred and satisfaction could not be checked,
7399 /// false otherwise.
7400 bool CheckConstraintSatisfaction(
7401 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
7402 const MultiLevelTemplateArgumentList &TemplateArgLists,
7403 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction) {
7404 llvm::SmallVector<Expr *, 4> Converted;
7405 return CheckConstraintSatisfaction(Template, ConstraintExprs, Converted,
7406 TemplateArgLists, TemplateIDRange,
7407 Satisfaction);
7408 }
7409
7410 /// \brief Check whether the given list of constraint expressions are
7411 /// satisfied (as if in a 'conjunction') given template arguments.
7412 /// Additionally, takes an empty list of Expressions which is populated with
7413 /// the instantiated versions of the ConstraintExprs.
7414 /// \param Template the template-like entity that triggered the constraints
7415 /// check (either a concept or a constrained entity).
7416 /// \param ConstraintExprs a list of constraint expressions, treated as if
7417 /// they were 'AND'ed together.
7418 /// \param ConvertedConstraints a out parameter that will get populated with
7419 /// the instantiated version of the ConstraintExprs if we successfully checked
7420 /// satisfaction.
7421 /// \param TemplateArgList the multi-level list of template arguments to
7422 /// substitute into the constraint expression. This should be relative to the
7423 /// top-level (hence multi-level), since we need to instantiate fully at the
7424 /// time of checking.
7425 /// \param TemplateIDRange The source range of the template id that
7426 /// caused the constraints check.
7427 /// \param Satisfaction if true is returned, will contain details of the
7428 /// satisfaction, with enough information to diagnose an unsatisfied
7429 /// expression.
7430 /// \returns true if an error occurred and satisfaction could not be checked,
7431 /// false otherwise.
7432 bool CheckConstraintSatisfaction(
7433 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
7434 llvm::SmallVectorImpl<Expr *> &ConvertedConstraints,
7435 const MultiLevelTemplateArgumentList &TemplateArgList,
7436 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
7437
7438 /// \brief Check whether the given non-dependent constraint expression is
7439 /// satisfied. Returns false and updates Satisfaction with the satisfaction
7440 /// verdict if successful, emits a diagnostic and returns true if an error
7441 /// occurred and satisfaction could not be determined.
7442 ///
7443 /// \returns true if an error occurred, false otherwise.
7444 bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
7445 ConstraintSatisfaction &Satisfaction);
7446
7447 /// Check whether the given function decl's trailing requires clause is
7448 /// satisfied, if any. Returns false and updates Satisfaction with the
7449 /// satisfaction verdict if successful, emits a diagnostic and returns true if
7450 /// an error occurred and satisfaction could not be determined.
7451 ///
7452 /// \returns true if an error occurred, false otherwise.
7453 bool CheckFunctionConstraints(const FunctionDecl *FD,
7454 ConstraintSatisfaction &Satisfaction,
7455 SourceLocation UsageLoc = SourceLocation(),
7456 bool ForOverloadResolution = false);
7457
7458 /// \brief Ensure that the given template arguments satisfy the constraints
7459 /// associated with the given template, emitting a diagnostic if they do not.
7460 ///
7461 /// \param Template The template to which the template arguments are being
7462 /// provided.
7463 ///
7464 /// \param TemplateArgs The converted, canonicalized template arguments.
7465 ///
7466 /// \param TemplateIDRange The source range of the template id that
7467 /// caused the constraints check.
7468 ///
7469 /// \returns true if the constrains are not satisfied or could not be checked
7470 /// for satisfaction, false if the constraints are satisfied.
7471 bool EnsureTemplateArgumentListConstraints(
7472 TemplateDecl *Template,
7473 const MultiLevelTemplateArgumentList &TemplateArgs,
7474 SourceRange TemplateIDRange);
7475
7476 /// \brief Emit diagnostics explaining why a constraint expression was deemed
7477 /// unsatisfied.
7478 /// \param First whether this is the first time an unsatisfied constraint is
7479 /// diagnosed for this error.
7480 void
7481 DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
7482 bool First = true);
7483
7484 /// \brief Emit diagnostics explaining why a constraint expression was deemed
7485 /// unsatisfied.
7486 void
7487 DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
7488 bool First = true);
7489
7490 // ParseObjCStringLiteral - Parse Objective-C string literals.
7491 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
7492 ArrayRef<Expr *> Strings);
7493
7494 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
7495
7496 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
7497 /// numeric literal expression. Type of the expression will be "NSNumber *"
7498 /// or "id" if NSNumber is unavailable.
7499 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
7500 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
7501 bool Value);
7502 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
7503
7504 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
7505 /// '@' prefixed parenthesized expression. The type of the expression will
7506 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
7507 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
7508 /// "const char *" or C structure with attribute 'objc_boxable'.
7509 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
7510
7511 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
7512 Expr *IndexExpr,
7513 ObjCMethodDecl *getterMethod,
7514 ObjCMethodDecl *setterMethod);
7515
7516 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
7517 MutableArrayRef<ObjCDictionaryElement> Elements);
7518
7519 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
7520 TypeSourceInfo *EncodedTypeInfo,
7521 SourceLocation RParenLoc);
7522 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
7523 CXXConversionDecl *Method,
7524 bool HadMultipleCandidates);
7525
7526 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
7527 SourceLocation EncodeLoc,
7528 SourceLocation LParenLoc,
7529 ParsedType Ty,
7530 SourceLocation RParenLoc);
7531
7532 /// ParseObjCSelectorExpression - Build selector expression for \@selector
7533 ExprResult ParseObjCSelectorExpression(Selector Sel,
7534 SourceLocation AtLoc,
7535 SourceLocation SelLoc,
7536 SourceLocation LParenLoc,
7537 SourceLocation RParenLoc,
7538 bool WarnMultipleSelectors);
7539
7540 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
7541 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
7542 SourceLocation AtLoc,
7543 SourceLocation ProtoLoc,
7544 SourceLocation LParenLoc,
7545 SourceLocation ProtoIdLoc,
7546 SourceLocation RParenLoc);
7547
7548 //===--------------------------------------------------------------------===//
7549 // C++ Declarations
7550 //
7551 Decl *ActOnStartLinkageSpecification(Scope *S,
7552 SourceLocation ExternLoc,
7553 Expr *LangStr,
7554 SourceLocation LBraceLoc);
7555 Decl *ActOnFinishLinkageSpecification(Scope *S,
7556 Decl *LinkageSpec,
7557 SourceLocation RBraceLoc);
7558
7559
7560 //===--------------------------------------------------------------------===//
7561 // C++ Classes
7562 //
7563 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
7564 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
7565 const CXXScopeSpec *SS = nullptr);
7566 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
7567
7568 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
7569 SourceLocation ColonLoc,
7570 const ParsedAttributesView &Attrs);
7571
7572 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
7573 Declarator &D,
7574 MultiTemplateParamsArg TemplateParameterLists,
7575 Expr *BitfieldWidth, const VirtSpecifiers &VS,
7576 InClassInitStyle InitStyle);
7577
7578 void ActOnStartCXXInClassMemberInitializer();
7579 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
7580 SourceLocation EqualLoc,
7581 Expr *Init);
7582
7583 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7584 Scope *S,
7585 CXXScopeSpec &SS,
7586 IdentifierInfo *MemberOrBase,
7587 ParsedType TemplateTypeTy,
7588 const DeclSpec &DS,
7589 SourceLocation IdLoc,
7590 SourceLocation LParenLoc,
7591 ArrayRef<Expr *> Args,
7592 SourceLocation RParenLoc,
7593 SourceLocation EllipsisLoc);
7594
7595 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7596 Scope *S,
7597 CXXScopeSpec &SS,
7598 IdentifierInfo *MemberOrBase,
7599 ParsedType TemplateTypeTy,
7600 const DeclSpec &DS,
7601 SourceLocation IdLoc,
7602 Expr *InitList,
7603 SourceLocation EllipsisLoc);
7604
7605 MemInitResult BuildMemInitializer(Decl *ConstructorD,
7606 Scope *S,
7607 CXXScopeSpec &SS,
7608 IdentifierInfo *MemberOrBase,
7609 ParsedType TemplateTypeTy,
7610 const DeclSpec &DS,
7611 SourceLocation IdLoc,
7612 Expr *Init,
7613 SourceLocation EllipsisLoc);
7614
7615 MemInitResult BuildMemberInitializer(ValueDecl *Member,
7616 Expr *Init,
7617 SourceLocation IdLoc);
7618
7619 MemInitResult BuildBaseInitializer(QualType BaseType,
7620 TypeSourceInfo *BaseTInfo,
7621 Expr *Init,
7622 CXXRecordDecl *ClassDecl,
7623 SourceLocation EllipsisLoc);
7624
7625 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
7626 Expr *Init,
7627 CXXRecordDecl *ClassDecl);
7628
7629 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
7630 CXXCtorInitializer *Initializer);
7631
7632 bool SetCtorInitializers(
7633 CXXConstructorDecl *Constructor, bool AnyErrors,
7634 ArrayRef<CXXCtorInitializer *> Initializers = std::nullopt);
7635
7636 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
7637
7638
7639 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
7640 /// mark all the non-trivial destructors of its members and bases as
7641 /// referenced.
7642 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
7643 CXXRecordDecl *Record);
7644
7645 /// Mark destructors of virtual bases of this class referenced. In the Itanium
7646 /// C++ ABI, this is done when emitting a destructor for any non-abstract
7647 /// class. In the Microsoft C++ ABI, this is done any time a class's
7648 /// destructor is referenced.
7649 void MarkVirtualBaseDestructorsReferenced(
7650 SourceLocation Location, CXXRecordDecl *ClassDecl,
7651 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr);
7652
7653 /// Do semantic checks to allow the complete destructor variant to be emitted
7654 /// when the destructor is defined in another translation unit. In the Itanium
7655 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
7656 /// can be emitted in separate TUs. To emit the complete variant, run a subset
7657 /// of the checks performed when emitting a regular destructor.
7658 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
7659 CXXDestructorDecl *Dtor);
7660
7661 /// The list of classes whose vtables have been used within
7662 /// this translation unit, and the source locations at which the
7663 /// first use occurred.
7664 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
7665
7666 /// The list of vtables that are required but have not yet been
7667 /// materialized.
7668 SmallVector<VTableUse, 16> VTableUses;
7669
7670 /// The set of classes whose vtables have been used within
7671 /// this translation unit, and a bit that will be true if the vtable is
7672 /// required to be emitted (otherwise, it should be emitted only if needed
7673 /// by code generation).
7674 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
7675
7676 /// Load any externally-stored vtable uses.
7677 void LoadExternalVTableUses();
7678
7679 /// Note that the vtable for the given class was used at the
7680 /// given location.
7681 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7682 bool DefinitionRequired = false);
7683
7684 /// Mark the exception specifications of all virtual member functions
7685 /// in the given class as needed.
7686 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
7687 const CXXRecordDecl *RD);
7688
7689 /// MarkVirtualMembersReferenced - Will mark all members of the given
7690 /// CXXRecordDecl referenced.
7691 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
7692 bool ConstexprOnly = false);
7693
7694 /// Define all of the vtables that have been used in this
7695 /// translation unit and reference any virtual members used by those
7696 /// vtables.
7697 ///
7698 /// \returns true if any work was done, false otherwise.
7699 bool DefineUsedVTables();
7700
7701 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
7702
7703 void ActOnMemInitializers(Decl *ConstructorDecl,
7704 SourceLocation ColonLoc,
7705 ArrayRef<CXXCtorInitializer*> MemInits,
7706 bool AnyErrors);
7707
7708 /// Check class-level dllimport/dllexport attribute. The caller must
7709 /// ensure that referenceDLLExportedClassMethods is called some point later
7710 /// when all outer classes of Class are complete.
7711 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
7712 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
7713
7714 void referenceDLLExportedClassMethods();
7715
7716 void propagateDLLAttrToBaseClassTemplate(
7717 CXXRecordDecl *Class, Attr *ClassAttr,
7718 ClassTemplateSpecializationDecl *BaseTemplateSpec,
7719 SourceLocation BaseLoc);
7720
7721 /// Add gsl::Pointer attribute to std::container::iterator
7722 /// \param ND The declaration that introduces the name
7723 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
7724 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
7725
7726 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
7727 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
7728
7729 /// Add [[gsl::Pointer]] attributes for std:: types.
7730 void inferGslPointerAttribute(TypedefNameDecl *TD);
7731
7732 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
7733
7734 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
7735 /// conditions that are needed for the attribute to have an effect.
7736 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
7737
7738 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
7739 Decl *TagDecl, SourceLocation LBrac,
7740 SourceLocation RBrac,
7741 const ParsedAttributesView &AttrList);
7742 void ActOnFinishCXXMemberDecls();
7743 void ActOnFinishCXXNonNestedClass();
7744
7745 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
7746 unsigned ActOnReenterTemplateScope(Decl *Template,
7747 llvm::function_ref<Scope *()> EnterScope);
7748 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
7749 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7750 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
7751 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
7752 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7753 void ActOnFinishDelayedMemberInitializers(Decl *Record);
7754 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
7755 CachedTokens &Toks);
7756 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
7757 bool IsInsideALocalClassWithinATemplateFunction();
7758
7759 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7760 Expr *AssertExpr,
7761 Expr *AssertMessageExpr,
7762 SourceLocation RParenLoc);
7763 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7764 Expr *AssertExpr,
7765 StringLiteral *AssertMessageExpr,
7766 SourceLocation RParenLoc,
7767 bool Failed);
7768 void DiagnoseStaticAssertDetails(const Expr *E);
7769
7770 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
7771 SourceLocation FriendLoc,
7772 TypeSourceInfo *TSInfo);
7773 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
7774 MultiTemplateParamsArg TemplateParams);
7775 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
7776 MultiTemplateParamsArg TemplateParams);
7777
7778 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
7779 StorageClass& SC);
7780 void CheckConstructor(CXXConstructorDecl *Constructor);
7781 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
7782 StorageClass& SC);
7783 bool CheckDestructor(CXXDestructorDecl *Destructor);
7784 void CheckConversionDeclarator(Declarator &D, QualType &R,
7785 StorageClass& SC);
7786 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
7787 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
7788 StorageClass &SC);
7789 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
7790
7791 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
7792
7793 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7794 CXXSpecialMember CSM,
7795 SourceLocation DefaultLoc);
7796 void CheckDelayedMemberExceptionSpecs();
7797
7798 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
7799 DefaultedComparisonKind DCK);
7800 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
7801 FunctionDecl *Spaceship);
7802 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
7803 DefaultedComparisonKind DCK);
7804
7805 //===--------------------------------------------------------------------===//
7806 // C++ Derived Classes
7807 //
7808
7809 /// ActOnBaseSpecifier - Parsed a base specifier
7810 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
7811 SourceRange SpecifierRange,
7812 bool Virtual, AccessSpecifier Access,
7813 TypeSourceInfo *TInfo,
7814 SourceLocation EllipsisLoc);
7815
7816 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
7817 const ParsedAttributesView &Attrs, bool Virtual,
7818 AccessSpecifier Access, ParsedType basetype,
7819 SourceLocation BaseLoc,
7820 SourceLocation EllipsisLoc);
7821
7822 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
7823 MutableArrayRef<CXXBaseSpecifier *> Bases);
7824 void ActOnBaseSpecifiers(Decl *ClassDecl,
7825 MutableArrayRef<CXXBaseSpecifier *> Bases);
7826
7827 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
7828 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
7829 CXXBasePaths &Paths);
7830
7831 // FIXME: I don't like this name.
7832 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
7833
7834 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7835 SourceLocation Loc, SourceRange Range,
7836 CXXCastPath *BasePath = nullptr,
7837 bool IgnoreAccess = false);
7838 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7839 unsigned InaccessibleBaseID,
7840 unsigned AmbiguousBaseConvID,
7841 SourceLocation Loc, SourceRange Range,
7842 DeclarationName Name,
7843 CXXCastPath *BasePath,
7844 bool IgnoreAccess = false);
7845
7846 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
7847
7848 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
7849 const CXXMethodDecl *Old);
7850
7851 /// CheckOverridingFunctionReturnType - Checks whether the return types are
7852 /// covariant, according to C++ [class.virtual]p5.
7853 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
7854 const CXXMethodDecl *Old);
7855
7856 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
7857 /// spec is a subset of base spec.
7858 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
7859 const CXXMethodDecl *Old);
7860
7861 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
7862
7863 /// CheckOverrideControl - Check C++11 override control semantics.
7864 void CheckOverrideControl(NamedDecl *D);
7865
7866 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
7867 /// not used in the declaration of an overriding method.
7868 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
7869
7870 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
7871 /// overrides a virtual member function marked 'final', according to
7872 /// C++11 [class.virtual]p4.
7873 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
7874 const CXXMethodDecl *Old);
7875
7876
7877 //===--------------------------------------------------------------------===//
7878 // C++ Access Control
7879 //
7880
7881 enum AccessResult {
7882 AR_accessible,
7883 AR_inaccessible,
7884 AR_dependent,
7885 AR_delayed
7886 };
7887
7888 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
7889 NamedDecl *PrevMemberDecl,
7890 AccessSpecifier LexicalAS);
7891
7892 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
7893 DeclAccessPair FoundDecl);
7894 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
7895 DeclAccessPair FoundDecl);
7896 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
7897 SourceRange PlacementRange,
7898 CXXRecordDecl *NamingClass,
7899 DeclAccessPair FoundDecl,
7900 bool Diagnose = true);
7901 AccessResult CheckConstructorAccess(SourceLocation Loc,
7902 CXXConstructorDecl *D,
7903 DeclAccessPair FoundDecl,
7904 const InitializedEntity &Entity,
7905 bool IsCopyBindingRefToTemp = false);
7906 AccessResult CheckConstructorAccess(SourceLocation Loc,
7907 CXXConstructorDecl *D,
7908 DeclAccessPair FoundDecl,
7909 const InitializedEntity &Entity,
7910 const PartialDiagnostic &PDiag);
7911 AccessResult CheckDestructorAccess(SourceLocation Loc,
7912 CXXDestructorDecl *Dtor,
7913 const PartialDiagnostic &PDiag,
7914 QualType objectType = QualType());
7915 AccessResult CheckFriendAccess(NamedDecl *D);
7916 AccessResult CheckMemberAccess(SourceLocation UseLoc,
7917 CXXRecordDecl *NamingClass,
7918 DeclAccessPair Found);
7919 AccessResult
7920 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
7921 CXXRecordDecl *DecomposedClass,
7922 DeclAccessPair Field);
7923 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
7924 const SourceRange &,
7925 DeclAccessPair FoundDecl);
7926 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
7927 Expr *ObjectExpr,
7928 Expr *ArgExpr,
7929 DeclAccessPair FoundDecl);
7930 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
7931 ArrayRef<Expr *> ArgExprs,
7932 DeclAccessPair FoundDecl);
7933 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
7934 DeclAccessPair FoundDecl);
7935 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
7936 QualType Base, QualType Derived,
7937 const CXXBasePath &Path,
7938 unsigned DiagID,
7939 bool ForceCheck = false,
7940 bool ForceUnprivileged = false);
7941 void CheckLookupAccess(const LookupResult &R);
7942 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
7943 QualType BaseType);
7944 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7945 DeclAccessPair Found, QualType ObjectType,
7946 SourceLocation Loc,
7947 const PartialDiagnostic &Diag);
7948 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7949 DeclAccessPair Found,
7950 QualType ObjectType) {
7951 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
7952 SourceLocation(), PDiag());
7953 }
7954
7955 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
7956 const MultiLevelTemplateArgumentList &TemplateArgs);
7957 void PerformDependentDiagnostics(const DeclContext *Pattern,
7958 const MultiLevelTemplateArgumentList &TemplateArgs);
7959
7960 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
7961
7962 /// When true, access checking violations are treated as SFINAE
7963 /// failures rather than hard errors.
7964 bool AccessCheckingSFINAE;
7965
7966 enum AbstractDiagSelID {
7967 AbstractNone = -1,
7968 AbstractReturnType,
7969 AbstractParamType,
7970 AbstractVariableType,
7971 AbstractFieldType,
7972 AbstractIvarType,
7973 AbstractSynthesizedIvarType,
7974 AbstractArrayType
7975 };
7976
7977 bool isAbstractType(SourceLocation Loc, QualType T);
7978 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
7979 TypeDiagnoser &Diagnoser);
7980 template <typename... Ts>
7981 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
7982 const Ts &...Args) {
7983 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
7984 return RequireNonAbstractType(Loc, T, Diagnoser);
7985 }
7986
7987 void DiagnoseAbstractType(const CXXRecordDecl *RD);
7988
7989 //===--------------------------------------------------------------------===//
7990 // C++ Overloaded Operators [C++ 13.5]
7991 //
7992
7993 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
7994
7995 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
7996
7997 //===--------------------------------------------------------------------===//
7998 // C++ Templates [C++ 14]
7999 //
8000 void FilterAcceptableTemplateNames(LookupResult &R,
8001 bool AllowFunctionTemplates = true,
8002 bool AllowDependent = true);
8003 bool hasAnyAcceptableTemplateNames(LookupResult &R,
8004 bool AllowFunctionTemplates = true,
8005 bool AllowDependent = true,
8006 bool AllowNonTemplateFunctions = false);
8007 /// Try to interpret the lookup result D as a template-name.
8008 ///
8009 /// \param D A declaration found by name lookup.
8010 /// \param AllowFunctionTemplates Whether function templates should be
8011 /// considered valid results.
8012 /// \param AllowDependent Whether unresolved using declarations (that might
8013 /// name templates) should be considered valid results.
8014 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
8015 bool AllowFunctionTemplates = true,
8016 bool AllowDependent = true);
8017
8018 enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
8019 /// Whether and why a template name is required in this lookup.
8020 class RequiredTemplateKind {
8021 public:
8022 /// Template name is required if TemplateKWLoc is valid.
8023 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
8024 : TemplateKW(TemplateKWLoc) {}
8025 /// Template name is unconditionally required.
8026 RequiredTemplateKind(TemplateNameIsRequiredTag) {}
8027
8028 SourceLocation getTemplateKeywordLoc() const {
8029 return TemplateKW.value_or(SourceLocation());
8030 }
8031 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
8032 bool isRequired() const { return TemplateKW != SourceLocation(); }
8033 explicit operator bool() const { return isRequired(); }
8034
8035 private:
8036 std::optional<SourceLocation> TemplateKW;
8037 };
8038
8039 enum class AssumedTemplateKind {
8040 /// This is not assumed to be a template name.
8041 None,
8042 /// This is assumed to be a template name because lookup found nothing.
8043 FoundNothing,
8044 /// This is assumed to be a template name because lookup found one or more
8045 /// functions (but no function templates).
8046 FoundFunctions,
8047 };
8048 bool LookupTemplateName(
8049 LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType,
8050 bool EnteringContext, bool &MemberOfUnknownSpecialization,
8051 RequiredTemplateKind RequiredTemplate = SourceLocation(),
8052 AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true);
8053
8054 TemplateNameKind isTemplateName(Scope *S,
8055 CXXScopeSpec &SS,
8056 bool hasTemplateKeyword,
8057 const UnqualifiedId &Name,
8058 ParsedType ObjectType,
8059 bool EnteringContext,
8060 TemplateTy &Template,
8061 bool &MemberOfUnknownSpecialization,
8062 bool Disambiguation = false);
8063
8064 /// Try to resolve an undeclared template name as a type template.
8065 ///
8066 /// Sets II to the identifier corresponding to the template name, and updates
8067 /// Name to a corresponding (typo-corrected) type template name and TNK to
8068 /// the corresponding kind, if possible.
8069 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
8070 TemplateNameKind &TNK,
8071 SourceLocation NameLoc,
8072 IdentifierInfo *&II);
8073
8074 bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
8075 SourceLocation NameLoc,
8076 bool Diagnose = true);
8077
8078 /// Determine whether a particular identifier might be the name in a C++1z
8079 /// deduction-guide declaration.
8080 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
8081 SourceLocation NameLoc, CXXScopeSpec &SS,
8082 ParsedTemplateTy *Template = nullptr);
8083
8084 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
8085 SourceLocation IILoc,
8086 Scope *S,
8087 const CXXScopeSpec *SS,
8088 TemplateTy &SuggestedTemplate,
8089 TemplateNameKind &SuggestedKind);
8090
8091 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
8092 NamedDecl *Instantiation,
8093 bool InstantiatedFromMember,
8094 const NamedDecl *Pattern,
8095 const NamedDecl *PatternDef,
8096 TemplateSpecializationKind TSK,
8097 bool Complain = true);
8098
8099 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
8100 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
8101
8102 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
8103 SourceLocation EllipsisLoc,
8104 SourceLocation KeyLoc,
8105 IdentifierInfo *ParamName,
8106 SourceLocation ParamNameLoc,
8107 unsigned Depth, unsigned Position,
8108 SourceLocation EqualLoc,
8109 ParsedType DefaultArg, bool HasTypeConstraint);
8110
8111 bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint);
8112
8113 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
8114 TemplateIdAnnotation *TypeConstraint,
8115 TemplateTypeParmDecl *ConstrainedParameter,
8116 SourceLocation EllipsisLoc);
8117 bool BuildTypeConstraint(const CXXScopeSpec &SS,
8118 TemplateIdAnnotation *TypeConstraint,
8119 TemplateTypeParmDecl *ConstrainedParameter,
8120 SourceLocation EllipsisLoc,
8121 bool AllowUnexpandedPack);
8122
8123 bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
8124 DeclarationNameInfo NameInfo,
8125 ConceptDecl *NamedConcept,
8126 const TemplateArgumentListInfo *TemplateArgs,
8127 TemplateTypeParmDecl *ConstrainedParameter,
8128 SourceLocation EllipsisLoc);
8129
8130 bool AttachTypeConstraint(AutoTypeLoc TL,
8131 NonTypeTemplateParmDecl *NewConstrainedParm,
8132 NonTypeTemplateParmDecl *OrigConstrainedParm,
8133 SourceLocation EllipsisLoc);
8134
8135 bool RequireStructuralType(QualType T, SourceLocation Loc);
8136
8137 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
8138 SourceLocation Loc);
8139 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
8140
8141 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
8142 unsigned Depth,
8143 unsigned Position,
8144 SourceLocation EqualLoc,
8145 Expr *DefaultArg);
8146 NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
8147 SourceLocation TmpLoc,
8148 TemplateParameterList *Params,
8149 SourceLocation EllipsisLoc,
8150 IdentifierInfo *ParamName,
8151 SourceLocation ParamNameLoc,
8152 unsigned Depth,
8153 unsigned Position,
8154 SourceLocation EqualLoc,
8155 ParsedTemplateArgument DefaultArg);
8156
8157 TemplateParameterList *
8158 ActOnTemplateParameterList(unsigned Depth,
8159 SourceLocation ExportLoc,
8160 SourceLocation TemplateLoc,
8161 SourceLocation LAngleLoc,
8162 ArrayRef<NamedDecl *> Params,
8163 SourceLocation RAngleLoc,
8164 Expr *RequiresClause);
8165
8166 /// The context in which we are checking a template parameter list.
8167 enum TemplateParamListContext {
8168 TPC_ClassTemplate,
8169 TPC_VarTemplate,
8170 TPC_FunctionTemplate,
8171 TPC_ClassTemplateMember,
8172 TPC_FriendClassTemplate,
8173 TPC_FriendFunctionTemplate,
8174 TPC_FriendFunctionTemplateDefinition,
8175 TPC_TypeAliasTemplate
8176 };
8177
8178 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
8179 TemplateParameterList *OldParams,
8180 TemplateParamListContext TPC,
8181 SkipBodyInfo *SkipBody = nullptr);
8182 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
8183 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
8184 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
8185 ArrayRef<TemplateParameterList *> ParamLists,
8186 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
8187 bool SuppressDiagnostic = false);
8188
8189 DeclResult CheckClassTemplate(
8190 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8191 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
8192 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
8193 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
8194 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
8195 TemplateParameterList **OuterTemplateParamLists,
8196 SkipBodyInfo *SkipBody = nullptr);
8197
8198 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
8199 QualType NTTPType,
8200 SourceLocation Loc);
8201
8202 /// Get a template argument mapping the given template parameter to itself,
8203 /// e.g. for X in \c template<int X>, this would return an expression template
8204 /// argument referencing X.
8205 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
8206 SourceLocation Location);
8207
8208 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
8209 TemplateArgumentListInfo &Out);
8210
8211 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
8212
8213 void NoteAllFoundTemplates(TemplateName Name);
8214
8215 QualType CheckTemplateIdType(TemplateName Template,
8216 SourceLocation TemplateLoc,
8217 TemplateArgumentListInfo &TemplateArgs);
8218
8219 TypeResult
8220 ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8221 TemplateTy Template, IdentifierInfo *TemplateII,
8222 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
8223 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
8224 bool IsCtorOrDtorName = false, bool IsClassName = false,
8225 ImplicitTypenameContext AllowImplicitTypename =
8226 ImplicitTypenameContext::No);
8227
8228 /// Parsed an elaborated-type-specifier that refers to a template-id,
8229 /// such as \c class T::template apply<U>.
8230 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
8231 TypeSpecifierType TagSpec,
8232 SourceLocation TagLoc,
8233 CXXScopeSpec &SS,
8234 SourceLocation TemplateKWLoc,
8235 TemplateTy TemplateD,
8236 SourceLocation TemplateLoc,
8237 SourceLocation LAngleLoc,
8238 ASTTemplateArgsPtr TemplateArgsIn,
8239 SourceLocation RAngleLoc);
8240
8241 DeclResult ActOnVarTemplateSpecialization(
8242 Scope *S, Declarator &D, TypeSourceInfo *DI,
8243 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
8244 StorageClass SC, bool IsPartialSpecialization);
8245
8246 /// Get the specialization of the given variable template corresponding to
8247 /// the specified argument list, or a null-but-valid result if the arguments
8248 /// are dependent.
8249 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
8250 SourceLocation TemplateLoc,
8251 SourceLocation TemplateNameLoc,
8252 const TemplateArgumentListInfo &TemplateArgs);
8253
8254 /// Form a reference to the specialization of the given variable template
8255 /// corresponding to the specified argument list, or a null-but-valid result
8256 /// if the arguments are dependent.
8257 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
8258 const DeclarationNameInfo &NameInfo,
8259 VarTemplateDecl *Template,
8260 SourceLocation TemplateLoc,
8261 const TemplateArgumentListInfo *TemplateArgs);
8262
8263 ExprResult
8264 CheckConceptTemplateId(const CXXScopeSpec &SS,
8265 SourceLocation TemplateKWLoc,
8266 const DeclarationNameInfo &ConceptNameInfo,
8267 NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
8268 const TemplateArgumentListInfo *TemplateArgs);
8269
8270 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
8271
8272 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
8273 SourceLocation TemplateKWLoc,
8274 LookupResult &R,
8275 bool RequiresADL,
8276 const TemplateArgumentListInfo *TemplateArgs);
8277
8278 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
8279 SourceLocation TemplateKWLoc,
8280 const DeclarationNameInfo &NameInfo,
8281 const TemplateArgumentListInfo *TemplateArgs);
8282
8283 TemplateNameKind ActOnTemplateName(
8284 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8285 const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
8286 TemplateTy &Template, bool AllowInjectedClassName = false);
8287
8288 DeclResult ActOnClassTemplateSpecialization(
8289 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8290 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8291 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8292 MultiTemplateParamsArg TemplateParameterLists,
8293 SkipBodyInfo *SkipBody = nullptr);
8294
8295 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
8296 TemplateDecl *PrimaryTemplate,
8297 unsigned NumExplicitArgs,
8298 ArrayRef<TemplateArgument> Args);
8299 void CheckTemplatePartialSpecialization(
8300 ClassTemplatePartialSpecializationDecl *Partial);
8301 void CheckTemplatePartialSpecialization(
8302 VarTemplatePartialSpecializationDecl *Partial);
8303
8304 Decl *ActOnTemplateDeclarator(Scope *S,
8305 MultiTemplateParamsArg TemplateParameterLists,
8306 Declarator &D);
8307
8308 bool
8309 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
8310 TemplateSpecializationKind NewTSK,
8311 NamedDecl *PrevDecl,
8312 TemplateSpecializationKind PrevTSK,
8313 SourceLocation PrevPtOfInstantiation,
8314 bool &SuppressNew);
8315
8316 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8317 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8318 LookupResult &Previous);
8319
8320 bool CheckFunctionTemplateSpecialization(
8321 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8322 LookupResult &Previous, bool QualifiedFriend = false);
8323 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
8324 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
8325
8326 DeclResult ActOnExplicitInstantiation(
8327 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8328 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8329 TemplateTy Template, SourceLocation TemplateNameLoc,
8330 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
8331 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
8332
8333 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
8334 SourceLocation TemplateLoc,
8335 unsigned TagSpec, SourceLocation KWLoc,
8336 CXXScopeSpec &SS, IdentifierInfo *Name,
8337 SourceLocation NameLoc,
8338 const ParsedAttributesView &Attr);
8339
8340 DeclResult ActOnExplicitInstantiation(Scope *S,
8341 SourceLocation ExternLoc,
8342 SourceLocation TemplateLoc,
8343 Declarator &D);
8344
8345 TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(
8346 TemplateDecl *Template, SourceLocation TemplateLoc,
8347 SourceLocation RAngleLoc, Decl *Param,
8348 ArrayRef<TemplateArgument> SugaredConverted,
8349 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
8350
8351 /// Specifies the context in which a particular template
8352 /// argument is being checked.
8353 enum CheckTemplateArgumentKind {
8354 /// The template argument was specified in the code or was
8355 /// instantiated with some deduced template arguments.
8356 CTAK_Specified,
8357
8358 /// The template argument was deduced via template argument
8359 /// deduction.
8360 CTAK_Deduced,
8361
8362 /// The template argument was deduced from an array bound
8363 /// via template argument deduction.
8364 CTAK_DeducedFromArrayBound
8365 };
8366
8367 bool
8368 CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
8369 NamedDecl *Template, SourceLocation TemplateLoc,
8370 SourceLocation RAngleLoc, unsigned ArgumentPackIndex,
8371 SmallVectorImpl<TemplateArgument> &SugaredConverted,
8372 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
8373 CheckTemplateArgumentKind CTAK);
8374
8375 /// Check that the given template arguments can be provided to
8376 /// the given template, converting the arguments along the way.
8377 ///
8378 /// \param Template The template to which the template arguments are being
8379 /// provided.
8380 ///
8381 /// \param TemplateLoc The location of the template name in the source.
8382 ///
8383 /// \param TemplateArgs The list of template arguments. If the template is
8384 /// a template template parameter, this function may extend the set of
8385 /// template arguments to also include substituted, defaulted template
8386 /// arguments.
8387 ///
8388 /// \param PartialTemplateArgs True if the list of template arguments is
8389 /// intentionally partial, e.g., because we're checking just the initial
8390 /// set of template arguments.
8391 ///
8392 /// \param Converted Will receive the converted, canonicalized template
8393 /// arguments.
8394 ///
8395 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
8396 /// contain the converted forms of the template arguments as written.
8397 /// Otherwise, \p TemplateArgs will not be modified.
8398 ///
8399 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
8400 /// receive true if the cause for the error is the associated constraints of
8401 /// the template not being satisfied by the template arguments.
8402 ///
8403 /// \returns true if an error occurred, false otherwise.
8404 bool CheckTemplateArgumentList(
8405 TemplateDecl *Template, SourceLocation TemplateLoc,
8406 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
8407 SmallVectorImpl<TemplateArgument> &SugaredConverted,
8408 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
8409 bool UpdateArgsWithConversions = true,
8410 bool *ConstraintsNotSatisfied = nullptr);
8411
8412 bool CheckTemplateTypeArgument(
8413 TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
8414 SmallVectorImpl<TemplateArgument> &SugaredConverted,
8415 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
8416
8417 bool CheckTemplateArgument(TypeSourceInfo *Arg);
8418 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
8419 QualType InstantiatedParamType, Expr *Arg,
8420 TemplateArgument &SugaredConverted,
8421 TemplateArgument &CanonicalConverted,
8422 CheckTemplateArgumentKind CTAK);
8423 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
8424 TemplateParameterList *Params,
8425 TemplateArgumentLoc &Arg);
8426
8427 ExprResult
8428 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
8429 QualType ParamType,
8430 SourceLocation Loc);
8431 ExprResult
8432 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
8433 SourceLocation Loc);
8434
8435 /// Enumeration describing how template parameter lists are compared
8436 /// for equality.
8437 enum TemplateParameterListEqualKind {
8438 /// We are matching the template parameter lists of two templates
8439 /// that might be redeclarations.
8440 ///
8441 /// \code
8442 /// template<typename T> struct X;
8443 /// template<typename T> struct X;
8444 /// \endcode
8445 TPL_TemplateMatch,
8446
8447 /// We are matching the template parameter lists of two template
8448 /// template parameters as part of matching the template parameter lists
8449 /// of two templates that might be redeclarations.
8450 ///
8451 /// \code
8452 /// template<template<int I> class TT> struct X;
8453 /// template<template<int Value> class Other> struct X;
8454 /// \endcode
8455 TPL_TemplateTemplateParmMatch,
8456
8457 /// We are matching the template parameter lists of a template
8458 /// template argument against the template parameter lists of a template
8459 /// template parameter.
8460 ///
8461 /// \code
8462 /// template<template<int Value> class Metafun> struct X;
8463 /// template<int Value> struct integer_c;
8464 /// X<integer_c> xic;
8465 /// \endcode
8466 TPL_TemplateTemplateArgumentMatch,
8467
8468 /// We are determining whether the template-parameters are equivalent
8469 /// according to C++ [temp.over.link]/6. This comparison does not consider
8470 /// constraints.
8471 ///
8472 /// \code
8473 /// template<C1 T> void f(T);
8474 /// template<C2 T> void f(T);
8475 /// \endcode
8476 TPL_TemplateParamsEquivalent,
8477 };
8478
8479 bool TemplateParameterListsAreEqual(
8480 const NamedDecl *NewInstFrom, TemplateParameterList *New,
8481 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8482 TemplateParameterListEqualKind Kind,
8483 SourceLocation TemplateArgLoc = SourceLocation());
8484
8485 bool TemplateParameterListsAreEqual(
8486 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
8487 TemplateParameterListEqualKind Kind,
8488 SourceLocation TemplateArgLoc = SourceLocation()) {
8489 return TemplateParameterListsAreEqual(nullptr, New, nullptr, Old, Complain,
8490 Kind, TemplateArgLoc);
8491 }
8492
8493 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
8494
8495 /// Called when the parser has parsed a C++ typename
8496 /// specifier, e.g., "typename T::type".
8497 ///
8498 /// \param S The scope in which this typename type occurs.
8499 /// \param TypenameLoc the location of the 'typename' keyword
8500 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
8501 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
8502 /// \param IdLoc the location of the identifier.
8503 /// \param IsImplicitTypename context where T::type refers to a type.
8504 TypeResult ActOnTypenameType(
8505 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
8506 const IdentifierInfo &II, SourceLocation IdLoc,
8507 ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No);
8508
8509 /// Called when the parser has parsed a C++ typename
8510 /// specifier that ends in a template-id, e.g.,
8511 /// "typename MetaFun::template apply<T1, T2>".
8512 ///
8513 /// \param S The scope in which this typename type occurs.
8514 /// \param TypenameLoc the location of the 'typename' keyword
8515 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
8516 /// \param TemplateLoc the location of the 'template' keyword, if any.
8517 /// \param TemplateName The template name.
8518 /// \param TemplateII The identifier used to name the template.
8519 /// \param TemplateIILoc The location of the template name.
8520 /// \param LAngleLoc The location of the opening angle bracket ('<').
8521 /// \param TemplateArgs The template arguments.
8522 /// \param RAngleLoc The location of the closing angle bracket ('>').
8523 TypeResult
8524 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8525 const CXXScopeSpec &SS,
8526 SourceLocation TemplateLoc,
8527 TemplateTy TemplateName,
8528 IdentifierInfo *TemplateII,
8529 SourceLocation TemplateIILoc,
8530 SourceLocation LAngleLoc,
8531 ASTTemplateArgsPtr TemplateArgs,
8532 SourceLocation RAngleLoc);
8533
8534 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
8535 SourceLocation KeywordLoc,
8536 NestedNameSpecifierLoc QualifierLoc,
8537 const IdentifierInfo &II,
8538 SourceLocation IILoc,
8539 TypeSourceInfo **TSI,
8540 bool DeducedTSTContext);
8541
8542 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
8543 SourceLocation KeywordLoc,
8544 NestedNameSpecifierLoc QualifierLoc,
8545 const IdentifierInfo &II,
8546 SourceLocation IILoc,
8547 bool DeducedTSTContext = true);
8548
8549
8550 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8551 SourceLocation Loc,
8552 DeclarationName Name);
8553 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
8554
8555 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
8556 bool RebuildTemplateParamsInCurrentInstantiation(
8557 TemplateParameterList *Params);
8558
8559 std::string
8560 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8561 const TemplateArgumentList &Args);
8562
8563 std::string
8564 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8565 const TemplateArgument *Args,
8566 unsigned NumArgs);
8567
8568 //===--------------------------------------------------------------------===//
8569 // C++ Concepts
8570 //===--------------------------------------------------------------------===//
8571 Decl *ActOnConceptDefinition(
8572 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8573 IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
8574
8575 void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous,
8576 bool &AddToScope);
8577
8578 RequiresExprBodyDecl *
8579 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8580 ArrayRef<ParmVarDecl *> LocalParameters,
8581 Scope *BodyScope);
8582 void ActOnFinishRequiresExpr();
8583 concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8584 concepts::Requirement *ActOnTypeRequirement(
8585 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
8586 IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
8587 concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8588 SourceLocation NoexceptLoc);
8589 concepts::Requirement *
8590 ActOnCompoundRequirement(
8591 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8592 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8593 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8594 concepts::ExprRequirement *
8595 BuildExprRequirement(
8596 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8597 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8598 concepts::ExprRequirement *
8599 BuildExprRequirement(
8600 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8601 bool IsSatisfied, SourceLocation NoexceptLoc,
8602 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8603 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8604 concepts::TypeRequirement *
8605 BuildTypeRequirement(
8606 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8607 concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8608 concepts::NestedRequirement *
8609 BuildNestedRequirement(StringRef InvalidConstraintEntity,
8610 const ASTConstraintSatisfaction &Satisfaction);
8611 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8612 RequiresExprBodyDecl *Body,
8613 ArrayRef<ParmVarDecl *> LocalParameters,
8614 ArrayRef<concepts::Requirement *> Requirements,
8615 SourceLocation ClosingBraceLoc);
8616
8617 //===--------------------------------------------------------------------===//
8618 // C++ Variadic Templates (C++0x [temp.variadic])
8619 //===--------------------------------------------------------------------===//
8620
8621 /// Determine whether an unexpanded parameter pack might be permitted in this
8622 /// location. Useful for error recovery.
8623 bool isUnexpandedParameterPackPermitted();
8624
8625 /// The context in which an unexpanded parameter pack is
8626 /// being diagnosed.
8627 ///
8628 /// Note that the values of this enumeration line up with the first
8629 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
8630 enum UnexpandedParameterPackContext {
8631 /// An arbitrary expression.
8632 UPPC_Expression = 0,
8633
8634 /// The base type of a class type.
8635 UPPC_BaseType,
8636
8637 /// The type of an arbitrary declaration.
8638 UPPC_DeclarationType,
8639
8640 /// The type of a data member.
8641 UPPC_DataMemberType,
8642
8643 /// The size of a bit-field.
8644 UPPC_BitFieldWidth,
8645
8646 /// The expression in a static assertion.
8647 UPPC_StaticAssertExpression,
8648
8649 /// The fixed underlying type of an enumeration.
8650 UPPC_FixedUnderlyingType,
8651
8652 /// The enumerator value.
8653 UPPC_EnumeratorValue,
8654
8655 /// A using declaration.
8656 UPPC_UsingDeclaration,
8657
8658 /// A friend declaration.
8659 UPPC_FriendDeclaration,
8660
8661 /// A declaration qualifier.
8662 UPPC_DeclarationQualifier,
8663
8664 /// An initializer.
8665 UPPC_Initializer,
8666
8667 /// A default argument.
8668 UPPC_DefaultArgument,
8669
8670 /// The type of a non-type template parameter.
8671 UPPC_NonTypeTemplateParameterType,
8672
8673 /// The type of an exception.
8674 UPPC_ExceptionType,
8675
8676 /// Partial specialization.
8677 UPPC_PartialSpecialization,
8678
8679 /// Microsoft __if_exists.
8680 UPPC_IfExists,
8681
8682 /// Microsoft __if_not_exists.
8683 UPPC_IfNotExists,
8684
8685 /// Lambda expression.
8686 UPPC_Lambda,
8687
8688 /// Block expression.
8689 UPPC_Block,
8690
8691 /// A type constraint.
8692 UPPC_TypeConstraint,
8693
8694 // A requirement in a requires-expression.
8695 UPPC_Requirement,
8696
8697 // A requires-clause.
8698 UPPC_RequiresClause,
8699 };
8700
8701 /// Diagnose unexpanded parameter packs.
8702 ///
8703 /// \param Loc The location at which we should emit the diagnostic.
8704 ///
8705 /// \param UPPC The context in which we are diagnosing unexpanded
8706 /// parameter packs.
8707 ///
8708 /// \param Unexpanded the set of unexpanded parameter packs.
8709 ///
8710 /// \returns true if an error occurred, false otherwise.
8711 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
8712 UnexpandedParameterPackContext UPPC,
8713 ArrayRef<UnexpandedParameterPack> Unexpanded);
8714
8715 /// If the given type contains an unexpanded parameter pack,
8716 /// diagnose the error.
8717 ///
8718 /// \param Loc The source location where a diagnostc should be emitted.
8719 ///
8720 /// \param T The type that is being checked for unexpanded parameter
8721 /// packs.
8722 ///
8723 /// \returns true if an error occurred, false otherwise.
8724 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
8725 UnexpandedParameterPackContext UPPC);
8726
8727 /// If the given expression contains an unexpanded parameter
8728 /// pack, diagnose the error.
8729 ///
8730 /// \param E The expression that is being checked for unexpanded
8731 /// parameter packs.
8732 ///
8733 /// \returns true if an error occurred, false otherwise.
8734 bool DiagnoseUnexpandedParameterPack(Expr *E,
8735 UnexpandedParameterPackContext UPPC = UPPC_Expression);
8736
8737 /// If the given requirees-expression contains an unexpanded reference to one
8738 /// of its own parameter packs, diagnose the error.
8739 ///
8740 /// \param RE The requiress-expression that is being checked for unexpanded
8741 /// parameter packs.
8742 ///
8743 /// \returns true if an error occurred, false otherwise.
8744 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
8745
8746 /// If the given nested-name-specifier contains an unexpanded
8747 /// parameter pack, diagnose the error.
8748 ///
8749 /// \param SS The nested-name-specifier that is being checked for
8750 /// unexpanded parameter packs.
8751 ///
8752 /// \returns true if an error occurred, false otherwise.
8753 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
8754 UnexpandedParameterPackContext UPPC);
8755
8756 /// If the given name contains an unexpanded parameter pack,
8757 /// diagnose the error.
8758 ///
8759 /// \param NameInfo The name (with source location information) that
8760 /// is being checked for unexpanded parameter packs.
8761 ///
8762 /// \returns true if an error occurred, false otherwise.
8763 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
8764 UnexpandedParameterPackContext UPPC);
8765
8766 /// If the given template name contains an unexpanded parameter pack,
8767 /// diagnose the error.
8768 ///
8769 /// \param Loc The location of the template name.
8770 ///
8771 /// \param Template The template name that is being checked for unexpanded
8772 /// parameter packs.
8773 ///
8774 /// \returns true if an error occurred, false otherwise.
8775 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
8776 TemplateName Template,
8777 UnexpandedParameterPackContext UPPC);
8778
8779 /// If the given template argument contains an unexpanded parameter
8780 /// pack, diagnose the error.
8781 ///
8782 /// \param Arg The template argument that is being checked for unexpanded
8783 /// parameter packs.
8784 ///
8785 /// \returns true if an error occurred, false otherwise.
8786 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
8787 UnexpandedParameterPackContext UPPC);
8788
8789 /// Collect the set of unexpanded parameter packs within the given
8790 /// template argument.
8791 ///
8792 /// \param Arg The template argument that will be traversed to find
8793 /// unexpanded parameter packs.
8794 void collectUnexpandedParameterPacks(TemplateArgument Arg,
8795 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8796
8797 /// Collect the set of unexpanded parameter packs within the given
8798 /// template argument.
8799 ///
8800 /// \param Arg The template argument that will be traversed to find
8801 /// unexpanded parameter packs.
8802 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
8803 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8804
8805 /// Collect the set of unexpanded parameter packs within the given
8806 /// type.
8807 ///
8808 /// \param T The type that will be traversed to find
8809 /// unexpanded parameter packs.
8810 void collectUnexpandedParameterPacks(QualType T,
8811 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8812
8813 /// Collect the set of unexpanded parameter packs within the given
8814 /// type.
8815 ///
8816 /// \param TL The type that will be traversed to find
8817 /// unexpanded parameter packs.
8818 void collectUnexpandedParameterPacks(TypeLoc TL,
8819 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8820
8821 /// Collect the set of unexpanded parameter packs within the given
8822 /// nested-name-specifier.
8823 ///
8824 /// \param NNS The nested-name-specifier that will be traversed to find
8825 /// unexpanded parameter packs.
8826 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
8827 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8828
8829 /// Collect the set of unexpanded parameter packs within the given
8830 /// name.
8831 ///
8832 /// \param NameInfo The name that will be traversed to find
8833 /// unexpanded parameter packs.
8834 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
8835 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8836
8837 /// Invoked when parsing a template argument followed by an
8838 /// ellipsis, which creates a pack expansion.
8839 ///
8840 /// \param Arg The template argument preceding the ellipsis, which
8841 /// may already be invalid.
8842 ///
8843 /// \param EllipsisLoc The location of the ellipsis.
8844 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
8845 SourceLocation EllipsisLoc);
8846
8847 /// Invoked when parsing a type followed by an ellipsis, which
8848 /// creates a pack expansion.
8849 ///
8850 /// \param Type The type preceding the ellipsis, which will become
8851 /// the pattern of the pack expansion.
8852 ///
8853 /// \param EllipsisLoc The location of the ellipsis.
8854 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
8855
8856 /// Construct a pack expansion type from the pattern of the pack
8857 /// expansion.
8858 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
8859 SourceLocation EllipsisLoc,
8860 std::optional<unsigned> NumExpansions);
8861
8862 /// Construct a pack expansion type from the pattern of the pack
8863 /// expansion.
8864 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
8865 SourceLocation EllipsisLoc,
8866 std::optional<unsigned> NumExpansions);
8867
8868 /// Invoked when parsing an expression followed by an ellipsis, which
8869 /// creates a pack expansion.
8870 ///
8871 /// \param Pattern The expression preceding the ellipsis, which will become
8872 /// the pattern of the pack expansion.
8873 ///
8874 /// \param EllipsisLoc The location of the ellipsis.
8875 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
8876
8877 /// Invoked when parsing an expression followed by an ellipsis, which
8878 /// creates a pack expansion.
8879 ///
8880 /// \param Pattern The expression preceding the ellipsis, which will become
8881 /// the pattern of the pack expansion.
8882 ///
8883 /// \param EllipsisLoc The location of the ellipsis.
8884 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
8885 std::optional<unsigned> NumExpansions);
8886
8887 /// Determine whether we could expand a pack expansion with the
8888 /// given set of parameter packs into separate arguments by repeatedly
8889 /// transforming the pattern.
8890 ///
8891 /// \param EllipsisLoc The location of the ellipsis that identifies the
8892 /// pack expansion.
8893 ///
8894 /// \param PatternRange The source range that covers the entire pattern of
8895 /// the pack expansion.
8896 ///
8897 /// \param Unexpanded The set of unexpanded parameter packs within the
8898 /// pattern.
8899 ///
8900 /// \param ShouldExpand Will be set to \c true if the transformer should
8901 /// expand the corresponding pack expansions into separate arguments. When
8902 /// set, \c NumExpansions must also be set.
8903 ///
8904 /// \param RetainExpansion Whether the caller should add an unexpanded
8905 /// pack expansion after all of the expanded arguments. This is used
8906 /// when extending explicitly-specified template argument packs per
8907 /// C++0x [temp.arg.explicit]p9.
8908 ///
8909 /// \param NumExpansions The number of separate arguments that will be in
8910 /// the expanded form of the corresponding pack expansion. This is both an
8911 /// input and an output parameter, which can be set by the caller if the
8912 /// number of expansions is known a priori (e.g., due to a prior substitution)
8913 /// and will be set by the callee when the number of expansions is known.
8914 /// The callee must set this value when \c ShouldExpand is \c true; it may
8915 /// set this value in other cases.
8916 ///
8917 /// \returns true if an error occurred (e.g., because the parameter packs
8918 /// are to be instantiated with arguments of different lengths), false
8919 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
8920 /// must be set.
8921 bool CheckParameterPacksForExpansion(
8922 SourceLocation EllipsisLoc, SourceRange PatternRange,
8923 ArrayRef<UnexpandedParameterPack> Unexpanded,
8924 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
8925 bool &RetainExpansion, std::optional<unsigned> &NumExpansions);
8926
8927 /// Determine the number of arguments in the given pack expansion
8928 /// type.
8929 ///
8930 /// This routine assumes that the number of arguments in the expansion is
8931 /// consistent across all of the unexpanded parameter packs in its pattern.
8932 ///
8933 /// Returns an empty Optional if the type can't be expanded.
8934 std::optional<unsigned> getNumArgumentsInExpansion(
8935 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
8936
8937 /// Determine whether the given declarator contains any unexpanded
8938 /// parameter packs.
8939 ///
8940 /// This routine is used by the parser to disambiguate function declarators
8941 /// with an ellipsis prior to the ')', e.g.,
8942 ///
8943 /// \code
8944 /// void f(T...);
8945 /// \endcode
8946 ///
8947 /// To determine whether we have an (unnamed) function parameter pack or
8948 /// a variadic function.
8949 ///
8950 /// \returns true if the declarator contains any unexpanded parameter packs,
8951 /// false otherwise.
8952 bool containsUnexpandedParameterPacks(Declarator &D);
8953
8954 /// Returns the pattern of the pack expansion for a template argument.
8955 ///
8956 /// \param OrigLoc The template argument to expand.
8957 ///
8958 /// \param Ellipsis Will be set to the location of the ellipsis.
8959 ///
8960 /// \param NumExpansions Will be set to the number of expansions that will
8961 /// be generated from this pack expansion, if known a priori.
8962 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
8963 TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis,
8964 std::optional<unsigned> &NumExpansions) const;
8965
8966 /// Given a template argument that contains an unexpanded parameter pack, but
8967 /// which has already been substituted, attempt to determine the number of
8968 /// elements that will be produced once this argument is fully-expanded.
8969 ///
8970 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
8971 /// avoid actually expanding the pack where possible.
8972 std::optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
8973
8974 //===--------------------------------------------------------------------===//
8975 // C++ Template Argument Deduction (C++ [temp.deduct])
8976 //===--------------------------------------------------------------------===//
8977
8978 /// Adjust the type \p ArgFunctionType to match the calling convention,
8979 /// noreturn, and optionally the exception specification of \p FunctionType.
8980 /// Deduction often wants to ignore these properties when matching function
8981 /// types.
8982 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
8983 bool AdjustExceptionSpec = false);
8984
8985 /// Describes the result of template argument deduction.
8986 ///
8987 /// The TemplateDeductionResult enumeration describes the result of
8988 /// template argument deduction, as returned from
8989 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
8990 /// structure provides additional information about the results of
8991 /// template argument deduction, e.g., the deduced template argument
8992 /// list (if successful) or the specific template parameters or
8993 /// deduced arguments that were involved in the failure.
8994 enum TemplateDeductionResult {
8995 /// Template argument deduction was successful.
8996 TDK_Success = 0,
8997 /// The declaration was invalid; do nothing.
8998 TDK_Invalid,
8999 /// Template argument deduction exceeded the maximum template
9000 /// instantiation depth (which has already been diagnosed).
9001 TDK_InstantiationDepth,
9002 /// Template argument deduction did not deduce a value
9003 /// for every template parameter.
9004 TDK_Incomplete,
9005 /// Template argument deduction did not deduce a value for every
9006 /// expansion of an expanded template parameter pack.
9007 TDK_IncompletePack,
9008 /// Template argument deduction produced inconsistent
9009 /// deduced values for the given template parameter.
9010 TDK_Inconsistent,
9011 /// Template argument deduction failed due to inconsistent
9012 /// cv-qualifiers on a template parameter type that would
9013 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
9014 /// but were given a non-const "X".
9015 TDK_Underqualified,
9016 /// Substitution of the deduced template argument values
9017 /// resulted in an error.
9018 TDK_SubstitutionFailure,
9019 /// After substituting deduced template arguments, a dependent
9020 /// parameter type did not match the corresponding argument.
9021 TDK_DeducedMismatch,
9022 /// After substituting deduced template arguments, an element of
9023 /// a dependent parameter type did not match the corresponding element
9024 /// of the corresponding argument (when deducing from an initializer list).
9025 TDK_DeducedMismatchNested,
9026 /// A non-depnedent component of the parameter did not match the
9027 /// corresponding component of the argument.
9028 TDK_NonDeducedMismatch,
9029 /// When performing template argument deduction for a function
9030 /// template, there were too many call arguments.
9031 TDK_TooManyArguments,
9032 /// When performing template argument deduction for a function
9033 /// template, there were too few call arguments.
9034 TDK_TooFewArguments,
9035 /// The explicitly-specified template arguments were not valid
9036 /// template arguments for the given template.
9037 TDK_InvalidExplicitArguments,
9038 /// Checking non-dependent argument conversions failed.
9039 TDK_NonDependentConversionFailure,
9040 /// The deduced arguments did not satisfy the constraints associated
9041 /// with the template.
9042 TDK_ConstraintsNotSatisfied,
9043 /// Deduction failed; that's all we know.
9044 TDK_MiscellaneousDeductionFailure,
9045 /// CUDA Target attributes do not match.
9046 TDK_CUDATargetMismatch,
9047 /// Some error which was already diagnosed.
9048 TDK_AlreadyDiagnosed
9049 };
9050
9051 TemplateDeductionResult
9052 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
9053 const TemplateArgumentList &TemplateArgs,
9054 sema::TemplateDeductionInfo &Info);
9055
9056 TemplateDeductionResult
9057 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
9058 const TemplateArgumentList &TemplateArgs,
9059 sema::TemplateDeductionInfo &Info);
9060
9061 TemplateDeductionResult SubstituteExplicitTemplateArguments(
9062 FunctionTemplateDecl *FunctionTemplate,
9063 TemplateArgumentListInfo &ExplicitTemplateArgs,
9064 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
9065 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
9066 sema::TemplateDeductionInfo &Info);
9067
9068 /// brief A function argument from which we performed template argument
9069 // deduction for a call.
9070 struct OriginalCallArg {
9071 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
9072 unsigned ArgIdx, QualType OriginalArgType)
9073 : OriginalParamType(OriginalParamType),
9074 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
9075 OriginalArgType(OriginalArgType) {}
9076
9077 QualType OriginalParamType;
9078 bool DecomposedParam;
9079 unsigned ArgIdx;
9080 QualType OriginalArgType;
9081 };
9082
9083 TemplateDeductionResult FinishTemplateArgumentDeduction(
9084 FunctionTemplateDecl *FunctionTemplate,
9085 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
9086 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
9087 sema::TemplateDeductionInfo &Info,
9088 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
9089 bool PartialOverloading = false,
9090 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
9091
9092 TemplateDeductionResult DeduceTemplateArguments(
9093 FunctionTemplateDecl *FunctionTemplate,
9094 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
9095 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
9096 bool PartialOverloading,
9097 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
9098
9099 TemplateDeductionResult
9100 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
9101 TemplateArgumentListInfo *ExplicitTemplateArgs,
9102 QualType ArgFunctionType,
9103 FunctionDecl *&Specialization,
9104 sema::TemplateDeductionInfo &Info,
9105 bool IsAddressOfFunction = false);
9106
9107 TemplateDeductionResult
9108 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
9109 QualType ToType,
9110 CXXConversionDecl *&Specialization,
9111 sema::TemplateDeductionInfo &Info);
9112
9113 TemplateDeductionResult
9114 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
9115 TemplateArgumentListInfo *ExplicitTemplateArgs,
9116 FunctionDecl *&Specialization,
9117 sema::TemplateDeductionInfo &Info,
9118 bool IsAddressOfFunction = false);
9119
9120 /// Substitute Replacement for \p auto in \p TypeWithAuto
9121 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
9122 /// Substitute Replacement for auto in TypeWithAuto
9123 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
9124 QualType Replacement);
9125
9126 // Substitute auto in TypeWithAuto for a Dependent auto type
9127 QualType SubstAutoTypeDependent(QualType TypeWithAuto);
9128
9129 // Substitute auto in TypeWithAuto for a Dependent auto type
9130 TypeSourceInfo *
9131 SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
9132
9133 /// Completely replace the \c auto in \p TypeWithAuto by
9134 /// \p Replacement. This does not retain any \c auto type sugar.
9135 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
9136 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
9137 QualType Replacement);
9138
9139 TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer,
9140 QualType &Result,
9141 sema::TemplateDeductionInfo &Info,
9142 bool DependentDeduction = false,
9143 bool IgnoreConstraints = false);
9144 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
9145 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
9146 bool Diagnose = true);
9147
9148 /// Declare implicit deduction guides for a class template if we've
9149 /// not already done so.
9150 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
9151 SourceLocation Loc);
9152
9153 QualType DeduceTemplateSpecializationFromInitializer(
9154 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9155 const InitializationKind &Kind, MultiExprArg Init);
9156
9157 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
9158 QualType Type, TypeSourceInfo *TSI,
9159 SourceRange Range, bool DirectInit,
9160 Expr *Init);
9161
9162 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
9163
9164 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
9165 SourceLocation ReturnLoc, Expr *RetExpr,
9166 const AutoType *AT);
9167
9168 FunctionTemplateDecl *getMoreSpecializedTemplate(
9169 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
9170 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
9171 unsigned NumCallArguments2, bool Reversed = false);
9172 UnresolvedSetIterator
9173 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
9174 TemplateSpecCandidateSet &FailedCandidates,
9175 SourceLocation Loc,
9176 const PartialDiagnostic &NoneDiag,
9177 const PartialDiagnostic &AmbigDiag,
9178 const PartialDiagnostic &CandidateDiag,
9179 bool Complain = true, QualType TargetType = QualType());
9180
9181 ClassTemplatePartialSpecializationDecl *
9182 getMoreSpecializedPartialSpecialization(
9183 ClassTemplatePartialSpecializationDecl *PS1,
9184 ClassTemplatePartialSpecializationDecl *PS2,
9185 SourceLocation Loc);
9186
9187 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
9188 sema::TemplateDeductionInfo &Info);
9189
9190 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
9191 VarTemplatePartialSpecializationDecl *PS1,
9192 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
9193
9194 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
9195 sema::TemplateDeductionInfo &Info);
9196
9197 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
9198 TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
9199
9200 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
9201 unsigned Depth, llvm::SmallBitVector &Used);
9202
9203 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
9204 bool OnlyDeduced,
9205 unsigned Depth,
9206 llvm::SmallBitVector &Used);
9207 void MarkDeducedTemplateParameters(
9208 const FunctionTemplateDecl *FunctionTemplate,
9209 llvm::SmallBitVector &Deduced) {
9210 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
9211 }
9212 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
9213 const FunctionTemplateDecl *FunctionTemplate,
9214 llvm::SmallBitVector &Deduced);
9215
9216 //===--------------------------------------------------------------------===//
9217 // C++ Template Instantiation
9218 //
9219
9220 MultiLevelTemplateArgumentList
9221 getTemplateInstantiationArgs(const NamedDecl *D, bool Final = false,
9222 const TemplateArgumentList *Innermost = nullptr,
9223 bool RelativeToPrimary = false,
9224 const FunctionDecl *Pattern = nullptr,
9225 bool ForConstraintInstantiation = false,
9226 bool SkipForSpecialization = false);
9227
9228 /// A context in which code is being synthesized (where a source location
9229 /// alone is not sufficient to identify the context). This covers template
9230 /// instantiation and various forms of implicitly-generated functions.
9231 struct CodeSynthesisContext {
9232 /// The kind of template instantiation we are performing
9233 enum SynthesisKind {
9234 /// We are instantiating a template declaration. The entity is
9235 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
9236 TemplateInstantiation,
9237
9238 /// We are instantiating a default argument for a template
9239 /// parameter. The Entity is the template parameter whose argument is
9240 /// being instantiated, the Template is the template, and the
9241 /// TemplateArgs/NumTemplateArguments provide the template arguments as
9242 /// specified.
9243 DefaultTemplateArgumentInstantiation,
9244
9245 /// We are instantiating a default argument for a function.
9246 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
9247 /// provides the template arguments as specified.
9248 DefaultFunctionArgumentInstantiation,
9249
9250 /// We are substituting explicit template arguments provided for
9251 /// a function template. The entity is a FunctionTemplateDecl.
9252 ExplicitTemplateArgumentSubstitution,
9253
9254 /// We are substituting template argument determined as part of
9255 /// template argument deduction for either a class template
9256 /// partial specialization or a function template. The
9257 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
9258 /// a TemplateDecl.
9259 DeducedTemplateArgumentSubstitution,
9260
9261 /// We are substituting into a lambda expression.
9262 LambdaExpressionSubstitution,
9263
9264 /// We are substituting prior template arguments into a new
9265 /// template parameter. The template parameter itself is either a
9266 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
9267 PriorTemplateArgumentSubstitution,
9268
9269 /// We are checking the validity of a default template argument that
9270 /// has been used when naming a template-id.
9271 DefaultTemplateArgumentChecking,
9272
9273 /// We are computing the exception specification for a defaulted special
9274 /// member function.
9275 ExceptionSpecEvaluation,
9276
9277 /// We are instantiating the exception specification for a function
9278 /// template which was deferred until it was needed.
9279 ExceptionSpecInstantiation,
9280
9281 /// We are instantiating a requirement of a requires expression.
9282 RequirementInstantiation,
9283
9284 /// We are checking the satisfaction of a nested requirement of a requires
9285 /// expression.
9286 NestedRequirementConstraintsCheck,
9287
9288 /// We are declaring an implicit special member function.
9289 DeclaringSpecialMember,
9290
9291 /// We are declaring an implicit 'operator==' for a defaulted
9292 /// 'operator<=>'.
9293 DeclaringImplicitEqualityComparison,
9294
9295 /// We are defining a synthesized function (such as a defaulted special
9296 /// member).
9297 DefiningSynthesizedFunction,
9298
9299 // We are checking the constraints associated with a constrained entity or
9300 // the constraint expression of a concept. This includes the checks that
9301 // atomic constraints have the type 'bool' and that they can be constant
9302 // evaluated.
9303 ConstraintsCheck,
9304
9305 // We are substituting template arguments into a constraint expression.
9306 ConstraintSubstitution,
9307
9308 // We are normalizing a constraint expression.
9309 ConstraintNormalization,
9310
9311 // Instantiating a Requires Expression parameter clause.
9312 RequirementParameterInstantiation,
9313
9314 // We are substituting into the parameter mapping of an atomic constraint
9315 // during normalization.
9316 ParameterMappingSubstitution,
9317
9318 /// We are rewriting a comparison operator in terms of an operator<=>.
9319 RewritingOperatorAsSpaceship,
9320
9321 /// We are initializing a structured binding.
9322 InitializingStructuredBinding,
9323
9324 /// We are marking a class as __dllexport.
9325 MarkingClassDllexported,
9326
9327 /// We are building an implied call from __builtin_dump_struct. The
9328 /// arguments are in CallArgs.
9329 BuildingBuiltinDumpStructCall,
9330
9331 /// Added for Template instantiation observation.
9332 /// Memoization means we are _not_ instantiating a template because
9333 /// it is already instantiated (but we entered a context where we
9334 /// would have had to if it was not already instantiated).
9335 Memoization
9336 } Kind;
9337
9338 /// Was the enclosing context a non-instantiation SFINAE context?
9339 bool SavedInNonInstantiationSFINAEContext;
9340
9341 /// The point of instantiation or synthesis within the source code.
9342 SourceLocation PointOfInstantiation;
9343
9344 /// The entity that is being synthesized.
9345 Decl *Entity;
9346
9347 /// The template (or partial specialization) in which we are
9348 /// performing the instantiation, for substitutions of prior template
9349 /// arguments.
9350 NamedDecl *Template;
9351
9352 union {
9353 /// The list of template arguments we are substituting, if they
9354 /// are not part of the entity.
9355 const TemplateArgument *TemplateArgs;
9356
9357 /// The list of argument expressions in a synthesized call.
9358 const Expr *const *CallArgs;
9359 };
9360
9361 // FIXME: Wrap this union around more members, or perhaps store the
9362 // kind-specific members in the RAII object owning the context.
9363 union {
9364 /// The number of template arguments in TemplateArgs.
9365 unsigned NumTemplateArgs;
9366
9367 /// The number of expressions in CallArgs.
9368 unsigned NumCallArgs;
9369
9370 /// The special member being declared or defined.
9371 CXXSpecialMember SpecialMember;
9372 };
9373
9374 ArrayRef<TemplateArgument> template_arguments() const {
9375 assert(Kind != DeclaringSpecialMember)(static_cast <bool> (Kind != DeclaringSpecialMember) ? void
(0) : __assert_fail ("Kind != DeclaringSpecialMember", "clang/include/clang/Sema/Sema.h"
, 9375, __extension__ __PRETTY_FUNCTION__))
;
9376 return {TemplateArgs, NumTemplateArgs};
9377 }
9378
9379 /// The template deduction info object associated with the
9380 /// substitution or checking of explicit or deduced template arguments.
9381 sema::TemplateDeductionInfo *DeductionInfo;
9382
9383 /// The source range that covers the construct that cause
9384 /// the instantiation, e.g., the template-id that causes a class
9385 /// template instantiation.
9386 SourceRange InstantiationRange;
9387
9388 CodeSynthesisContext()
9389 : Kind(TemplateInstantiation),
9390 SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
9391 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
9392 DeductionInfo(nullptr) {}
9393
9394 /// Determines whether this template is an actual instantiation
9395 /// that should be counted toward the maximum instantiation depth.
9396 bool isInstantiationRecord() const;
9397 };
9398
9399 /// List of active code synthesis contexts.
9400 ///
9401 /// This vector is treated as a stack. As synthesis of one entity requires
9402 /// synthesis of another, additional contexts are pushed onto the stack.
9403 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
9404
9405 /// Specializations whose definitions are currently being instantiated.
9406 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
9407
9408 /// Non-dependent types used in templates that have already been instantiated
9409 /// by some template instantiation.
9410 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
9411
9412 /// Extra modules inspected when performing a lookup during a template
9413 /// instantiation. Computed lazily.
9414 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
9415
9416 /// Cache of additional modules that should be used for name lookup
9417 /// within the current template instantiation. Computed lazily; use
9418 /// getLookupModules() to get a complete set.
9419 llvm::DenseSet<Module*> LookupModulesCache;
9420
9421 /// Get the set of additional modules that should be checked during
9422 /// name lookup. A module and its imports become visible when instanting a
9423 /// template defined within it.
9424 llvm::DenseSet<Module*> &getLookupModules();
9425
9426 /// Map from the most recent declaration of a namespace to the most
9427 /// recent visible declaration of that namespace.
9428 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
9429
9430 /// Whether we are in a SFINAE context that is not associated with
9431 /// template instantiation.
9432 ///
9433 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
9434 /// of a template instantiation or template argument deduction.
9435 bool InNonInstantiationSFINAEContext;
9436
9437 /// The number of \p CodeSynthesisContexts that are not template
9438 /// instantiations and, therefore, should not be counted as part of the
9439 /// instantiation depth.
9440 ///
9441 /// When the instantiation depth reaches the user-configurable limit
9442 /// \p LangOptions::InstantiationDepth we will abort instantiation.
9443 // FIXME: Should we have a similar limit for other forms of synthesis?
9444 unsigned NonInstantiationEntries;
9445
9446 /// The depth of the context stack at the point when the most recent
9447 /// error or warning was produced.
9448 ///
9449 /// This value is used to suppress printing of redundant context stacks
9450 /// when there are multiple errors or warnings in the same instantiation.
9451 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
9452 unsigned LastEmittedCodeSynthesisContextDepth = 0;
9453
9454 /// The template instantiation callbacks to trace or track
9455 /// instantiations (objects can be chained).
9456 ///
9457 /// This callbacks is used to print, trace or track template
9458 /// instantiations as they are being constructed.
9459 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
9460 TemplateInstCallbacks;
9461
9462 /// The current index into pack expansion arguments that will be
9463 /// used for substitution of parameter packs.
9464 ///
9465 /// The pack expansion index will be -1 to indicate that parameter packs
9466 /// should be instantiated as themselves. Otherwise, the index specifies
9467 /// which argument within the parameter pack will be used for substitution.
9468 int ArgumentPackSubstitutionIndex;
9469
9470 /// RAII object used to change the argument pack substitution index
9471 /// within a \c Sema object.
9472 ///
9473 /// See \c ArgumentPackSubstitutionIndex for more information.
9474 class ArgumentPackSubstitutionIndexRAII {
9475 Sema &Self;
9476 int OldSubstitutionIndex;
9477
9478 public:
9479 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
9480 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
9481 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
9482 }
9483
9484 ~ArgumentPackSubstitutionIndexRAII() {
9485 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
9486 }
9487 };
9488
9489 friend class ArgumentPackSubstitutionRAII;
9490
9491 /// For each declaration that involved template argument deduction, the
9492 /// set of diagnostics that were suppressed during that template argument
9493 /// deduction.
9494 ///
9495 /// FIXME: Serialize this structure to the AST file.
9496 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
9497 SuppressedDiagnosticsMap;
9498 SuppressedDiagnosticsMap SuppressedDiagnostics;
9499
9500 /// A stack object to be created when performing template
9501 /// instantiation.
9502 ///
9503 /// Construction of an object of type \c InstantiatingTemplate
9504 /// pushes the current instantiation onto the stack of active
9505 /// instantiations. If the size of this stack exceeds the maximum
9506 /// number of recursive template instantiations, construction
9507 /// produces an error and evaluates true.
9508 ///
9509 /// Destruction of this object will pop the named instantiation off
9510 /// the stack.
9511 struct InstantiatingTemplate {
9512 /// Note that we are instantiating a class template,
9513 /// function template, variable template, alias template,
9514 /// or a member thereof.
9515 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9516 Decl *Entity,
9517 SourceRange InstantiationRange = SourceRange());
9518
9519 struct ExceptionSpecification {};
9520 /// Note that we are instantiating an exception specification
9521 /// of a function template.
9522 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9523 FunctionDecl *Entity, ExceptionSpecification,
9524 SourceRange InstantiationRange = SourceRange());
9525
9526 /// Note that we are instantiating a default argument in a
9527 /// template-id.
9528 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9529 TemplateParameter Param, TemplateDecl *Template,
9530 ArrayRef<TemplateArgument> TemplateArgs,
9531 SourceRange InstantiationRange = SourceRange());
9532
9533 /// Note that we are substituting either explicitly-specified or
9534 /// deduced template arguments during function template argument deduction.
9535 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9536 FunctionTemplateDecl *FunctionTemplate,
9537 ArrayRef<TemplateArgument> TemplateArgs,
9538 CodeSynthesisContext::SynthesisKind Kind,
9539 sema::TemplateDeductionInfo &DeductionInfo,
9540 SourceRange InstantiationRange = SourceRange());
9541
9542 /// Note that we are instantiating as part of template
9543 /// argument deduction for a class template declaration.
9544 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9545 TemplateDecl *Template,
9546 ArrayRef<TemplateArgument> TemplateArgs,
9547 sema::TemplateDeductionInfo &DeductionInfo,
9548 SourceRange InstantiationRange = SourceRange());
9549
9550 /// Note that we are instantiating as part of template
9551 /// argument deduction for a class template partial
9552 /// specialization.
9553 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9554 ClassTemplatePartialSpecializationDecl *PartialSpec,
9555 ArrayRef<TemplateArgument> TemplateArgs,
9556 sema::TemplateDeductionInfo &DeductionInfo,
9557 SourceRange InstantiationRange = SourceRange());
9558
9559 /// Note that we are instantiating as part of template
9560 /// argument deduction for a variable template partial
9561 /// specialization.
9562 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9563 VarTemplatePartialSpecializationDecl *PartialSpec,
9564 ArrayRef<TemplateArgument> TemplateArgs,
9565 sema::TemplateDeductionInfo &DeductionInfo,
9566 SourceRange InstantiationRange = SourceRange());
9567
9568 /// Note that we are instantiating a default argument for a function
9569 /// parameter.
9570 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9571 ParmVarDecl *Param,
9572 ArrayRef<TemplateArgument> TemplateArgs,
9573 SourceRange InstantiationRange = SourceRange());
9574
9575 /// Note that we are substituting prior template arguments into a
9576 /// non-type parameter.
9577 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9578 NamedDecl *Template,
9579 NonTypeTemplateParmDecl *Param,
9580 ArrayRef<TemplateArgument> TemplateArgs,
9581 SourceRange InstantiationRange);
9582
9583 /// Note that we are substituting prior template arguments into a
9584 /// template template parameter.
9585 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9586 NamedDecl *Template,
9587 TemplateTemplateParmDecl *Param,
9588 ArrayRef<TemplateArgument> TemplateArgs,
9589 SourceRange InstantiationRange);
9590
9591 /// Note that we are checking the default template argument
9592 /// against the template parameter for a given template-id.
9593 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9594 TemplateDecl *Template,
9595 NamedDecl *Param,
9596 ArrayRef<TemplateArgument> TemplateArgs,
9597 SourceRange InstantiationRange);
9598
9599 struct ConstraintsCheck {};
9600 /// \brief Note that we are checking the constraints associated with some
9601 /// constrained entity (a concept declaration or a template with associated
9602 /// constraints).
9603 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9604 ConstraintsCheck, NamedDecl *Template,
9605 ArrayRef<TemplateArgument> TemplateArgs,
9606 SourceRange InstantiationRange);
9607
9608 struct ConstraintSubstitution {};
9609 /// \brief Note that we are checking a constraint expression associated
9610 /// with a template declaration or as part of the satisfaction check of a
9611 /// concept.
9612 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9613 ConstraintSubstitution, NamedDecl *Template,
9614 sema::TemplateDeductionInfo &DeductionInfo,
9615 SourceRange InstantiationRange);
9616
9617 struct ConstraintNormalization {};
9618 /// \brief Note that we are normalizing a constraint expression.
9619 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9620 ConstraintNormalization, NamedDecl *Template,
9621 SourceRange InstantiationRange);
9622
9623 struct ParameterMappingSubstitution {};
9624 /// \brief Note that we are subtituting into the parameter mapping of an
9625 /// atomic constraint during constraint normalization.
9626 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9627 ParameterMappingSubstitution, NamedDecl *Template,
9628 SourceRange InstantiationRange);
9629
9630 /// \brief Note that we are substituting template arguments into a part of
9631 /// a requirement of a requires expression.
9632 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9633 concepts::Requirement *Req,
9634 sema::TemplateDeductionInfo &DeductionInfo,
9635 SourceRange InstantiationRange = SourceRange());
9636
9637 /// \brief Note that we are checking the satisfaction of the constraint
9638 /// expression inside of a nested requirement.
9639 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9640 concepts::NestedRequirement *Req, ConstraintsCheck,
9641 SourceRange InstantiationRange = SourceRange());
9642
9643 /// \brief Note that we are checking a requires clause.
9644 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9645 const RequiresExpr *E,
9646 sema::TemplateDeductionInfo &DeductionInfo,
9647 SourceRange InstantiationRange);
9648 /// Note that we have finished instantiating this template.
9649 void Clear();
9650
9651 ~InstantiatingTemplate() { Clear(); }
9652
9653 /// Determines whether we have exceeded the maximum
9654 /// recursive template instantiations.
9655 bool isInvalid() const { return Invalid; }
9656
9657 /// Determine whether we are already instantiating this
9658 /// specialization in some surrounding active instantiation.
9659 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
9660
9661 private:
9662 Sema &SemaRef;
9663 bool Invalid;
9664 bool AlreadyInstantiating;
9665 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
9666 SourceRange InstantiationRange);
9667
9668 InstantiatingTemplate(
9669 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
9670 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
9671 Decl *Entity, NamedDecl *Template = nullptr,
9672 ArrayRef<TemplateArgument> TemplateArgs = std::nullopt,
9673 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
9674
9675 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
9676
9677 InstantiatingTemplate&
9678 operator=(const InstantiatingTemplate&) = delete;
9679 };
9680
9681 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
9682 void popCodeSynthesisContext();
9683
9684 /// Determine whether we are currently performing template instantiation.
9685 bool inTemplateInstantiation() const {
9686 return CodeSynthesisContexts.size() > NonInstantiationEntries;
9687 }
9688
9689 void PrintContextStack() {
9690 if (!CodeSynthesisContexts.empty() &&
9691 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
9692 PrintInstantiationStack();
9693 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
9694 }
9695 if (PragmaAttributeCurrentTargetDecl)
9696 PrintPragmaAttributeInstantiationPoint();
9697 }
9698 void PrintInstantiationStack();
9699
9700 void PrintPragmaAttributeInstantiationPoint();
9701
9702 /// Determines whether we are currently in a context where
9703 /// template argument substitution failures are not considered
9704 /// errors.
9705 ///
9706 /// \returns An empty \c Optional if we're not in a SFINAE context.
9707 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
9708 /// template-deduction context object, which can be used to capture
9709 /// diagnostics that will be suppressed.
9710 std::optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
9711
9712 /// Determines whether we are currently in a context that
9713 /// is not evaluated as per C++ [expr] p5.
9714 bool isUnevaluatedContext() const {
9715 assert(!ExprEvalContexts.empty() &&(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9716, __extension__ __PRETTY_FUNCTION__
))
9716 "Must be in an expression evaluation context")(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9716, __extension__ __PRETTY_FUNCTION__
))
;
9717 return ExprEvalContexts.back().isUnevaluated();
9718 }
9719
9720 bool isConstantEvaluatedContext() const {
9721 assert(!ExprEvalContexts.empty() &&(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9722, __extension__ __PRETTY_FUNCTION__
))
9722 "Must be in an expression evaluation context")(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9722, __extension__ __PRETTY_FUNCTION__
))
;
9723 return ExprEvalContexts.back().isConstantEvaluated();
9724 }
9725
9726 bool isImmediateFunctionContext() const {
9727 assert(!ExprEvalContexts.empty() &&(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9728, __extension__ __PRETTY_FUNCTION__
))
9728 "Must be in an expression evaluation context")(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9728, __extension__ __PRETTY_FUNCTION__
))
;
9729 return ExprEvalContexts.back().isImmediateFunctionContext();
9730 }
9731
9732 bool isCheckingDefaultArgumentOrInitializer() const {
9733 assert(!ExprEvalContexts.empty() &&(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9734, __extension__ __PRETTY_FUNCTION__
))
9734 "Must be in an expression evaluation context")(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9734, __extension__ __PRETTY_FUNCTION__
))
;
9735 const ExpressionEvaluationContextRecord &Ctx = ExprEvalContexts.back();
9736 return (Ctx.Context ==
9737 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) ||
9738 Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer;
9739 }
9740
9741 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
9742 InnermostDeclarationWithDelayedImmediateInvocations() const {
9743 assert(!ExprEvalContexts.empty() &&(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9744, __extension__ __PRETTY_FUNCTION__
))
9744 "Must be in an expression evaluation context")(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9744, __extension__ __PRETTY_FUNCTION__
))
;
9745 for (const auto &Ctx : llvm::reverse(ExprEvalContexts)) {
9746 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
9747 Ctx.DelayedDefaultInitializationContext)
9748 return Ctx.DelayedDefaultInitializationContext;
9749 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
9750 Ctx.isUnevaluated())
9751 break;
9752 }
9753 return std::nullopt;
9754 }
9755
9756 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
9757 OutermostDeclarationWithDelayedImmediateInvocations() const {
9758 assert(!ExprEvalContexts.empty() &&(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9759, __extension__ __PRETTY_FUNCTION__
))
9759 "Must be in an expression evaluation context")(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9759, __extension__ __PRETTY_FUNCTION__
))
;
9760 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
9761 for (auto &Ctx : llvm::reverse(ExprEvalContexts)) {
9762 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
9763 !Ctx.DelayedDefaultInitializationContext && Res)
9764 break;
9765 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
9766 Ctx.isUnevaluated())
9767 break;
9768 Res = Ctx.DelayedDefaultInitializationContext;
9769 }
9770 return Res;
9771 }
9772
9773 /// RAII class used to determine whether SFINAE has
9774 /// trapped any errors that occur during template argument
9775 /// deduction.
9776 class SFINAETrap {
9777 Sema &SemaRef;
9778 unsigned PrevSFINAEErrors;
9779 bool PrevInNonInstantiationSFINAEContext;
9780 bool PrevAccessCheckingSFINAE;
9781 bool PrevLastDiagnosticIgnored;
9782
9783 public:
9784 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
9785 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
9786 PrevInNonInstantiationSFINAEContext(
9787 SemaRef.InNonInstantiationSFINAEContext),
9788 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
9789 PrevLastDiagnosticIgnored(
9790 SemaRef.getDiagnostics().isLastDiagnosticIgnored())
9791 {
9792 if (!SemaRef.isSFINAEContext())
9793 SemaRef.InNonInstantiationSFINAEContext = true;
9794 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
9795 }
9796
9797 ~SFINAETrap() {
9798 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
9799 SemaRef.InNonInstantiationSFINAEContext
9800 = PrevInNonInstantiationSFINAEContext;
9801 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
9802 SemaRef.getDiagnostics().setLastDiagnosticIgnored(
9803 PrevLastDiagnosticIgnored);
9804 }
9805
9806 /// Determine whether any SFINAE errors have been trapped.
9807 bool hasErrorOccurred() const {
9808 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
9809 }
9810 };
9811
9812 /// RAII class used to indicate that we are performing provisional
9813 /// semantic analysis to determine the validity of a construct, so
9814 /// typo-correction and diagnostics in the immediate context (not within
9815 /// implicitly-instantiated templates) should be suppressed.
9816 class TentativeAnalysisScope {
9817 Sema &SemaRef;
9818 // FIXME: Using a SFINAETrap for this is a hack.
9819 SFINAETrap Trap;
9820 bool PrevDisableTypoCorrection;
9821 public:
9822 explicit TentativeAnalysisScope(Sema &SemaRef)
9823 : SemaRef(SemaRef), Trap(SemaRef, true),
9824 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
9825 SemaRef.DisableTypoCorrection = true;
9826 }
9827 ~TentativeAnalysisScope() {
9828 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
9829 }
9830 };
9831
9832 /// The current instantiation scope used to store local
9833 /// variables.
9834 LocalInstantiationScope *CurrentInstantiationScope;
9835
9836 /// Tracks whether we are in a context where typo correction is
9837 /// disabled.
9838 bool DisableTypoCorrection;
9839
9840 /// The number of typos corrected by CorrectTypo.
9841 unsigned TyposCorrected;
9842
9843 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9844 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9845
9846 /// A cache containing identifiers for which typo correction failed and
9847 /// their locations, so that repeated attempts to correct an identifier in a
9848 /// given location are ignored if typo correction already failed for it.
9849 IdentifierSourceLocations TypoCorrectionFailures;
9850
9851 /// Worker object for performing CFG-based warnings.
9852 sema::AnalysisBasedWarnings AnalysisWarnings;
9853 threadSafety::BeforeSet *ThreadSafetyDeclCache;
9854
9855 /// An entity for which implicit template instantiation is required.
9856 ///
9857 /// The source location associated with the declaration is the first place in
9858 /// the source code where the declaration was "used". It is not necessarily
9859 /// the point of instantiation (which will be either before or after the
9860 /// namespace-scope declaration that triggered this implicit instantiation),
9861 /// However, it is the location that diagnostics should generally refer to,
9862 /// because users will need to know what code triggered the instantiation.
9863 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
9864
9865 /// The queue of implicit template instantiations that are required
9866 /// but have not yet been performed.
9867 std::deque<PendingImplicitInstantiation> PendingInstantiations;
9868
9869 /// Queue of implicit template instantiations that cannot be performed
9870 /// eagerly.
9871 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
9872
9873 SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses;
9874 SmallVector<std::deque<PendingImplicitInstantiation>, 8>
9875 SavedPendingInstantiations;
9876
9877 class GlobalEagerInstantiationScope {
9878 public:
9879 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
9880 : S(S), Enabled(Enabled) {
9881 if (!Enabled) return;
9882
9883 S.SavedPendingInstantiations.emplace_back();
9884 S.SavedPendingInstantiations.back().swap(S.PendingInstantiations);
9885
9886 S.SavedVTableUses.emplace_back();
9887 S.SavedVTableUses.back().swap(S.VTableUses);
9888 }
9889
9890 void perform() {
9891 if (Enabled
32.1
Field 'Enabled' is true
32.1
Field 'Enabled' is true
) {
33
Taking true branch
9892 S.DefineUsedVTables();
9893 S.PerformPendingInstantiations();
34
Calling 'Sema::PerformPendingInstantiations'
9894 }
9895 }
9896
9897 ~GlobalEagerInstantiationScope() {
9898 if (!Enabled) return;
9899
9900 // Restore the set of pending vtables.
9901 assert(S.VTableUses.empty() &&(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "clang/include/clang/Sema/Sema.h", 9902, __extension__ __PRETTY_FUNCTION__
))
9902 "VTableUses should be empty before it is discarded.")(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "clang/include/clang/Sema/Sema.h", 9902, __extension__ __PRETTY_FUNCTION__
))
;
9903 S.VTableUses.swap(S.SavedVTableUses.back());
9904 S.SavedVTableUses.pop_back();
9905
9906 // Restore the set of pending implicit instantiations.
9907 if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) {
9908 assert(S.PendingInstantiations.empty() &&(static_cast <bool> (S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "clang/include/clang/Sema/Sema.h", 9909, __extension__ __PRETTY_FUNCTION__
))
9909 "PendingInstantiations should be empty before it is discarded.")(static_cast <bool> (S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "clang/include/clang/Sema/Sema.h", 9909, __extension__ __PRETTY_FUNCTION__
))
;
9910 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
9911 S.SavedPendingInstantiations.pop_back();
9912 } else {
9913 // Template instantiations in the PCH may be delayed until the TU.
9914 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
9915 S.PendingInstantiations.insert(
9916 S.PendingInstantiations.end(),
9917 S.SavedPendingInstantiations.back().begin(),
9918 S.SavedPendingInstantiations.back().end());
9919 S.SavedPendingInstantiations.pop_back();
9920 }
9921 }
9922
9923 private:
9924 Sema &S;
9925 bool Enabled;
9926 };
9927
9928 /// The queue of implicit template instantiations that are required
9929 /// and must be performed within the current local scope.
9930 ///
9931 /// This queue is only used for member functions of local classes in
9932 /// templates, which must be instantiated in the same scope as their
9933 /// enclosing function, so that they can reference function-local
9934 /// types, static variables, enumerators, etc.
9935 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
9936
9937 class LocalEagerInstantiationScope {
9938 public:
9939 LocalEagerInstantiationScope(Sema &S) : S(S) {
9940 SavedPendingLocalImplicitInstantiations.swap(
9941 S.PendingLocalImplicitInstantiations);
9942 }
9943
9944 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
9945
9946 ~LocalEagerInstantiationScope() {
9947 assert(S.PendingLocalImplicitInstantiations.empty() &&(static_cast <bool> (S.PendingLocalImplicitInstantiations
.empty() && "there shouldn't be any pending local implicit instantiations"
) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "clang/include/clang/Sema/Sema.h", 9948, __extension__ __PRETTY_FUNCTION__
))
9948 "there shouldn't be any pending local implicit instantiations")(static_cast <bool> (S.PendingLocalImplicitInstantiations
.empty() && "there shouldn't be any pending local implicit instantiations"
) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "clang/include/clang/Sema/Sema.h", 9948, __extension__ __PRETTY_FUNCTION__
))
;
9949 SavedPendingLocalImplicitInstantiations.swap(
9950 S.PendingLocalImplicitInstantiations);
9951 }
9952
9953 private:
9954 Sema &S;
9955 std::deque<PendingImplicitInstantiation>
9956 SavedPendingLocalImplicitInstantiations;
9957 };
9958
9959 /// A helper class for building up ExtParameterInfos.
9960 class ExtParameterInfoBuilder {
9961 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
9962 bool HasInteresting = false;
9963
9964 public:
9965 /// Set the ExtParameterInfo for the parameter at the given index,
9966 ///
9967 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
9968 assert(Infos.size() <= index)(static_cast <bool> (Infos.size() <= index) ? void (
0) : __assert_fail ("Infos.size() <= index", "clang/include/clang/Sema/Sema.h"
, 9968, __extension__ __PRETTY_FUNCTION__))
;
9969 Infos.resize(index);
9970 Infos.push_back(info);
9971
9972 if (!HasInteresting)
9973 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
9974 }
9975
9976 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
9977 /// ExtParameterInfo array we've built up.
9978 const FunctionProtoType::ExtParameterInfo *
9979 getPointerOrNull(unsigned numParams) {
9980 if (!HasInteresting) return nullptr;
9981 Infos.resize(numParams);
9982 return Infos.data();
9983 }
9984 };
9985
9986 void PerformPendingInstantiations(bool LocalOnly = false);
9987
9988 TypeSourceInfo *SubstType(TypeSourceInfo *T,
9989 const MultiLevelTemplateArgumentList &TemplateArgs,
9990 SourceLocation Loc, DeclarationName Entity,
9991 bool AllowDeducedTST = false);
9992
9993 QualType SubstType(QualType T,
9994 const MultiLevelTemplateArgumentList &TemplateArgs,
9995 SourceLocation Loc, DeclarationName Entity);
9996
9997 TypeSourceInfo *SubstType(TypeLoc TL,
9998 const MultiLevelTemplateArgumentList &TemplateArgs,
9999 SourceLocation Loc, DeclarationName Entity);
10000
10001 TypeSourceInfo *SubstFunctionDeclType(
10002 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
10003 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
10004 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
10005 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
10006 const MultiLevelTemplateArgumentList &Args);
10007 bool SubstExceptionSpec(SourceLocation Loc,
10008 FunctionProtoType::ExceptionSpecInfo &ESI,
10009 SmallVectorImpl<QualType> &ExceptionStorage,
10010 const MultiLevelTemplateArgumentList &Args);
10011 ParmVarDecl *
10012 SubstParmVarDecl(ParmVarDecl *D,
10013 const MultiLevelTemplateArgumentList &TemplateArgs,
10014 int indexAdjustment, std::optional<unsigned> NumExpansions,
10015 bool ExpectParameterPack, bool EvaluateConstraints = true);
10016 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
10017 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
10018 const MultiLevelTemplateArgumentList &TemplateArgs,
10019 SmallVectorImpl<QualType> &ParamTypes,
10020 SmallVectorImpl<ParmVarDecl *> *OutParams,
10021 ExtParameterInfoBuilder &ParamInfos);
10022 bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param,
10023 const MultiLevelTemplateArgumentList &TemplateArgs,
10024 bool ForCallExpr = false);
10025 ExprResult SubstExpr(Expr *E,
10026 const MultiLevelTemplateArgumentList &TemplateArgs);
10027
10028 // A RAII type used by the TemplateDeclInstantiator and TemplateInstantiator
10029 // to disable constraint evaluation, then restore the state.
10030 template <typename InstTy> struct ConstraintEvalRAII {
10031 InstTy &TI;
10032 bool OldValue;
10033
10034 ConstraintEvalRAII(InstTy &TI)
10035 : TI(TI), OldValue(TI.getEvaluateConstraints()) {
10036 TI.setEvaluateConstraints(false);
10037 }
10038 ~ConstraintEvalRAII() { TI.setEvaluateConstraints(OldValue); }
10039 };
10040
10041 // Unlike the above, this evaluates constraints, which should only happen at
10042 // 'constraint checking' time.
10043 ExprResult
10044 SubstConstraintExpr(Expr *E,
10045 const MultiLevelTemplateArgumentList &TemplateArgs);
10046
10047 /// Substitute the given template arguments into a list of
10048 /// expressions, expanding pack expansions if required.
10049 ///
10050 /// \param Exprs The list of expressions to substitute into.
10051 ///
10052 /// \param IsCall Whether this is some form of call, in which case
10053 /// default arguments will be dropped.
10054 ///
10055 /// \param TemplateArgs The set of template arguments to substitute.
10056 ///
10057 /// \param Outputs Will receive all of the substituted arguments.
10058 ///
10059 /// \returns true if an error occurred, false otherwise.
10060 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
10061 const MultiLevelTemplateArgumentList &TemplateArgs,
10062 SmallVectorImpl<Expr *> &Outputs);
10063
10064 StmtResult SubstStmt(Stmt *S,
10065 const MultiLevelTemplateArgumentList &TemplateArgs);
10066
10067 TemplateParameterList *
10068 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
10069 const MultiLevelTemplateArgumentList &TemplateArgs,
10070 bool EvaluateConstraints = true);
10071
10072 bool
10073 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
10074 const MultiLevelTemplateArgumentList &TemplateArgs,
10075 TemplateArgumentListInfo &Outputs);
10076
10077 Decl *SubstDecl(Decl *D, DeclContext *Owner,
10078 const MultiLevelTemplateArgumentList &TemplateArgs);
10079
10080 /// Substitute the name and return type of a defaulted 'operator<=>' to form
10081 /// an implicit 'operator=='.
10082 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
10083 FunctionDecl *Spaceship);
10084
10085 ExprResult SubstInitializer(Expr *E,
10086 const MultiLevelTemplateArgumentList &TemplateArgs,
10087 bool CXXDirectInit);
10088
10089 bool
10090 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
10091 CXXRecordDecl *Pattern,
10092 const MultiLevelTemplateArgumentList &TemplateArgs);
10093
10094 bool
10095 InstantiateClass(SourceLocation PointOfInstantiation,
10096 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
10097 const MultiLevelTemplateArgumentList &TemplateArgs,
10098 TemplateSpecializationKind TSK,
10099 bool Complain = true);
10100
10101 bool InstantiateEnum(SourceLocation PointOfInstantiation,
10102 EnumDecl *Instantiation, EnumDecl *Pattern,
10103 const MultiLevelTemplateArgumentList &TemplateArgs,
10104 TemplateSpecializationKind TSK);
10105
10106 bool InstantiateInClassInitializer(
10107 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
10108 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
10109
10110 struct LateInstantiatedAttribute {
10111 const Attr *TmplAttr;
10112 LocalInstantiationScope *Scope;
10113 Decl *NewDecl;
10114
10115 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
10116 Decl *D)
10117 : TmplAttr(A), Scope(S), NewDecl(D)
10118 { }
10119 };
10120 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
10121
10122 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
10123 const Decl *Pattern, Decl *Inst,
10124 LateInstantiatedAttrVec *LateAttrs = nullptr,
10125 LocalInstantiationScope *OuterMostScope = nullptr);
10126 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
10127
10128 void
10129 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
10130 const Decl *Pattern, Decl *Inst,
10131 LateInstantiatedAttrVec *LateAttrs = nullptr,
10132 LocalInstantiationScope *OuterMostScope = nullptr);
10133
10134 void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
10135
10136 bool usesPartialOrExplicitSpecialization(
10137 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
10138
10139 bool
10140 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
10141 ClassTemplateSpecializationDecl *ClassTemplateSpec,
10142 TemplateSpecializationKind TSK,
10143 bool Complain = true);
10144
10145 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
10146 CXXRecordDecl *Instantiation,
10147 const MultiLevelTemplateArgumentList &TemplateArgs,
10148 TemplateSpecializationKind TSK);
10149
10150 void InstantiateClassTemplateSpecializationMembers(
10151 SourceLocation PointOfInstantiation,
10152 ClassTemplateSpecializationDecl *ClassTemplateSpec,
10153 TemplateSpecializationKind TSK);
10154
10155 NestedNameSpecifierLoc
10156 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
10157 const MultiLevelTemplateArgumentList &TemplateArgs);
10158
10159 DeclarationNameInfo
10160 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
10161 const MultiLevelTemplateArgumentList &TemplateArgs);
10162 TemplateName
10163 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
10164 SourceLocation Loc,
10165 const MultiLevelTemplateArgumentList &TemplateArgs);
10166
10167 bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
10168 const MultiLevelTemplateArgumentList &TemplateArgs,
10169 bool EvaluateConstraint);
10170
10171 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
10172 ParmVarDecl *Param);
10173 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
10174 FunctionDecl *Function);
10175 bool CheckInstantiatedFunctionTemplateConstraints(
10176 SourceLocation PointOfInstantiation, FunctionDecl *Decl,
10177 ArrayRef<TemplateArgument> TemplateArgs,
10178 ConstraintSatisfaction &Satisfaction);
10179 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
10180 const TemplateArgumentList *Args,
10181 SourceLocation Loc);
10182 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
10183 FunctionDecl *Function,
10184 bool Recursive = false,
10185 bool DefinitionRequired = false,
10186 bool AtEndOfTU = false);
10187 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
10188 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
10189 const TemplateArgumentList &TemplateArgList,
10190 const TemplateArgumentListInfo &TemplateArgsInfo,
10191 SmallVectorImpl<TemplateArgument> &Converted,
10192 SourceLocation PointOfInstantiation,
10193 LateInstantiatedAttrVec *LateAttrs = nullptr,
10194 LocalInstantiationScope *StartingScope = nullptr);
10195 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
10196 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
10197 const MultiLevelTemplateArgumentList &TemplateArgs);
10198 void
10199 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
10200 const MultiLevelTemplateArgumentList &TemplateArgs,
10201 LateInstantiatedAttrVec *LateAttrs,
10202 DeclContext *Owner,
10203 LocalInstantiationScope *StartingScope,
10204 bool InstantiatingVarTemplate = false,
10205 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
10206
10207 void InstantiateVariableInitializer(
10208 VarDecl *Var, VarDecl *OldVar,
10209 const MultiLevelTemplateArgumentList &TemplateArgs);
10210 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
10211 VarDecl *Var, bool Recursive = false,
10212 bool DefinitionRequired = false,
10213 bool AtEndOfTU = false);
10214
10215 void InstantiateMemInitializers(CXXConstructorDecl *New,
10216 const CXXConstructorDecl *Tmpl,
10217 const MultiLevelTemplateArgumentList &TemplateArgs);
10218
10219 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
10220 const MultiLevelTemplateArgumentList &TemplateArgs,
10221 bool FindingInstantiatedContext = false);
10222 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
10223 const MultiLevelTemplateArgumentList &TemplateArgs);
10224
10225 // Objective-C declarations.
10226 enum ObjCContainerKind {
10227 OCK_None = -1,
10228 OCK_Interface = 0,
10229 OCK_Protocol,
10230 OCK_Category,
10231 OCK_ClassExtension,
10232 OCK_Implementation,
10233 OCK_CategoryImplementation
10234 };
10235 ObjCContainerKind getObjCContainerKind() const;
10236
10237 DeclResult actOnObjCTypeParam(Scope *S,
10238 ObjCTypeParamVariance variance,
10239 SourceLocation varianceLoc,
10240 unsigned index,
10241 IdentifierInfo *paramName,
10242 SourceLocation paramLoc,
10243 SourceLocation colonLoc,
10244 ParsedType typeBound);
10245
10246 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
10247 ArrayRef<Decl *> typeParams,
10248 SourceLocation rAngleLoc);
10249 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
10250
10251 ObjCInterfaceDecl *ActOnStartClassInterface(
10252 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
10253 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
10254 IdentifierInfo *SuperName, SourceLocation SuperLoc,
10255 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
10256 Decl *const *ProtoRefs, unsigned NumProtoRefs,
10257 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
10258 const ParsedAttributesView &AttrList, SkipBodyInfo *SkipBody);
10259
10260 void ActOnSuperClassOfClassInterface(Scope *S,
10261 SourceLocation AtInterfaceLoc,
10262 ObjCInterfaceDecl *IDecl,
10263 IdentifierInfo *ClassName,
10264 SourceLocation ClassLoc,
10265 IdentifierInfo *SuperName,
10266 SourceLocation SuperLoc,
10267 ArrayRef<ParsedType> SuperTypeArgs,
10268 SourceRange SuperTypeArgsRange);
10269
10270 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
10271 SmallVectorImpl<SourceLocation> &ProtocolLocs,
10272 IdentifierInfo *SuperName,
10273 SourceLocation SuperLoc);
10274
10275 Decl *ActOnCompatibilityAlias(
10276 SourceLocation AtCompatibilityAliasLoc,
10277 IdentifierInfo *AliasName, SourceLocation AliasLocation,
10278 IdentifierInfo *ClassName, SourceLocation ClassLocation);
10279
10280 bool CheckForwardProtocolDeclarationForCircularDependency(
10281 IdentifierInfo *PName,
10282 SourceLocation &PLoc, SourceLocation PrevLoc,
10283 const ObjCList<ObjCProtocolDecl> &PList);
10284
10285 ObjCProtocolDecl *ActOnStartProtocolInterface(
10286 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
10287 SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
10288 unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
10289 SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList,
10290 SkipBodyInfo *SkipBody);
10291
10292 ObjCCategoryDecl *ActOnStartCategoryInterface(
10293 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
10294 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
10295 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
10296 Decl *const *ProtoRefs, unsigned NumProtoRefs,
10297 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
10298 const ParsedAttributesView &AttrList);
10299
10300 ObjCImplementationDecl *ActOnStartClassImplementation(
10301 SourceLocation AtClassImplLoc, IdentifierInfo *ClassName,
10302 SourceLocation ClassLoc, IdentifierInfo *SuperClassname,
10303 SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList);
10304
10305 ObjCCategoryImplDecl *ActOnStartCategoryImplementation(
10306 SourceLocation AtCatImplLoc, IdentifierInfo *ClassName,
10307 SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc,
10308 const ParsedAttributesView &AttrList);
10309
10310 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
10311 ArrayRef<Decl *> Decls);
10312
10313 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
10314 IdentifierInfo **IdentList,
10315 SourceLocation *IdentLocs,
10316 ArrayRef<ObjCTypeParamList *> TypeParamLists,
10317 unsigned NumElts);
10318
10319 DeclGroupPtrTy
10320 ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
10321 ArrayRef<IdentifierLocPair> IdentList,
10322 const ParsedAttributesView &attrList);
10323
10324 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
10325 ArrayRef<IdentifierLocPair> ProtocolId,
10326 SmallVectorImpl<Decl *> &Protocols);
10327
10328 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
10329 SourceLocation ProtocolLoc,
10330 IdentifierInfo *TypeArgId,
10331 SourceLocation TypeArgLoc,
10332 bool SelectProtocolFirst = false);
10333
10334 /// Given a list of identifiers (and their locations), resolve the
10335 /// names to either Objective-C protocol qualifiers or type
10336 /// arguments, as appropriate.
10337 void actOnObjCTypeArgsOrProtocolQualifiers(
10338 Scope *S,
10339 ParsedType baseType,
10340 SourceLocation lAngleLoc,
10341 ArrayRef<IdentifierInfo *> identifiers,
10342 ArrayRef<SourceLocation> identifierLocs,
10343 SourceLocation rAngleLoc,
10344 SourceLocation &typeArgsLAngleLoc,
10345 SmallVectorImpl<ParsedType> &typeArgs,
10346 SourceLocation &typeArgsRAngleLoc,
10347 SourceLocation &protocolLAngleLoc,
10348 SmallVectorImpl<Decl *> &protocols,
10349 SourceLocation &protocolRAngleLoc,
10350 bool warnOnIncompleteProtocols);
10351
10352 /// Build a an Objective-C protocol-qualified 'id' type where no
10353 /// base type was specified.
10354 TypeResult actOnObjCProtocolQualifierType(
10355 SourceLocation lAngleLoc,
10356 ArrayRef<Decl *> protocols,
10357 ArrayRef<SourceLocation> protocolLocs,
10358 SourceLocation rAngleLoc);
10359
10360 /// Build a specialized and/or protocol-qualified Objective-C type.
10361 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
10362 Scope *S,
10363 SourceLocation Loc,
10364 ParsedType BaseType,
10365 SourceLocation TypeArgsLAngleLoc,
10366 ArrayRef<ParsedType> TypeArgs,
10367 SourceLocation TypeArgsRAngleLoc,
10368 SourceLocation ProtocolLAngleLoc,
10369 ArrayRef<Decl *> Protocols,
10370 ArrayRef<SourceLocation> ProtocolLocs,
10371 SourceLocation ProtocolRAngleLoc);
10372
10373 /// Build an Objective-C type parameter type.
10374 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
10375 SourceLocation ProtocolLAngleLoc,
10376 ArrayRef<ObjCProtocolDecl *> Protocols,
10377 ArrayRef<SourceLocation> ProtocolLocs,
10378 SourceLocation ProtocolRAngleLoc,
10379 bool FailOnError = false);
10380
10381 /// Build an Objective-C object pointer type.
10382 QualType BuildObjCObjectType(
10383 QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc,
10384 ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc,
10385 SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols,
10386 ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc,
10387 bool FailOnError, bool Rebuilding);
10388
10389 /// Ensure attributes are consistent with type.
10390 /// \param [in, out] Attributes The attributes to check; they will
10391 /// be modified to be consistent with \p PropertyTy.
10392 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
10393 SourceLocation Loc,
10394 unsigned &Attributes,
10395 bool propertyInPrimaryClass);
10396
10397 /// Process the specified property declaration and create decls for the
10398 /// setters and getters as needed.
10399 /// \param property The property declaration being processed
10400 void ProcessPropertyDecl(ObjCPropertyDecl *property);
10401
10402
10403 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
10404 ObjCPropertyDecl *SuperProperty,
10405 const IdentifierInfo *Name,
10406 bool OverridingProtocolProperty);
10407
10408 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
10409 ObjCInterfaceDecl *ID);
10410
10411 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
10412 ArrayRef<Decl *> allMethods = std::nullopt,
10413 ArrayRef<DeclGroupPtrTy> allTUVars = std::nullopt);
10414
10415 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
10416 SourceLocation LParenLoc,
10417 FieldDeclarator &FD, ObjCDeclSpec &ODS,
10418 Selector GetterSel, Selector SetterSel,
10419 tok::ObjCKeywordKind MethodImplKind,
10420 DeclContext *lexicalDC = nullptr);
10421
10422 Decl *ActOnPropertyImplDecl(Scope *S,
10423 SourceLocation AtLoc,
10424 SourceLocation PropertyLoc,
10425 bool ImplKind,
10426 IdentifierInfo *PropertyId,
10427 IdentifierInfo *PropertyIvar,
10428 SourceLocation PropertyIvarLoc,
10429 ObjCPropertyQueryKind QueryKind);
10430
10431 enum ObjCSpecialMethodKind {
10432 OSMK_None,
10433 OSMK_Alloc,
10434 OSMK_New,
10435 OSMK_Copy,
10436 OSMK_RetainingInit,
10437 OSMK_NonRetainingInit
10438 };
10439
10440 struct ObjCArgInfo {
10441 IdentifierInfo *Name;
10442 SourceLocation NameLoc;
10443 // The Type is null if no type was specified, and the DeclSpec is invalid
10444 // in this case.
10445 ParsedType Type;
10446 ObjCDeclSpec DeclSpec;
10447
10448 /// ArgAttrs - Attribute list for this argument.
10449 ParsedAttributesView ArgAttrs;
10450 };
10451
10452 Decl *ActOnMethodDeclaration(
10453 Scope *S,
10454 SourceLocation BeginLoc, // location of the + or -.
10455 SourceLocation EndLoc, // location of the ; or {.
10456 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
10457 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
10458 // optional arguments. The number of types/arguments is obtained
10459 // from the Sel.getNumArgs().
10460 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
10461 unsigned CNumArgs, // c-style args
10462 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
10463 bool isVariadic, bool MethodDefinition);
10464
10465 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
10466 const ObjCObjectPointerType *OPT,
10467 bool IsInstance);
10468 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
10469 bool IsInstance);
10470
10471 bool CheckARCMethodDecl(ObjCMethodDecl *method);
10472 bool inferObjCARCLifetime(ValueDecl *decl);
10473
10474 void deduceOpenCLAddressSpace(ValueDecl *decl);
10475
10476 ExprResult
10477 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
10478 Expr *BaseExpr,
10479 SourceLocation OpLoc,
10480 DeclarationName MemberName,
10481 SourceLocation MemberLoc,
10482 SourceLocation SuperLoc, QualType SuperType,
10483 bool Super);
10484
10485 ExprResult
10486 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
10487 IdentifierInfo &propertyName,
10488 SourceLocation receiverNameLoc,
10489 SourceLocation propertyNameLoc);
10490
10491 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
10492
10493 /// Describes the kind of message expression indicated by a message
10494 /// send that starts with an identifier.
10495 enum ObjCMessageKind {
10496 /// The message is sent to 'super'.
10497 ObjCSuperMessage,
10498 /// The message is an instance message.
10499 ObjCInstanceMessage,
10500 /// The message is a class message, and the identifier is a type
10501 /// name.
10502 ObjCClassMessage
10503 };
10504
10505 ObjCMessageKind getObjCMessageKind(Scope *S,
10506 IdentifierInfo *Name,
10507 SourceLocation NameLoc,
10508 bool IsSuper,
10509 bool HasTrailingDot,
10510 ParsedType &ReceiverType);
10511
10512 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
10513 Selector Sel,
10514 SourceLocation LBracLoc,
10515 ArrayRef<SourceLocation> SelectorLocs,
10516 SourceLocation RBracLoc,
10517 MultiExprArg Args);
10518
10519 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
10520 QualType ReceiverType,
10521 SourceLocation SuperLoc,
10522 Selector Sel,
10523 ObjCMethodDecl *Method,
10524 SourceLocation LBracLoc,
10525 ArrayRef<SourceLocation> SelectorLocs,
10526 SourceLocation RBracLoc,
10527 MultiExprArg Args,
10528 bool isImplicit = false);
10529
10530 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
10531 bool isSuperReceiver,
10532 SourceLocation Loc,
10533 Selector Sel,
10534 ObjCMethodDecl *Method,
10535 MultiExprArg Args);
10536
10537 ExprResult ActOnClassMessage(Scope *S,
10538 ParsedType Receiver,
10539 Selector Sel,
10540 SourceLocation LBracLoc,
10541 ArrayRef<SourceLocation> SelectorLocs,
10542 SourceLocation RBracLoc,
10543 MultiExprArg Args);
10544
10545 ExprResult BuildInstanceMessage(Expr *Receiver,
10546 QualType ReceiverType,
10547 SourceLocation SuperLoc,
10548 Selector Sel,
10549 ObjCMethodDecl *Method,
10550 SourceLocation LBracLoc,
10551 ArrayRef<SourceLocation> SelectorLocs,
10552 SourceLocation RBracLoc,
10553 MultiExprArg Args,
10554 bool isImplicit = false);
10555
10556 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
10557 QualType ReceiverType,
10558 SourceLocation Loc,
10559 Selector Sel,
10560 ObjCMethodDecl *Method,
10561 MultiExprArg Args);
10562
10563 ExprResult ActOnInstanceMessage(Scope *S,
10564 Expr *Receiver,
10565 Selector Sel,
10566 SourceLocation LBracLoc,
10567 ArrayRef<SourceLocation> SelectorLocs,
10568 SourceLocation RBracLoc,
10569 MultiExprArg Args);
10570
10571 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
10572 ObjCBridgeCastKind Kind,
10573 SourceLocation BridgeKeywordLoc,
10574 TypeSourceInfo *TSInfo,
10575 Expr *SubExpr);
10576
10577 ExprResult ActOnObjCBridgedCast(Scope *S,
10578 SourceLocation LParenLoc,
10579 ObjCBridgeCastKind Kind,
10580 SourceLocation BridgeKeywordLoc,
10581 ParsedType Type,
10582 SourceLocation RParenLoc,
10583 Expr *SubExpr);
10584
10585 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
10586
10587 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
10588
10589 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
10590 CastKind &Kind);
10591
10592 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
10593 QualType DestType, QualType SrcType,
10594 ObjCInterfaceDecl *&RelatedClass,
10595 ObjCMethodDecl *&ClassMethod,
10596 ObjCMethodDecl *&InstanceMethod,
10597 TypedefNameDecl *&TDNDecl,
10598 bool CfToNs, bool Diagnose = true);
10599
10600 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
10601 QualType DestType, QualType SrcType,
10602 Expr *&SrcExpr, bool Diagnose = true);
10603
10604 bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr,
10605 bool Diagnose = true);
10606
10607 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
10608
10609 /// Check whether the given new method is a valid override of the
10610 /// given overridden method, and set any properties that should be inherited.
10611 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
10612 const ObjCMethodDecl *Overridden);
10613
10614 /// Describes the compatibility of a result type with its method.
10615 enum ResultTypeCompatibilityKind {
10616 RTC_Compatible,
10617 RTC_Incompatible,
10618 RTC_Unknown
10619 };
10620
10621 void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
10622 ObjCMethodDecl *overridden);
10623
10624 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
10625 ObjCInterfaceDecl *CurrentClass,
10626 ResultTypeCompatibilityKind RTC);
10627
10628 enum PragmaOptionsAlignKind {
10629 POAK_Native, // #pragma options align=native
10630 POAK_Natural, // #pragma options align=natural
10631 POAK_Packed, // #pragma options align=packed
10632 POAK_Power, // #pragma options align=power
10633 POAK_Mac68k, // #pragma options align=mac68k
10634 POAK_Reset // #pragma options align=reset
10635 };
10636
10637 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
10638 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
10639 PragmaClangSectionAction Action,
10640 PragmaClangSectionKind SecKind, StringRef SecName);
10641
10642 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
10643 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
10644 SourceLocation PragmaLoc);
10645
10646 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
10647 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
10648 StringRef SlotLabel, Expr *Alignment);
10649
10650 enum class PragmaAlignPackDiagnoseKind {
10651 NonDefaultStateAtInclude,
10652 ChangedStateAtExit
10653 };
10654
10655 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
10656 SourceLocation IncludeLoc);
10657 void DiagnoseUnterminatedPragmaAlignPack();
10658
10659 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
10660 /// strict_gs_check.
10661 void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
10662 PragmaMsStackAction Action,
10663 bool Value);
10664
10665 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
10666 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
10667
10668 /// ActOnPragmaMSComment - Called on well formed
10669 /// \#pragma comment(kind, "arg").
10670 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
10671 StringRef Arg);
10672
10673 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
10674 /// pointers_to_members(representation method[, general purpose
10675 /// representation]).
10676 void ActOnPragmaMSPointersToMembers(
10677 LangOptions::PragmaMSPointersToMembersKind Kind,
10678 SourceLocation PragmaLoc);
10679
10680 /// Called on well formed \#pragma vtordisp().
10681 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
10682 SourceLocation PragmaLoc,
10683 MSVtorDispMode Value);
10684
10685 enum PragmaSectionKind {
10686 PSK_DataSeg,
10687 PSK_BSSSeg,
10688 PSK_ConstSeg,
10689 PSK_CodeSeg,
10690 };
10691
10692 bool UnifySection(StringRef SectionName, int SectionFlags,
10693 NamedDecl *TheDecl);
10694 bool UnifySection(StringRef SectionName,
10695 int SectionFlags,
10696 SourceLocation PragmaSectionLocation);
10697
10698 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
10699 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
10700 PragmaMsStackAction Action,
10701 llvm::StringRef StackSlotLabel,
10702 StringLiteral *SegmentName,
10703 llvm::StringRef PragmaName);
10704
10705 /// Called on well formed \#pragma section().
10706 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
10707 int SectionFlags, StringLiteral *SegmentName);
10708
10709 /// Called on well-formed \#pragma init_seg().
10710 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
10711 StringLiteral *SegmentName);
10712
10713 /// Called on well-formed \#pragma alloc_text().
10714 void ActOnPragmaMSAllocText(
10715 SourceLocation PragmaLocation, StringRef Section,
10716 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
10717 &Functions);
10718
10719 /// Called on #pragma clang __debug dump II
10720 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
10721
10722 /// Called on #pragma clang __debug dump E
10723 void ActOnPragmaDump(Expr *E);
10724
10725 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
10726 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
10727 StringRef Value);
10728
10729 /// Are precise floating point semantics currently enabled?
10730 bool isPreciseFPEnabled() {
10731 return !CurFPFeatures.getAllowFPReassociate() &&
10732 !CurFPFeatures.getNoSignedZero() &&
10733 !CurFPFeatures.getAllowReciprocal() &&
10734 !CurFPFeatures.getAllowApproxFunc();
10735 }
10736
10737 void ActOnPragmaFPEvalMethod(SourceLocation Loc,
10738 LangOptions::FPEvalMethodKind Value);
10739
10740 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
10741 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
10742 PragmaFloatControlKind Value);
10743
10744 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
10745 void ActOnPragmaUnused(const Token &Identifier,
10746 Scope *curScope,
10747 SourceLocation PragmaLoc);
10748
10749 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
10750 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
10751 SourceLocation PragmaLoc);
10752
10753 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
10754 SourceLocation Loc);
10755 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
10756
10757 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
10758 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
10759 SourceLocation PragmaLoc,
10760 SourceLocation WeakNameLoc);
10761
10762 /// ActOnPragmaRedefineExtname - Called on well formed
10763 /// \#pragma redefine_extname oldname newname.
10764 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
10765 IdentifierInfo* AliasName,
10766 SourceLocation PragmaLoc,
10767 SourceLocation WeakNameLoc,
10768 SourceLocation AliasNameLoc);
10769
10770 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
10771 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
10772 IdentifierInfo* AliasName,
10773 SourceLocation PragmaLoc,
10774 SourceLocation WeakNameLoc,
10775 SourceLocation AliasNameLoc);
10776
10777 /// ActOnPragmaFPContract - Called on well formed
10778 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
10779 /// \#pragma clang fp contract
10780 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
10781
10782 /// Called on well formed
10783 /// \#pragma clang fp reassociate
10784 void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled);
10785
10786 /// ActOnPragmaFenvAccess - Called on well formed
10787 /// \#pragma STDC FENV_ACCESS
10788 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
10789
10790 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
10791 void ActOnPragmaFPExceptions(SourceLocation Loc,
10792 LangOptions::FPExceptionModeKind);
10793
10794 /// Called to set constant rounding mode for floating point operations.
10795 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
10796
10797 /// Called to set exception behavior for floating point operations.
10798 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
10799
10800 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
10801 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
10802 void AddAlignmentAttributesForRecord(RecordDecl *RD);
10803
10804 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
10805 void AddMsStructLayoutForRecord(RecordDecl *RD);
10806
10807 /// PushNamespaceVisibilityAttr - Note that we've entered a
10808 /// namespace with a visibility attribute.
10809 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
10810 SourceLocation Loc);
10811
10812 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
10813 /// add an appropriate visibility attribute.
10814 void AddPushedVisibilityAttribute(Decl *RD);
10815
10816 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
10817 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
10818 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
10819
10820 /// FreeVisContext - Deallocate and null out VisContext.
10821 void FreeVisContext();
10822
10823 /// AddCFAuditedAttribute - Check whether we're currently within
10824 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
10825 /// the appropriate attribute.
10826 void AddCFAuditedAttribute(Decl *D);
10827
10828 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
10829 SourceLocation PragmaLoc,
10830 attr::ParsedSubjectMatchRuleSet Rules);
10831 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
10832 const IdentifierInfo *Namespace);
10833
10834 /// Called on well-formed '\#pragma clang attribute pop'.
10835 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
10836 const IdentifierInfo *Namespace);
10837
10838 /// Adds the attributes that have been specified using the
10839 /// '\#pragma clang attribute push' directives to the given declaration.
10840 void AddPragmaAttributes(Scope *S, Decl *D);
10841
10842 void DiagnoseUnterminatedPragmaAttribute();
10843
10844 /// Called on well formed \#pragma clang optimize.
10845 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
10846
10847 /// #pragma optimize("[optimization-list]", on | off).
10848 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
10849
10850 /// Call on well formed \#pragma function.
10851 void
10852 ActOnPragmaMSFunction(SourceLocation Loc,
10853 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
10854
10855 /// Get the location for the currently active "\#pragma clang optimize
10856 /// off". If this location is invalid, then the state of the pragma is "on".
10857 SourceLocation getOptimizeOffPragmaLocation() const {
10858 return OptimizeOffPragmaLocation;
10859 }
10860
10861 /// Only called on function definitions; if there is a pragma in scope
10862 /// with the effect of a range-based optnone, consider marking the function
10863 /// with attribute optnone.
10864 void AddRangeBasedOptnone(FunctionDecl *FD);
10865
10866 /// Only called on function definitions; if there is a `#pragma alloc_text`
10867 /// that decides which code section the function should be in, add
10868 /// attribute section to the function.
10869 void AddSectionMSAllocText(FunctionDecl *FD);
10870
10871 /// Adds the 'optnone' attribute to the function declaration if there
10872 /// are no conflicts; Loc represents the location causing the 'optnone'
10873 /// attribute to be added (usually because of a pragma).
10874 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
10875
10876 /// Only called on function definitions; if there is a MSVC #pragma optimize
10877 /// in scope, consider changing the function's attributes based on the
10878 /// optimization list passed to the pragma.
10879 void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD);
10880
10881 /// Only called on function definitions; if there is a pragma in scope
10882 /// with the effect of a range-based no_builtin, consider marking the function
10883 /// with attribute no_builtin.
10884 void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
10885
10886 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
10887 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10888 bool IsPackExpansion);
10889 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
10890 bool IsPackExpansion);
10891
10892 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
10893 /// declaration.
10894 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10895 Expr *OE);
10896
10897 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
10898 /// declaration.
10899 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
10900 Expr *ParamExpr);
10901
10902 /// AddAlignValueAttr - Adds an align_value attribute to a particular
10903 /// declaration.
10904 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
10905
10906 /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
10907 void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
10908 StringRef Annot, MutableArrayRef<Expr *> Args);
10909
10910 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
10911 /// (unless they are value dependent or type dependent). Returns false
10912 /// and emits a diagnostic if one or more of the arguments could not be
10913 /// folded into a constant.
10914 bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
10915 MutableArrayRef<Expr *> Args);
10916
10917 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
10918 /// declaration.
10919 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
10920 Expr *MaxThreads, Expr *MinBlocks);
10921
10922 /// AddModeAttr - Adds a mode attribute to a particular declaration.
10923 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
10924 bool InInstantiation = false);
10925
10926 void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
10927 ParameterABI ABI);
10928
10929 enum class RetainOwnershipKind {NS, CF, OS};
10930 void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
10931 RetainOwnershipKind K, bool IsTemplateInstantiation);
10932
10933 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
10934 /// attribute to a particular declaration.
10935 void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
10936 Expr *Min, Expr *Max);
10937
10938 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
10939 /// particular declaration.
10940 void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
10941 Expr *Min, Expr *Max);
10942
10943 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
10944
10945 //===--------------------------------------------------------------------===//
10946 // C++ Coroutines
10947 //
10948 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
10949 StringRef Keyword);
10950 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10951 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10952 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
10953
10954 ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
10955 ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
10956 UnresolvedLookupExpr *Lookup);
10957 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
10958 Expr *Awaiter, bool IsImplicit = false);
10959 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
10960 UnresolvedLookupExpr *Lookup);
10961 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
10962 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
10963 bool IsImplicit = false);
10964 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
10965 bool buildCoroutineParameterMoves(SourceLocation Loc);
10966 VarDecl *buildCoroutinePromise(SourceLocation Loc);
10967 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
10968 /// Lookup 'coroutine_traits' in std namespace and std::experimental
10969 /// namespace. The namespace found is recorded in Namespace.
10970 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
10971 SourceLocation FuncLoc);
10972 /// Check that the expression co_await promise.final_suspend() shall not be
10973 /// potentially-throwing.
10974 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
10975
10976 //===--------------------------------------------------------------------===//
10977 // OpenMP directives and clauses.
10978 //
10979private:
10980 void *VarDataSharingAttributesStack;
10981
10982 struct DeclareTargetContextInfo {
10983 struct MapInfo {
10984 OMPDeclareTargetDeclAttr::MapTypeTy MT;
10985 SourceLocation Loc;
10986 };
10987 /// Explicitly listed variables and functions in a 'to' or 'link' clause.
10988 llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped;
10989
10990 /// The 'device_type' as parsed from the clause.
10991 OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any;
10992
10993 /// The directive kind, `begin declare target` or `declare target`.
10994 OpenMPDirectiveKind Kind;
10995
10996 /// The directive with indirect clause.
10997 std::optional<Expr *> Indirect;
10998
10999 /// The directive location.
11000 SourceLocation Loc;
11001
11002 DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc)
11003 : Kind(Kind), Loc(Loc) {}
11004 };
11005
11006 /// Number of nested '#pragma omp declare target' directives.
11007 SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting;
11008
11009 /// Initialization of data-sharing attributes stack.
11010 void InitDataSharingAttributesStack();
11011 void DestroyDataSharingAttributesStack();
11012 ExprResult
11013 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
11014 bool StrictlyPositive = true,
11015 bool SuppressExprDiags = false);
11016 /// Returns OpenMP nesting level for current directive.
11017 unsigned getOpenMPNestingLevel() const;
11018
11019 /// Adjusts the function scopes index for the target-based regions.
11020 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
11021 unsigned Level) const;
11022
11023 /// Returns the number of scopes associated with the construct on the given
11024 /// OpenMP level.
11025 int getNumberOfConstructScopes(unsigned Level) const;
11026
11027 /// Push new OpenMP function region for non-capturing function.
11028 void pushOpenMPFunctionRegion();
11029
11030 /// Pop OpenMP function region for non-capturing function.
11031 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
11032
11033 /// Analyzes and checks a loop nest for use by a loop transformation.
11034 ///
11035 /// \param Kind The loop transformation directive kind.
11036 /// \param NumLoops How many nested loops the directive is expecting.
11037 /// \param AStmt Associated statement of the transformation directive.
11038 /// \param LoopHelpers [out] The loop analysis result.
11039 /// \param Body [out] The body code nested in \p NumLoops loop.
11040 /// \param OriginalInits [out] Collection of statements and declarations that
11041 /// must have been executed/declared before entering the
11042 /// loop.
11043 ///
11044 /// \return Whether there was any error.
11045 bool checkTransformableLoopNest(
11046 OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
11047 SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
11048 Stmt *&Body,
11049 SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
11050 &OriginalInits);
11051
11052 /// Helper to keep information about the current `omp begin/end declare
11053 /// variant` nesting.
11054 struct OMPDeclareVariantScope {
11055 /// The associated OpenMP context selector.
11056 OMPTraitInfo *TI;
11057
11058 /// The associated OpenMP context selector mangling.
11059 std::string NameSuffix;
11060
11061 OMPDeclareVariantScope(OMPTraitInfo &TI);
11062 };
11063
11064 /// Return the OMPTraitInfo for the surrounding scope, if any.
11065 OMPTraitInfo *getOMPTraitInfoForSurroundingScope() {
11066 return OMPDeclareVariantScopes.empty() ? nullptr
11067 : OMPDeclareVariantScopes.back().TI;
11068 }
11069
11070 /// The current `omp begin/end declare variant` scopes.
11071 SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
11072
11073 /// The current `omp begin/end assumes` scopes.
11074 SmallVector<AssumptionAttr *, 4> OMPAssumeScoped;
11075
11076 /// All `omp assumes` we encountered so far.
11077 SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal;
11078
11079public:
11080 /// The declarator \p D defines a function in the scope \p S which is nested
11081 /// in an `omp begin/end declare variant` scope. In this method we create a
11082 /// declaration for \p D and rename \p D according to the OpenMP context
11083 /// selector of the surrounding scope. Return all base functions in \p Bases.
11084 void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
11085 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists,
11086 SmallVectorImpl<FunctionDecl *> &Bases);
11087
11088 /// Register \p D as specialization of all base functions in \p Bases in the
11089 /// current `omp begin/end declare variant` scope.
11090 void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
11091 Decl *D, SmallVectorImpl<FunctionDecl *> &Bases);
11092
11093 /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`.
11094 void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D);
11095
11096 /// Can we exit an OpenMP declare variant scope at the moment.
11097 bool isInOpenMPDeclareVariantScope() const {
11098 return !OMPDeclareVariantScopes.empty();
11099 }
11100
11101 /// Given the potential call expression \p Call, determine if there is a
11102 /// specialization via the OpenMP declare variant mechanism available. If
11103 /// there is, return the specialized call expression, otherwise return the
11104 /// original \p Call.
11105 ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope,
11106 SourceLocation LParenLoc, MultiExprArg ArgExprs,
11107 SourceLocation RParenLoc, Expr *ExecConfig);
11108
11109 /// Handle a `omp begin declare variant`.
11110 void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI);
11111
11112 /// Handle a `omp end declare variant`.
11113 void ActOnOpenMPEndDeclareVariant();
11114
11115 /// Checks if the variant/multiversion functions are compatible.
11116 bool areMultiversionVariantFunctionsCompatible(
11117 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11118 const PartialDiagnostic &NoProtoDiagID,
11119 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11120 const PartialDiagnosticAt &NoSupportDiagIDAt,
11121 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11122 bool ConstexprSupported, bool CLinkageMayDiffer);
11123
11124 /// Function tries to capture lambda's captured variables in the OpenMP region
11125 /// before the original lambda is captured.
11126 void tryCaptureOpenMPLambdas(ValueDecl *V);
11127
11128 /// Return true if the provided declaration \a VD should be captured by
11129 /// reference.
11130 /// \param Level Relative level of nested OpenMP construct for that the check
11131 /// is performed.
11132 /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
11133 bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
11134 unsigned OpenMPCaptureLevel) const;
11135
11136 /// Check if the specified variable is used in one of the private
11137 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
11138 /// constructs.
11139 VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
11140 unsigned StopAt = 0);
11141
11142 /// The member expression(this->fd) needs to be rebuilt in the template
11143 /// instantiation to generate private copy for OpenMP when default
11144 /// clause is used. The function will return true if default
11145 /// cluse is used.
11146 bool isOpenMPRebuildMemberExpr(ValueDecl *D);
11147
11148 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
11149 ExprObjectKind OK, SourceLocation Loc);
11150
11151 /// If the current region is a loop-based region, mark the start of the loop
11152 /// construct.
11153 void startOpenMPLoop();
11154
11155 /// If the current region is a range loop-based region, mark the start of the
11156 /// loop construct.
11157 void startOpenMPCXXRangeFor();
11158
11159 /// Check if the specified variable is used in 'private' clause.
11160 /// \param Level Relative level of nested OpenMP construct for that the check
11161 /// is performed.
11162 OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
11163 unsigned CapLevel) const;
11164
11165 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
11166 /// for \p FD based on DSA for the provided corresponding captured declaration
11167 /// \p D.
11168 void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
11169
11170 /// Check if the specified variable is captured by 'target' directive.
11171 /// \param Level Relative level of nested OpenMP construct for that the check
11172 /// is performed.
11173 bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
11174 unsigned CaptureLevel) const;
11175
11176 /// Check if the specified global variable must be captured by outer capture
11177 /// regions.
11178 /// \param Level Relative level of nested OpenMP construct for that
11179 /// the check is performed.
11180 bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
11181 unsigned CaptureLevel) const;
11182
11183 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
11184 Expr *Op);
11185 /// Called on start of new data sharing attribute block.
11186 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
11187 const DeclarationNameInfo &DirName, Scope *CurScope,
11188 SourceLocation Loc);
11189 /// Start analysis of clauses.
11190 void StartOpenMPClause(OpenMPClauseKind K);
11191 /// End analysis of clauses.
11192 void EndOpenMPClause();
11193 /// Called on end of data sharing attribute block.
11194 void EndOpenMPDSABlock(Stmt *CurDirective);
11195
11196 /// Check if the current region is an OpenMP loop region and if it is,
11197 /// mark loop control variable, used in \p Init for loop initialization, as
11198 /// private by default.
11199 /// \param Init First part of the for loop.
11200 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
11201
11202 /// Called on well-formed '\#pragma omp metadirective' after parsing
11203 /// of the associated statement.
11204 StmtResult ActOnOpenMPMetaDirective(ArrayRef<OMPClause *> Clauses,
11205 Stmt *AStmt, SourceLocation StartLoc,
11206 SourceLocation EndLoc);
11207
11208 // OpenMP directives and clauses.
11209 /// Called on correct id-expression from the '#pragma omp
11210 /// threadprivate'.
11211 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
11212 const DeclarationNameInfo &Id,
11213 OpenMPDirectiveKind Kind);
11214 /// Called on well-formed '#pragma omp threadprivate'.
11215 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
11216 SourceLocation Loc,
11217 ArrayRef<Expr *> VarList);
11218 /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
11219 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
11220 ArrayRef<Expr *> VarList);
11221 /// Called on well-formed '#pragma omp allocate'.
11222 DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
11223 ArrayRef<Expr *> VarList,
11224 ArrayRef<OMPClause *> Clauses,
11225 DeclContext *Owner = nullptr);
11226
11227 /// Called on well-formed '#pragma omp [begin] assume[s]'.
11228 void ActOnOpenMPAssumesDirective(SourceLocation Loc,
11229 OpenMPDirectiveKind DKind,
11230 ArrayRef<std::string> Assumptions,
11231 bool SkippedClauses);
11232
11233 /// Check if there is an active global `omp begin assumes` directive.
11234 bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); }
11235
11236 /// Check if there is an active global `omp assumes` directive.
11237 bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); }
11238
11239 /// Called on well-formed '#pragma omp end assumes'.
11240 void ActOnOpenMPEndAssumesDirective();
11241
11242 /// Called on well-formed '#pragma omp requires'.
11243 DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
11244 ArrayRef<OMPClause *> ClauseList);
11245 /// Check restrictions on Requires directive
11246 OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
11247 ArrayRef<OMPClause *> Clauses);
11248 /// Check if the specified type is allowed to be used in 'omp declare
11249 /// reduction' construct.
11250 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11251 TypeResult ParsedType);
11252 /// Called on start of '#pragma omp declare reduction'.
11253 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
11254 Scope *S, DeclContext *DC, DeclarationName Name,
11255 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11256 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
11257 /// Initialize declare reduction construct initializer.
11258 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
11259 /// Finish current declare reduction construct initializer.
11260 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
11261 /// Initialize declare reduction construct initializer.
11262 /// \return omp_priv variable.
11263 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
11264 /// Finish current declare reduction construct initializer.
11265 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
11266 VarDecl *OmpPrivParm);
11267 /// Called at the end of '#pragma omp declare reduction'.
11268 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
11269 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
11270
11271 /// Check variable declaration in 'omp declare mapper' construct.
11272 TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
11273 /// Check if the specified type is allowed to be used in 'omp declare
11274 /// mapper' construct.
11275 QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
11276 TypeResult ParsedType);
11277 /// Called on start of '#pragma omp declare mapper'.
11278 DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(
11279 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
11280 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
11281 Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses,
11282 Decl *PrevDeclInScope = nullptr);
11283 /// Build the mapper variable of '#pragma omp declare mapper'.
11284 ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S,
11285 QualType MapperType,
11286 SourceLocation StartLoc,
11287 DeclarationName VN);
11288 void ActOnOpenMPIteratorVarDecl(VarDecl *VD);
11289 bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const;
11290 const ValueDecl *getOpenMPDeclareMapperVarName() const;
11291
11292 /// Called on the start of target region i.e. '#pragma omp declare target'.
11293 bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
11294
11295 /// Called at the end of target region i.e. '#pragma omp end declare target'.
11296 const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective();
11297
11298 /// Called once a target context is completed, that can be when a
11299 /// '#pragma omp end declare target' was encountered or when a
11300 /// '#pragma omp declare target' without declaration-definition-seq was
11301 /// encountered.
11302 void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
11303
11304 /// Report unterminated 'omp declare target' or 'omp begin declare target' at
11305 /// the end of a compilation unit.
11306 void DiagnoseUnterminatedOpenMPDeclareTarget();
11307
11308 /// Searches for the provided declaration name for OpenMP declare target
11309 /// directive.
11310 NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope,
11311 CXXScopeSpec &ScopeSpec,
11312 const DeclarationNameInfo &Id);
11313
11314 /// Called on correct id-expression from the '#pragma omp declare target'.
11315 void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
11316 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11317 DeclareTargetContextInfo &DTCI);
11318
11319 /// Check declaration inside target region.
11320 void
11321 checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
11322 SourceLocation IdLoc = SourceLocation());
11323 /// Finishes analysis of the deferred functions calls that may be declared as
11324 /// host/nohost during device/host compilation.
11325 void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
11326 const FunctionDecl *Callee,
11327 SourceLocation Loc);
11328
11329 /// Return true if currently in OpenMP task with untied clause context.
11330 bool isInOpenMPTaskUntiedContext() const;
11331
11332 /// Return true inside OpenMP declare target region.
11333 bool isInOpenMPDeclareTargetContext() const {
11334 return !DeclareTargetNesting.empty();
11335 }
11336 /// Return true inside OpenMP target region.
11337 bool isInOpenMPTargetExecutionDirective() const;
11338
11339 /// Return the number of captured regions created for an OpenMP directive.
11340 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
11341
11342 /// Initialization of captured region for OpenMP region.
11343 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
11344
11345 /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to
11346 /// an OpenMP loop directive.
11347 StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt);
11348
11349 /// Process a canonical OpenMP loop nest that can either be a canonical
11350 /// literal loop (ForStmt or CXXForRangeStmt), or the generated loop of an
11351 /// OpenMP loop transformation construct.
11352 StmtResult ActOnOpenMPLoopnest(Stmt *AStmt);
11353
11354 /// End of OpenMP region.
11355 ///
11356 /// \param S Statement associated with the current OpenMP region.
11357 /// \param Clauses List of clauses for the current OpenMP region.
11358 ///
11359 /// \returns Statement for finished OpenMP region.
11360 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
11361 StmtResult ActOnOpenMPExecutableDirective(
11362 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
11363 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
11364 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
11365 /// Called on well-formed '\#pragma omp parallel' after parsing
11366 /// of the associated statement.
11367 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
11368 Stmt *AStmt,
11369 SourceLocation StartLoc,
11370 SourceLocation EndLoc);
11371 using VarsWithInheritedDSAType =
11372 llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
11373 /// Called on well-formed '\#pragma omp simd' after parsing
11374 /// of the associated statement.
11375 StmtResult
11376 ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11377 SourceLocation StartLoc, SourceLocation EndLoc,
11378 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11379 /// Called on well-formed '#pragma omp tile' after parsing of its clauses and
11380 /// the associated statement.
11381 StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
11382 Stmt *AStmt, SourceLocation StartLoc,
11383 SourceLocation EndLoc);
11384 /// Called on well-formed '#pragma omp unroll' after parsing of its clauses
11385 /// and the associated statement.
11386 StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
11387 Stmt *AStmt, SourceLocation StartLoc,
11388 SourceLocation EndLoc);
11389 /// Called on well-formed '\#pragma omp for' after parsing
11390 /// of the associated statement.
11391 StmtResult
11392 ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11393 SourceLocation StartLoc, SourceLocation EndLoc,
11394 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11395 /// Called on well-formed '\#pragma omp for simd' after parsing
11396 /// of the associated statement.
11397 StmtResult
11398 ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11399 SourceLocation StartLoc, SourceLocation EndLoc,
11400 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11401 /// Called on well-formed '\#pragma omp sections' after parsing
11402 /// of the associated statement.
11403 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
11404 Stmt *AStmt, SourceLocation StartLoc,
11405 SourceLocation EndLoc);
11406 /// Called on well-formed '\#pragma omp section' after parsing of the
11407 /// associated statement.
11408 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
11409 SourceLocation EndLoc);
11410 /// Called on well-formed '\#pragma omp single' after parsing of the
11411 /// associated statement.
11412 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
11413 Stmt *AStmt, SourceLocation StartLoc,
11414 SourceLocation EndLoc);
11415 /// Called on well-formed '\#pragma omp master' after parsing of the
11416 /// associated statement.
11417 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
11418 SourceLocation EndLoc);
11419 /// Called on well-formed '\#pragma omp critical' after parsing of the
11420 /// associated statement.
11421 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
11422 ArrayRef<OMPClause *> Clauses,
11423 Stmt *AStmt, SourceLocation StartLoc,
11424 SourceLocation EndLoc);
11425 /// Called on well-formed '\#pragma omp parallel for' after parsing
11426 /// of the associated statement.
11427 StmtResult ActOnOpenMPParallelForDirective(
11428 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11429 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11430 /// Called on well-formed '\#pragma omp parallel for simd' after
11431 /// parsing of the associated statement.
11432 StmtResult ActOnOpenMPParallelForSimdDirective(
11433 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11434 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11435 /// Called on well-formed '\#pragma omp parallel master' after
11436 /// parsing of the associated statement.
11437 StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
11438 Stmt *AStmt,
11439 SourceLocation StartLoc,
11440 SourceLocation EndLoc);
11441 /// Called on well-formed '\#pragma omp parallel masked' after
11442 /// parsing of the associated statement.
11443 StmtResult ActOnOpenMPParallelMaskedDirective(ArrayRef<OMPClause *> Clauses,
11444 Stmt *AStmt,
11445 SourceLocation StartLoc,
11446 SourceLocation EndLoc);
11447 /// Called on well-formed '\#pragma omp parallel sections' after
11448 /// parsing of the associated statement.
11449 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
11450 Stmt *AStmt,
11451 SourceLocation StartLoc,
11452 SourceLocation EndLoc);
11453 /// Called on well-formed '\#pragma omp task' after parsing of the
11454 /// associated statement.
11455 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
11456 Stmt *AStmt, SourceLocation StartLoc,
11457 SourceLocation EndLoc);
11458 /// Called on well-formed '\#pragma omp taskyield'.
11459 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
11460 SourceLocation EndLoc);
11461 /// Called on well-formed '\#pragma omp error'.
11462 /// Error direcitive is allowed in both declared and excutable contexts.
11463 /// Adding InExContext to identify which context is called from.
11464 StmtResult ActOnOpenMPErrorDirective(ArrayRef<OMPClause *> Clauses,
11465 SourceLocation StartLoc,
11466 SourceLocation EndLoc,
11467 bool InExContext = true);
11468 /// Called on well-formed '\#pragma omp barrier'.
11469 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
11470 SourceLocation EndLoc);
11471 /// Called on well-formed '\#pragma omp taskwait'.
11472 StmtResult ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses,
11473 SourceLocation StartLoc,
11474 SourceLocation EndLoc);
11475 /// Called on well-formed '\#pragma omp taskgroup'.
11476 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
11477 Stmt *AStmt, SourceLocation StartLoc,
11478 SourceLocation EndLoc);
11479 /// Called on well-formed '\#pragma omp flush'.
11480 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
11481 SourceLocation StartLoc,
11482 SourceLocation EndLoc);
11483 /// Called on well-formed '\#pragma omp depobj'.
11484 StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
11485 SourceLocation StartLoc,
11486 SourceLocation EndLoc);
11487 /// Called on well-formed '\#pragma omp scan'.
11488 StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
11489 SourceLocation StartLoc,
11490 SourceLocation EndLoc);
11491 /// Called on well-formed '\#pragma omp ordered' after parsing of the
11492 /// associated statement.
11493 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
11494 Stmt *AStmt, SourceLocation StartLoc,
11495 SourceLocation EndLoc);
11496 /// Called on well-formed '\#pragma omp atomic' after parsing of the
11497 /// associated statement.
11498 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
11499 Stmt *AStmt, SourceLocation StartLoc,
11500 SourceLocation EndLoc);
11501 /// Called on well-formed '\#pragma omp target' after parsing of the
11502 /// associated statement.
11503 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
11504 Stmt *AStmt, SourceLocation StartLoc,
11505 SourceLocation EndLoc);
11506 /// Called on well-formed '\#pragma omp target data' after parsing of
11507 /// the associated statement.
11508 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
11509 Stmt *AStmt, SourceLocation StartLoc,
11510 SourceLocation EndLoc);
11511 /// Called on well-formed '\#pragma omp target enter data' after
11512 /// parsing of the associated statement.
11513 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
11514 SourceLocation StartLoc,
11515 SourceLocation EndLoc,
11516 Stmt *AStmt);
11517 /// Called on well-formed '\#pragma omp target exit data' after
11518 /// parsing of the associated statement.
11519 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
11520 SourceLocation StartLoc,
11521 SourceLocation EndLoc,
11522 Stmt *AStmt);
11523 /// Called on well-formed '\#pragma omp target parallel' after
11524 /// parsing of the associated statement.
11525 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
11526 Stmt *AStmt,
11527 SourceLocation StartLoc,
11528 SourceLocation EndLoc);
11529 /// Called on well-formed '\#pragma omp target parallel for' after
11530 /// parsing of the associated statement.
11531 StmtResult ActOnOpenMPTargetParallelForDirective(
11532 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11533 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11534 /// Called on well-formed '\#pragma omp teams' after parsing of the
11535 /// associated statement.
11536 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
11537 Stmt *AStmt, SourceLocation StartLoc,
11538 SourceLocation EndLoc);
11539 /// Called on well-formed '\#pragma omp teams loop' after parsing of the
11540 /// associated statement.
11541 StmtResult ActOnOpenMPTeamsGenericLoopDirective(
11542 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11543 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11544 /// Called on well-formed '\#pragma omp target teams loop' after parsing of
11545 /// the associated statement.
11546 StmtResult ActOnOpenMPTargetTeamsGenericLoopDirective(
11547 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11548 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11549 /// Called on well-formed '\#pragma omp parallel loop' after parsing of the
11550 /// associated statement.
11551 StmtResult ActOnOpenMPParallelGenericLoopDirective(
11552 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11553 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11554 /// Called on well-formed '\#pragma omp target parallel loop' after parsing
11555 /// of the associated statement.
11556 StmtResult ActOnOpenMPTargetParallelGenericLoopDirective(
11557 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11558 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11559 /// Called on well-formed '\#pragma omp cancellation point'.
11560 StmtResult
11561 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
11562 SourceLocation EndLoc,
11563 OpenMPDirectiveKind CancelRegion);
11564 /// Called on well-formed '\#pragma omp cancel'.
11565 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
11566 SourceLocation StartLoc,
11567 SourceLocation EndLoc,
11568 OpenMPDirectiveKind CancelRegion);
11569 /// Called on well-formed '\#pragma omp taskloop' after parsing of the
11570 /// associated statement.
11571 StmtResult
11572 ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11573 SourceLocation StartLoc, SourceLocation EndLoc,
11574 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11575 /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
11576 /// the associated statement.
11577 StmtResult ActOnOpenMPTaskLoopSimdDirective(
11578 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11579 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11580 /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
11581 /// associated statement.
11582 StmtResult ActOnOpenMPMasterTaskLoopDirective(
11583 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11584 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11585 /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
11586 /// the associated statement.
11587 StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
11588 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11589 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11590 /// Called on well-formed '\#pragma omp parallel master taskloop' after
11591 /// parsing of the associated statement.
11592 StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
11593 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11594 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11595 /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
11596 /// parsing of the associated statement.
11597 StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
11598 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11599 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11600 /// Called on well-formed '\#pragma omp masked taskloop' after parsing of the
11601 /// associated statement.
11602 StmtResult ActOnOpenMPMaskedTaskLoopDirective(
11603 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11604 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11605 /// Called on well-formed '\#pragma omp masked taskloop simd' after parsing of
11606 /// the associated statement.
11607 StmtResult ActOnOpenMPMaskedTaskLoopSimdDirective(
11608 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11609 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11610 /// Called on well-formed '\#pragma omp parallel masked taskloop' after
11611 /// parsing of the associated statement.
11612 StmtResult ActOnOpenMPParallelMaskedTaskLoopDirective(
11613 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11614 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11615 /// Called on well-formed '\#pragma omp parallel masked taskloop simd' after
11616 /// parsing of the associated statement.
11617 StmtResult ActOnOpenMPParallelMaskedTaskLoopSimdDirective(
11618 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11619 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11620 /// Called on well-formed '\#pragma omp distribute' after parsing
11621 /// of the associated statement.
11622 StmtResult
11623 ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11624 SourceLocation StartLoc, SourceLocation EndLoc,
11625 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11626 /// Called on well-formed '\#pragma omp target update'.
11627 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
11628 SourceLocation StartLoc,
11629 SourceLocation EndLoc,
11630 Stmt *AStmt);
11631 /// Called on well-formed '\#pragma omp distribute parallel for' after
11632 /// parsing of the associated statement.
11633 StmtResult ActOnOpenMPDistributeParallelForDirective(
11634 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11635 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11636 /// Called on well-formed '\#pragma omp distribute parallel for simd'
11637 /// after parsing of the associated statement.
11638 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
11639 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11640 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11641 /// Called on well-formed '\#pragma omp distribute simd' after
11642 /// parsing of the associated statement.
11643 StmtResult ActOnOpenMPDistributeSimdDirective(
11644 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11645 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11646 /// Called on well-formed '\#pragma omp target parallel for simd' after
11647 /// parsing of the associated statement.
11648 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
11649 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11650 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11651 /// Called on well-formed '\#pragma omp target simd' after parsing of
11652 /// the associated statement.
11653 StmtResult
11654 ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11655 SourceLocation StartLoc, SourceLocation EndLoc,
11656 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11657 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
11658 /// the associated statement.
11659 StmtResult ActOnOpenMPTeamsDistributeDirective(
11660 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11661 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11662 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
11663 /// of the associated statement.
11664 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
11665 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11666 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11667 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
11668 /// after parsing of the associated statement.
11669 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
11670 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11671 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11672 /// Called on well-formed '\#pragma omp teams distribute parallel for'
11673 /// after parsing of the associated statement.
11674 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
11675 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11676 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11677 /// Called on well-formed '\#pragma omp target teams' after parsing of the
11678 /// associated statement.
11679 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
11680 Stmt *AStmt,
11681 SourceLocation StartLoc,
11682 SourceLocation EndLoc);
11683 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
11684 /// of the associated statement.
11685 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
11686 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11687 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11688 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
11689 /// after parsing of the associated statement.
11690 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
11691 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11692 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11693 /// Called on well-formed '\#pragma omp target teams distribute parallel for
11694 /// simd' after parsing of the associated statement.
11695 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
11696 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11697 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11698 /// Called on well-formed '\#pragma omp target teams distribute simd' after
11699 /// parsing of the associated statement.
11700 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
11701 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11702 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11703 /// Called on well-formed '\#pragma omp interop'.
11704 StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
11705 SourceLocation StartLoc,
11706 SourceLocation EndLoc);
11707 /// Called on well-formed '\#pragma omp dispatch' after parsing of the
11708 // /associated statement.
11709 StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
11710 Stmt *AStmt, SourceLocation StartLoc,
11711 SourceLocation EndLoc);
11712 /// Called on well-formed '\#pragma omp masked' after parsing of the
11713 // /associated statement.
11714 StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
11715 Stmt *AStmt, SourceLocation StartLoc,
11716 SourceLocation EndLoc);
11717
11718 /// Called on well-formed '\#pragma omp loop' after parsing of the
11719 /// associated statement.
11720 StmtResult ActOnOpenMPGenericLoopDirective(
11721 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11722 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11723
11724 /// Checks correctness of linear modifiers.
11725 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11726 SourceLocation LinLoc);
11727 /// Checks that the specified declaration matches requirements for the linear
11728 /// decls.
11729 bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
11730 OpenMPLinearClauseKind LinKind, QualType Type,
11731 bool IsDeclareSimd = false);
11732
11733 /// Called on well-formed '\#pragma omp declare simd' after parsing of
11734 /// the associated method/function.
11735 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
11736 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
11737 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
11738 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
11739 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
11740
11741 /// Checks '\#pragma omp declare variant' variant function and original
11742 /// functions after parsing of the associated method/function.
11743 /// \param DG Function declaration to which declare variant directive is
11744 /// applied to.
11745 /// \param VariantRef Expression that references the variant function, which
11746 /// must be used instead of the original one, specified in \p DG.
11747 /// \param TI The trait info object representing the match clause.
11748 /// \param NumAppendArgs The number of omp_interop_t arguments to account for
11749 /// in checking.
11750 /// \returns std::nullopt, if the function/variant function are not compatible
11751 /// with the pragma, pair of original function/variant ref expression
11752 /// otherwise.
11753 std::optional<std::pair<FunctionDecl *, Expr *>>
11754 checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef,
11755 OMPTraitInfo &TI, unsigned NumAppendArgs,
11756 SourceRange SR);
11757
11758 /// Called on well-formed '\#pragma omp declare variant' after parsing of
11759 /// the associated method/function.
11760 /// \param FD Function declaration to which declare variant directive is
11761 /// applied to.
11762 /// \param VariantRef Expression that references the variant function, which
11763 /// must be used instead of the original one, specified in \p DG.
11764 /// \param TI The context traits associated with the function variant.
11765 /// \param AdjustArgsNothing The list of 'nothing' arguments.
11766 /// \param AdjustArgsNeedDevicePtr The list of 'need_device_ptr' arguments.
11767 /// \param AppendArgs The list of 'append_args' arguments.
11768 /// \param AdjustArgsLoc The Location of an 'adjust_args' clause.
11769 /// \param AppendArgsLoc The Location of an 'append_args' clause.
11770 /// \param SR The SourceRange of the 'declare variant' directive.
11771 void ActOnOpenMPDeclareVariantDirective(
11772 FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
11773 ArrayRef<Expr *> AdjustArgsNothing,
11774 ArrayRef<Expr *> AdjustArgsNeedDevicePtr,
11775 ArrayRef<OMPInteropInfo> AppendArgs, SourceLocation AdjustArgsLoc,
11776 SourceLocation AppendArgsLoc, SourceRange SR);
11777
11778 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
11779 Expr *Expr,
11780 SourceLocation StartLoc,
11781 SourceLocation LParenLoc,
11782 SourceLocation EndLoc);
11783 /// Called on well-formed 'allocator' clause.
11784 OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
11785 SourceLocation StartLoc,
11786 SourceLocation LParenLoc,
11787 SourceLocation EndLoc);
11788 /// Called on well-formed 'if' clause.
11789 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11790 Expr *Condition, SourceLocation StartLoc,
11791 SourceLocation LParenLoc,
11792 SourceLocation NameModifierLoc,
11793 SourceLocation ColonLoc,
11794 SourceLocation EndLoc);
11795 /// Called on well-formed 'final' clause.
11796 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
11797 SourceLocation LParenLoc,
11798 SourceLocation EndLoc);
11799 /// Called on well-formed 'num_threads' clause.
11800 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11801 SourceLocation StartLoc,
11802 SourceLocation LParenLoc,
11803 SourceLocation EndLoc);
11804 /// Called on well-formed 'align' clause.
11805 OMPClause *ActOnOpenMPAlignClause(Expr *Alignment, SourceLocation StartLoc,
11806 SourceLocation LParenLoc,
11807 SourceLocation EndLoc);
11808 /// Called on well-formed 'safelen' clause.
11809 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
11810 SourceLocation StartLoc,
11811 SourceLocation LParenLoc,
11812 SourceLocation EndLoc);
11813 /// Called on well-formed 'simdlen' clause.
11814 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
11815 SourceLocation LParenLoc,
11816 SourceLocation EndLoc);
11817 /// Called on well-form 'sizes' clause.
11818 OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
11819 SourceLocation StartLoc,
11820 SourceLocation LParenLoc,
11821 SourceLocation EndLoc);
11822 /// Called on well-form 'full' clauses.
11823 OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc,
11824 SourceLocation EndLoc);
11825 /// Called on well-form 'partial' clauses.
11826 OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, SourceLocation StartLoc,
11827 SourceLocation LParenLoc,
11828 SourceLocation EndLoc);
11829 /// Called on well-formed 'collapse' clause.
11830 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
11831 SourceLocation StartLoc,
11832 SourceLocation LParenLoc,
11833 SourceLocation EndLoc);
11834 /// Called on well-formed 'ordered' clause.
11835 OMPClause *
11836 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
11837 SourceLocation LParenLoc = SourceLocation(),
11838 Expr *NumForLoops = nullptr);
11839 /// Called on well-formed 'grainsize' clause.
11840 OMPClause *ActOnOpenMPGrainsizeClause(OpenMPGrainsizeClauseModifier Modifier,
11841 Expr *Size, SourceLocation StartLoc,
11842 SourceLocation LParenLoc,
11843 SourceLocation ModifierLoc,
11844 SourceLocation EndLoc);
11845 /// Called on well-formed 'num_tasks' clause.
11846 OMPClause *ActOnOpenMPNumTasksClause(OpenMPNumTasksClauseModifier Modifier,
11847 Expr *NumTasks, SourceLocation StartLoc,
11848 SourceLocation LParenLoc,
11849 SourceLocation ModifierLoc,
11850 SourceLocation EndLoc);
11851 /// Called on well-formed 'hint' clause.
11852 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11853 SourceLocation LParenLoc,
11854 SourceLocation EndLoc);
11855 /// Called on well-formed 'detach' clause.
11856 OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
11857 SourceLocation LParenLoc,
11858 SourceLocation EndLoc);
11859
11860 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
11861 unsigned Argument,
11862 SourceLocation ArgumentLoc,
11863 SourceLocation StartLoc,
11864 SourceLocation LParenLoc,
11865 SourceLocation EndLoc);
11866 /// Called on well-formed 'when' clause.
11867 OMPClause *ActOnOpenMPWhenClause(OMPTraitInfo &TI, SourceLocation StartLoc,
11868 SourceLocation LParenLoc,
11869 SourceLocation EndLoc);
11870 /// Called on well-formed 'default' clause.
11871 OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind,
11872 SourceLocation KindLoc,
11873 SourceLocation StartLoc,
11874 SourceLocation LParenLoc,
11875 SourceLocation EndLoc);
11876 /// Called on well-formed 'proc_bind' clause.
11877 OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
11878 SourceLocation KindLoc,
11879 SourceLocation StartLoc,
11880 SourceLocation LParenLoc,
11881 SourceLocation EndLoc);
11882 /// Called on well-formed 'order' clause.
11883 OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseModifier Modifier,
11884 OpenMPOrderClauseKind Kind,
11885 SourceLocation StartLoc,
11886 SourceLocation LParenLoc,
11887 SourceLocation MLoc, SourceLocation KindLoc,
11888 SourceLocation EndLoc);
11889 /// Called on well-formed 'update' clause.
11890 OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
11891 SourceLocation KindLoc,
11892 SourceLocation StartLoc,
11893 SourceLocation LParenLoc,
11894 SourceLocation EndLoc);
11895
11896 OMPClause *ActOnOpenMPSingleExprWithArgClause(
11897 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
11898 SourceLocation StartLoc, SourceLocation LParenLoc,
11899 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
11900 SourceLocation EndLoc);
11901 /// Called on well-formed 'schedule' clause.
11902 OMPClause *ActOnOpenMPScheduleClause(
11903 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
11904 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11905 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11906 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
11907
11908 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
11909 SourceLocation EndLoc);
11910 /// Called on well-formed 'nowait' clause.
11911 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
11912 SourceLocation EndLoc);
11913 /// Called on well-formed 'untied' clause.
11914 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
11915 SourceLocation EndLoc);
11916 /// Called on well-formed 'mergeable' clause.
11917 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
11918 SourceLocation EndLoc);
11919 /// Called on well-formed 'read' clause.
11920 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
11921 SourceLocation EndLoc);
11922 /// Called on well-formed 'write' clause.
11923 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
11924 SourceLocation EndLoc);
11925 /// Called on well-formed 'update' clause.
11926 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
11927 SourceLocation EndLoc);
11928 /// Called on well-formed 'capture' clause.
11929 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
11930 SourceLocation EndLoc);
11931 /// Called on well-formed 'compare' clause.
11932 OMPClause *ActOnOpenMPCompareClause(SourceLocation StartLoc,
11933 SourceLocation EndLoc);
11934 /// Called on well-formed 'seq_cst' clause.
11935 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
11936 SourceLocation EndLoc);
11937 /// Called on well-formed 'acq_rel' clause.
11938 OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
11939 SourceLocation EndLoc);
11940 /// Called on well-formed 'acquire' clause.
11941 OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc,
11942 SourceLocation EndLoc);
11943 /// Called on well-formed 'release' clause.
11944 OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc,
11945 SourceLocation EndLoc);
11946 /// Called on well-formed 'relaxed' clause.
11947 OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
11948 SourceLocation EndLoc);
11949
11950 /// Called on well-formed 'init' clause.
11951 OMPClause *
11952 ActOnOpenMPInitClause(Expr *InteropVar, OMPInteropInfo &InteropInfo,
11953 SourceLocation StartLoc, SourceLocation LParenLoc,
11954 SourceLocation VarLoc, SourceLocation EndLoc);
11955
11956 /// Called on well-formed 'use' clause.
11957 OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
11958 SourceLocation LParenLoc,
11959 SourceLocation VarLoc, SourceLocation EndLoc);
11960
11961 /// Called on well-formed 'destroy' clause.
11962 OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
11963 SourceLocation LParenLoc,
11964 SourceLocation VarLoc,
11965 SourceLocation EndLoc);
11966 /// Called on well-formed 'novariants' clause.
11967 OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition,
11968 SourceLocation StartLoc,
11969 SourceLocation LParenLoc,
11970 SourceLocation EndLoc);
11971 /// Called on well-formed 'nocontext' clause.
11972 OMPClause *ActOnOpenMPNocontextClause(Expr *Condition,
11973 SourceLocation StartLoc,
11974 SourceLocation LParenLoc,
11975 SourceLocation EndLoc);
11976 /// Called on well-formed 'filter' clause.
11977 OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
11978 SourceLocation LParenLoc,
11979 SourceLocation EndLoc);
11980 /// Called on well-formed 'threads' clause.
11981 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
11982 SourceLocation EndLoc);
11983 /// Called on well-formed 'simd' clause.
11984 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
11985 SourceLocation EndLoc);
11986 /// Called on well-formed 'nogroup' clause.
11987 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
11988 SourceLocation EndLoc);
11989 /// Called on well-formed 'unified_address' clause.
11990 OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
11991 SourceLocation EndLoc);
11992
11993 /// Called on well-formed 'unified_address' clause.
11994 OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
11995 SourceLocation EndLoc);
11996
11997 /// Called on well-formed 'reverse_offload' clause.
11998 OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
11999 SourceLocation EndLoc);
12000
12001 /// Called on well-formed 'dynamic_allocators' clause.
12002 OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
12003 SourceLocation EndLoc);
12004
12005 /// Called on well-formed 'atomic_default_mem_order' clause.
12006 OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
12007 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
12008 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
12009
12010 /// Called on well-formed 'at' clause.
12011 OMPClause *ActOnOpenMPAtClause(OpenMPAtClauseKind Kind,
12012 SourceLocation KindLoc,
12013 SourceLocation StartLoc,
12014 SourceLocation LParenLoc,
12015 SourceLocation EndLoc);
12016
12017 /// Called on well-formed 'severity' clause.
12018 OMPClause *ActOnOpenMPSeverityClause(OpenMPSeverityClauseKind Kind,
12019 SourceLocation KindLoc,
12020 SourceLocation StartLoc,
12021 SourceLocation LParenLoc,
12022 SourceLocation EndLoc);
12023
12024 /// Called on well-formed 'message' clause.
12025 /// passing string for message.
12026 OMPClause *ActOnOpenMPMessageClause(Expr *MS, SourceLocation StartLoc,
12027 SourceLocation LParenLoc,
12028 SourceLocation EndLoc);
12029
12030 /// Data used for processing a list of variables in OpenMP clauses.
12031 struct OpenMPVarListDataTy final {
12032 Expr *DepModOrTailExpr = nullptr;
12033 Expr *IteratorExpr = nullptr;
12034 SourceLocation ColonLoc;
12035 SourceLocation RLoc;
12036 CXXScopeSpec ReductionOrMapperIdScopeSpec;
12037 DeclarationNameInfo ReductionOrMapperId;
12038 int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or
12039 ///< lastprivate clause.
12040 SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
12041 MapTypeModifiers;
12042 SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
12043 MapTypeModifiersLoc;
12044 SmallVector<OpenMPMotionModifierKind, NumberOfOMPMotionModifiers>
12045 MotionModifiers;
12046 SmallVector<SourceLocation, NumberOfOMPMotionModifiers> MotionModifiersLoc;
12047 bool IsMapTypeImplicit = false;
12048 SourceLocation ExtraModifierLoc;
12049 SourceLocation OmpAllMemoryLoc;
12050 };
12051
12052 OMPClause *ActOnOpenMPVarListClause(OpenMPClauseKind Kind,
12053 ArrayRef<Expr *> Vars,
12054 const OMPVarListLocTy &Locs,
12055 OpenMPVarListDataTy &Data);
12056 /// Called on well-formed 'inclusive' clause.
12057 OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
12058 SourceLocation StartLoc,
12059 SourceLocation LParenLoc,
12060 SourceLocation EndLoc);
12061 /// Called on well-formed 'exclusive' clause.
12062 OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
12063 SourceLocation StartLoc,
12064 SourceLocation LParenLoc,
12065 SourceLocation EndLoc);
12066 /// Called on well-formed 'allocate' clause.
12067 OMPClause *
12068 ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
12069 SourceLocation StartLoc, SourceLocation ColonLoc,
12070 SourceLocation LParenLoc, SourceLocation EndLoc);
12071 /// Called on well-formed 'private' clause.
12072 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
12073 SourceLocation StartLoc,
12074 SourceLocation LParenLoc,
12075 SourceLocation EndLoc);
12076 /// Called on well-formed 'firstprivate' clause.
12077 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12078 SourceLocation StartLoc,
12079 SourceLocation LParenLoc,
12080 SourceLocation EndLoc);
12081 /// Called on well-formed 'lastprivate' clause.
12082 OMPClause *ActOnOpenMPLastprivateClause(
12083 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
12084 SourceLocation LPKindLoc, SourceLocation ColonLoc,
12085 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
12086 /// Called on well-formed 'shared' clause.
12087 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
12088 SourceLocation StartLoc,
12089 SourceLocation LParenLoc,
12090 SourceLocation EndLoc);
12091 /// Called on well-formed 'reduction' clause.
12092 OMPClause *ActOnOpenMPReductionClause(
12093 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
12094 SourceLocation StartLoc, SourceLocation LParenLoc,
12095 SourceLocation ModifierLoc, SourceLocation ColonLoc,
12096 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
12097 const DeclarationNameInfo &ReductionId,
12098 ArrayRef<Expr *> UnresolvedReductions = std::nullopt);
12099 /// Called on well-formed 'task_reduction' clause.
12100 OMPClause *ActOnOpenMPTaskReductionClause(
12101 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12102 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
12103 CXXScopeSpec &ReductionIdScopeSpec,
12104 const DeclarationNameInfo &ReductionId,
12105 ArrayRef<Expr *> UnresolvedReductions = std::nullopt);
12106 /// Called on well-formed 'in_reduction' clause.
12107 OMPClause *ActOnOpenMPInReductionClause(
12108 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12109 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
12110 CXXScopeSpec &ReductionIdScopeSpec,
12111 const DeclarationNameInfo &ReductionId,
12112 ArrayRef<Expr *> UnresolvedReductions = std::nullopt);
12113 /// Called on well-formed 'linear' clause.
12114 OMPClause *
12115 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
12116 SourceLocation StartLoc, SourceLocation LParenLoc,
12117 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
12118 SourceLocation ColonLoc, SourceLocation EndLoc);
12119 /// Called on well-formed 'aligned' clause.
12120 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
12121 Expr *Alignment,
12122 SourceLocation StartLoc,
12123 SourceLocation LParenLoc,
12124 SourceLocation ColonLoc,
12125 SourceLocation EndLoc);
12126 /// Called on well-formed 'copyin' clause.
12127 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12128 SourceLocation StartLoc,
12129 SourceLocation LParenLoc,
12130 SourceLocation EndLoc);
12131 /// Called on well-formed 'copyprivate' clause.
12132 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12133 SourceLocation StartLoc,
12134 SourceLocation LParenLoc,
12135 SourceLocation EndLoc);
12136 /// Called on well-formed 'flush' pseudo clause.
12137 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12138 SourceLocation StartLoc,
12139 SourceLocation LParenLoc,
12140 SourceLocation EndLoc);
12141 /// Called on well-formed 'depobj' pseudo clause.
12142 OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
12143 SourceLocation LParenLoc,
12144 SourceLocation EndLoc);
12145 /// Called on well-formed 'depend' clause.
12146 OMPClause *ActOnOpenMPDependClause(const OMPDependClause::DependDataTy &Data,
12147 Expr *DepModifier,
12148 ArrayRef<Expr *> VarList,
12149 SourceLocation StartLoc,
12150 SourceLocation LParenLoc,
12151 SourceLocation EndLoc);
12152 /// Called on well-formed 'device' clause.
12153 OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
12154 Expr *Device, SourceLocation StartLoc,
12155 SourceLocation LParenLoc,
12156 SourceLocation ModifierLoc,
12157 SourceLocation EndLoc);
12158 /// Called on well-formed 'map' clause.
12159 OMPClause *ActOnOpenMPMapClause(
12160 Expr *IteratorModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
12161 ArrayRef<SourceLocation> MapTypeModifiersLoc,
12162 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
12163 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12164 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
12165 const OMPVarListLocTy &Locs, bool NoDiagnose = false,
12166 ArrayRef<Expr *> UnresolvedMappers = std::nullopt);
12167 /// Called on well-formed 'num_teams' clause.
12168 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
12169 SourceLocation LParenLoc,
12170 SourceLocation EndLoc);
12171 /// Called on well-formed 'thread_limit' clause.
12172 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12173 SourceLocation StartLoc,
12174 SourceLocation LParenLoc,
12175 SourceLocation EndLoc);
12176 /// Called on well-formed 'priority' clause.
12177 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
12178 SourceLocation LParenLoc,
12179 SourceLocation EndLoc);
12180 /// Called on well-formed 'dist_schedule' clause.
12181 OMPClause *ActOnOpenMPDistScheduleClause(
12182 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
12183 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
12184 SourceLocation CommaLoc, SourceLocation EndLoc);
12185 /// Called on well-formed 'defaultmap' clause.
12186 OMPClause *ActOnOpenMPDefaultmapClause(
12187 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12188 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12189 SourceLocation KindLoc, SourceLocation EndLoc);
12190 /// Called on well-formed 'to' clause.
12191 OMPClause *
12192 ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
12193 ArrayRef<SourceLocation> MotionModifiersLoc,
12194 CXXScopeSpec &MapperIdScopeSpec,
12195 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
12196 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
12197 ArrayRef<Expr *> UnresolvedMappers = std::nullopt);
12198 /// Called on well-formed 'from' clause.
12199 OMPClause *
12200 ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
12201 ArrayRef<SourceLocation> MotionModifiersLoc,
12202 CXXScopeSpec &MapperIdScopeSpec,
12203 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
12204 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
12205 ArrayRef<Expr *> UnresolvedMappers = std::nullopt);
12206 /// Called on well-formed 'use_device_ptr' clause.
12207 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
12208 const OMPVarListLocTy &Locs);
12209 /// Called on well-formed 'use_device_addr' clause.
12210 OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
12211 const OMPVarListLocTy &Locs);
12212 /// Called on well-formed 'is_device_ptr' clause.
12213 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
12214 const OMPVarListLocTy &Locs);
12215 /// Called on well-formed 'has_device_addr' clause.
12216 OMPClause *ActOnOpenMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
12217 const OMPVarListLocTy &Locs);
12218 /// Called on well-formed 'nontemporal' clause.
12219 OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
12220 SourceLocation StartLoc,
12221 SourceLocation LParenLoc,
12222 SourceLocation EndLoc);
12223
12224 /// Data for list of allocators.
12225 struct UsesAllocatorsData {
12226 /// Allocator.
12227 Expr *Allocator = nullptr;
12228 /// Allocator traits.
12229 Expr *AllocatorTraits = nullptr;
12230 /// Locations of '(' and ')' symbols.
12231 SourceLocation LParenLoc, RParenLoc;
12232 };
12233 /// Called on well-formed 'uses_allocators' clause.
12234 OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc,
12235 SourceLocation LParenLoc,
12236 SourceLocation EndLoc,
12237 ArrayRef<UsesAllocatorsData> Data);
12238 /// Called on well-formed 'affinity' clause.
12239 OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc,
12240 SourceLocation LParenLoc,
12241 SourceLocation ColonLoc,
12242 SourceLocation EndLoc, Expr *Modifier,
12243 ArrayRef<Expr *> Locators);
12244 /// Called on a well-formed 'bind' clause.
12245 OMPClause *ActOnOpenMPBindClause(OpenMPBindClauseKind Kind,
12246 SourceLocation KindLoc,
12247 SourceLocation StartLoc,
12248 SourceLocation LParenLoc,
12249 SourceLocation EndLoc);
12250
12251 /// Called on a well-formed 'ompx_dyn_cgroup_mem' clause.
12252 OMPClause *ActOnOpenMPXDynCGroupMemClause(Expr *Size, SourceLocation StartLoc,
12253 SourceLocation LParenLoc,
12254 SourceLocation EndLoc);
12255
12256 /// The kind of conversion being performed.
12257 enum CheckedConversionKind {
12258 /// An implicit conversion.
12259 CCK_ImplicitConversion,
12260 /// A C-style cast.
12261 CCK_CStyleCast,
12262 /// A functional-style cast.
12263 CCK_FunctionalCast,
12264 /// A cast other than a C-style cast.
12265 CCK_OtherCast,
12266 /// A conversion for an operand of a builtin overloaded operator.
12267 CCK_ForBuiltinOverloadedOp
12268 };
12269
12270 static bool isCast(CheckedConversionKind CCK) {
12271 return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
12272 CCK == CCK_OtherCast;
12273 }
12274
12275 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
12276 /// cast. If there is already an implicit cast, merge into the existing one.
12277 /// If isLvalue, the result of the cast is an lvalue.
12278 ExprResult
12279 ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
12280 ExprValueKind VK = VK_PRValue,
12281 const CXXCastPath *BasePath = nullptr,
12282 CheckedConversionKind CCK = CCK_ImplicitConversion);
12283
12284 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
12285 /// to the conversion from scalar type ScalarTy to the Boolean type.
12286 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
12287
12288 /// IgnoredValueConversions - Given that an expression's result is
12289 /// syntactically ignored, perform any conversions that are
12290 /// required.
12291 ExprResult IgnoredValueConversions(Expr *E);
12292
12293 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
12294 // functions and arrays to their respective pointers (C99 6.3.2.1).
12295 ExprResult UsualUnaryConversions(Expr *E);
12296
12297 /// CallExprUnaryConversions - a special case of an unary conversion
12298 /// performed on a function designator of a call expression.
12299 ExprResult CallExprUnaryConversions(Expr *E);
12300
12301 // DefaultFunctionArrayConversion - converts functions and arrays
12302 // to their respective pointers (C99 6.3.2.1).
12303 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
12304
12305 // DefaultFunctionArrayLvalueConversion - converts functions and
12306 // arrays to their respective pointers and performs the
12307 // lvalue-to-rvalue conversion.
12308 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
12309 bool Diagnose = true);
12310
12311 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
12312 // the operand. This function is a no-op if the operand has a function type
12313 // or an array type.
12314 ExprResult DefaultLvalueConversion(Expr *E);
12315
12316 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
12317 // do not have a prototype. Integer promotions are performed on each
12318 // argument, and arguments that have type float are promoted to double.
12319 ExprResult DefaultArgumentPromotion(Expr *E);
12320
12321 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
12322 /// it as an xvalue. In C++98, the result will still be a prvalue, because
12323 /// we don't have xvalues there.
12324 ExprResult TemporaryMaterializationConversion(Expr *E);
12325
12326 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
12327 enum VariadicCallType {
12328 VariadicFunction,
12329 VariadicBlock,
12330 VariadicMethod,
12331 VariadicConstructor,
12332 VariadicDoesNotApply
12333 };
12334
12335 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
12336 const FunctionProtoType *Proto,
12337 Expr *Fn);
12338
12339 // Used for determining in which context a type is allowed to be passed to a
12340 // vararg function.
12341 enum VarArgKind {
12342 VAK_Valid,
12343 VAK_ValidInCXX11,
12344 VAK_Undefined,
12345 VAK_MSVCUndefined,
12346 VAK_Invalid
12347 };
12348
12349 // Determines which VarArgKind fits an expression.
12350 VarArgKind isValidVarArgType(const QualType &Ty);
12351
12352 /// Check to see if the given expression is a valid argument to a variadic
12353 /// function, issuing a diagnostic if not.
12354 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
12355
12356 /// Check whether the given statement can have musttail applied to it,
12357 /// issuing a diagnostic and returning false if not. In the success case,
12358 /// the statement is rewritten to remove implicit nodes from the return
12359 /// value.
12360 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
12361
12362private:
12363 /// Check whether the given statement can have musttail applied to it,
12364 /// issuing a diagnostic and returning false if not.
12365 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
12366
12367public:
12368 /// Check to see if a given expression could have '.c_str()' called on it.
12369 bool hasCStrMethod(const Expr *E);
12370
12371 /// GatherArgumentsForCall - Collector argument expressions for various
12372 /// form of call prototypes.
12373 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
12374 const FunctionProtoType *Proto,
12375 unsigned FirstParam, ArrayRef<Expr *> Args,
12376 SmallVectorImpl<Expr *> &AllArgs,
12377 VariadicCallType CallType = VariadicDoesNotApply,
12378 bool AllowExplicit = false,
12379 bool IsListInitialization = false);
12380
12381 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
12382 // will create a runtime trap if the resulting type is not a POD type.
12383 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
12384 FunctionDecl *FDecl);
12385
12386 /// Context in which we're performing a usual arithmetic conversion.
12387 enum ArithConvKind {
12388 /// An arithmetic operation.
12389 ACK_Arithmetic,
12390 /// A bitwise operation.
12391 ACK_BitwiseOp,
12392 /// A comparison.
12393 ACK_Comparison,
12394 /// A conditional (?:) operator.
12395 ACK_Conditional,
12396 /// A compound assignment expression.
12397 ACK_CompAssign,
12398 };
12399
12400 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
12401 // operands and then handles various conversions that are common to binary
12402 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
12403 // routine returns the first non-arithmetic type found. The client is
12404 // responsible for emitting appropriate error diagnostics.
12405 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
12406 SourceLocation Loc, ArithConvKind ACK);
12407
12408 /// AssignConvertType - All of the 'assignment' semantic checks return this
12409 /// enum to indicate whether the assignment was allowed. These checks are
12410 /// done for simple assignments, as well as initialization, return from
12411 /// function, argument passing, etc. The query is phrased in terms of a
12412 /// source and destination type.
12413 enum AssignConvertType {
12414 /// Compatible - the types are compatible according to the standard.
12415 Compatible,
12416
12417 /// PointerToInt - The assignment converts a pointer to an int, which we
12418 /// accept as an extension.
12419 PointerToInt,
12420
12421 /// IntToPointer - The assignment converts an int to a pointer, which we
12422 /// accept as an extension.
12423 IntToPointer,
12424
12425 /// FunctionVoidPointer - The assignment is between a function pointer and
12426 /// void*, which the standard doesn't allow, but we accept as an extension.
12427 FunctionVoidPointer,
12428
12429 /// IncompatiblePointer - The assignment is between two pointers types that
12430 /// are not compatible, but we accept them as an extension.
12431 IncompatiblePointer,
12432
12433 /// IncompatibleFunctionPointer - The assignment is between two function
12434 /// pointers types that are not compatible, but we accept them as an
12435 /// extension.
12436 IncompatibleFunctionPointer,
12437
12438 /// IncompatibleFunctionPointerStrict - The assignment is between two
12439 /// function pointer types that are not identical, but are compatible,
12440 /// unless compiled with -fsanitize=cfi, in which case the type mismatch
12441 /// may trip an indirect call runtime check.
12442 IncompatibleFunctionPointerStrict,
12443
12444 /// IncompatiblePointerSign - The assignment is between two pointers types
12445 /// which point to integers which have a different sign, but are otherwise
12446 /// identical. This is a subset of the above, but broken out because it's by
12447 /// far the most common case of incompatible pointers.
12448 IncompatiblePointerSign,
12449
12450 /// CompatiblePointerDiscardsQualifiers - The assignment discards
12451 /// c/v/r qualifiers, which we accept as an extension.
12452 CompatiblePointerDiscardsQualifiers,
12453
12454 /// IncompatiblePointerDiscardsQualifiers - The assignment
12455 /// discards qualifiers that we don't permit to be discarded,
12456 /// like address spaces.
12457 IncompatiblePointerDiscardsQualifiers,
12458
12459 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
12460 /// changes address spaces in nested pointer types which is not allowed.
12461 /// For instance, converting __private int ** to __generic int ** is
12462 /// illegal even though __private could be converted to __generic.
12463 IncompatibleNestedPointerAddressSpaceMismatch,
12464
12465 /// IncompatibleNestedPointerQualifiers - The assignment is between two
12466 /// nested pointer types, and the qualifiers other than the first two
12467 /// levels differ e.g. char ** -> const char **, but we accept them as an
12468 /// extension.
12469 IncompatibleNestedPointerQualifiers,
12470
12471 /// IncompatibleVectors - The assignment is between two vector types that
12472 /// have the same size, which we accept as an extension.
12473 IncompatibleVectors,
12474
12475 /// IntToBlockPointer - The assignment converts an int to a block
12476 /// pointer. We disallow this.
12477 IntToBlockPointer,
12478
12479 /// IncompatibleBlockPointer - The assignment is between two block
12480 /// pointers types that are not compatible.
12481 IncompatibleBlockPointer,
12482
12483 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
12484 /// id type and something else (that is incompatible with it). For example,
12485 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
12486 IncompatibleObjCQualifiedId,
12487
12488 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
12489 /// object with __weak qualifier.
12490 IncompatibleObjCWeakRef,
12491
12492 /// Incompatible - We reject this conversion outright, it is invalid to
12493 /// represent it in the AST.
12494 Incompatible
12495 };
12496
12497 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
12498 /// assignment conversion type specified by ConvTy. This returns true if the
12499 /// conversion was invalid or false if the conversion was accepted.
12500 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
12501 SourceLocation Loc,
12502 QualType DstType, QualType SrcType,
12503 Expr *SrcExpr, AssignmentAction Action,
12504 bool *Complained = nullptr);
12505
12506 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
12507 /// enum. If AllowMask is true, then we also allow the complement of a valid
12508 /// value, to be used as a mask.
12509 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
12510 bool AllowMask) const;
12511
12512 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
12513 /// integer not in the range of enum values.
12514 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
12515 Expr *SrcExpr);
12516
12517 /// CheckAssignmentConstraints - Perform type checking for assignment,
12518 /// argument passing, variable initialization, and function return values.
12519 /// C99 6.5.16.
12520 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
12521 QualType LHSType,
12522 QualType RHSType);
12523
12524 /// Check assignment constraints and optionally prepare for a conversion of
12525 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
12526 /// is true.
12527 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
12528 ExprResult &RHS,
12529 CastKind &Kind,
12530 bool ConvertRHS = true);
12531
12532 /// Check assignment constraints for an assignment of RHS to LHSType.
12533 ///
12534 /// \param LHSType The destination type for the assignment.
12535 /// \param RHS The source expression for the assignment.
12536 /// \param Diagnose If \c true, diagnostics may be produced when checking
12537 /// for assignability. If a diagnostic is produced, \p RHS will be
12538 /// set to ExprError(). Note that this function may still return
12539 /// without producing a diagnostic, even for an invalid assignment.
12540 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
12541 /// in an audited Core Foundation API and does not need to be checked
12542 /// for ARC retain issues.
12543 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
12544 /// conversions necessary to perform the assignment. If \c false,
12545 /// \p Diagnose must also be \c false.
12546 AssignConvertType CheckSingleAssignmentConstraints(
12547 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
12548 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
12549
12550 // If the lhs type is a transparent union, check whether we
12551 // can initialize the transparent union with the given expression.
12552 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
12553 ExprResult &RHS);
12554
12555 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
12556
12557 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
12558
12559 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
12560 AssignmentAction Action,
12561 bool AllowExplicit = false);
12562 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
12563 const ImplicitConversionSequence& ICS,
12564 AssignmentAction Action,
12565 CheckedConversionKind CCK
12566 = CCK_ImplicitConversion);
12567 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
12568 const StandardConversionSequence& SCS,
12569 AssignmentAction Action,
12570 CheckedConversionKind CCK);
12571
12572 ExprResult PerformQualificationConversion(
12573 Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
12574 CheckedConversionKind CCK = CCK_ImplicitConversion);
12575
12576 /// the following "Check" methods will return a valid/converted QualType
12577 /// or a null QualType (indicating an error diagnostic was issued).
12578
12579 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
12580 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
12581 ExprResult &RHS);
12582 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
12583 ExprResult &RHS);
12584 QualType CheckPointerToMemberOperands( // C++ 5.5
12585 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
12586 SourceLocation OpLoc, bool isIndirect);
12587 QualType CheckMultiplyDivideOperands( // C99 6.5.5
12588 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
12589 bool IsDivide);
12590 QualType CheckRemainderOperands( // C99 6.5.5
12591 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12592 bool IsCompAssign = false);
12593 QualType CheckAdditionOperands( // C99 6.5.6
12594 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12595 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
12596 QualType CheckSubtractionOperands( // C99 6.5.6
12597 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12598 QualType* CompLHSTy = nullptr);
12599 QualType CheckShiftOperands( // C99 6.5.7
12600 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12601 BinaryOperatorKind Opc, bool IsCompAssign = false);
12602 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
12603 QualType CheckCompareOperands( // C99 6.5.8/9
12604 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12605 BinaryOperatorKind Opc);
12606 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
12607 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12608 BinaryOperatorKind Opc);
12609 QualType CheckLogicalOperands( // C99 6.5.[13,14]
12610 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12611 BinaryOperatorKind Opc);
12612 // CheckAssignmentOperands is used for both simple and compound assignment.
12613 // For simple assignment, pass both expressions and a null converted type.
12614 // For compound assignment, pass both expressions and the converted type.
12615 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
12616 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
12617 BinaryOperatorKind Opc);
12618
12619 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
12620 UnaryOperatorKind Opcode, Expr *Op);
12621 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
12622 BinaryOperatorKind Opcode,
12623 Expr *LHS, Expr *RHS);
12624 ExprResult checkPseudoObjectRValue(Expr *E);
12625 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
12626
12627 QualType CheckConditionalOperands( // C99 6.5.15
12628 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
12629 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
12630 QualType CXXCheckConditionalOperands( // C++ 5.16
12631 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
12632 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
12633 QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
12634 ExprResult &RHS,
12635 SourceLocation QuestionLoc);
12636
12637 QualType CheckSizelessVectorConditionalTypes(ExprResult &Cond,
12638 ExprResult &LHS, ExprResult &RHS,
12639 SourceLocation QuestionLoc);
12640 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
12641 bool ConvertArgs = true);
12642 QualType FindCompositePointerType(SourceLocation Loc,
12643 ExprResult &E1, ExprResult &E2,
12644 bool ConvertArgs = true) {
12645 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
12646 QualType Composite =
12647 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
12648 E1 = E1Tmp;
12649 E2 = E2Tmp;
12650 return Composite;
12651 }
12652
12653 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
12654 SourceLocation QuestionLoc);
12655
12656 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
12657 SourceLocation QuestionLoc);
12658
12659 void DiagnoseAlwaysNonNullPointer(Expr *E,
12660 Expr::NullPointerConstantKind NullType,
12661 bool IsEqual, SourceRange Range);
12662
12663 /// type checking for vector binary operators.
12664 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
12665 SourceLocation Loc, bool IsCompAssign,
12666 bool AllowBothBool, bool AllowBoolConversion,
12667 bool AllowBoolOperation, bool ReportInvalid);
12668 QualType GetSignedVectorType(QualType V);
12669 QualType GetSignedSizelessVectorType(QualType V);
12670 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12671 SourceLocation Loc,
12672 BinaryOperatorKind Opc);
12673 QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12674 SourceLocation Loc,
12675 BinaryOperatorKind Opc);
12676 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12677 SourceLocation Loc);
12678
12679 // type checking for sizeless vector binary operators.
12680 QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
12681 SourceLocation Loc, bool IsCompAssign,
12682 ArithConvKind OperationKind);
12683
12684 /// Type checking for matrix binary operators.
12685 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12686 SourceLocation Loc,
12687 bool IsCompAssign);
12688 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12689 SourceLocation Loc, bool IsCompAssign);
12690
12691 bool isValidSveBitcast(QualType srcType, QualType destType);
12692 bool isValidRVVBitcast(QualType srcType, QualType destType);
12693
12694 bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
12695
12696 bool areVectorTypesSameSize(QualType srcType, QualType destType);
12697 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
12698 bool isLaxVectorConversion(QualType srcType, QualType destType);
12699 bool anyAltivecTypes(QualType srcType, QualType destType);
12700
12701 /// type checking declaration initializers (C99 6.7.8)
12702 bool CheckForConstantInitializer(Expr *e, QualType t);
12703
12704 // type checking C++ declaration initializers (C++ [dcl.init]).
12705
12706 /// ReferenceCompareResult - Expresses the result of comparing two
12707 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
12708 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
12709 enum ReferenceCompareResult {
12710 /// Ref_Incompatible - The two types are incompatible, so direct
12711 /// reference binding is not possible.
12712 Ref_Incompatible = 0,
12713 /// Ref_Related - The two types are reference-related, which means
12714 /// that their unqualified forms (T1 and T2) are either the same
12715 /// or T1 is a base class of T2.
12716 Ref_Related,
12717 /// Ref_Compatible - The two types are reference-compatible.
12718 Ref_Compatible
12719 };
12720
12721 // Fake up a scoped enumeration that still contextually converts to bool.
12722 struct ReferenceConversionsScope {
12723 /// The conversions that would be performed on an lvalue of type T2 when
12724 /// binding a reference of type T1 to it, as determined when evaluating
12725 /// whether T1 is reference-compatible with T2.
12726 enum ReferenceConversions {
12727 Qualification = 0x1,
12728 NestedQualification = 0x2,
12729 Function = 0x4,
12730 DerivedToBase = 0x8,
12731 ObjC = 0x10,
12732 ObjCLifetime = 0x20,
12733
12734 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)LLVM_BITMASK_LARGEST_ENUMERATOR = ObjCLifetime
12735 };
12736 };
12737 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
12738
12739 ReferenceCompareResult
12740 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
12741 ReferenceConversions *Conv = nullptr);
12742
12743 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12744 Expr *CastExpr, CastKind &CastKind,
12745 ExprValueKind &VK, CXXCastPath &Path);
12746
12747 /// Force an expression with unknown-type to an expression of the
12748 /// given type.
12749 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
12750
12751 /// Type-check an expression that's being passed to an
12752 /// __unknown_anytype parameter.
12753 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
12754 Expr *result, QualType &paramType);
12755
12756 // CheckMatrixCast - Check type constraints for matrix casts.
12757 // We allow casting between matrixes of the same dimensions i.e. when they
12758 // have the same number of rows and column. Returns true if the cast is
12759 // invalid.
12760 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
12761 CastKind &Kind);
12762
12763 // CheckVectorCast - check type constraints for vectors.
12764 // Since vectors are an extension, there are no C standard reference for this.
12765 // We allow casting between vectors and integer datatypes of the same size.
12766 // returns true if the cast is invalid
12767 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
12768 CastKind &Kind);
12769
12770 /// Prepare `SplattedExpr` for a vector splat operation, adding
12771 /// implicit casts if necessary.
12772 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
12773
12774 // CheckExtVectorCast - check type constraints for extended vectors.
12775 // Since vectors are an extension, there are no C standard reference for this.
12776 // We allow casting between vectors and integer datatypes of the same size,
12777 // or vectors and the element type of that vector.
12778 // returns the cast expr
12779 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
12780 CastKind &Kind);
12781
12782 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
12783 SourceLocation LParenLoc,
12784 Expr *CastExpr,
12785 SourceLocation RParenLoc);
12786
12787 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
12788
12789 /// Checks for invalid conversions and casts between
12790 /// retainable pointers and other pointer kinds for ARC and Weak.
12791 ARCConversionResult CheckObjCConversion(SourceRange castRange,
12792 QualType castType, Expr *&op,
12793 CheckedConversionKind CCK,
12794 bool Diagnose = true,
12795 bool DiagnoseCFAudited = false,
12796 BinaryOperatorKind Opc = BO_PtrMemD
12797 );
12798
12799 Expr *stripARCUnbridgedCast(Expr *e);
12800 void diagnoseARCUnbridgedCast(Expr *e);
12801
12802 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
12803 QualType ExprType);
12804
12805 /// checkRetainCycles - Check whether an Objective-C message send
12806 /// might create an obvious retain cycle.
12807 void checkRetainCycles(ObjCMessageExpr *msg);
12808 void checkRetainCycles(Expr *receiver, Expr *argument);
12809 void checkRetainCycles(VarDecl *Var, Expr *Init);
12810
12811 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
12812 /// to weak/__unsafe_unretained type.
12813 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
12814
12815 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
12816 /// to weak/__unsafe_unretained expression.
12817 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
12818
12819 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
12820 /// \param Method - May be null.
12821 /// \param [out] ReturnType - The return type of the send.
12822 /// \return true iff there were any incompatible types.
12823 bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
12824 MultiExprArg Args, Selector Sel,
12825 ArrayRef<SourceLocation> SelectorLocs,
12826 ObjCMethodDecl *Method, bool isClassMessage,
12827 bool isSuperMessage, SourceLocation lbrac,
12828 SourceLocation rbrac, SourceRange RecRange,
12829 QualType &ReturnType, ExprValueKind &VK);
12830
12831 /// Determine the result of a message send expression based on
12832 /// the type of the receiver, the method expected to receive the message,
12833 /// and the form of the message send.
12834 QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
12835 ObjCMethodDecl *Method, bool isClassMessage,
12836 bool isSuperMessage);
12837
12838 /// If the given expression involves a message send to a method
12839 /// with a related result type, emit a note describing what happened.
12840 void EmitRelatedResultTypeNote(const Expr *E);
12841
12842 /// Given that we had incompatible pointer types in a return
12843 /// statement, check whether we're in a method with a related result
12844 /// type, and if so, emit a note describing what happened.
12845 void EmitRelatedResultTypeNoteForReturn(QualType destType);
12846
12847 class ConditionResult {
12848 Decl *ConditionVar;
12849 FullExprArg Condition;
12850 bool Invalid;
12851 std::optional<bool> KnownValue;
12852
12853 friend class Sema;
12854 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
12855 bool IsConstexpr)
12856 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
12857 if (IsConstexpr && Condition.get()) {
12858 if (std::optional<llvm::APSInt> Val =
12859 Condition.get()->getIntegerConstantExpr(S.Context)) {
12860 KnownValue = !!(*Val);
12861 }
12862 }
12863 }
12864 explicit ConditionResult(bool Invalid)
12865 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
12866 KnownValue(std::nullopt) {}
12867
12868 public:
12869 ConditionResult() : ConditionResult(false) {}
12870 bool isInvalid() const { return Invalid; }
12871 std::pair<VarDecl *, Expr *> get() const {
12872 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
12873 Condition.get());
12874 }
12875 std::optional<bool> getKnownValue() const { return KnownValue; }
12876 };
12877 static ConditionResult ConditionError() { return ConditionResult(true); }
12878
12879 enum class ConditionKind {
12880 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
12881 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
12882 Switch ///< An integral condition for a 'switch' statement.
12883 };
12884 QualType PreferredConditionType(ConditionKind K) const {
12885 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
12886 }
12887
12888 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
12889 ConditionKind CK, bool MissingOK = false);
12890
12891 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
12892 SourceLocation StmtLoc,
12893 ConditionKind CK);
12894
12895 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
12896
12897 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
12898 SourceLocation StmtLoc,
12899 ConditionKind CK);
12900 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
12901
12902 /// CheckBooleanCondition - Diagnose problems involving the use of
12903 /// the given expression as a boolean condition (e.g. in an if
12904 /// statement). Also performs the standard function and array
12905 /// decays, possibly changing the input variable.
12906 ///
12907 /// \param Loc - A location associated with the condition, e.g. the
12908 /// 'if' keyword.
12909 /// \return true iff there were any errors
12910 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
12911 bool IsConstexpr = false);
12912
12913 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
12914 /// found in an explicit(bool) specifier.
12915 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
12916
12917 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
12918 /// Returns true if the explicit specifier is now resolved.
12919 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
12920
12921 /// DiagnoseAssignmentAsCondition - Given that an expression is
12922 /// being used as a boolean condition, warn if it's an assignment.
12923 void DiagnoseAssignmentAsCondition(Expr *E);
12924
12925 /// Redundant parentheses over an equality comparison can indicate
12926 /// that the user intended an assignment used as condition.
12927 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
12928
12929 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
12930 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
12931
12932 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
12933 /// the specified width and sign. If an overflow occurs, detect it and emit
12934 /// the specified diagnostic.
12935 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
12936 unsigned NewWidth, bool NewSign,
12937 SourceLocation Loc, unsigned DiagID);
12938
12939 /// Checks that the Objective-C declaration is declared in the global scope.
12940 /// Emits an error and marks the declaration as invalid if it's not declared
12941 /// in the global scope.
12942 bool CheckObjCDeclScope(Decl *D);
12943
12944 /// Abstract base class used for diagnosing integer constant
12945 /// expression violations.
12946 class VerifyICEDiagnoser {
12947 public:
12948 bool Suppress;
12949
12950 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
12951
12952 virtual SemaDiagnosticBuilder
12953 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
12954 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
12955 SourceLocation Loc) = 0;
12956 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
12957 virtual ~VerifyICEDiagnoser() {}
12958 };
12959
12960 enum AllowFoldKind {
12961 NoFold,
12962 AllowFold,
12963 };
12964
12965 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
12966 /// and reports the appropriate diagnostics. Returns false on success.
12967 /// Can optionally return the value of the expression.
12968 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12969 VerifyICEDiagnoser &Diagnoser,
12970 AllowFoldKind CanFold = NoFold);
12971 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12972 unsigned DiagID,
12973 AllowFoldKind CanFold = NoFold);
12974 ExprResult VerifyIntegerConstantExpression(Expr *E,
12975 llvm::APSInt *Result = nullptr,
12976 AllowFoldKind CanFold = NoFold);
12977 ExprResult VerifyIntegerConstantExpression(Expr *E,
12978 AllowFoldKind CanFold = NoFold) {
12979 return VerifyIntegerConstantExpression(E, nullptr, CanFold);
12980 }
12981
12982 /// VerifyBitField - verifies that a bit field expression is an ICE and has
12983 /// the correct width, and that the field type is valid.
12984 /// Returns false on success.
12985 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
12986 QualType FieldTy, bool IsMsStruct, Expr *BitWidth);
12987
12988private:
12989 unsigned ForceCUDAHostDeviceDepth = 0;
12990
12991public:
12992 /// Increments our count of the number of times we've seen a pragma forcing
12993 /// functions to be __host__ __device__. So long as this count is greater
12994 /// than zero, all functions encountered will be __host__ __device__.
12995 void PushForceCUDAHostDevice();
12996
12997 /// Decrements our count of the number of times we've seen a pragma forcing
12998 /// functions to be __host__ __device__. Returns false if the count is 0
12999 /// before incrementing, so you can emit an error.
13000 bool PopForceCUDAHostDevice();
13001
13002 /// Diagnostics that are emitted only if we discover that the given function
13003 /// must be codegen'ed. Because handling these correctly adds overhead to
13004 /// compilation, this is currently only enabled for CUDA compilations.
13005 llvm::DenseMap<CanonicalDeclPtr<const FunctionDecl>,
13006 std::vector<PartialDiagnosticAt>>
13007 DeviceDeferredDiags;
13008
13009 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
13010 /// key in a hashtable, both the FD and location are hashed.
13011 struct FunctionDeclAndLoc {
13012 CanonicalDeclPtr<const FunctionDecl> FD;
13013 SourceLocation Loc;
13014 };
13015
13016 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
13017 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
13018 /// same deferred diag twice.
13019 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
13020
13021 /// An inverse call graph, mapping known-emitted functions to one of their
13022 /// known-emitted callers (plus the location of the call).
13023 ///
13024 /// Functions that we can tell a priori must be emitted aren't added to this
13025 /// map.
13026 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<const FunctionDecl>,
13027 /* Caller = */ FunctionDeclAndLoc>
13028 DeviceKnownEmittedFns;
13029
13030 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
13031 /// context is "used as device code".
13032 ///
13033 /// - If CurContext is a __host__ function, does not emit any diagnostics
13034 /// unless \p EmitOnBothSides is true.
13035 /// - If CurContext is a __device__ or __global__ function, emits the
13036 /// diagnostics immediately.
13037 /// - If CurContext is a __host__ __device__ function and we are compiling for
13038 /// the device, creates a diagnostic which is emitted if and when we realize
13039 /// that the function will be codegen'ed.
13040 ///
13041 /// Example usage:
13042 ///
13043 /// // Variable-length arrays are not allowed in CUDA device code.
13044 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
13045 /// return ExprError();
13046 /// // Otherwise, continue parsing as normal.
13047 SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc,
13048 unsigned DiagID);
13049
13050 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
13051 /// context is "used as host code".
13052 ///
13053 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
13054 SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
13055
13056 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
13057 /// context is "used as device code".
13058 ///
13059 /// - If CurContext is a `declare target` function or it is known that the
13060 /// function is emitted for the device, emits the diagnostics immediately.
13061 /// - If CurContext is a non-`declare target` function and we are compiling
13062 /// for the device, creates a diagnostic which is emitted if and when we
13063 /// realize that the function will be codegen'ed.
13064 ///
13065 /// Example usage:
13066 ///
13067 /// // Variable-length arrays are not allowed in NVPTX device code.
13068 /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
13069 /// return ExprError();
13070 /// // Otherwise, continue parsing as normal.
13071 SemaDiagnosticBuilder diagIfOpenMPDeviceCode(SourceLocation Loc,
13072 unsigned DiagID,
13073 const FunctionDecl *FD);
13074
13075 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
13076 /// context is "used as host code".
13077 ///
13078 /// - If CurContext is a `declare target` function or it is known that the
13079 /// function is emitted for the host, emits the diagnostics immediately.
13080 /// - If CurContext is a non-host function, just ignore it.
13081 ///
13082 /// Example usage:
13083 ///
13084 /// // Variable-length arrays are not allowed in NVPTX device code.
13085 /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
13086 /// return ExprError();
13087 /// // Otherwise, continue parsing as normal.
13088 SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc,
13089 unsigned DiagID,
13090 const FunctionDecl *FD);
13091
13092 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
13093 const FunctionDecl *FD = nullptr);
13094 SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
13095 const PartialDiagnostic &PD,
13096 const FunctionDecl *FD = nullptr) {
13097 return targetDiag(Loc, PD.getDiagID(), FD) << PD;
13098 }
13099
13100 /// Check if the type is allowed to be used for the current target.
13101 void checkTypeSupport(QualType Ty, SourceLocation Loc,
13102 ValueDecl *D = nullptr);
13103
13104 enum CUDAFunctionTarget {
13105 CFT_Device,
13106 CFT_Global,
13107 CFT_Host,
13108 CFT_HostDevice,
13109 CFT_InvalidTarget
13110 };
13111
13112 /// Determines whether the given function is a CUDA device/host/kernel/etc.
13113 /// function.
13114 ///
13115 /// Use this rather than examining the function's attributes yourself -- you
13116 /// will get it wrong. Returns CFT_Host if D is null.
13117 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
13118 bool IgnoreImplicitHDAttr = false);
13119 CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
13120
13121 enum CUDAVariableTarget {
13122 CVT_Device, /// Emitted on device side with a shadow variable on host side
13123 CVT_Host, /// Emitted on host side only
13124 CVT_Both, /// Emitted on both sides with different addresses
13125 CVT_Unified, /// Emitted as a unified address, e.g. managed variables
13126 };
13127 /// Determines whether the given variable is emitted on host or device side.
13128 CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D);
13129
13130 /// Gets the CUDA target for the current context.
13131 CUDAFunctionTarget CurrentCUDATarget() {
13132 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
13133 }
13134
13135 static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D);
13136
13137 // CUDA function call preference. Must be ordered numerically from
13138 // worst to best.
13139 enum CUDAFunctionPreference {
13140 CFP_Never, // Invalid caller/callee combination.
13141 CFP_WrongSide, // Calls from host-device to host or device
13142 // function that do not match current compilation
13143 // mode.
13144 CFP_HostDevice, // Any calls to host/device functions.
13145 CFP_SameSide, // Calls from host-device to host or device
13146 // function matching current compilation mode.
13147 CFP_Native, // host-to-host or device-to-device calls.
13148 };
13149
13150 /// Identifies relative preference of a given Caller/Callee
13151 /// combination, based on their host/device attributes.
13152 /// \param Caller function which needs address of \p Callee.
13153 /// nullptr in case of global context.
13154 /// \param Callee target function
13155 ///
13156 /// \returns preference value for particular Caller/Callee combination.
13157 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
13158 const FunctionDecl *Callee);
13159
13160 /// Determines whether Caller may invoke Callee, based on their CUDA
13161 /// host/device attributes. Returns false if the call is not allowed.
13162 ///
13163 /// Note: Will return true for CFP_WrongSide calls. These may appear in
13164 /// semantically correct CUDA programs, but only if they're never codegen'ed.
13165 bool IsAllowedCUDACall(const FunctionDecl *Caller,
13166 const FunctionDecl *Callee) {
13167 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
13168 }
13169
13170 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
13171 /// depending on FD and the current compilation settings.
13172 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
13173 const LookupResult &Previous);
13174
13175 /// May add implicit CUDAConstantAttr attribute to VD, depending on VD
13176 /// and current compilation settings.
13177 void MaybeAddCUDAConstantAttr(VarDecl *VD);
13178
13179public:
13180 /// Check whether we're allowed to call Callee from the current context.
13181 ///
13182 /// - If the call is never allowed in a semantically-correct program
13183 /// (CFP_Never), emits an error and returns false.
13184 ///
13185 /// - If the call is allowed in semantically-correct programs, but only if
13186 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
13187 /// be emitted if and when the caller is codegen'ed, and returns true.
13188 ///
13189 /// Will only create deferred diagnostics for a given SourceLocation once,
13190 /// so you can safely call this multiple times without generating duplicate
13191 /// deferred errors.
13192 ///
13193 /// - Otherwise, returns true without emitting any diagnostics.
13194 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
13195
13196 void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture);
13197
13198 /// Set __device__ or __host__ __device__ attributes on the given lambda
13199 /// operator() method.
13200 ///
13201 /// CUDA lambdas by default is host device function unless it has explicit
13202 /// host or device attribute.
13203 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
13204
13205 /// Finds a function in \p Matches with highest calling priority
13206 /// from \p Caller context and erases all functions with lower
13207 /// calling priority.
13208 void EraseUnwantedCUDAMatches(
13209 const FunctionDecl *Caller,
13210 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
13211
13212 /// Given a implicit special member, infer its CUDA target from the
13213 /// calls it needs to make to underlying base/field special members.
13214 /// \param ClassDecl the class for which the member is being created.
13215 /// \param CSM the kind of special member.
13216 /// \param MemberDecl the special member itself.
13217 /// \param ConstRHS true if this is a copy operation with a const object on
13218 /// its RHS.
13219 /// \param Diagnose true if this call should emit diagnostics.
13220 /// \return true if there was an error inferring.
13221 /// The result of this call is implicit CUDA target attribute(s) attached to
13222 /// the member declaration.
13223 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
13224 CXXSpecialMember CSM,
13225 CXXMethodDecl *MemberDecl,
13226 bool ConstRHS,
13227 bool Diagnose);
13228
13229 /// \return true if \p CD can be considered empty according to CUDA
13230 /// (E.2.3.1 in CUDA 7.5 Programming guide).
13231 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
13232 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
13233
13234 // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
13235 // case of error emits appropriate diagnostic and invalidates \p Var.
13236 //
13237 // \details CUDA allows only empty constructors as initializers for global
13238 // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
13239 // __shared__ variables whether they are local or not (they all are implicitly
13240 // static in CUDA). One exception is that CUDA allows constant initializers
13241 // for __constant__ and __device__ variables.
13242 void checkAllowedCUDAInitializer(VarDecl *VD);
13243
13244 /// Check whether NewFD is a valid overload for CUDA. Emits
13245 /// diagnostics and invalidates NewFD if not.
13246 void checkCUDATargetOverload(FunctionDecl *NewFD,
13247 const LookupResult &Previous);
13248 /// Copies target attributes from the template TD to the function FD.
13249 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
13250
13251 /// Returns the name of the launch configuration function. This is the name
13252 /// of the function that will be called to configure kernel call, with the
13253 /// parameters specified via <<<>>>.
13254 std::string getCudaConfigureFuncName() const;
13255
13256 /// \name Code completion
13257 //@{
13258 /// Describes the context in which code completion occurs.
13259 enum ParserCompletionContext {
13260 /// Code completion occurs at top-level or namespace context.
13261 PCC_Namespace,
13262 /// Code completion occurs within a class, struct, or union.
13263 PCC_Class,
13264 /// Code completion occurs within an Objective-C interface, protocol,
13265 /// or category.
13266 PCC_ObjCInterface,
13267 /// Code completion occurs within an Objective-C implementation or
13268 /// category implementation
13269 PCC_ObjCImplementation,
13270 /// Code completion occurs within the list of instance variables
13271 /// in an Objective-C interface, protocol, category, or implementation.
13272 PCC_ObjCInstanceVariableList,
13273 /// Code completion occurs following one or more template
13274 /// headers.
13275 PCC_Template,
13276 /// Code completion occurs following one or more template
13277 /// headers within a class.
13278 PCC_MemberTemplate,
13279 /// Code completion occurs within an expression.
13280 PCC_Expression,
13281 /// Code completion occurs within a statement, which may
13282 /// also be an expression or a declaration.
13283 PCC_Statement,
13284 /// Code completion occurs at the beginning of the
13285 /// initialization statement (or expression) in a for loop.
13286 PCC_ForInit,
13287 /// Code completion occurs within the condition of an if,
13288 /// while, switch, or for statement.
13289 PCC_Condition,
13290 /// Code completion occurs within the body of a function on a
13291 /// recovery path, where we do not have a specific handle on our position
13292 /// in the grammar.
13293 PCC_RecoveryInFunction,
13294 /// Code completion occurs where only a type is permitted.
13295 PCC_Type,
13296 /// Code completion occurs in a parenthesized expression, which
13297 /// might also be a type cast.
13298 PCC_ParenthesizedExpression,
13299 /// Code completion occurs within a sequence of declaration
13300 /// specifiers within a function, method, or block.
13301 PCC_LocalDeclarationSpecifiers
13302 };
13303
13304 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
13305 void CodeCompleteOrdinaryName(Scope *S,
13306 ParserCompletionContext CompletionContext);
13307 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
13308 bool AllowNonIdentifiers,
13309 bool AllowNestedNameSpecifiers);
13310
13311 struct CodeCompleteExpressionData;
13312 void CodeCompleteExpression(Scope *S,
13313 const CodeCompleteExpressionData &Data);
13314 void CodeCompleteExpression(Scope *S, QualType PreferredType,
13315 bool IsParenthesized = false);
13316 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
13317 SourceLocation OpLoc, bool IsArrow,
13318 bool IsBaseExprStatement,
13319 QualType PreferredType);
13320 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
13321 QualType PreferredType);
13322 void CodeCompleteTag(Scope *S, unsigned TagSpec);
13323 void CodeCompleteTypeQualifiers(DeclSpec &DS);
13324 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
13325 const VirtSpecifiers *VS = nullptr);
13326 void CodeCompleteBracketDeclarator(Scope *S);
13327 void CodeCompleteCase(Scope *S);
13328 enum class AttributeCompletion {
13329 Attribute,
13330 Scope,
13331 None,
13332 };
13333 void CodeCompleteAttribute(
13334 AttributeCommonInfo::Syntax Syntax,
13335 AttributeCompletion Completion = AttributeCompletion::Attribute,
13336 const IdentifierInfo *Scope = nullptr);
13337 /// Determines the preferred type of the current function argument, by
13338 /// examining the signatures of all possible overloads.
13339 /// Returns null if unknown or ambiguous, or if code completion is off.
13340 ///
13341 /// If the code completion point has been reached, also reports the function
13342 /// signatures that were considered.
13343 ///
13344 /// FIXME: rename to GuessCallArgumentType to reduce confusion.
13345 QualType ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args,
13346 SourceLocation OpenParLoc);
13347 QualType ProduceConstructorSignatureHelp(QualType Type, SourceLocation Loc,
13348 ArrayRef<Expr *> Args,
13349 SourceLocation OpenParLoc,
13350 bool Braced);
13351 QualType ProduceCtorInitMemberSignatureHelp(
13352 Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy,
13353 ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc,
13354 bool Braced);
13355 QualType ProduceTemplateArgumentSignatureHelp(
13356 TemplateTy, ArrayRef<ParsedTemplateArgument>, SourceLocation LAngleLoc);
13357 void CodeCompleteInitializer(Scope *S, Decl *D);
13358 /// Trigger code completion for a record of \p BaseType. \p InitExprs are
13359 /// expressions in the initializer list seen so far and \p D is the current
13360 /// Designation being parsed.
13361 void CodeCompleteDesignator(const QualType BaseType,
13362 llvm::ArrayRef<Expr *> InitExprs,
13363 const Designation &D);
13364 void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
13365
13366 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
13367 bool IsUsingDeclaration, QualType BaseType,
13368 QualType PreferredType);
13369 void CodeCompleteUsing(Scope *S);
13370 void CodeCompleteUsingDirective(Scope *S);
13371 void CodeCompleteNamespaceDecl(Scope *S);
13372 void CodeCompleteNamespaceAliasDecl(Scope *S);
13373 void CodeCompleteOperatorName(Scope *S);
13374 void CodeCompleteConstructorInitializer(
13375 Decl *Constructor,
13376 ArrayRef<CXXCtorInitializer *> Initializers);
13377
13378 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
13379 bool AfterAmpersand);
13380 void CodeCompleteAfterFunctionEquals(Declarator &D);
13381
13382 void CodeCompleteObjCAtDirective(Scope *S);
13383 void CodeCompleteObjCAtVisibility(Scope *S);
13384 void CodeCompleteObjCAtStatement(Scope *S);
13385 void CodeCompleteObjCAtExpression(Scope *S);
13386 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
13387 void CodeCompleteObjCPropertyGetter(Scope *S);
13388 void CodeCompleteObjCPropertySetter(Scope *S);
13389 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
13390 bool IsParameter);
13391 void CodeCompleteObjCMessageReceiver(Scope *S);
13392 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
13393 ArrayRef<IdentifierInfo *> SelIdents,
13394 bool AtArgumentExpression);
13395 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
13396 ArrayRef<IdentifierInfo *> SelIdents,
13397 bool AtArgumentExpression,
13398 bool IsSuper = false);
13399 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
13400 ArrayRef<IdentifierInfo *> SelIdents,
13401 bool AtArgumentExpression,
13402 ObjCInterfaceDecl *Super = nullptr);
13403 void CodeCompleteObjCForCollection(Scope *S,
13404 DeclGroupPtrTy IterationVar);
13405 void CodeCompleteObjCSelector(Scope *S,
13406 ArrayRef<IdentifierInfo *> SelIdents);
13407 void CodeCompleteObjCProtocolReferences(
13408 ArrayRef<IdentifierLocPair> Protocols);
13409 void CodeCompleteObjCProtocolDecl(Scope *S);
13410 void CodeCompleteObjCInterfaceDecl(Scope *S);
13411 void CodeCompleteObjCSuperclass(Scope *S,
13412 IdentifierInfo *ClassName,
13413 SourceLocation ClassNameLoc);
13414 void CodeCompleteObjCImplementationDecl(Scope *S);
13415 void CodeCompleteObjCInterfaceCategory(Scope *S,
13416 IdentifierInfo *ClassName,
13417 SourceLocation ClassNameLoc);
13418 void CodeCompleteObjCImplementationCategory(Scope *S,
13419 IdentifierInfo *ClassName,
13420 SourceLocation ClassNameLoc);
13421 void CodeCompleteObjCPropertyDefinition(Scope *S);
13422 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
13423 IdentifierInfo *PropertyName);
13424 void CodeCompleteObjCMethodDecl(Scope *S,
13425 std::optional<bool> IsInstanceMethod,
13426 ParsedType ReturnType);
13427 void CodeCompleteObjCMethodDeclSelector(Scope *S,
13428 bool IsInstanceMethod,
13429 bool AtParameterName,
13430 ParsedType ReturnType,
13431 ArrayRef<IdentifierInfo *> SelIdents);
13432 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
13433 SourceLocation ClassNameLoc,
13434 bool IsBaseExprStatement);
13435 void CodeCompletePreprocessorDirective(bool InConditional);
13436 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
13437 void CodeCompletePreprocessorMacroName(bool IsDefinition);
13438 void CodeCompletePreprocessorExpression();
13439 void CodeCompletePreprocessorMacroArgument(Scope *S,
13440 IdentifierInfo *Macro,
13441 MacroInfo *MacroInfo,
13442 unsigned Argument);
13443 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
13444 void CodeCompleteNaturalLanguage();
13445 void CodeCompleteAvailabilityPlatformName();
13446 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
13447 CodeCompletionTUInfo &CCTUInfo,
13448 SmallVectorImpl<CodeCompletionResult> &Results);
13449 //@}
13450
13451 //===--------------------------------------------------------------------===//
13452 // Extra semantic analysis beyond the C type system
13453
13454public:
13455 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
13456 unsigned ByteNo) const;
13457
13458 enum FormatArgumentPassingKind {
13459 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
13460 FAPK_Variadic, // values to format are passed as variadic arguments
13461 FAPK_VAList, // values to format are passed in a va_list
13462 };
13463
13464 // Used to grab the relevant information from a FormatAttr and a
13465 // FunctionDeclaration.
13466 struct FormatStringInfo {
13467 unsigned FormatIdx;
13468 unsigned FirstDataArg;
13469 FormatArgumentPassingKind ArgPassingKind;
13470 };
13471
13472 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
13473 bool IsVariadic, FormatStringInfo *FSI);
13474
13475private:
13476 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13477 const ArraySubscriptExpr *ASE = nullptr,
13478 bool AllowOnePastEnd = true, bool IndexNegated = false);
13479 void CheckArrayAccess(const Expr *E);
13480
13481 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
13482 const FunctionProtoType *Proto);
13483 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
13484 ArrayRef<const Expr *> Args);
13485 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
13486 const FunctionProtoType *Proto);
13487 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
13488 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
13489 ArrayRef<const Expr *> Args,
13490 const FunctionProtoType *Proto, SourceLocation Loc);
13491
13492 void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg);
13493
13494 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
13495 StringRef ParamName, QualType ArgTy, QualType ParamTy);
13496
13497 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
13498 const Expr *ThisArg, ArrayRef<const Expr *> Args,
13499 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
13500 VariadicCallType CallType);
13501
13502 bool CheckObjCString(Expr *Arg);
13503 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
13504
13505 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
13506 unsigned BuiltinID, CallExpr *TheCall);
13507
13508 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13509 CallExpr *TheCall);
13510
13511 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
13512
13513 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
13514 unsigned MaxWidth);
13515 bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13516 CallExpr *TheCall);
13517 bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13518 bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13519 bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13520 CallExpr *TheCall);
13521 bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg,
13522 bool WantCDE);
13523 bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13524 CallExpr *TheCall);
13525
13526 bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13527 CallExpr *TheCall);
13528 bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13529 bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13530 bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
13531 bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13532 CallExpr *TheCall);
13533 bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
13534 CallExpr *TheCall);
13535 bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
13536 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13537 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
13538 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
13539 bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall);
13540 bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
13541 ArrayRef<int> ArgNums);
13542 bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums);
13543 bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
13544 ArrayRef<int> ArgNums);
13545 bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13546 CallExpr *TheCall);
13547 bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13548 CallExpr *TheCall);
13549 bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13550 bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum);
13551 bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13552 CallExpr *TheCall);
13553 bool CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI,
13554 unsigned BuiltinID, CallExpr *TheCall);
13555 bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI,
13556 unsigned BuiltinID,
13557 CallExpr *TheCall);
13558
13559 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
13560 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
13561 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
13562 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
13563 bool SemaBuiltinComplex(CallExpr *TheCall);
13564 bool SemaBuiltinVSX(CallExpr *TheCall);
13565 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
13566 bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
13567
13568public:
13569 // Used by C++ template instantiation.
13570 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
13571 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
13572 SourceLocation BuiltinLoc,
13573 SourceLocation RParenLoc);
13574
13575private:
13576 bool SemaBuiltinPrefetch(CallExpr *TheCall);
13577 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
13578 bool SemaBuiltinArithmeticFence(CallExpr *TheCall);
13579 bool SemaBuiltinAssume(CallExpr *TheCall);
13580 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
13581 bool SemaBuiltinLongjmp(CallExpr *TheCall);
13582 bool SemaBuiltinSetjmp(CallExpr *TheCall);
13583 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
13584 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
13585 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
13586 AtomicExpr::AtomicOp Op);
13587 ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
13588 bool IsDelete);
13589 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
13590 llvm::APSInt &Result);
13591 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
13592 int High, bool RangeIsError = true);
13593 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
13594 unsigned Multiple);
13595 bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
13596 bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
13597 unsigned ArgBits);
13598 bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
13599 unsigned ArgBits);
13600 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
13601 int ArgNum, unsigned ExpectedFieldNum,
13602 bool AllowName);
13603 bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
13604 bool SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
13605 const char *TypeDesc);
13606
13607 bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc);
13608
13609 bool SemaBuiltinElementwiseMath(CallExpr *TheCall);
13610 bool SemaBuiltinElementwiseTernaryMath(CallExpr *TheCall);
13611 bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall);
13612 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
13613
13614 bool SemaBuiltinNonDeterministicValue(CallExpr *TheCall);
13615
13616 // Matrix builtin handling.
13617 ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall,
13618 ExprResult CallResult);
13619 ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
13620 ExprResult CallResult);
13621 ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
13622 ExprResult CallResult);
13623
13624 // WebAssembly builtin handling.
13625 bool BuiltinWasmRefNullExtern(CallExpr *TheCall);
13626 bool BuiltinWasmRefNullFunc(CallExpr *TheCall);
13627
13628public:
13629 enum FormatStringType {
13630 FST_Scanf,
13631 FST_Printf,
13632 FST_NSString,
13633 FST_Strftime,
13634 FST_Strfmon,
13635 FST_Kprintf,
13636 FST_FreeBSDKPrintf,
13637 FST_OSTrace,
13638 FST_OSLog,
13639 FST_Unknown
13640 };
13641 static FormatStringType GetFormatStringType(const FormatAttr *Format);
13642
13643 bool FormatStringHasSArg(const StringLiteral *FExpr);
13644
13645 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
13646
13647private:
13648 bool CheckFormatArguments(const FormatAttr *Format,
13649 ArrayRef<const Expr *> Args, bool IsCXXMember,
13650 VariadicCallType CallType, SourceLocation Loc,
13651 SourceRange Range,
13652 llvm::SmallBitVector &CheckedVarArgs);
13653 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
13654 FormatArgumentPassingKind FAPK, unsigned format_idx,
13655 unsigned firstDataArg, FormatStringType Type,
13656 VariadicCallType CallType, SourceLocation Loc,
13657 SourceRange range,
13658 llvm::SmallBitVector &CheckedVarArgs);
13659
13660 void CheckAbsoluteValueFunction(const CallExpr *Call,
13661 const FunctionDecl *FDecl);
13662
13663 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
13664
13665 void CheckMemaccessArguments(const CallExpr *Call,
13666 unsigned BId,
13667 IdentifierInfo *FnName);
13668
13669 void CheckStrlcpycatArguments(const CallExpr *Call,
13670 IdentifierInfo *FnName);
13671
13672 void CheckStrncatArguments(const CallExpr *Call,
13673 IdentifierInfo *FnName);
13674
13675 void CheckFreeArguments(const CallExpr *E);
13676
13677 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
13678 SourceLocation ReturnLoc,
13679 bool isObjCMethod = false,
13680 const AttrVec *Attrs = nullptr,
13681 const FunctionDecl *FD = nullptr);
13682
13683public:
13684 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,
13685 BinaryOperatorKind Opcode);
13686
13687private:
13688 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
13689 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
13690 void CheckForIntOverflow(Expr *E);
13691 void CheckUnsequencedOperations(const Expr *E);
13692
13693 /// Perform semantic checks on a completed expression. This will either
13694 /// be a full-expression or a default argument expression.
13695 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
13696 bool IsConstexpr = false);
13697
13698 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
13699 Expr *Init);
13700
13701 /// Check if there is a field shadowing.
13702 void CheckShadowInheritedFields(const SourceLocation &Loc,
13703 DeclarationName FieldName,
13704 const CXXRecordDecl *RD,
13705 bool DeclIsField = true);
13706
13707 /// Check if the given expression contains 'break' or 'continue'
13708 /// statement that produces control flow different from GCC.
13709 void CheckBreakContinueBinding(Expr *E);
13710
13711 /// Check whether receiver is mutable ObjC container which
13712 /// attempts to add itself into the container
13713 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
13714
13715 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
13716 const NamedDecl *Callee);
13717
13718 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
13719 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
13720 bool DeleteWasArrayForm);
13721public:
13722 /// Register a magic integral constant to be used as a type tag.
13723 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13724 uint64_t MagicValue, QualType Type,
13725 bool LayoutCompatible, bool MustBeNull);
13726
13727 struct TypeTagData {
13728 TypeTagData() {}
13729
13730 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
13731 Type(Type), LayoutCompatible(LayoutCompatible),
13732 MustBeNull(MustBeNull)
13733 {}
13734
13735 QualType Type;
13736
13737 /// If true, \c Type should be compared with other expression's types for
13738 /// layout-compatibility.
13739 unsigned LayoutCompatible : 1;
13740 unsigned MustBeNull : 1;
13741 };
13742
13743 /// A pair of ArgumentKind identifier and magic value. This uniquely
13744 /// identifies the magic value.
13745 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
13746
13747private:
13748 /// A map from magic value to type information.
13749 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
13750 TypeTagForDatatypeMagicValues;
13751
13752 /// Peform checks on a call of a function with argument_with_type_tag
13753 /// or pointer_with_type_tag attributes.
13754 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13755 const ArrayRef<const Expr *> ExprArgs,
13756 SourceLocation CallSiteLoc);
13757
13758 /// Check if we are taking the address of a packed field
13759 /// as this may be a problem if the pointer value is dereferenced.
13760 void CheckAddressOfPackedMember(Expr *rhs);
13761
13762 /// The parser's current scope.
13763 ///
13764 /// The parser maintains this state here.
13765 Scope *CurScope;
13766
13767 mutable IdentifierInfo *Ident_super;
13768 mutable IdentifierInfo *Ident___float128;
13769
13770 /// Nullability type specifiers.
13771 IdentifierInfo *Ident__Nonnull = nullptr;
13772 IdentifierInfo *Ident__Nullable = nullptr;
13773 IdentifierInfo *Ident__Nullable_result = nullptr;
13774 IdentifierInfo *Ident__Null_unspecified = nullptr;
13775
13776 IdentifierInfo *Ident_NSError = nullptr;
13777
13778 /// The handler for the FileChanged preprocessor events.
13779 ///
13780 /// Used for diagnostics that implement custom semantic analysis for #include
13781 /// directives, like -Wpragma-pack.
13782 sema::SemaPPCallbacks *SemaPPCallbackHandler;
13783
13784protected:
13785 friend class Parser;
13786 friend class InitializationSequence;
13787 friend class ASTReader;
13788 friend class ASTDeclReader;
13789 friend class ASTWriter;
13790
13791public:
13792 /// Retrieve the keyword associated
13793 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
13794
13795 /// The struct behind the CFErrorRef pointer.
13796 RecordDecl *CFError = nullptr;
13797 bool isCFError(RecordDecl *D);
13798
13799 /// Retrieve the identifier "NSError".
13800 IdentifierInfo *getNSErrorIdent();
13801
13802 /// Retrieve the parser's current scope.
13803 ///
13804 /// This routine must only be used when it is certain that semantic analysis
13805 /// and the parser are in precisely the same context, which is not the case
13806 /// when, e.g., we are performing any kind of template instantiation.
13807 /// Therefore, the only safe places to use this scope are in the parser
13808 /// itself and in routines directly invoked from the parser and *never* from
13809 /// template substitution or instantiation.
13810 Scope *getCurScope() const { return CurScope; }
13811
13812 void incrementMSManglingNumber() const {
13813 return CurScope->incrementMSManglingNumber();
13814 }
13815
13816 IdentifierInfo *getSuperIdentifier() const;
13817 IdentifierInfo *getFloat128Identifier() const;
13818
13819 ObjCContainerDecl *getObjCDeclContext() const;
13820
13821 DeclContext *getCurLexicalContext() const {
13822 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
13823 }
13824
13825 const DeclContext *getCurObjCLexicalContext() const {
13826 const DeclContext *DC = getCurLexicalContext();
13827 // A category implicitly has the attribute of the interface.
13828 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
13829 DC = CatD->getClassInterface();
13830 return DC;
13831 }
13832
13833 /// Determine the number of levels of enclosing template parameters. This is
13834 /// only usable while parsing. Note that this does not include dependent
13835 /// contexts in which no template parameters have yet been declared, such as
13836 /// in a terse function template or generic lambda before the first 'auto' is
13837 /// encountered.
13838 unsigned getTemplateDepth(Scope *S) const;
13839
13840 /// To be used for checking whether the arguments being passed to
13841 /// function exceeds the number of parameters expected for it.
13842 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
13843 bool PartialOverloading = false) {
13844 // We check whether we're just after a comma in code-completion.
13845 if (NumArgs > 0 && PartialOverloading)
13846 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
13847 return NumArgs > NumParams;
13848 }
13849
13850 // Emitting members of dllexported classes is delayed until the class
13851 // (including field initializers) is fully parsed.
13852 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
13853 SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
13854
13855private:
13856 int ParsingClassDepth = 0;
13857
13858 class SavePendingParsedClassStateRAII {
13859 public:
13860 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
13861
13862 ~SavePendingParsedClassStateRAII() {
13863 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&(static_cast <bool> (S.DelayedOverridingExceptionSpecChecks
.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "clang/include/clang/Sema/Sema.h", 13864, __extension__ __PRETTY_FUNCTION__
))
13864 "there shouldn't be any pending delayed exception spec checks")(static_cast <bool> (S.DelayedOverridingExceptionSpecChecks
.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "clang/include/clang/Sema/Sema.h", 13864, __extension__ __PRETTY_FUNCTION__
))
;
13865 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&(static_cast <bool> (S.DelayedEquivalentExceptionSpecChecks
.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "clang/include/clang/Sema/Sema.h", 13866, __extension__ __PRETTY_FUNCTION__
))
13866 "there shouldn't be any pending delayed exception spec checks")(static_cast <bool> (S.DelayedEquivalentExceptionSpecChecks
.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "clang/include/clang/Sema/Sema.h", 13866, __extension__ __PRETTY_FUNCTION__
))
;
13867 swapSavedState();
13868 }
13869
13870 private:
13871 Sema &S;
13872 decltype(DelayedOverridingExceptionSpecChecks)
13873 SavedOverridingExceptionSpecChecks;
13874 decltype(DelayedEquivalentExceptionSpecChecks)
13875 SavedEquivalentExceptionSpecChecks;
13876
13877 void swapSavedState() {
13878 SavedOverridingExceptionSpecChecks.swap(
13879 S.DelayedOverridingExceptionSpecChecks);
13880 SavedEquivalentExceptionSpecChecks.swap(
13881 S.DelayedEquivalentExceptionSpecChecks);
13882 }
13883 };
13884
13885 /// Helper class that collects misaligned member designations and
13886 /// their location info for delayed diagnostics.
13887 struct MisalignedMember {
13888 Expr *E;
13889 RecordDecl *RD;
13890 ValueDecl *MD;
13891 CharUnits Alignment;
13892
13893 MisalignedMember() : E(), RD(), MD() {}
13894 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
13895 CharUnits Alignment)
13896 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
13897 explicit MisalignedMember(Expr *E)
13898 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
13899
13900 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
13901 };
13902 /// Small set of gathered accesses to potentially misaligned members
13903 /// due to the packed attribute.
13904 SmallVector<MisalignedMember, 4> MisalignedMembers;
13905
13906 /// Adds an expression to the set of gathered misaligned members.
13907 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13908 CharUnits Alignment);
13909
13910public:
13911 /// Diagnoses the current set of gathered accesses. This typically
13912 /// happens at full expression level. The set is cleared after emitting the
13913 /// diagnostics.
13914 void DiagnoseMisalignedMembers();
13915
13916 /// This function checks if the expression is in the sef of potentially
13917 /// misaligned members and it is converted to some pointer type T with lower
13918 /// or equal alignment requirements. If so it removes it. This is used when
13919 /// we do not want to diagnose such misaligned access (e.g. in conversions to
13920 /// void*).
13921 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
13922
13923 /// This function calls Action when it determines that E designates a
13924 /// misaligned member due to the packed attribute. This is used to emit
13925 /// local diagnostics like in reference binding.
13926 void RefersToMemberWithReducedAlignment(
13927 Expr *E,
13928 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13929 Action);
13930
13931 /// Describes the reason a calling convention specification was ignored, used
13932 /// for diagnostics.
13933 enum class CallingConventionIgnoredReason {
13934 ForThisTarget = 0,
13935 VariadicFunction,
13936 ConstructorDestructor,
13937 BuiltinFunction
13938 };
13939 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
13940 /// context is "used as device code".
13941 ///
13942 /// - If CurLexicalContext is a kernel function or it is known that the
13943 /// function will be emitted for the device, emits the diagnostics
13944 /// immediately.
13945 /// - If CurLexicalContext is a function and we are compiling
13946 /// for the device, but we don't know that this function will be codegen'ed
13947 /// for devive yet, creates a diagnostic which is emitted if and when we
13948 /// realize that the function will be codegen'ed.
13949 ///
13950 /// Example usage:
13951 ///
13952 /// Diagnose __float128 type usage only from SYCL device code if the current
13953 /// target doesn't support it
13954 /// if (!S.Context.getTargetInfo().hasFloat128Type() &&
13955 /// S.getLangOpts().SYCLIsDevice)
13956 /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
13957 SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc,
13958 unsigned DiagID);
13959
13960 void deepTypeCheckForSYCLDevice(SourceLocation UsedAt,
13961 llvm::DenseSet<QualType> Visited,
13962 ValueDecl *DeclToCheck);
13963};
13964
13965DeductionFailureInfo
13966MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
13967 sema::TemplateDeductionInfo &Info);
13968
13969/// Contains a late templated function.
13970/// Will be parsed at the end of the translation unit, used by Sema & Parser.
13971struct LateParsedTemplate {
13972 CachedTokens Toks;
13973 /// The template function declaration to be late parsed.
13974 Decl *D;
13975};
13976
13977template <>
13978void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
13979 PragmaMsStackAction Action,
13980 llvm::StringRef StackSlotLabel,
13981 AlignPackInfo Value);
13982
13983std::unique_ptr<sema::RISCVIntrinsicManager>
13984CreateRISCVIntrinsicManager(Sema &S);
13985} // end namespace clang
13986
13987namespace llvm {
13988// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
13989// SourceLocation.
13990template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
13991 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
13992 using FDBaseInfo =
13993 DenseMapInfo<clang::CanonicalDeclPtr<const clang::FunctionDecl>>;
13994
13995 static FunctionDeclAndLoc getEmptyKey() {
13996 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
13997 }
13998
13999 static FunctionDeclAndLoc getTombstoneKey() {
14000 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
14001 }
14002
14003 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
14004 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
14005 FDL.Loc.getHashValue());
14006 }
14007
14008 static bool isEqual(const FunctionDeclAndLoc &LHS,
14009 const FunctionDeclAndLoc &RHS) {
14010 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
14011 }
14012};
14013} // namespace llvm
14014
14015#endif