Bug Summary

File:clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Warning:line 5291, 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 -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiateDecl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-08-06-171148-17323-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

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

/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/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/TypeLoc.h"
36#include "clang/AST/TypeOrdering.h"
37#include "clang/Basic/BitmaskEnum.h"
38#include "clang/Basic/ExpressionTraits.h"
39#include "clang/Basic/Module.h"
40#include "clang/Basic/OpenCLOptions.h"
41#include "clang/Basic/OpenMPKinds.h"
42#include "clang/Basic/PragmaKinds.h"
43#include "clang/Basic/Specifiers.h"
44#include "clang/Basic/TemplateKinds.h"
45#include "clang/Basic/TypeTraits.h"
46#include "clang/Sema/AnalysisBasedWarnings.h"
47#include "clang/Sema/CleanupInfo.h"
48#include "clang/Sema/DeclSpec.h"
49#include "clang/Sema/ExternalSemaSource.h"
50#include "clang/Sema/IdentifierResolver.h"
51#include "clang/Sema/ObjCMethodList.h"
52#include "clang/Sema/Ownership.h"
53#include "clang/Sema/Scope.h"
54#include "clang/Sema/SemaConcept.h"
55#include "clang/Sema/TypoCorrection.h"
56#include "clang/Sema/Weak.h"
57#include "llvm/ADT/ArrayRef.h"
58#include "llvm/ADT/Optional.h"
59#include "llvm/ADT/SetVector.h"
60#include "llvm/ADT/SmallBitVector.h"
61#include "llvm/ADT/SmallSet.h"
62#include "llvm/ADT/SmallPtrSet.h"
63#include "llvm/ADT/SmallVector.h"
64#include "llvm/ADT/TinyPtrVector.h"
65#include "llvm/Frontend/OpenMP/OMPConstants.h"
66#include <deque>
67#include <memory>
68#include <string>
69#include <tuple>
70#include <vector>
71
72namespace llvm {
73 class APSInt;
74 template <typename ValueT> struct DenseMapInfo;
75 template <typename ValueT, typename ValueInfoT> class DenseSet;
76 class SmallBitVector;
77 struct InlineAsmIdentifierInfo;
78}
79
80namespace clang {
81 class ADLResult;
82 class ASTConsumer;
83 class ASTContext;
84 class ASTMutationListener;
85 class ASTReader;
86 class ASTWriter;
87 class ArrayType;
88 class ParsedAttr;
89 class BindingDecl;
90 class BlockDecl;
91 class CapturedDecl;
92 class CXXBasePath;
93 class CXXBasePaths;
94 class CXXBindTemporaryExpr;
95 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
96 class CXXConstructorDecl;
97 class CXXConversionDecl;
98 class CXXDeleteExpr;
99 class CXXDestructorDecl;
100 class CXXFieldCollector;
101 class CXXMemberCallExpr;
102 class CXXMethodDecl;
103 class CXXScopeSpec;
104 class CXXTemporary;
105 class CXXTryStmt;
106 class CallExpr;
107 class ClassTemplateDecl;
108 class ClassTemplatePartialSpecializationDecl;
109 class ClassTemplateSpecializationDecl;
110 class VarTemplatePartialSpecializationDecl;
111 class CodeCompleteConsumer;
112 class CodeCompletionAllocator;
113 class CodeCompletionTUInfo;
114 class CodeCompletionResult;
115 class CoroutineBodyStmt;
116 class Decl;
117 class DeclAccessPair;
118 class DeclContext;
119 class DeclRefExpr;
120 class DeclaratorDecl;
121 class DeducedTemplateArgument;
122 class DependentDiagnostic;
123 class DesignatedInitExpr;
124 class Designation;
125 class EnableIfAttr;
126 class EnumConstantDecl;
127 class Expr;
128 class ExtVectorType;
129 class FormatAttr;
130 class FriendDecl;
131 class FunctionDecl;
132 class FunctionProtoType;
133 class FunctionTemplateDecl;
134 class ImplicitConversionSequence;
135 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
136 class InitListExpr;
137 class InitializationKind;
138 class InitializationSequence;
139 class InitializedEntity;
140 class IntegerLiteral;
141 class LabelStmt;
142 class LambdaExpr;
143 class LangOptions;
144 class LocalInstantiationScope;
145 class LookupResult;
146 class MacroInfo;
147 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
148 class ModuleLoader;
149 class MultiLevelTemplateArgumentList;
150 class NamedDecl;
151 class ObjCCategoryDecl;
152 class ObjCCategoryImplDecl;
153 class ObjCCompatibleAliasDecl;
154 class ObjCContainerDecl;
155 class ObjCImplDecl;
156 class ObjCImplementationDecl;
157 class ObjCInterfaceDecl;
158 class ObjCIvarDecl;
159 template <class T> class ObjCList;
160 class ObjCMessageExpr;
161 class ObjCMethodDecl;
162 class ObjCPropertyDecl;
163 class ObjCProtocolDecl;
164 class OMPThreadPrivateDecl;
165 class OMPRequiresDecl;
166 class OMPDeclareReductionDecl;
167 class OMPDeclareSimdDecl;
168 class OMPClause;
169 struct OMPVarListLocTy;
170 struct OverloadCandidate;
171 enum class OverloadCandidateParamOrder : char;
172 enum OverloadCandidateRewriteKind : unsigned;
173 class OverloadCandidateSet;
174 class OverloadExpr;
175 class ParenListExpr;
176 class ParmVarDecl;
177 class Preprocessor;
178 class PseudoDestructorTypeStorage;
179 class PseudoObjectExpr;
180 class QualType;
181 class StandardConversionSequence;
182 class Stmt;
183 class StringLiteral;
184 class SwitchStmt;
185 class TemplateArgument;
186 class TemplateArgumentList;
187 class TemplateArgumentLoc;
188 class TemplateDecl;
189 class TemplateInstantiationCallback;
190 class TemplateParameterList;
191 class TemplatePartialOrderingContext;
192 class TemplateTemplateParmDecl;
193 class Token;
194 class TypeAliasDecl;
195 class TypedefDecl;
196 class TypedefNameDecl;
197 class TypeLoc;
198 class TypoCorrectionConsumer;
199 class UnqualifiedId;
200 class UnresolvedLookupExpr;
201 class UnresolvedMemberExpr;
202 class UnresolvedSetImpl;
203 class UnresolvedSetIterator;
204 class UsingDecl;
205 class UsingShadowDecl;
206 class ValueDecl;
207 class VarDecl;
208 class VarTemplateSpecializationDecl;
209 class VisibilityAttr;
210 class VisibleDeclConsumer;
211 class IndirectFieldDecl;
212 struct DeductionFailureInfo;
213 class TemplateSpecCandidateSet;
214
215namespace sema {
216 class AccessedEntity;
217 class BlockScopeInfo;
218 class Capture;
219 class CapturedRegionScopeInfo;
220 class CapturingScopeInfo;
221 class CompoundScopeInfo;
222 class DelayedDiagnostic;
223 class DelayedDiagnosticPool;
224 class FunctionScopeInfo;
225 class LambdaScopeInfo;
226 class PossiblyUnreachableDiag;
227 class SemaPPCallbacks;
228 class TemplateDeductionInfo;
229}
230
231namespace threadSafety {
232 class BeforeSet;
233 void threadSafetyCleanup(BeforeSet* Cache);
234}
235
236// FIXME: No way to easily map from TemplateTypeParmTypes to
237// TemplateTypeParmDecls, so we have this horrible PointerUnion.
238typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
239 SourceLocation> UnexpandedParameterPack;
240
241/// Describes whether we've seen any nullability information for the given
242/// file.
243struct FileNullability {
244 /// The first pointer declarator (of any pointer kind) in the file that does
245 /// not have a corresponding nullability annotation.
246 SourceLocation PointerLoc;
247
248 /// The end location for the first pointer declarator in the file. Used for
249 /// placing fix-its.
250 SourceLocation PointerEndLoc;
251
252 /// Which kind of pointer declarator we saw.
253 uint8_t PointerKind;
254
255 /// Whether we saw any type nullability annotations in the given file.
256 bool SawTypeNullability = false;
257};
258
259/// A mapping from file IDs to a record of whether we've seen nullability
260/// information in that file.
261class FileNullabilityMap {
262 /// A mapping from file IDs to the nullability information for each file ID.
263 llvm::DenseMap<FileID, FileNullability> Map;
264
265 /// A single-element cache based on the file ID.
266 struct {
267 FileID File;
268 FileNullability Nullability;
269 } Cache;
270
271public:
272 FileNullability &operator[](FileID file) {
273 // Check the single-element cache.
274 if (file == Cache.File)
275 return Cache.Nullability;
276
277 // It's not in the single-element cache; flush the cache if we have one.
278 if (!Cache.File.isInvalid()) {
279 Map[Cache.File] = Cache.Nullability;
280 }
281
282 // Pull this entry into the cache.
283 Cache.File = file;
284 Cache.Nullability = Map[file];
285 return Cache.Nullability;
286 }
287};
288
289/// Keeps track of expected type during expression parsing. The type is tied to
290/// a particular token, all functions that update or consume the type take a
291/// start location of the token they are looking at as a parameter. This allows
292/// to avoid updating the type on hot paths in the parser.
293class PreferredTypeBuilder {
294public:
295 PreferredTypeBuilder() = default;
296 explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
297
298 void enterCondition(Sema &S, SourceLocation Tok);
299 void enterReturn(Sema &S, SourceLocation Tok);
300 void enterVariableInit(SourceLocation Tok, Decl *D);
301 /// Computing a type for the function argument may require running
302 /// overloading, so we postpone its computation until it is actually needed.
303 ///
304 /// Clients should be very careful when using this funciton, as it stores a
305 /// function_ref, clients should make sure all calls to get() with the same
306 /// location happen while function_ref is alive.
307 void enterFunctionArgument(SourceLocation Tok,
308 llvm::function_ref<QualType()> ComputeType);
309
310 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
311 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
312 SourceLocation OpLoc);
313 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
314 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
315 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
316 /// Handles all type casts, including C-style cast, C++ casts, etc.
317 void enterTypeCast(SourceLocation Tok, QualType CastType);
318
319 QualType get(SourceLocation Tok) const {
320 if (Tok != ExpectedLoc)
321 return QualType();
322 if (!Type.isNull())
323 return Type;
324 if (ComputeType)
325 return ComputeType();
326 return QualType();
327 }
328
329private:
330 /// Start position of a token for which we store expected type.
331 SourceLocation ExpectedLoc;
332 /// Expected type for a token starting at ExpectedLoc.
333 QualType Type;
334 /// A function to compute expected type at ExpectedLoc. It is only considered
335 /// if Type is null.
336 llvm::function_ref<QualType()> ComputeType;
337};
338
339/// Sema - This implements semantic analysis and AST building for C.
340class Sema final {
341 Sema(const Sema &) = delete;
342 void operator=(const Sema &) = delete;
343
344 /// A key method to reduce duplicate debug info from Sema.
345 virtual void anchor();
346
347 ///Source of additional semantic information.
348 ExternalSemaSource *ExternalSource;
349
350 ///Whether Sema has generated a multiplexer and has to delete it.
351 bool isMultiplexExternalSource;
352
353 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
354
355 bool isVisibleSlow(const NamedDecl *D);
356
357 /// Determine whether two declarations should be linked together, given that
358 /// the old declaration might not be visible and the new declaration might
359 /// not have external linkage.
360 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
361 const NamedDecl *New) {
362 if (isVisible(Old))
363 return true;
364 // See comment in below overload for why it's safe to compute the linkage
365 // of the new declaration here.
366 if (New->isExternallyDeclarable()) {
367 assert(Old->isExternallyDeclarable() &&((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 368, __PRETTY_FUNCTION__))
368 "should not have found a non-externally-declarable previous decl")((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 368, __PRETTY_FUNCTION__))
;
369 return true;
370 }
371 return false;
372 }
373 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
374
375 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
376 QualType ResultTy,
377 ArrayRef<QualType> Args);
378
379public:
380 /// The maximum alignment, same as in llvm::Value. We duplicate them here
381 /// because that allows us not to duplicate the constants in clang code,
382 /// which we must to since we can't directly use the llvm constants.
383 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
384 ///
385 /// This is the greatest alignment value supported by load, store, and alloca
386 /// instructions, and global values.
387 static const unsigned MaxAlignmentExponent = 29;
388 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
389
390 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
391 typedef OpaquePtr<TemplateName> TemplateTy;
392 typedef OpaquePtr<QualType> TypeTy;
393
394 OpenCLOptions OpenCLFeatures;
395 FPOptions CurFPFeatures;
396
397 const LangOptions &LangOpts;
398 Preprocessor &PP;
399 ASTContext &Context;
400 ASTConsumer &Consumer;
401 DiagnosticsEngine &Diags;
402 SourceManager &SourceMgr;
403
404 /// Flag indicating whether or not to collect detailed statistics.
405 bool CollectStats;
406
407 /// Code-completion consumer.
408 CodeCompleteConsumer *CodeCompleter;
409
410 /// CurContext - This is the current declaration context of parsing.
411 DeclContext *CurContext;
412
413 /// Generally null except when we temporarily switch decl contexts,
414 /// like in \see ActOnObjCTemporaryExitContainerContext.
415 DeclContext *OriginalLexicalContext;
416
417 /// VAListTagName - The declaration name corresponding to __va_list_tag.
418 /// This is used as part of a hack to omit that class from ADL results.
419 DeclarationName VAListTagName;
420
421 bool MSStructPragmaOn; // True when \#pragma ms_struct on
422
423 /// Controls member pointer representation format under the MS ABI.
424 LangOptions::PragmaMSPointersToMembersKind
425 MSPointerToMemberRepresentationMethod;
426
427 /// Stack of active SEH __finally scopes. Can be empty.
428 SmallVector<Scope*, 2> CurrentSEHFinally;
429
430 /// Source location for newly created implicit MSInheritanceAttrs
431 SourceLocation ImplicitMSInheritanceAttrLoc;
432
433 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
434 /// `TransformTypos` in order to keep track of any TypoExprs that are created
435 /// recursively during typo correction and wipe them away if the correction
436 /// fails.
437 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
438
439 /// pragma clang section kind
440 enum PragmaClangSectionKind {
441 PCSK_Invalid = 0,
442 PCSK_BSS = 1,
443 PCSK_Data = 2,
444 PCSK_Rodata = 3,
445 PCSK_Text = 4,
446 PCSK_Relro = 5
447 };
448
449 enum PragmaClangSectionAction {
450 PCSA_Set = 0,
451 PCSA_Clear = 1
452 };
453
454 struct PragmaClangSection {
455 std::string SectionName;
456 bool Valid = false;
457 SourceLocation PragmaLocation;
458
459 void Act(SourceLocation PragmaLocation,
460 PragmaClangSectionAction Action,
461 StringLiteral* Name);
462 };
463
464 PragmaClangSection PragmaClangBSSSection;
465 PragmaClangSection PragmaClangDataSection;
466 PragmaClangSection PragmaClangRodataSection;
467 PragmaClangSection PragmaClangRelroSection;
468 PragmaClangSection PragmaClangTextSection;
469
470 enum PragmaMsStackAction {
471 PSK_Reset = 0x0, // #pragma ()
472 PSK_Set = 0x1, // #pragma (value)
473 PSK_Push = 0x2, // #pragma (push[, id])
474 PSK_Pop = 0x4, // #pragma (pop[, id])
475 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
476 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
477 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
478 };
479
480 template<typename ValueType>
481 struct PragmaStack {
482 struct Slot {
483 llvm::StringRef StackSlotLabel;
484 ValueType Value;
485 SourceLocation PragmaLocation;
486 SourceLocation PragmaPushLocation;
487 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
488 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
489 : StackSlotLabel(StackSlotLabel), Value(Value),
490 PragmaLocation(PragmaLocation),
491 PragmaPushLocation(PragmaPushLocation) {}
492 };
493
494 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
495 llvm::StringRef StackSlotLabel, ValueType Value) {
496 if (Action == PSK_Reset) {
497 CurrentValue = DefaultValue;
498 CurrentPragmaLocation = PragmaLocation;
499 return;
500 }
501 if (Action & PSK_Push)
502 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
503 PragmaLocation);
504 else if (Action & PSK_Pop) {
505 if (!StackSlotLabel.empty()) {
506 // If we've got a label, try to find it and jump there.
507 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
508 return x.StackSlotLabel == StackSlotLabel;
509 });
510 // If we found the label so pop from there.
511 if (I != Stack.rend()) {
512 CurrentValue = I->Value;
513 CurrentPragmaLocation = I->PragmaLocation;
514 Stack.erase(std::prev(I.base()), Stack.end());
515 }
516 } else if (!Stack.empty()) {
517 // We do not have a label, just pop the last entry.
518 CurrentValue = Stack.back().Value;
519 CurrentPragmaLocation = Stack.back().PragmaLocation;
520 Stack.pop_back();
521 }
522 }
523 if (Action & PSK_Set) {
524 CurrentValue = Value;
525 CurrentPragmaLocation = PragmaLocation;
526 }
527 }
528
529 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
530 // method body to restore the stacks on exit, so it works like this:
531 //
532 // struct S {
533 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
534 // void Method {}
535 // #pragma <name>(pop, InternalPragmaSlot)
536 // };
537 //
538 // It works even with #pragma vtordisp, although MSVC doesn't support
539 // #pragma vtordisp(push [, id], n)
540 // syntax.
541 //
542 // Push / pop a named sentinel slot.
543 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
544 assert((Action == PSK_Push || Action == PSK_Pop) &&(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 545, __PRETTY_FUNCTION__))
545 "Can only push / pop #pragma stack sentinels!")(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 545, __PRETTY_FUNCTION__))
;
546 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
547 }
548
549 // Constructors.
550 explicit PragmaStack(const ValueType &Default)
551 : DefaultValue(Default), CurrentValue(Default) {}
552
553 bool hasValue() const { return CurrentValue != DefaultValue; }
554
555 SmallVector<Slot, 2> Stack;
556 ValueType DefaultValue; // Value used for PSK_Reset action.
557 ValueType CurrentValue;
558 SourceLocation CurrentPragmaLocation;
559 };
560 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
561 // we shouldn't do so if they're in a module).
562
563 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
564 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
565 ///
566 /// 0: Suppress all vtordisps
567 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
568 /// structors
569 /// 2: Always insert vtordisps to support RTTI on partially constructed
570 /// objects
571 PragmaStack<MSVtorDispMode> VtorDispStack;
572 // #pragma pack.
573 // Sentinel to represent when the stack is set to mac68k alignment.
574 static const unsigned kMac68kAlignmentSentinel = ~0U;
575 PragmaStack<unsigned> PackStack;
576 // The current #pragma pack values and locations at each #include.
577 struct PackIncludeState {
578 unsigned CurrentValue;
579 SourceLocation CurrentPragmaLocation;
580 bool HasNonDefaultValue, ShouldWarnOnInclude;
581 };
582 SmallVector<PackIncludeState, 8> PackIncludeStack;
583 // Segment #pragmas.
584 PragmaStack<StringLiteral *> DataSegStack;
585 PragmaStack<StringLiteral *> BSSSegStack;
586 PragmaStack<StringLiteral *> ConstSegStack;
587 PragmaStack<StringLiteral *> CodeSegStack;
588
589 // This stack tracks the current state of Sema.CurFPFeatures.
590 PragmaStack<FPOptionsOverride::storage_type> FpPragmaStack;
591 FPOptionsOverride CurFPFeatureOverrides() {
592 FPOptionsOverride result;
593 if (!FpPragmaStack.hasValue()) {
594 result = FPOptionsOverride();
595 } else {
596 result = FPOptionsOverride(FpPragmaStack.CurrentValue);
597 }
598 return result;
599 }
600
601 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
602 // Actions should be performed only if we enter / exit a C++ method body.
603 class PragmaStackSentinelRAII {
604 public:
605 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
606 ~PragmaStackSentinelRAII();
607
608 private:
609 Sema &S;
610 StringRef SlotLabel;
611 bool ShouldAct;
612 };
613
614 /// A mapping that describes the nullability we've seen in each header file.
615 FileNullabilityMap NullabilityMap;
616
617 /// Last section used with #pragma init_seg.
618 StringLiteral *CurInitSeg;
619 SourceLocation CurInitSegLoc;
620
621 /// VisContext - Manages the stack for \#pragma GCC visibility.
622 void *VisContext; // Really a "PragmaVisStack*"
623
624 /// This an attribute introduced by \#pragma clang attribute.
625 struct PragmaAttributeEntry {
626 SourceLocation Loc;
627 ParsedAttr *Attribute;
628 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
629 bool IsUsed;
630 };
631
632 /// A push'd group of PragmaAttributeEntries.
633 struct PragmaAttributeGroup {
634 /// The location of the push attribute.
635 SourceLocation Loc;
636 /// The namespace of this push group.
637 const IdentifierInfo *Namespace;
638 SmallVector<PragmaAttributeEntry, 2> Entries;
639 };
640
641 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
642
643 /// The declaration that is currently receiving an attribute from the
644 /// #pragma attribute stack.
645 const Decl *PragmaAttributeCurrentTargetDecl;
646
647 /// This represents the last location of a "#pragma clang optimize off"
648 /// directive if such a directive has not been closed by an "on" yet. If
649 /// optimizations are currently "on", this is set to an invalid location.
650 SourceLocation OptimizeOffPragmaLocation;
651
652 /// Flag indicating if Sema is building a recovery call expression.
653 ///
654 /// This flag is used to avoid building recovery call expressions
655 /// if Sema is already doing so, which would cause infinite recursions.
656 bool IsBuildingRecoveryCallExpr;
657
658 /// Used to control the generation of ExprWithCleanups.
659 CleanupInfo Cleanup;
660
661 /// ExprCleanupObjects - This is the stack of objects requiring
662 /// cleanup that are created by the current full expression.
663 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
664
665 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
666 /// to a variable (constant) that may or may not be odr-used in this Expr, and
667 /// we won't know until all lvalue-to-rvalue and discarded value conversions
668 /// have been applied to all subexpressions of the enclosing full expression.
669 /// This is cleared at the end of each full expression.
670 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
671 llvm::SmallPtrSet<Expr *, 4>>;
672 MaybeODRUseExprSet MaybeODRUseExprs;
673
674 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
675
676 /// Stack containing information about each of the nested
677 /// function, block, and method scopes that are currently active.
678 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
679
680 /// The index of the first FunctionScope that corresponds to the current
681 /// context.
682 unsigned FunctionScopesStart = 0;
683
684 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
685 return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
686 FunctionScopes.end());
687 }
688
689 /// Stack containing information needed when in C++2a an 'auto' is encountered
690 /// in a function declaration parameter type specifier in order to invent a
691 /// corresponding template parameter in the enclosing abbreviated function
692 /// template. This information is also present in LambdaScopeInfo, stored in
693 /// the FunctionScopes stack.
694 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
695
696 /// The index of the first InventedParameterInfo that refers to the current
697 /// context.
698 unsigned InventedParameterInfosStart = 0;
699
700 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
701 return llvm::makeArrayRef(InventedParameterInfos.begin() +
702 InventedParameterInfosStart,
703 InventedParameterInfos.end());
704 }
705
706 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
707 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
708 ExtVectorDeclsType;
709
710 /// ExtVectorDecls - This is a list all the extended vector types. This allows
711 /// us to associate a raw vector type with one of the ext_vector type names.
712 /// This is only necessary for issuing pretty diagnostics.
713 ExtVectorDeclsType ExtVectorDecls;
714
715 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
716 std::unique_ptr<CXXFieldCollector> FieldCollector;
717
718 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
719
720 /// Set containing all declared private fields that are not used.
721 NamedDeclSetType UnusedPrivateFields;
722
723 /// Set containing all typedefs that are likely unused.
724 llvm::SmallSetVector<const TypedefNameDecl *, 4>
725 UnusedLocalTypedefNameCandidates;
726
727 /// Delete-expressions to be analyzed at the end of translation unit
728 ///
729 /// This list contains class members, and locations of delete-expressions
730 /// that could not be proven as to whether they mismatch with new-expression
731 /// used in initializer of the field.
732 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
733 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
734 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
735
736 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
737
738 /// PureVirtualClassDiagSet - a set of class declarations which we have
739 /// emitted a list of pure virtual functions. Used to prevent emitting the
740 /// same list more than once.
741 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
742
743 /// ParsingInitForAutoVars - a set of declarations with auto types for which
744 /// we are currently parsing the initializer.
745 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
746
747 /// Look for a locally scoped extern "C" declaration by the given name.
748 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
749
750 typedef LazyVector<VarDecl *, ExternalSemaSource,
751 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
752 TentativeDefinitionsType;
753
754 /// All the tentative definitions encountered in the TU.
755 TentativeDefinitionsType TentativeDefinitions;
756
757 /// All the external declarations encoutered and used in the TU.
758 SmallVector<VarDecl *, 4> ExternalDeclarations;
759
760 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
761 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
762 UnusedFileScopedDeclsType;
763
764 /// The set of file scoped decls seen so far that have not been used
765 /// and must warn if not used. Only contains the first declaration.
766 UnusedFileScopedDeclsType UnusedFileScopedDecls;
767
768 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
769 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
770 DelegatingCtorDeclsType;
771
772 /// All the delegating constructors seen so far in the file, used for
773 /// cycle detection at the end of the TU.
774 DelegatingCtorDeclsType DelegatingCtorDecls;
775
776 /// All the overriding functions seen during a class definition
777 /// that had their exception spec checks delayed, plus the overridden
778 /// function.
779 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
780 DelayedOverridingExceptionSpecChecks;
781
782 /// All the function redeclarations seen during a class definition that had
783 /// their exception spec checks delayed, plus the prior declaration they
784 /// should be checked against. Except during error recovery, the new decl
785 /// should always be a friend declaration, as that's the only valid way to
786 /// redeclare a special member before its class is complete.
787 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
788 DelayedEquivalentExceptionSpecChecks;
789
790 typedef llvm::MapVector<const FunctionDecl *,
791 std::unique_ptr<LateParsedTemplate>>
792 LateParsedTemplateMapT;
793 LateParsedTemplateMapT LateParsedTemplateMap;
794
795 /// Callback to the parser to parse templated functions when needed.
796 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
797 typedef void LateTemplateParserCleanupCB(void *P);
798 LateTemplateParserCB *LateTemplateParser;
799 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
800 void *OpaqueParser;
801
802 void SetLateTemplateParser(LateTemplateParserCB *LTP,
803 LateTemplateParserCleanupCB *LTPCleanup,
804 void *P) {
805 LateTemplateParser = LTP;
806 LateTemplateParserCleanup = LTPCleanup;
807 OpaqueParser = P;
808 }
809
810 class DelayedDiagnostics;
811
812 class DelayedDiagnosticsState {
813 sema::DelayedDiagnosticPool *SavedPool;
814 friend class Sema::DelayedDiagnostics;
815 };
816 typedef DelayedDiagnosticsState ParsingDeclState;
817 typedef DelayedDiagnosticsState ProcessingContextState;
818
819 /// A class which encapsulates the logic for delaying diagnostics
820 /// during parsing and other processing.
821 class DelayedDiagnostics {
822 /// The current pool of diagnostics into which delayed
823 /// diagnostics should go.
824 sema::DelayedDiagnosticPool *CurPool;
825
826 public:
827 DelayedDiagnostics() : CurPool(nullptr) {}
828
829 /// Adds a delayed diagnostic.
830 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
831
832 /// Determines whether diagnostics should be delayed.
833 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
834
835 /// Returns the current delayed-diagnostics pool.
836 sema::DelayedDiagnosticPool *getCurrentPool() const {
837 return CurPool;
838 }
839
840 /// Enter a new scope. Access and deprecation diagnostics will be
841 /// collected in this pool.
842 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
843 DelayedDiagnosticsState state;
844 state.SavedPool = CurPool;
845 CurPool = &pool;
846 return state;
847 }
848
849 /// Leave a delayed-diagnostic state that was previously pushed.
850 /// Do not emit any of the diagnostics. This is performed as part
851 /// of the bookkeeping of popping a pool "properly".
852 void popWithoutEmitting(DelayedDiagnosticsState state) {
853 CurPool = state.SavedPool;
854 }
855
856 /// Enter a new scope where access and deprecation diagnostics are
857 /// not delayed.
858 DelayedDiagnosticsState pushUndelayed() {
859 DelayedDiagnosticsState state;
860 state.SavedPool = CurPool;
861 CurPool = nullptr;
862 return state;
863 }
864
865 /// Undo a previous pushUndelayed().
866 void popUndelayed(DelayedDiagnosticsState state) {
867 assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 867, __PRETTY_FUNCTION__))
;
868 CurPool = state.SavedPool;
869 }
870 } DelayedDiagnostics;
871
872 /// A RAII object to temporarily push a declaration context.
873 class ContextRAII {
874 private:
875 Sema &S;
876 DeclContext *SavedContext;
877 ProcessingContextState SavedContextState;
878 QualType SavedCXXThisTypeOverride;
879 unsigned SavedFunctionScopesStart;
880 unsigned SavedInventedParameterInfosStart;
881
882 public:
883 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
884 : S(S), SavedContext(S.CurContext),
885 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
886 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
887 SavedFunctionScopesStart(S.FunctionScopesStart),
888 SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
889 {
890 assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast
<void> (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 890, __PRETTY_FUNCTION__))
;
891 S.CurContext = ContextToPush;
892 if (NewThisContext)
893 S.CXXThisTypeOverride = QualType();
894 // Any saved FunctionScopes do not refer to this context.
895 S.FunctionScopesStart = S.FunctionScopes.size();
896 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
897 }
898
899 void pop() {
900 if (!SavedContext) return;
901 S.CurContext = SavedContext;
902 S.DelayedDiagnostics.popUndelayed(SavedContextState);
903 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
904 S.FunctionScopesStart = SavedFunctionScopesStart;
905 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
906 SavedContext = nullptr;
907 }
908
909 ~ContextRAII() {
910 pop();
911 }
912 };
913
914 /// Whether the AST is currently being rebuilt to correct immediate
915 /// invocations. Immediate invocation candidates and references to consteval
916 /// functions aren't tracked when this is set.
917 bool RebuildingImmediateInvocation = false;
918
919 /// Used to change context to isConstantEvaluated without pushing a heavy
920 /// ExpressionEvaluationContextRecord object.
921 bool isConstantEvaluatedOverride;
922
923 bool isConstantEvaluated() {
924 return ExprEvalContexts.back().isConstantEvaluated() ||
925 isConstantEvaluatedOverride;
926 }
927
928 /// RAII object to handle the state changes required to synthesize
929 /// a function body.
930 class SynthesizedFunctionScope {
931 Sema &S;
932 Sema::ContextRAII SavedContext;
933 bool PushedCodeSynthesisContext = false;
934
935 public:
936 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
937 : S(S), SavedContext(S, DC) {
938 S.PushFunctionScope();
939 S.PushExpressionEvaluationContext(
940 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
941 if (auto *FD = dyn_cast<FunctionDecl>(DC))
942 FD->setWillHaveBody(true);
943 else
944 assert(isa<ObjCMethodDecl>(DC))((isa<ObjCMethodDecl>(DC)) ? static_cast<void> (0
) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 944, __PRETTY_FUNCTION__))
;
945 }
946
947 void addContextNote(SourceLocation UseLoc) {
948 assert(!PushedCodeSynthesisContext)((!PushedCodeSynthesisContext) ? static_cast<void> (0) :
__assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 948, __PRETTY_FUNCTION__))
;
949
950 Sema::CodeSynthesisContext Ctx;
951 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
952 Ctx.PointOfInstantiation = UseLoc;
953 Ctx.Entity = cast<Decl>(S.CurContext);
954 S.pushCodeSynthesisContext(Ctx);
955
956 PushedCodeSynthesisContext = true;
957 }
958
959 ~SynthesizedFunctionScope() {
960 if (PushedCodeSynthesisContext)
961 S.popCodeSynthesisContext();
962 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
963 FD->setWillHaveBody(false);
964 S.PopExpressionEvaluationContext();
965 S.PopFunctionScopeInfo();
966 }
967 };
968
969 /// WeakUndeclaredIdentifiers - Identifiers contained in
970 /// \#pragma weak before declared. rare. may alias another
971 /// identifier, declared or undeclared
972 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
973
974 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
975 /// \#pragma redefine_extname before declared. Used in Solaris system headers
976 /// to define functions that occur in multiple standards to call the version
977 /// in the currently selected standard.
978 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
979
980
981 /// Load weak undeclared identifiers from the external source.
982 void LoadExternalWeakUndeclaredIdentifiers();
983
984 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
985 /// \#pragma weak during processing of other Decls.
986 /// I couldn't figure out a clean way to generate these in-line, so
987 /// we store them here and handle separately -- which is a hack.
988 /// It would be best to refactor this.
989 SmallVector<Decl*,2> WeakTopLevelDecl;
990
991 IdentifierResolver IdResolver;
992
993 /// Translation Unit Scope - useful to Objective-C actions that need
994 /// to lookup file scope declarations in the "ordinary" C decl namespace.
995 /// For example, user-defined classes, built-in "id" type, etc.
996 Scope *TUScope;
997
998 /// The C++ "std" namespace, where the standard library resides.
999 LazyDeclPtr StdNamespace;
1000
1001 /// The C++ "std::bad_alloc" class, which is defined by the C++
1002 /// standard library.
1003 LazyDeclPtr StdBadAlloc;
1004
1005 /// The C++ "std::align_val_t" enum class, which is defined by the C++
1006 /// standard library.
1007 LazyDeclPtr StdAlignValT;
1008
1009 /// The C++ "std::experimental" namespace, where the experimental parts
1010 /// of the standard library resides.
1011 NamespaceDecl *StdExperimentalNamespaceCache;
1012
1013 /// The C++ "std::initializer_list" template, which is defined in
1014 /// \<initializer_list>.
1015 ClassTemplateDecl *StdInitializerList;
1016
1017 /// The C++ "std::coroutine_traits" template, which is defined in
1018 /// \<coroutine_traits>
1019 ClassTemplateDecl *StdCoroutineTraitsCache;
1020
1021 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1022 RecordDecl *CXXTypeInfoDecl;
1023
1024 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1025 RecordDecl *MSVCGuidDecl;
1026
1027 /// Caches identifiers/selectors for NSFoundation APIs.
1028 std::unique_ptr<NSAPI> NSAPIObj;
1029
1030 /// The declaration of the Objective-C NSNumber class.
1031 ObjCInterfaceDecl *NSNumberDecl;
1032
1033 /// The declaration of the Objective-C NSValue class.
1034 ObjCInterfaceDecl *NSValueDecl;
1035
1036 /// Pointer to NSNumber type (NSNumber *).
1037 QualType NSNumberPointer;
1038
1039 /// Pointer to NSValue type (NSValue *).
1040 QualType NSValuePointer;
1041
1042 /// The Objective-C NSNumber methods used to create NSNumber literals.
1043 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1044
1045 /// The declaration of the Objective-C NSString class.
1046 ObjCInterfaceDecl *NSStringDecl;
1047
1048 /// Pointer to NSString type (NSString *).
1049 QualType NSStringPointer;
1050
1051 /// The declaration of the stringWithUTF8String: method.
1052 ObjCMethodDecl *StringWithUTF8StringMethod;
1053
1054 /// The declaration of the valueWithBytes:objCType: method.
1055 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1056
1057 /// The declaration of the Objective-C NSArray class.
1058 ObjCInterfaceDecl *NSArrayDecl;
1059
1060 /// The declaration of the arrayWithObjects:count: method.
1061 ObjCMethodDecl *ArrayWithObjectsMethod;
1062
1063 /// The declaration of the Objective-C NSDictionary class.
1064 ObjCInterfaceDecl *NSDictionaryDecl;
1065
1066 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1067 ObjCMethodDecl *DictionaryWithObjectsMethod;
1068
1069 /// id<NSCopying> type.
1070 QualType QIDNSCopying;
1071
1072 /// will hold 'respondsToSelector:'
1073 Selector RespondsToSelectorSel;
1074
1075 /// A flag to remember whether the implicit forms of operator new and delete
1076 /// have been declared.
1077 bool GlobalNewDeleteDeclared;
1078
1079 /// A flag to indicate that we're in a context that permits abstract
1080 /// references to fields. This is really a
1081 bool AllowAbstractFieldReference;
1082
1083 /// Describes how the expressions currently being parsed are
1084 /// evaluated at run-time, if at all.
1085 enum class ExpressionEvaluationContext {
1086 /// The current expression and its subexpressions occur within an
1087 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1088 /// \c sizeof, where the type of the expression may be significant but
1089 /// no code will be generated to evaluate the value of the expression at
1090 /// run time.
1091 Unevaluated,
1092
1093 /// The current expression occurs within a braced-init-list within
1094 /// an unevaluated operand. This is mostly like a regular unevaluated
1095 /// context, except that we still instantiate constexpr functions that are
1096 /// referenced here so that we can perform narrowing checks correctly.
1097 UnevaluatedList,
1098
1099 /// The current expression occurs within a discarded statement.
1100 /// This behaves largely similarly to an unevaluated operand in preventing
1101 /// definitions from being required, but not in other ways.
1102 DiscardedStatement,
1103
1104 /// The current expression occurs within an unevaluated
1105 /// operand that unconditionally permits abstract references to
1106 /// fields, such as a SIZE operator in MS-style inline assembly.
1107 UnevaluatedAbstract,
1108
1109 /// The current context is "potentially evaluated" in C++11 terms,
1110 /// but the expression is evaluated at compile-time (like the values of
1111 /// cases in a switch statement).
1112 ConstantEvaluated,
1113
1114 /// The current expression is potentially evaluated at run time,
1115 /// which means that code may be generated to evaluate the value of the
1116 /// expression at run time.
1117 PotentiallyEvaluated,
1118
1119 /// The current expression is potentially evaluated, but any
1120 /// declarations referenced inside that expression are only used if
1121 /// in fact the current expression is used.
1122 ///
1123 /// This value is used when parsing default function arguments, for which
1124 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1125 /// through varargs) but do not want to mark declarations as "referenced"
1126 /// until the default argument is used.
1127 PotentiallyEvaluatedIfUsed
1128 };
1129
1130 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1131
1132 /// Data structure used to record current or nested
1133 /// expression evaluation contexts.
1134 struct ExpressionEvaluationContextRecord {
1135 /// The expression evaluation context.
1136 ExpressionEvaluationContext Context;
1137
1138 /// Whether the enclosing context needed a cleanup.
1139 CleanupInfo ParentCleanup;
1140
1141 /// Whether we are in a decltype expression.
1142 bool IsDecltype;
1143
1144 /// The number of active cleanup objects when we entered
1145 /// this expression evaluation context.
1146 unsigned NumCleanupObjects;
1147
1148 /// The number of typos encountered during this expression evaluation
1149 /// context (i.e. the number of TypoExprs created).
1150 unsigned NumTypos;
1151
1152 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1153
1154 /// The lambdas that are present within this context, if it
1155 /// is indeed an unevaluated context.
1156 SmallVector<LambdaExpr *, 2> Lambdas;
1157
1158 /// The declaration that provides context for lambda expressions
1159 /// and block literals if the normal declaration context does not
1160 /// suffice, e.g., in a default function argument.
1161 Decl *ManglingContextDecl;
1162
1163 /// If we are processing a decltype type, a set of call expressions
1164 /// for which we have deferred checking the completeness of the return type.
1165 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1166
1167 /// If we are processing a decltype type, a set of temporary binding
1168 /// expressions for which we have deferred checking the destructor.
1169 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1170
1171 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1172
1173 /// Expressions appearing as the LHS of a volatile assignment in this
1174 /// context. We produce a warning for these when popping the context if
1175 /// they are not discarded-value expressions nor unevaluated operands.
1176 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1177
1178 /// Set of candidates for starting an immediate invocation.
1179 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1180
1181 /// Set of DeclRefExprs referencing a consteval function when used in a
1182 /// context not already known to be immediately invoked.
1183 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1184
1185 /// \brief Describes whether we are in an expression constext which we have
1186 /// to handle differently.
1187 enum ExpressionKind {
1188 EK_Decltype, EK_TemplateArgument, EK_Other
1189 } ExprContext;
1190
1191 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1192 unsigned NumCleanupObjects,
1193 CleanupInfo ParentCleanup,
1194 Decl *ManglingContextDecl,
1195 ExpressionKind ExprContext)
1196 : Context(Context), ParentCleanup(ParentCleanup),
1197 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1198 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1199
1200 bool isUnevaluated() const {
1201 return Context == ExpressionEvaluationContext::Unevaluated ||
1202 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1203 Context == ExpressionEvaluationContext::UnevaluatedList;
1204 }
1205 bool isConstantEvaluated() const {
1206 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1207 }
1208 };
1209
1210 /// A stack of expression evaluation contexts.
1211 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1212
1213 /// Emit a warning for all pending noderef expressions that we recorded.
1214 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1215
1216 /// Compute the mangling number context for a lambda expression or
1217 /// block literal. Also return the extra mangling decl if any.
1218 ///
1219 /// \param DC - The DeclContext containing the lambda expression or
1220 /// block literal.
1221 std::tuple<MangleNumberingContext *, Decl *>
1222 getCurrentMangleNumberContext(const DeclContext *DC);
1223
1224
1225 /// SpecialMemberOverloadResult - The overloading result for a special member
1226 /// function.
1227 ///
1228 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1229 /// integer are used to determine whether overload resolution succeeded.
1230 class SpecialMemberOverloadResult {
1231 public:
1232 enum Kind {
1233 NoMemberOrDeleted,
1234 Ambiguous,
1235 Success
1236 };
1237
1238 private:
1239 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1240
1241 public:
1242 SpecialMemberOverloadResult() : Pair() {}
1243 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1244 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1245
1246 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1247 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1248
1249 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1250 void setKind(Kind K) { Pair.setInt(K); }
1251 };
1252
1253 class SpecialMemberOverloadResultEntry
1254 : public llvm::FastFoldingSetNode,
1255 public SpecialMemberOverloadResult {
1256 public:
1257 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1258 : FastFoldingSetNode(ID)
1259 {}
1260 };
1261
1262 /// A cache of special member function overload resolution results
1263 /// for C++ records.
1264 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1265
1266 /// A cache of the flags available in enumerations with the flag_bits
1267 /// attribute.
1268 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1269
1270 /// The kind of translation unit we are processing.
1271 ///
1272 /// When we're processing a complete translation unit, Sema will perform
1273 /// end-of-translation-unit semantic tasks (such as creating
1274 /// initializers for tentative definitions in C) once parsing has
1275 /// completed. Modules and precompiled headers perform different kinds of
1276 /// checks.
1277 TranslationUnitKind TUKind;
1278
1279 llvm::BumpPtrAllocator BumpAlloc;
1280
1281 /// The number of SFINAE diagnostics that have been trapped.
1282 unsigned NumSFINAEErrors;
1283
1284 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1285 UnparsedDefaultArgInstantiationsMap;
1286
1287 /// A mapping from parameters with unparsed default arguments to the
1288 /// set of instantiations of each parameter.
1289 ///
1290 /// This mapping is a temporary data structure used when parsing
1291 /// nested class templates or nested classes of class templates,
1292 /// where we might end up instantiating an inner class before the
1293 /// default arguments of its methods have been parsed.
1294 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1295
1296 // Contains the locations of the beginning of unparsed default
1297 // argument locations.
1298 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1299
1300 /// UndefinedInternals - all the used, undefined objects which require a
1301 /// definition in this translation unit.
1302 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1303
1304 /// Determine if VD, which must be a variable or function, is an external
1305 /// symbol that nonetheless can't be referenced from outside this translation
1306 /// unit because its type has no linkage and it's not extern "C".
1307 bool isExternalWithNoLinkageType(ValueDecl *VD);
1308
1309 /// Obtain a sorted list of functions that are undefined but ODR-used.
1310 void getUndefinedButUsed(
1311 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1312
1313 /// Retrieves list of suspicious delete-expressions that will be checked at
1314 /// the end of translation unit.
1315 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1316 getMismatchingDeleteExpressions() const;
1317
1318 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1319 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1320
1321 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1322 /// We need to maintain a list, since selectors can have differing signatures
1323 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1324 /// of selectors are "overloaded").
1325 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1326 /// methods inside categories with a particular selector.
1327 GlobalMethodPool MethodPool;
1328
1329 /// Method selectors used in a \@selector expression. Used for implementation
1330 /// of -Wselector.
1331 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1332
1333 /// List of SourceLocations where 'self' is implicitly retained inside a
1334 /// block.
1335 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1336 ImplicitlyRetainedSelfLocs;
1337
1338 /// Kinds of C++ special members.
1339 enum CXXSpecialMember {
1340 CXXDefaultConstructor,
1341 CXXCopyConstructor,
1342 CXXMoveConstructor,
1343 CXXCopyAssignment,
1344 CXXMoveAssignment,
1345 CXXDestructor,
1346 CXXInvalid
1347 };
1348
1349 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1350 SpecialMemberDecl;
1351
1352 /// The C++ special members which we are currently in the process of
1353 /// declaring. If this process recursively triggers the declaration of the
1354 /// same special member, we should act as if it is not yet declared.
1355 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1356
1357 /// Kinds of defaulted comparison operator functions.
1358 enum class DefaultedComparisonKind : unsigned char {
1359 /// This is not a defaultable comparison operator.
1360 None,
1361 /// This is an operator== that should be implemented as a series of
1362 /// subobject comparisons.
1363 Equal,
1364 /// This is an operator<=> that should be implemented as a series of
1365 /// subobject comparisons.
1366 ThreeWay,
1367 /// This is an operator!= that should be implemented as a rewrite in terms
1368 /// of a == comparison.
1369 NotEqual,
1370 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1371 /// terms of a <=> comparison.
1372 Relational,
1373 };
1374
1375 /// The function definitions which were renamed as part of typo-correction
1376 /// to match their respective declarations. We want to keep track of them
1377 /// to ensure that we don't emit a "redefinition" error if we encounter a
1378 /// correctly named definition after the renamed definition.
1379 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1380
1381 /// Stack of types that correspond to the parameter entities that are
1382 /// currently being copy-initialized. Can be empty.
1383 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1384
1385 void ReadMethodPool(Selector Sel);
1386 void updateOutOfDateSelector(Selector Sel);
1387
1388 /// Private Helper predicate to check for 'self'.
1389 bool isSelfExpr(Expr *RExpr);
1390 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1391
1392 /// Cause the active diagnostic on the DiagosticsEngine to be
1393 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1394 /// should not be used elsewhere.
1395 void EmitCurrentDiagnostic(unsigned DiagID);
1396
1397 /// Records and restores the CurFPFeatures state on entry/exit of compound
1398 /// statements.
1399 class FPFeaturesStateRAII {
1400 public:
1401 FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) {
1402 OldOverrides = S.FpPragmaStack.CurrentValue;
1403 }
1404 ~FPFeaturesStateRAII() {
1405 S.CurFPFeatures = OldFPFeaturesState;
1406 S.FpPragmaStack.CurrentValue = OldOverrides;
1407 }
1408 FPOptionsOverride::storage_type getOverrides() { return OldOverrides; }
1409
1410 private:
1411 Sema& S;
1412 FPOptions OldFPFeaturesState;
1413 FPOptionsOverride::storage_type OldOverrides;
1414 };
1415
1416 void addImplicitTypedef(StringRef Name, QualType T);
1417
1418 bool WarnedStackExhausted = false;
1419
1420public:
1421 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1422 TranslationUnitKind TUKind = TU_Complete,
1423 CodeCompleteConsumer *CompletionConsumer = nullptr);
1424 ~Sema();
1425
1426 /// Perform initialization that occurs after the parser has been
1427 /// initialized but before it parses anything.
1428 void Initialize();
1429
1430 const LangOptions &getLangOpts() const { return LangOpts; }
1431 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1432 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
1433
1434 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1435 SourceManager &getSourceManager() const { return SourceMgr; }
1436 Preprocessor &getPreprocessor() const { return PP; }
1437 ASTContext &getASTContext() const { return Context; }
1438 ASTConsumer &getASTConsumer() const { return Consumer; }
1439 ASTMutationListener *getASTMutationListener() const;
1440 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1441
1442 ///Registers an external source. If an external source already exists,
1443 /// creates a multiplex external source and appends to it.
1444 ///
1445 ///\param[in] E - A non-null external sema source.
1446 ///
1447 void addExternalSource(ExternalSemaSource *E);
1448
1449 void PrintStats() const;
1450
1451 /// Warn that the stack is nearly exhausted.
1452 void warnStackExhausted(SourceLocation Loc);
1453
1454 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1455 /// guaranteed). Produces a warning if we're low on stack space and allocates
1456 /// more in that case. Use this in code that may recurse deeply (for example,
1457 /// in template instantiation) to avoid stack overflow.
1458 void runWithSufficientStackSpace(SourceLocation Loc,
1459 llvm::function_ref<void()> Fn);
1460
1461 /// Helper class that creates diagnostics with optional
1462 /// template instantiation stacks.
1463 ///
1464 /// This class provides a wrapper around the basic DiagnosticBuilder
1465 /// class that emits diagnostics. SemaDiagnosticBuilder is
1466 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1467 /// does) and, if the diagnostic comes from inside a template
1468 /// instantiation, printing the template instantiation stack as
1469 /// well.
1470 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1471 Sema &SemaRef;
1472 unsigned DiagID;
1473
1474 public:
1475 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1476 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1477
1478 // This is a cunning lie. DiagnosticBuilder actually performs move
1479 // construction in its copy constructor (but due to varied uses, it's not
1480 // possible to conveniently express this as actual move construction). So
1481 // the default copy ctor here is fine, because the base class disables the
1482 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1483 // in that case anwyay.
1484 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1485
1486 ~SemaDiagnosticBuilder() {
1487 // If we aren't active, there is nothing to do.
1488 if (!isActive()) return;
1489
1490 // Otherwise, we need to emit the diagnostic. First flush the underlying
1491 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1492 // won't emit the diagnostic in its own destructor.
1493 //
1494 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1495 // do its own needless checks to see if the diagnostic needs to be
1496 // emitted. However, because we take care to ensure that the builder
1497 // objects never escape, a sufficiently smart compiler will be able to
1498 // eliminate that code.
1499 FlushCounts();
1500 Clear();
1501
1502 // Dispatch to Sema to emit the diagnostic.
1503 SemaRef.EmitCurrentDiagnostic(DiagID);
1504 }
1505
1506 /// Teach operator<< to produce an object of the correct type.
1507 template<typename T>
1508 friend const SemaDiagnosticBuilder &operator<<(
1509 const SemaDiagnosticBuilder &Diag, const T &Value) {
1510 const DiagnosticBuilder &BaseDiag = Diag;
1511 BaseDiag << Value;
1512 return Diag;
1513 }
1514 };
1515
1516 /// Emit a diagnostic.
1517 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1518 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1519 return SemaDiagnosticBuilder(DB, *this, DiagID);
1520 }
1521
1522 /// Emit a partial diagnostic.
1523 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1524
1525 /// Build a partial diagnostic.
1526 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1527
1528 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1529
1530 /// Get a string to suggest for zero-initialization of a type.
1531 std::string
1532 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1533 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1534
1535 /// Calls \c Lexer::getLocForEndOfToken()
1536 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1537
1538 /// Retrieve the module loader associated with the preprocessor.
1539 ModuleLoader &getModuleLoader() const;
1540
1541 /// Invent a new identifier for parameters of abbreviated templates.
1542 IdentifierInfo *
1543 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1544 unsigned Index);
1545
1546 void emitAndClearUnusedLocalTypedefWarnings();
1547
1548 private:
1549 /// Function or variable declarations to be checked for whether the deferred
1550 /// diagnostics should be emitted.
1551 SmallVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1552
1553 public:
1554 // Emit all deferred diagnostics.
1555 void emitDeferredDiags();
1556
1557 enum TUFragmentKind {
1558 /// The global module fragment, between 'module;' and a module-declaration.
1559 Global,
1560 /// A normal translation unit fragment. For a non-module unit, this is the
1561 /// entire translation unit. Otherwise, it runs from the module-declaration
1562 /// to the private-module-fragment (if any) or the end of the TU (if not).
1563 Normal,
1564 /// The private module fragment, between 'module :private;' and the end of
1565 /// the translation unit.
1566 Private
1567 };
1568
1569 void ActOnStartOfTranslationUnit();
1570 void ActOnEndOfTranslationUnit();
1571 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1572
1573 void CheckDelegatingCtorCycles();
1574
1575 Scope *getScopeForContext(DeclContext *Ctx);
1576
1577 void PushFunctionScope();
1578 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1579 sema::LambdaScopeInfo *PushLambdaScope();
1580
1581 /// This is used to inform Sema what the current TemplateParameterDepth
1582 /// is during Parsing. Currently it is used to pass on the depth
1583 /// when parsing generic lambda 'auto' parameters.
1584 void RecordParsingTemplateParameterDepth(unsigned Depth);
1585
1586 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1587 RecordDecl *RD, CapturedRegionKind K,
1588 unsigned OpenMPCaptureLevel = 0);
1589
1590 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1591 /// time after they've been popped.
1592 class PoppedFunctionScopeDeleter {
1593 Sema *Self;
1594
1595 public:
1596 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1597 void operator()(sema::FunctionScopeInfo *Scope) const;
1598 };
1599
1600 using PoppedFunctionScopePtr =
1601 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1602
1603 PoppedFunctionScopePtr
1604 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1605 const Decl *D = nullptr,
1606 QualType BlockType = QualType());
1607
1608 sema::FunctionScopeInfo *getCurFunction() const {
1609 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1610 }
1611
1612 sema::FunctionScopeInfo *getEnclosingFunction() const;
1613
1614 void setFunctionHasBranchIntoScope();
1615 void setFunctionHasBranchProtectedScope();
1616 void setFunctionHasIndirectGoto();
1617
1618 void PushCompoundScope(bool IsStmtExpr);
1619 void PopCompoundScope();
1620
1621 sema::CompoundScopeInfo &getCurCompoundScope() const;
1622
1623 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1624
1625 /// Retrieve the current block, if any.
1626 sema::BlockScopeInfo *getCurBlock();
1627
1628 /// Get the innermost lambda enclosing the current location, if any. This
1629 /// looks through intervening non-lambda scopes such as local functions and
1630 /// blocks.
1631 sema::LambdaScopeInfo *getEnclosingLambda() const;
1632
1633 /// Retrieve the current lambda scope info, if any.
1634 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1635 /// lambda scope info ignoring all inner capturing scopes that are not
1636 /// lambda scopes.
1637 sema::LambdaScopeInfo *
1638 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1639
1640 /// Retrieve the current generic lambda info, if any.
1641 sema::LambdaScopeInfo *getCurGenericLambda();
1642
1643 /// Retrieve the current captured region, if any.
1644 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1645
1646 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1647 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1648
1649 /// Called before parsing a function declarator belonging to a function
1650 /// declaration.
1651 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
1652 unsigned TemplateParameterDepth);
1653
1654 /// Called after parsing a function declarator belonging to a function
1655 /// declaration.
1656 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
1657
1658 void ActOnComment(SourceRange Comment);
1659
1660 //===--------------------------------------------------------------------===//
1661 // Type Analysis / Processing: SemaType.cpp.
1662 //
1663
1664 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1665 const DeclSpec *DS = nullptr);
1666 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1667 const DeclSpec *DS = nullptr);
1668 QualType BuildPointerType(QualType T,
1669 SourceLocation Loc, DeclarationName Entity);
1670 QualType BuildReferenceType(QualType T, bool LValueRef,
1671 SourceLocation Loc, DeclarationName Entity);
1672 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1673 Expr *ArraySize, unsigned Quals,
1674 SourceRange Brackets, DeclarationName Entity);
1675 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1676 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1677 SourceLocation AttrLoc);
1678 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
1679 SourceLocation AttrLoc);
1680
1681 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1682 SourceLocation AttrLoc);
1683
1684 /// Same as above, but constructs the AddressSpace index if not provided.
1685 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1686 SourceLocation AttrLoc);
1687
1688 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1689
1690 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1691
1692 /// Build a function type.
1693 ///
1694 /// This routine checks the function type according to C++ rules and
1695 /// under the assumption that the result type and parameter types have
1696 /// just been instantiated from a template. It therefore duplicates
1697 /// some of the behavior of GetTypeForDeclarator, but in a much
1698 /// simpler form that is only suitable for this narrow use case.
1699 ///
1700 /// \param T The return type of the function.
1701 ///
1702 /// \param ParamTypes The parameter types of the function. This array
1703 /// will be modified to account for adjustments to the types of the
1704 /// function parameters.
1705 ///
1706 /// \param Loc The location of the entity whose type involves this
1707 /// function type or, if there is no such entity, the location of the
1708 /// type that will have function type.
1709 ///
1710 /// \param Entity The name of the entity that involves the function
1711 /// type, if known.
1712 ///
1713 /// \param EPI Extra information about the function type. Usually this will
1714 /// be taken from an existing function with the same prototype.
1715 ///
1716 /// \returns A suitable function type, if there are no errors. The
1717 /// unqualified type will always be a FunctionProtoType.
1718 /// Otherwise, returns a NULL type.
1719 QualType BuildFunctionType(QualType T,
1720 MutableArrayRef<QualType> ParamTypes,
1721 SourceLocation Loc, DeclarationName Entity,
1722 const FunctionProtoType::ExtProtoInfo &EPI);
1723
1724 QualType BuildMemberPointerType(QualType T, QualType Class,
1725 SourceLocation Loc,
1726 DeclarationName Entity);
1727 QualType BuildBlockPointerType(QualType T,
1728 SourceLocation Loc, DeclarationName Entity);
1729 QualType BuildParenType(QualType T);
1730 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1731 QualType BuildReadPipeType(QualType T,
1732 SourceLocation Loc);
1733 QualType BuildWritePipeType(QualType T,
1734 SourceLocation Loc);
1735 QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
1736
1737 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1738 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1739
1740 /// Package the given type and TSI into a ParsedType.
1741 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1742 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1743 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1744 static QualType GetTypeFromParser(ParsedType Ty,
1745 TypeSourceInfo **TInfo = nullptr);
1746 CanThrowResult canThrow(const Stmt *E);
1747 /// Determine whether the callee of a particular function call can throw.
1748 /// E, D and Loc are all optional.
1749 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
1750 SourceLocation Loc = SourceLocation());
1751 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1752 const FunctionProtoType *FPT);
1753 void UpdateExceptionSpec(FunctionDecl *FD,
1754 const FunctionProtoType::ExceptionSpecInfo &ESI);
1755 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1756 bool CheckDistantExceptionSpec(QualType T);
1757 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1758 bool CheckEquivalentExceptionSpec(
1759 const FunctionProtoType *Old, SourceLocation OldLoc,
1760 const FunctionProtoType *New, SourceLocation NewLoc);
1761 bool CheckEquivalentExceptionSpec(
1762 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1763 const FunctionProtoType *Old, SourceLocation OldLoc,
1764 const FunctionProtoType *New, SourceLocation NewLoc);
1765 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1766 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1767 const PartialDiagnostic &NestedDiagID,
1768 const PartialDiagnostic &NoteID,
1769 const PartialDiagnostic &NoThrowDiagID,
1770 const FunctionProtoType *Superset,
1771 SourceLocation SuperLoc,
1772 const FunctionProtoType *Subset,
1773 SourceLocation SubLoc);
1774 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1775 const PartialDiagnostic &NoteID,
1776 const FunctionProtoType *Target,
1777 SourceLocation TargetLoc,
1778 const FunctionProtoType *Source,
1779 SourceLocation SourceLoc);
1780
1781 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1782
1783 /// The parser has parsed the context-sensitive type 'instancetype'
1784 /// in an Objective-C message declaration. Return the appropriate type.
1785 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1786
1787 /// Abstract class used to diagnose incomplete types.
1788 struct TypeDiagnoser {
1789 TypeDiagnoser() {}
1790
1791 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1792 virtual ~TypeDiagnoser() {}
1793 };
1794
1795 static int getPrintable(int I) { return I; }
1796 static unsigned getPrintable(unsigned I) { return I; }
1797 static bool getPrintable(bool B) { return B; }
1798 static const char * getPrintable(const char *S) { return S; }
1799 static StringRef getPrintable(StringRef S) { return S; }
1800 static const std::string &getPrintable(const std::string &S) { return S; }
1801 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1802 return II;
1803 }
1804 static DeclarationName getPrintable(DeclarationName N) { return N; }
1805 static QualType getPrintable(QualType T) { return T; }
1806 static SourceRange getPrintable(SourceRange R) { return R; }
1807 static SourceRange getPrintable(SourceLocation L) { return L; }
1808 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1809 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1810
1811 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1812 protected:
1813 unsigned DiagID;
1814 std::tuple<const Ts &...> Args;
1815
1816 template <std::size_t... Is>
1817 void emit(const SemaDiagnosticBuilder &DB,
1818 std::index_sequence<Is...>) const {
1819 // Apply all tuple elements to the builder in order.
1820 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1821 (void)Dummy;
1822 }
1823
1824 public:
1825 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1826 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1827 assert(DiagID != 0 && "no diagnostic for type diagnoser")((DiagID != 0 && "no diagnostic for type diagnoser") ?
static_cast<void> (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 1827, __PRETTY_FUNCTION__))
;
1828 }
1829
1830 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1831 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1832 emit(DB, std::index_sequence_for<Ts...>());
1833 DB << T;
1834 }
1835 };
1836
1837 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
1838 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
1839 /// For example, a diagnostic with no other parameters would generally have
1840 /// the form "...%select{incomplete|sizeless}0 type %1...".
1841 template <typename... Ts>
1842 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
1843 public:
1844 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
1845 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
1846
1847 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1848 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
1849 this->emit(DB, std::index_sequence_for<Ts...>());
1850 DB << T->isSizelessType() << T;
1851 }
1852 };
1853
1854 enum class CompleteTypeKind {
1855 /// Apply the normal rules for complete types. In particular,
1856 /// treat all sizeless types as incomplete.
1857 Normal,
1858
1859 /// Relax the normal rules for complete types so that they include
1860 /// sizeless built-in types.
1861 AcceptSizeless,
1862
1863 // FIXME: Eventually we should flip the default to Normal and opt in
1864 // to AcceptSizeless rather than opt out of it.
1865 Default = AcceptSizeless
1866 };
1867
1868private:
1869 /// Methods for marking which expressions involve dereferencing a pointer
1870 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1871 /// they are parsed, meaning that a noderef pointer may not be accessed. For
1872 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1873 /// `*p`, but need to check that `address of` is called on it. This requires
1874 /// keeping a container of all pending expressions and checking if the address
1875 /// of them are eventually taken.
1876 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1877 void CheckAddressOfNoDeref(const Expr *E);
1878 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1879
1880 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1881 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
1882
1883 struct ModuleScope {
1884 SourceLocation BeginLoc;
1885 clang::Module *Module = nullptr;
1886 bool ModuleInterface = false;
1887 bool ImplicitGlobalModuleFragment = false;
1888 VisibleModuleSet OuterVisibleModules;
1889 };
1890 /// The modules we're currently parsing.
1891 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1892
1893 /// Namespace definitions that we will export when they finish.
1894 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1895
1896 /// Get the module whose scope we are currently within.
1897 Module *getCurrentModule() const {
1898 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1899 }
1900
1901 VisibleModuleSet VisibleModules;
1902
1903public:
1904 /// Get the module owning an entity.
1905 Module *getOwningModule(const Decl *Entity) {
1906 return Entity->getOwningModule();
1907 }
1908
1909 /// Make a merged definition of an existing hidden definition \p ND
1910 /// visible at the specified location.
1911 void makeMergedDefinitionVisible(NamedDecl *ND);
1912
1913 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1914
1915 /// Determine whether a declaration is visible to name lookup.
1916 bool isVisible(const NamedDecl *D) {
1917 return D->isUnconditionallyVisible() || isVisibleSlow(D);
1918 }
1919
1920 /// Determine whether any declaration of an entity is visible.
1921 bool
1922 hasVisibleDeclaration(const NamedDecl *D,
1923 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1924 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1925 }
1926 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1927 llvm::SmallVectorImpl<Module *> *Modules);
1928
1929 bool hasVisibleMergedDefinition(NamedDecl *Def);
1930 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1931
1932 /// Determine if \p D and \p Suggested have a structurally compatible
1933 /// layout as described in C11 6.2.7/1.
1934 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1935
1936 /// Determine if \p D has a visible definition. If not, suggest a declaration
1937 /// that should be made visible to expose the definition.
1938 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1939 bool OnlyNeedComplete = false);
1940 bool hasVisibleDefinition(const NamedDecl *D) {
1941 NamedDecl *Hidden;
1942 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1943 }
1944
1945 /// Determine if the template parameter \p D has a visible default argument.
1946 bool
1947 hasVisibleDefaultArgument(const NamedDecl *D,
1948 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1949
1950 /// Determine if there is a visible declaration of \p D that is an explicit
1951 /// specialization declaration for a specialization of a template. (For a
1952 /// member specialization, use hasVisibleMemberSpecialization.)
1953 bool hasVisibleExplicitSpecialization(
1954 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1955
1956 /// Determine if there is a visible declaration of \p D that is a member
1957 /// specialization declaration (as opposed to an instantiated declaration).
1958 bool hasVisibleMemberSpecialization(
1959 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1960
1961 /// Determine if \p A and \p B are equivalent internal linkage declarations
1962 /// from different modules, and thus an ambiguity error can be downgraded to
1963 /// an extension warning.
1964 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1965 const NamedDecl *B);
1966 void diagnoseEquivalentInternalLinkageDeclarations(
1967 SourceLocation Loc, const NamedDecl *D,
1968 ArrayRef<const NamedDecl *> Equiv);
1969
1970 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1971
1972 bool isCompleteType(SourceLocation Loc, QualType T,
1973 CompleteTypeKind Kind = CompleteTypeKind::Default) {
1974 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
1975 }
1976 bool RequireCompleteType(SourceLocation Loc, QualType T,
1977 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
1978 bool RequireCompleteType(SourceLocation Loc, QualType T,
1979 CompleteTypeKind Kind, unsigned DiagID);
1980
1981 bool RequireCompleteType(SourceLocation Loc, QualType T,
1982 TypeDiagnoser &Diagnoser) {
1983 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
1984 }
1985 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
1986 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
1987 }
1988
1989 template <typename... Ts>
1990 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1991 const Ts &...Args) {
1992 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1993 return RequireCompleteType(Loc, T, Diagnoser);
1994 }
1995
1996 template <typename... Ts>
1997 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
1998 const Ts &... Args) {
1999 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2000 CompleteTypeKind Kind = CompleteTypeKind::Normal;
2001 if (T->isVLST())
2002 Kind = CompleteTypeKind::AcceptSizeless;
2003 return RequireCompleteType(Loc, T, Kind, Diagnoser);
2004 }
2005
2006 void completeExprArrayBound(Expr *E);
2007 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2008 TypeDiagnoser &Diagnoser);
2009 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2010
2011 template <typename... Ts>
2012 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2013 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2014 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2015 }
2016
2017 template <typename... Ts>
2018 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2019 const Ts &... Args) {
2020 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2021 CompleteTypeKind Kind = CompleteTypeKind::Normal;
2022 if (E->getType()->isVLST())
2023 Kind = CompleteTypeKind::AcceptSizeless;
2024 return RequireCompleteExprType(E, Kind, Diagnoser);
2025 }
2026
2027 bool RequireLiteralType(SourceLocation Loc, QualType T,
2028 TypeDiagnoser &Diagnoser);
2029 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2030
2031 template <typename... Ts>
2032 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2033 const Ts &...Args) {
2034 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2035 return RequireLiteralType(Loc, T, Diagnoser);
2036 }
2037
2038 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2039 const CXXScopeSpec &SS, QualType T,
2040 TagDecl *OwnedTagDecl = nullptr);
2041
2042 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
2043 /// If AsUnevaluated is false, E is treated as though it were an evaluated
2044 /// context, such as when building a type for decltype(auto).
2045 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
2046 bool AsUnevaluated = true);
2047 QualType BuildUnaryTransformType(QualType BaseType,
2048 UnaryTransformType::UTTKind UKind,
2049 SourceLocation Loc);
2050
2051 //===--------------------------------------------------------------------===//
2052 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2053 //
2054
2055 struct SkipBodyInfo {
2056 SkipBodyInfo()
2057 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
2058 New(nullptr) {}
2059 bool ShouldSkip;
2060 bool CheckSameAsPrevious;
2061 NamedDecl *Previous;
2062 NamedDecl *New;
2063 };
2064
2065 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2066
2067 void DiagnoseUseOfUnimplementedSelectors();
2068
2069 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2070
2071 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2072 Scope *S, CXXScopeSpec *SS = nullptr,
2073 bool isClassName = false, bool HasTrailingDot = false,
2074 ParsedType ObjectType = nullptr,
2075 bool IsCtorOrDtorName = false,
2076 bool WantNontrivialTypeSourceInfo = false,
2077 bool IsClassTemplateDeductionContext = true,
2078 IdentifierInfo **CorrectedII = nullptr);
2079 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2080 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2081 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2082 SourceLocation IILoc,
2083 Scope *S,
2084 CXXScopeSpec *SS,
2085 ParsedType &SuggestedType,
2086 bool IsTemplateName = false);
2087
2088 /// Attempt to behave like MSVC in situations where lookup of an unqualified
2089 /// type name has failed in a dependent context. In these situations, we
2090 /// automatically form a DependentTypeName that will retry lookup in a related
2091 /// scope during instantiation.
2092 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2093 SourceLocation NameLoc,
2094 bool IsTemplateTypeArg);
2095
2096 /// Describes the result of the name lookup and resolution performed
2097 /// by \c ClassifyName().
2098 enum NameClassificationKind {
2099 /// This name is not a type or template in this context, but might be
2100 /// something else.
2101 NC_Unknown,
2102 /// Classification failed; an error has been produced.
2103 NC_Error,
2104 /// The name has been typo-corrected to a keyword.
2105 NC_Keyword,
2106 /// The name was classified as a type.
2107 NC_Type,
2108 /// The name was classified as a specific non-type, non-template
2109 /// declaration. ActOnNameClassifiedAsNonType should be called to
2110 /// convert the declaration to an expression.
2111 NC_NonType,
2112 /// The name was classified as an ADL-only function name.
2113 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2114 /// result to an expression.
2115 NC_UndeclaredNonType,
2116 /// The name denotes a member of a dependent type that could not be
2117 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2118 /// convert the result to an expression.
2119 NC_DependentNonType,
2120 /// The name was classified as an overload set, and an expression
2121 /// representing that overload set has been formed.
2122 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2123 /// expression referencing the overload set.
2124 NC_OverloadSet,
2125 /// The name was classified as a template whose specializations are types.
2126 NC_TypeTemplate,
2127 /// The name was classified as a variable template name.
2128 NC_VarTemplate,
2129 /// The name was classified as a function template name.
2130 NC_FunctionTemplate,
2131 /// The name was classified as an ADL-only function template name.
2132 NC_UndeclaredTemplate,
2133 /// The name was classified as a concept name.
2134 NC_Concept,
2135 };
2136
2137 class NameClassification {
2138 NameClassificationKind Kind;
2139 union {
2140 ExprResult Expr;
2141 NamedDecl *NonTypeDecl;
2142 TemplateName Template;
2143 ParsedType Type;
2144 };
2145
2146 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2147
2148 public:
2149 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2150
2151 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2152
2153 static NameClassification Error() {
2154 return NameClassification(NC_Error);
2155 }
2156
2157 static NameClassification Unknown() {
2158 return NameClassification(NC_Unknown);
2159 }
2160
2161 static NameClassification OverloadSet(ExprResult E) {
2162 NameClassification Result(NC_OverloadSet);
2163 Result.Expr = E;
2164 return Result;
2165 }
2166
2167 static NameClassification NonType(NamedDecl *D) {
2168 NameClassification Result(NC_NonType);
2169 Result.NonTypeDecl = D;
2170 return Result;
2171 }
2172
2173 static NameClassification UndeclaredNonType() {
2174 return NameClassification(NC_UndeclaredNonType);
2175 }
2176
2177 static NameClassification DependentNonType() {
2178 return NameClassification(NC_DependentNonType);
2179 }
2180
2181 static NameClassification TypeTemplate(TemplateName Name) {
2182 NameClassification Result(NC_TypeTemplate);
2183 Result.Template = Name;
2184 return Result;
2185 }
2186
2187 static NameClassification VarTemplate(TemplateName Name) {
2188 NameClassification Result(NC_VarTemplate);
2189 Result.Template = Name;
2190 return Result;
2191 }
2192
2193 static NameClassification FunctionTemplate(TemplateName Name) {
2194 NameClassification Result(NC_FunctionTemplate);
2195 Result.Template = Name;
2196 return Result;
2197 }
2198
2199 static NameClassification Concept(TemplateName Name) {
2200 NameClassification Result(NC_Concept);
2201 Result.Template = Name;
2202 return Result;
2203 }
2204
2205 static NameClassification UndeclaredTemplate(TemplateName Name) {
2206 NameClassification Result(NC_UndeclaredTemplate);
2207 Result.Template = Name;
2208 return Result;
2209 }
2210
2211 NameClassificationKind getKind() const { return Kind; }
2212
2213 ExprResult getExpression() const {
2214 assert(Kind == NC_OverloadSet)((Kind == NC_OverloadSet) ? static_cast<void> (0) : __assert_fail
("Kind == NC_OverloadSet", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 2214, __PRETTY_FUNCTION__))
;
2215 return Expr;
2216 }
2217
2218 ParsedType getType() const {
2219 assert(Kind == NC_Type)((Kind == NC_Type) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 2219, __PRETTY_FUNCTION__))
;
2220 return Type;
2221 }
2222
2223 NamedDecl *getNonTypeDecl() const {
2224 assert(Kind == NC_NonType)((Kind == NC_NonType) ? static_cast<void> (0) : __assert_fail
("Kind == NC_NonType", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 2224, __PRETTY_FUNCTION__))
;
2225 return NonTypeDecl;
2226 }
2227
2228 TemplateName getTemplateName() const {
2229 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate
) ? static_cast<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 2231, __PRETTY_FUNCTION__))
2230 Kind == NC_VarTemplate || Kind == NC_Concept ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate
) ? static_cast<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 2231, __PRETTY_FUNCTION__))
2231 Kind == NC_UndeclaredTemplate)((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate
) ? static_cast<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 2231, __PRETTY_FUNCTION__))
;
2232 return Template;
2233 }
2234
2235 TemplateNameKind getTemplateNameKind() const {
2236 switch (Kind) {
2237 case NC_TypeTemplate:
2238 return TNK_Type_template;
2239 case NC_FunctionTemplate:
2240 return TNK_Function_template;
2241 case NC_VarTemplate:
2242 return TNK_Var_template;
2243 case NC_Concept:
2244 return TNK_Concept_template;
2245 case NC_UndeclaredTemplate:
2246 return TNK_Undeclared_template;
2247 default:
2248 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 2248)
;
2249 }
2250 }
2251 };
2252
2253 /// Perform name lookup on the given name, classifying it based on
2254 /// the results of name lookup and the following token.
2255 ///
2256 /// This routine is used by the parser to resolve identifiers and help direct
2257 /// parsing. When the identifier cannot be found, this routine will attempt
2258 /// to correct the typo and classify based on the resulting name.
2259 ///
2260 /// \param S The scope in which we're performing name lookup.
2261 ///
2262 /// \param SS The nested-name-specifier that precedes the name.
2263 ///
2264 /// \param Name The identifier. If typo correction finds an alternative name,
2265 /// this pointer parameter will be updated accordingly.
2266 ///
2267 /// \param NameLoc The location of the identifier.
2268 ///
2269 /// \param NextToken The token following the identifier. Used to help
2270 /// disambiguate the name.
2271 ///
2272 /// \param CCC The correction callback, if typo correction is desired.
2273 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2274 IdentifierInfo *&Name, SourceLocation NameLoc,
2275 const Token &NextToken,
2276 CorrectionCandidateCallback *CCC = nullptr);
2277
2278 /// Act on the result of classifying a name as an undeclared (ADL-only)
2279 /// non-type declaration.
2280 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2281 SourceLocation NameLoc);
2282 /// Act on the result of classifying a name as an undeclared member of a
2283 /// dependent base class.
2284 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2285 IdentifierInfo *Name,
2286 SourceLocation NameLoc,
2287 bool IsAddressOfOperand);
2288 /// Act on the result of classifying a name as a specific non-type
2289 /// declaration.
2290 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2291 NamedDecl *Found,
2292 SourceLocation NameLoc,
2293 const Token &NextToken);
2294 /// Act on the result of classifying a name as an overload set.
2295 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2296
2297 /// Describes the detailed kind of a template name. Used in diagnostics.
2298 enum class TemplateNameKindForDiagnostics {
2299 ClassTemplate,
2300 FunctionTemplate,
2301 VarTemplate,
2302 AliasTemplate,
2303 TemplateTemplateParam,
2304 Concept,
2305 DependentTemplate
2306 };
2307 TemplateNameKindForDiagnostics
2308 getTemplateNameKindForDiagnostics(TemplateName Name);
2309
2310 /// Determine whether it's plausible that E was intended to be a
2311 /// template-name.
2312 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2313 if (!getLangOpts().CPlusPlus || E.isInvalid())
2314 return false;
2315 Dependent = false;
2316 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2317 return !DRE->hasExplicitTemplateArgs();
2318 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2319 return !ME->hasExplicitTemplateArgs();
2320 Dependent = true;
2321 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2322 return !DSDRE->hasExplicitTemplateArgs();
2323 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2324 return !DSME->hasExplicitTemplateArgs();
2325 // Any additional cases recognized here should also be handled by
2326 // diagnoseExprIntendedAsTemplateName.
2327 return false;
2328 }
2329 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2330 SourceLocation Less,
2331 SourceLocation Greater);
2332
2333 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2334
2335 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2336 MultiTemplateParamsArg TemplateParameterLists);
2337 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2338 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2339 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2340 DeclarationName Name, SourceLocation Loc,
2341 bool IsTemplateId);
2342 void
2343 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2344 SourceLocation FallbackLoc,
2345 SourceLocation ConstQualLoc = SourceLocation(),
2346 SourceLocation VolatileQualLoc = SourceLocation(),
2347 SourceLocation RestrictQualLoc = SourceLocation(),
2348 SourceLocation AtomicQualLoc = SourceLocation(),
2349 SourceLocation UnalignedQualLoc = SourceLocation());
2350
2351 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2352 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2353 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2354 const LookupResult &R);
2355 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2356 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2357 const LookupResult &R);
2358 void CheckShadow(Scope *S, VarDecl *D);
2359
2360 /// Warn if 'E', which is an expression that is about to be modified, refers
2361 /// to a shadowing declaration.
2362 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2363
2364 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2365
2366private:
2367 /// Map of current shadowing declarations to shadowed declarations. Warn if
2368 /// it looks like the user is trying to modify the shadowing declaration.
2369 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2370
2371public:
2372 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2373 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2374 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2375 TypedefNameDecl *NewTD);
2376 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2377 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2378 TypeSourceInfo *TInfo,
2379 LookupResult &Previous);
2380 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2381 LookupResult &Previous, bool &Redeclaration);
2382 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2383 TypeSourceInfo *TInfo,
2384 LookupResult &Previous,
2385 MultiTemplateParamsArg TemplateParamLists,
2386 bool &AddToScope,
2387 ArrayRef<BindingDecl *> Bindings = None);
2388 NamedDecl *
2389 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2390 MultiTemplateParamsArg TemplateParamLists);
2391 // Returns true if the variable declaration is a redeclaration
2392 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2393 void CheckVariableDeclarationType(VarDecl *NewVD);
2394 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2395 Expr *Init);
2396 void CheckCompleteVariableDeclaration(VarDecl *VD);
2397 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2398 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2399
2400 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2401 TypeSourceInfo *TInfo,
2402 LookupResult &Previous,
2403 MultiTemplateParamsArg TemplateParamLists,
2404 bool &AddToScope);
2405 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2406
2407 enum class CheckConstexprKind {
2408 /// Diagnose issues that are non-constant or that are extensions.
2409 Diagnose,
2410 /// Identify whether this function satisfies the formal rules for constexpr
2411 /// functions in the current lanugage mode (with no extensions).
2412 CheckValid
2413 };
2414
2415 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2416 CheckConstexprKind Kind);
2417
2418 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2419 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2420 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2421 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2422 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2423 // Returns true if the function declaration is a redeclaration
2424 bool CheckFunctionDeclaration(Scope *S,
2425 FunctionDecl *NewFD, LookupResult &Previous,
2426 bool IsMemberSpecialization);
2427 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2428 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2429 QualType NewT, QualType OldT);
2430 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2431 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2432 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2433 bool IsDefinition);
2434 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2435 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2436 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2437 SourceLocation Loc,
2438 QualType T);
2439 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2440 SourceLocation NameLoc, IdentifierInfo *Name,
2441 QualType T, TypeSourceInfo *TSInfo,
2442 StorageClass SC);
2443 void ActOnParamDefaultArgument(Decl *param,
2444 SourceLocation EqualLoc,
2445 Expr *defarg);
2446 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2447 SourceLocation ArgLoc);
2448 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2449 ExprResult ConvertParamDefaultArgument(const ParmVarDecl *Param,
2450 Expr *DefaultArg,
2451 SourceLocation EqualLoc);
2452 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2453 SourceLocation EqualLoc);
2454
2455 // Contexts where using non-trivial C union types can be disallowed. This is
2456 // passed to err_non_trivial_c_union_in_invalid_context.
2457 enum NonTrivialCUnionContext {
2458 // Function parameter.
2459 NTCUC_FunctionParam,
2460 // Function return.
2461 NTCUC_FunctionReturn,
2462 // Default-initialized object.
2463 NTCUC_DefaultInitializedObject,
2464 // Variable with automatic storage duration.
2465 NTCUC_AutoVar,
2466 // Initializer expression that might copy from another object.
2467 NTCUC_CopyInit,
2468 // Assignment.
2469 NTCUC_Assignment,
2470 // Compound literal.
2471 NTCUC_CompoundLiteral,
2472 // Block capture.
2473 NTCUC_BlockCapture,
2474 // lvalue-to-rvalue conversion of volatile type.
2475 NTCUC_LValueToRValueVolatile,
2476 };
2477
2478 /// Emit diagnostics if the initializer or any of its explicit or
2479 /// implicitly-generated subexpressions require copying or
2480 /// default-initializing a type that is or contains a C union type that is
2481 /// non-trivial to copy or default-initialize.
2482 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2483
2484 // These flags are passed to checkNonTrivialCUnion.
2485 enum NonTrivialCUnionKind {
2486 NTCUK_Init = 0x1,
2487 NTCUK_Destruct = 0x2,
2488 NTCUK_Copy = 0x4,
2489 };
2490
2491 /// Emit diagnostics if a non-trivial C union type or a struct that contains
2492 /// a non-trivial C union is used in an invalid context.
2493 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2494 NonTrivialCUnionContext UseContext,
2495 unsigned NonTrivialKind);
2496
2497 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2498 void ActOnUninitializedDecl(Decl *dcl);
2499 void ActOnInitializerError(Decl *Dcl);
2500
2501 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2502 void ActOnCXXForRangeDecl(Decl *D);
2503 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2504 IdentifierInfo *Ident,
2505 ParsedAttributes &Attrs,
2506 SourceLocation AttrEnd);
2507 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2508 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2509 void CheckStaticLocalForDllExport(VarDecl *VD);
2510 void FinalizeDeclaration(Decl *D);
2511 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2512 ArrayRef<Decl *> Group);
2513 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2514
2515 /// Should be called on all declarations that might have attached
2516 /// documentation comments.
2517 void ActOnDocumentableDecl(Decl *D);
2518 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2519
2520 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2521 SourceLocation LocAfterDecls);
2522 void CheckForFunctionRedefinition(
2523 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2524 SkipBodyInfo *SkipBody = nullptr);
2525 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2526 MultiTemplateParamsArg TemplateParamLists,
2527 SkipBodyInfo *SkipBody = nullptr);
2528 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2529 SkipBodyInfo *SkipBody = nullptr);
2530 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
2531 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
2532 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2533 bool isObjCMethodDecl(Decl *D) {
2534 return D && isa<ObjCMethodDecl>(D);
2535 }
2536
2537 /// Determine whether we can delay parsing the body of a function or
2538 /// function template until it is used, assuming we don't care about emitting
2539 /// code for that function.
2540 ///
2541 /// This will be \c false if we may need the body of the function in the
2542 /// middle of parsing an expression (where it's impractical to switch to
2543 /// parsing a different function), for instance, if it's constexpr in C++11
2544 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2545 bool canDelayFunctionBody(const Declarator &D);
2546
2547 /// Determine whether we can skip parsing the body of a function
2548 /// definition, assuming we don't care about analyzing its body or emitting
2549 /// code for that function.
2550 ///
2551 /// This will be \c false only if we may need the body of the function in
2552 /// order to parse the rest of the program (for instance, if it is
2553 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2554 bool canSkipFunctionBody(Decl *D);
2555
2556 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2557 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2558 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2559 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2560 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2561
2562 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2563 /// attribute for which parsing is delayed.
2564 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2565
2566 /// Diagnose any unused parameters in the given sequence of
2567 /// ParmVarDecl pointers.
2568 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2569
2570 /// Diagnose whether the size of parameters or return value of a
2571 /// function or obj-c method definition is pass-by-value and larger than a
2572 /// specified threshold.
2573 void
2574 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2575 QualType ReturnTy, NamedDecl *D);
2576
2577 void DiagnoseInvalidJumps(Stmt *Body);
2578 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2579 SourceLocation AsmLoc,
2580 SourceLocation RParenLoc);
2581
2582 /// Handle a C++11 empty-declaration and attribute-declaration.
2583 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2584 SourceLocation SemiLoc);
2585
2586 enum class ModuleDeclKind {
2587 Interface, ///< 'export module X;'
2588 Implementation, ///< 'module X;'
2589 };
2590
2591 /// The parser has processed a module-declaration that begins the definition
2592 /// of a module interface or implementation.
2593 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2594 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2595 ModuleIdPath Path, bool IsFirstDecl);
2596
2597 /// The parser has processed a global-module-fragment declaration that begins
2598 /// the definition of the global module fragment of the current module unit.
2599 /// \param ModuleLoc The location of the 'module' keyword.
2600 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2601
2602 /// The parser has processed a private-module-fragment declaration that begins
2603 /// the definition of the private module fragment of the current module unit.
2604 /// \param ModuleLoc The location of the 'module' keyword.
2605 /// \param PrivateLoc The location of the 'private' keyword.
2606 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2607 SourceLocation PrivateLoc);
2608
2609 /// The parser has processed a module import declaration.
2610 ///
2611 /// \param StartLoc The location of the first token in the declaration. This
2612 /// could be the location of an '@', 'export', or 'import'.
2613 /// \param ExportLoc The location of the 'export' keyword, if any.
2614 /// \param ImportLoc The location of the 'import' keyword.
2615 /// \param Path The module access path.
2616 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2617 SourceLocation ExportLoc,
2618 SourceLocation ImportLoc, ModuleIdPath Path);
2619 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2620 SourceLocation ExportLoc,
2621 SourceLocation ImportLoc, Module *M,
2622 ModuleIdPath Path = {});
2623
2624 /// The parser has processed a module import translated from a
2625 /// #include or similar preprocessing directive.
2626 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2627 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2628
2629 /// The parsed has entered a submodule.
2630 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2631 /// The parser has left a submodule.
2632 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2633
2634 /// Create an implicit import of the given module at the given
2635 /// source location, for error recovery, if possible.
2636 ///
2637 /// This routine is typically used when an entity found by name lookup
2638 /// is actually hidden within a module that we know about but the user
2639 /// has forgotten to import.
2640 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2641 Module *Mod);
2642
2643 /// Kinds of missing import. Note, the values of these enumerators correspond
2644 /// to %select values in diagnostics.
2645 enum class MissingImportKind {
2646 Declaration,
2647 Definition,
2648 DefaultArgument,
2649 ExplicitSpecialization,
2650 PartialSpecialization
2651 };
2652
2653 /// Diagnose that the specified declaration needs to be visible but
2654 /// isn't, and suggest a module import that would resolve the problem.
2655 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2656 MissingImportKind MIK, bool Recover = true);
2657 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2658 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2659 MissingImportKind MIK, bool Recover);
2660
2661 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2662 SourceLocation LBraceLoc);
2663 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2664 SourceLocation RBraceLoc);
2665
2666 /// We've found a use of a templated declaration that would trigger an
2667 /// implicit instantiation. Check that any relevant explicit specializations
2668 /// and partial specializations are visible, and diagnose if not.
2669 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2670
2671 /// We've found a use of a template specialization that would select a
2672 /// partial specialization. Check that the partial specialization is visible,
2673 /// and diagnose if not.
2674 void checkPartialSpecializationVisibility(SourceLocation Loc,
2675 NamedDecl *Spec);
2676
2677 /// Retrieve a suitable printing policy for diagnostics.
2678 PrintingPolicy getPrintingPolicy() const {
2679 return getPrintingPolicy(Context, PP);
2680 }
2681
2682 /// Retrieve a suitable printing policy for diagnostics.
2683 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2684 const Preprocessor &PP);
2685
2686 /// Scope actions.
2687 void ActOnPopScope(SourceLocation Loc, Scope *S);
2688 void ActOnTranslationUnitScope(Scope *S);
2689
2690 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2691 RecordDecl *&AnonRecord);
2692 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2693 MultiTemplateParamsArg TemplateParams,
2694 bool IsExplicitInstantiation,
2695 RecordDecl *&AnonRecord);
2696
2697 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2698 AccessSpecifier AS,
2699 RecordDecl *Record,
2700 const PrintingPolicy &Policy);
2701
2702 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2703 RecordDecl *Record);
2704
2705 /// Common ways to introduce type names without a tag for use in diagnostics.
2706 /// Keep in sync with err_tag_reference_non_tag.
2707 enum NonTagKind {
2708 NTK_NonStruct,
2709 NTK_NonClass,
2710 NTK_NonUnion,
2711 NTK_NonEnum,
2712 NTK_Typedef,
2713 NTK_TypeAlias,
2714 NTK_Template,
2715 NTK_TypeAliasTemplate,
2716 NTK_TemplateTemplateArgument,
2717 };
2718
2719 /// Given a non-tag type declaration, returns an enum useful for indicating
2720 /// what kind of non-tag type this is.
2721 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2722
2723 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2724 TagTypeKind NewTag, bool isDefinition,
2725 SourceLocation NewTagLoc,
2726 const IdentifierInfo *Name);
2727
2728 enum TagUseKind {
2729 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2730 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2731 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2732 TUK_Friend // Friend declaration: 'friend struct foo;'
2733 };
2734
2735 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2736 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2737 SourceLocation NameLoc, const ParsedAttributesView &Attr,
2738 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2739 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2740 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2741 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2742 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2743 SkipBodyInfo *SkipBody = nullptr);
2744
2745 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2746 unsigned TagSpec, SourceLocation TagLoc,
2747 CXXScopeSpec &SS, IdentifierInfo *Name,
2748 SourceLocation NameLoc,
2749 const ParsedAttributesView &Attr,
2750 MultiTemplateParamsArg TempParamLists);
2751
2752 TypeResult ActOnDependentTag(Scope *S,
2753 unsigned TagSpec,
2754 TagUseKind TUK,
2755 const CXXScopeSpec &SS,
2756 IdentifierInfo *Name,
2757 SourceLocation TagLoc,
2758 SourceLocation NameLoc);
2759
2760 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2761 IdentifierInfo *ClassName,
2762 SmallVectorImpl<Decl *> &Decls);
2763 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2764 Declarator &D, Expr *BitfieldWidth);
2765
2766 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2767 Declarator &D, Expr *BitfieldWidth,
2768 InClassInitStyle InitStyle,
2769 AccessSpecifier AS);
2770 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2771 SourceLocation DeclStart, Declarator &D,
2772 Expr *BitfieldWidth,
2773 InClassInitStyle InitStyle,
2774 AccessSpecifier AS,
2775 const ParsedAttr &MSPropertyAttr);
2776
2777 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2778 TypeSourceInfo *TInfo,
2779 RecordDecl *Record, SourceLocation Loc,
2780 bool Mutable, Expr *BitfieldWidth,
2781 InClassInitStyle InitStyle,
2782 SourceLocation TSSL,
2783 AccessSpecifier AS, NamedDecl *PrevDecl,
2784 Declarator *D = nullptr);
2785
2786 bool CheckNontrivialField(FieldDecl *FD);
2787 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2788
2789 enum TrivialABIHandling {
2790 /// The triviality of a method unaffected by "trivial_abi".
2791 TAH_IgnoreTrivialABI,
2792
2793 /// The triviality of a method affected by "trivial_abi".
2794 TAH_ConsiderTrivialABI
2795 };
2796
2797 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2798 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2799 bool Diagnose = false);
2800
2801 /// For a defaulted function, the kind of defaulted function that it is.
2802 class DefaultedFunctionKind {
2803 CXXSpecialMember SpecialMember : 8;
2804 DefaultedComparisonKind Comparison : 8;
2805
2806 public:
2807 DefaultedFunctionKind()
2808 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
2809 }
2810 DefaultedFunctionKind(CXXSpecialMember CSM)
2811 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
2812 DefaultedFunctionKind(DefaultedComparisonKind Comp)
2813 : SpecialMember(CXXInvalid), Comparison(Comp) {}
2814
2815 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
2816 bool isComparison() const {
2817 return Comparison != DefaultedComparisonKind::None;
2818 }
2819
2820 explicit operator bool() const {
2821 return isSpecialMember() || isComparison();
2822 }
2823
2824 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
2825 DefaultedComparisonKind asComparison() const { return Comparison; }
2826
2827 /// Get the index of this function kind for use in diagnostics.
2828 unsigned getDiagnosticIndex() const {
2829 static_assert(CXXInvalid > CXXDestructor,
2830 "invalid should have highest index");
2831 static_assert((unsigned)DefaultedComparisonKind::None == 0,
2832 "none should be equal to zero");
2833 return SpecialMember + (unsigned)Comparison;
2834 }
2835 };
2836
2837 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
2838
2839 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
2840 return getDefaultedFunctionKind(MD).asSpecialMember();
2841 }
2842 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
2843 return getDefaultedFunctionKind(FD).asComparison();
2844 }
2845
2846 void ActOnLastBitfield(SourceLocation DeclStart,
2847 SmallVectorImpl<Decl *> &AllIvarDecls);
2848 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2849 Declarator &D, Expr *BitfieldWidth,
2850 tok::ObjCKeywordKind visibility);
2851
2852 // This is used for both record definitions and ObjC interface declarations.
2853 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2854 ArrayRef<Decl *> Fields, SourceLocation LBrac,
2855 SourceLocation RBrac, const ParsedAttributesView &AttrList);
2856
2857 /// ActOnTagStartDefinition - Invoked when we have entered the
2858 /// scope of a tag's definition (e.g., for an enumeration, class,
2859 /// struct, or union).
2860 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2861
2862 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2863 /// Differently from C++, actually parse the body and reject / error out
2864 /// in case of a structural mismatch.
2865 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2866 SkipBodyInfo &SkipBody);
2867
2868 typedef void *SkippedDefinitionContext;
2869
2870 /// Invoked when we enter a tag definition that we're skipping.
2871 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2872
2873 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2874
2875 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2876 /// C++ record definition's base-specifiers clause and are starting its
2877 /// member declarations.
2878 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2879 SourceLocation FinalLoc,
2880 bool IsFinalSpelledSealed,
2881 SourceLocation LBraceLoc);
2882
2883 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2884 /// the definition of a tag (enumeration, class, struct, or union).
2885 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2886 SourceRange BraceRange);
2887
2888 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2889
2890 void ActOnObjCContainerFinishDefinition();
2891
2892 /// Invoked when we must temporarily exit the objective-c container
2893 /// scope for parsing/looking-up C constructs.
2894 ///
2895 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2896 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2897 void ActOnObjCReenterContainerContext(DeclContext *DC);
2898
2899 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2900 /// error parsing the definition of a tag.
2901 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2902
2903 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2904 EnumConstantDecl *LastEnumConst,
2905 SourceLocation IdLoc,
2906 IdentifierInfo *Id,
2907 Expr *val);
2908 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2909 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2910 QualType EnumUnderlyingTy, bool IsFixed,
2911 const EnumDecl *Prev);
2912
2913 /// Determine whether the body of an anonymous enumeration should be skipped.
2914 /// \param II The name of the first enumerator.
2915 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2916 SourceLocation IILoc);
2917
2918 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2919 SourceLocation IdLoc, IdentifierInfo *Id,
2920 const ParsedAttributesView &Attrs,
2921 SourceLocation EqualLoc, Expr *Val);
2922 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2923 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
2924 const ParsedAttributesView &Attr);
2925
2926 /// Set the current declaration context until it gets popped.
2927 void PushDeclContext(Scope *S, DeclContext *DC);
2928 void PopDeclContext();
2929
2930 /// EnterDeclaratorContext - Used when we must lookup names in the context
2931 /// of a declarator's nested name specifier.
2932 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2933 void ExitDeclaratorContext(Scope *S);
2934
2935 /// Enter a template parameter scope, after it's been associated with a particular
2936 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
2937 /// in the correct order.
2938 void EnterTemplatedContext(Scope *S, DeclContext *DC);
2939
2940 /// Push the parameters of D, which must be a function, into scope.
2941 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2942 void ActOnExitFunctionContext();
2943
2944 DeclContext *getFunctionLevelDeclContext();
2945
2946 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2947 /// to the function decl for the function being parsed. If we're currently
2948 /// in a 'block', this returns the containing context.
2949 FunctionDecl *getCurFunctionDecl();
2950
2951 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2952 /// the method decl for the method being parsed. If we're currently
2953 /// in a 'block', this returns the containing context.
2954 ObjCMethodDecl *getCurMethodDecl();
2955
2956 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2957 /// or C function we're in, otherwise return null. If we're currently
2958 /// in a 'block', this returns the containing context.
2959 NamedDecl *getCurFunctionOrMethodDecl();
2960
2961 /// Add this decl to the scope shadowed decl chains.
2962 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2963
2964 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2965 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2966 /// true if 'D' belongs to the given declaration context.
2967 ///
2968 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2969 /// enclosing namespace set of the context, rather than contained
2970 /// directly within it.
2971 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2972 bool AllowInlineNamespace = false);
2973
2974 /// Finds the scope corresponding to the given decl context, if it
2975 /// happens to be an enclosing scope. Otherwise return NULL.
2976 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2977
2978 /// Subroutines of ActOnDeclarator().
2979 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2980 TypeSourceInfo *TInfo);
2981 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2982
2983 /// Describes the kind of merge to perform for availability
2984 /// attributes (including "deprecated", "unavailable", and "availability").
2985 enum AvailabilityMergeKind {
2986 /// Don't merge availability attributes at all.
2987 AMK_None,
2988 /// Merge availability attributes for a redeclaration, which requires
2989 /// an exact match.
2990 AMK_Redeclaration,
2991 /// Merge availability attributes for an override, which requires
2992 /// an exact match or a weakening of constraints.
2993 AMK_Override,
2994 /// Merge availability attributes for an implementation of
2995 /// a protocol requirement.
2996 AMK_ProtocolImplementation,
2997 };
2998
2999 /// Describes the kind of priority given to an availability attribute.
3000 ///
3001 /// The sum of priorities deteremines the final priority of the attribute.
3002 /// The final priority determines how the attribute will be merged.
3003 /// An attribute with a lower priority will always remove higher priority
3004 /// attributes for the specified platform when it is being applied. An
3005 /// attribute with a higher priority will not be applied if the declaration
3006 /// already has an availability attribute with a lower priority for the
3007 /// specified platform. The final prirority values are not expected to match
3008 /// the values in this enumeration, but instead should be treated as a plain
3009 /// integer value. This enumeration just names the priority weights that are
3010 /// used to calculate that final vaue.
3011 enum AvailabilityPriority : int {
3012 /// The availability attribute was specified explicitly next to the
3013 /// declaration.
3014 AP_Explicit = 0,
3015
3016 /// The availability attribute was applied using '#pragma clang attribute'.
3017 AP_PragmaClangAttribute = 1,
3018
3019 /// The availability attribute for a specific platform was inferred from
3020 /// an availability attribute for another platform.
3021 AP_InferredFromOtherPlatform = 2
3022 };
3023
3024 /// Attribute merging methods. Return true if a new attribute was added.
3025 AvailabilityAttr *
3026 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3027 IdentifierInfo *Platform, bool Implicit,
3028 VersionTuple Introduced, VersionTuple Deprecated,
3029 VersionTuple Obsoleted, bool IsUnavailable,
3030 StringRef Message, bool IsStrict, StringRef Replacement,
3031 AvailabilityMergeKind AMK, int Priority);
3032 TypeVisibilityAttr *
3033 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3034 TypeVisibilityAttr::VisibilityType Vis);
3035 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3036 VisibilityAttr::VisibilityType Vis);
3037 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3038 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3039 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3040 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3041 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3042 const AttributeCommonInfo &CI,
3043 bool BestCase,
3044 MSInheritanceModel Model);
3045 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3046 IdentifierInfo *Format, int FormatIdx,
3047 int FirstArg);
3048 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3049 StringRef Name);
3050 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3051 StringRef Name);
3052 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3053 const AttributeCommonInfo &CI,
3054 const IdentifierInfo *Ident);
3055 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3056 NoSpeculativeLoadHardeningAttr *
3057 mergeNoSpeculativeLoadHardeningAttr(Decl *D,
3058 const NoSpeculativeLoadHardeningAttr &AL);
3059 SpeculativeLoadHardeningAttr *
3060 mergeSpeculativeLoadHardeningAttr(Decl *D,
3061 const SpeculativeLoadHardeningAttr &AL);
3062 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3063 const AttributeCommonInfo &CI);
3064 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3065 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3066 const InternalLinkageAttr &AL);
3067 CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
3068 CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
3069 WebAssemblyImportNameAttr *mergeImportNameAttr(
3070 Decl *D, const WebAssemblyImportNameAttr &AL);
3071 WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3072 Decl *D, const WebAssemblyImportModuleAttr &AL);
3073
3074 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3075 AvailabilityMergeKind AMK = AMK_Redeclaration);
3076 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
3077 LookupResult &OldDecls);
3078 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3079 bool MergeTypeWithOld);
3080 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3081 Scope *S, bool MergeTypeWithOld);
3082 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
3083 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
3084 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3085 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3086 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3087 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3088 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3089
3090 // AssignmentAction - This is used by all the assignment diagnostic functions
3091 // to represent what is actually causing the operation
3092 enum AssignmentAction {
3093 AA_Assigning,
3094 AA_Passing,
3095 AA_Returning,
3096 AA_Converting,
3097 AA_Initializing,
3098 AA_Sending,
3099 AA_Casting,
3100 AA_Passing_CFAudited
3101 };
3102
3103 /// C++ Overloading.
3104 enum OverloadKind {
3105 /// This is a legitimate overload: the existing declarations are
3106 /// functions or function templates with different signatures.
3107 Ovl_Overload,
3108
3109 /// This is not an overload because the signature exactly matches
3110 /// an existing declaration.
3111 Ovl_Match,
3112
3113 /// This is not an overload because the lookup results contain a
3114 /// non-function.
3115 Ovl_NonFunction
3116 };
3117 OverloadKind CheckOverload(Scope *S,
3118 FunctionDecl *New,
3119 const LookupResult &OldDecls,
3120 NamedDecl *&OldDecl,
3121 bool IsForUsingDecl);
3122 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
3123 bool ConsiderCudaAttrs = true,
3124 bool ConsiderRequiresClauses = true);
3125
3126 enum class AllowedExplicit {
3127 /// Allow no explicit functions to be used.
3128 None,
3129 /// Allow explicit conversion functions but not explicit constructors.
3130 Conversions,
3131 /// Allow both explicit conversion functions and explicit constructors.
3132 All
3133 };
3134
3135 ImplicitConversionSequence
3136 TryImplicitConversion(Expr *From, QualType ToType,
3137 bool SuppressUserConversions,
3138 AllowedExplicit AllowExplicit,
3139 bool InOverloadResolution,
3140 bool CStyle,
3141 bool AllowObjCWritebackConversion);
3142
3143 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3144 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3145 bool IsComplexPromotion(QualType FromType, QualType ToType);
3146 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3147 bool InOverloadResolution,
3148 QualType& ConvertedType, bool &IncompatibleObjC);
3149 bool isObjCPointerConversion(QualType FromType, QualType ToType,
3150 QualType& ConvertedType, bool &IncompatibleObjC);
3151 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3152 QualType &ConvertedType);
3153 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3154 QualType& ConvertedType);
3155 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3156 const FunctionProtoType *NewType,
3157 unsigned *ArgPos = nullptr);
3158 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3159 QualType FromType, QualType ToType);
3160
3161 void maybeExtendBlockObject(ExprResult &E);
3162 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
3163 bool CheckPointerConversion(Expr *From, QualType ToType,
3164 CastKind &Kind,
3165 CXXCastPath& BasePath,
3166 bool IgnoreBaseAccess,
3167 bool Diagnose = true);
3168 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3169 bool InOverloadResolution,
3170 QualType &ConvertedType);
3171 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3172 CastKind &Kind,
3173 CXXCastPath &BasePath,
3174 bool IgnoreBaseAccess);
3175 bool IsQualificationConversion(QualType FromType, QualType ToType,
3176 bool CStyle, bool &ObjCLifetimeConversion);
3177 bool IsFunctionConversion(QualType FromType, QualType ToType,
3178 QualType &ResultTy);
3179 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3180 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
3181
3182 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3183 const VarDecl *NRVOCandidate,
3184 QualType ResultType,
3185 Expr *Value,
3186 bool AllowNRVO = true);
3187
3188 bool CanPerformAggregateInitializationForOverloadResolution(
3189 const InitializedEntity &Entity, InitListExpr *From);
3190
3191 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3192 ExprResult Init);
3193 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3194 SourceLocation EqualLoc,
3195 ExprResult Init,
3196 bool TopLevelOfInitList = false,
3197 bool AllowExplicit = false);
3198 ExprResult PerformObjectArgumentInitialization(Expr *From,
3199 NestedNameSpecifier *Qualifier,
3200 NamedDecl *FoundDecl,
3201 CXXMethodDecl *Method);
3202
3203 /// Check that the lifetime of the initializer (and its subobjects) is
3204 /// sufficient for initializing the entity, and perform lifetime extension
3205 /// (when permitted) if not.
3206 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3207
3208 ExprResult PerformContextuallyConvertToBool(Expr *From);
3209 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3210
3211 /// Contexts in which a converted constant expression is required.
3212 enum CCEKind {
3213 CCEK_CaseValue, ///< Expression in a case label.
3214 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
3215 CCEK_TemplateArg, ///< Value of a non-type template parameter.
3216 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
3217 CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
3218 CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
3219 };
3220 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3221 llvm::APSInt &Value, CCEKind CCE);
3222 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3223 APValue &Value, CCEKind CCE);
3224
3225 /// Abstract base class used to perform a contextual implicit
3226 /// conversion from an expression to any type passing a filter.
3227 class ContextualImplicitConverter {
3228 public:
3229 bool Suppress;
3230 bool SuppressConversion;
3231
3232 ContextualImplicitConverter(bool Suppress = false,
3233 bool SuppressConversion = false)
3234 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3235
3236 /// Determine whether the specified type is a valid destination type
3237 /// for this conversion.
3238 virtual bool match(QualType T) = 0;
3239
3240 /// Emits a diagnostic complaining that the expression does not have
3241 /// integral or enumeration type.
3242 virtual SemaDiagnosticBuilder
3243 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3244
3245 /// Emits a diagnostic when the expression has incomplete class type.
3246 virtual SemaDiagnosticBuilder
3247 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3248
3249 /// Emits a diagnostic when the only matching conversion function
3250 /// is explicit.
3251 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3252 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3253
3254 /// Emits a note for the explicit conversion function.
3255 virtual SemaDiagnosticBuilder
3256 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3257
3258 /// Emits a diagnostic when there are multiple possible conversion
3259 /// functions.
3260 virtual SemaDiagnosticBuilder
3261 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3262
3263 /// Emits a note for one of the candidate conversions.
3264 virtual SemaDiagnosticBuilder
3265 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3266
3267 /// Emits a diagnostic when we picked a conversion function
3268 /// (for cases when we are not allowed to pick a conversion function).
3269 virtual SemaDiagnosticBuilder diagnoseConversion(
3270 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3271
3272 virtual ~ContextualImplicitConverter() {}
3273 };
3274
3275 class ICEConvertDiagnoser : public ContextualImplicitConverter {
3276 bool AllowScopedEnumerations;
3277
3278 public:
3279 ICEConvertDiagnoser(bool AllowScopedEnumerations,
3280 bool Suppress, bool SuppressConversion)
3281 : ContextualImplicitConverter(Suppress, SuppressConversion),
3282 AllowScopedEnumerations(AllowScopedEnumerations) {}
3283
3284 /// Match an integral or (possibly scoped) enumeration type.
3285 bool match(QualType T) override;
3286
3287 SemaDiagnosticBuilder
3288 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3289 return diagnoseNotInt(S, Loc, T);
3290 }
3291
3292 /// Emits a diagnostic complaining that the expression does not have
3293 /// integral or enumeration type.
3294 virtual SemaDiagnosticBuilder
3295 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3296 };
3297
3298 /// Perform a contextual implicit conversion.
3299 ExprResult PerformContextualImplicitConversion(
3300 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3301
3302
3303 enum ObjCSubscriptKind {
3304 OS_Array,
3305 OS_Dictionary,
3306 OS_Error
3307 };
3308 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3309
3310 // Note that LK_String is intentionally after the other literals, as
3311 // this is used for diagnostics logic.
3312 enum ObjCLiteralKind {
3313 LK_Array,
3314 LK_Dictionary,
3315 LK_Numeric,
3316 LK_Boxed,
3317 LK_String,
3318 LK_Block,
3319 LK_None
3320 };
3321 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3322
3323 ExprResult PerformObjectMemberConversion(Expr *From,
3324 NestedNameSpecifier *Qualifier,
3325 NamedDecl *FoundDecl,
3326 NamedDecl *Member);
3327
3328 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3329 // TODO: make this is a typesafe union.
3330 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
3331 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3332
3333 using ADLCallKind = CallExpr::ADLCallKind;
3334
3335 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3336 ArrayRef<Expr *> Args,
3337 OverloadCandidateSet &CandidateSet,
3338 bool SuppressUserConversions = false,
3339 bool PartialOverloading = false,
3340 bool AllowExplicit = true,
3341 bool AllowExplicitConversion = false,
3342 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3343 ConversionSequenceList EarlyConversions = None,
3344 OverloadCandidateParamOrder PO = {});
3345 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3346 ArrayRef<Expr *> Args,
3347 OverloadCandidateSet &CandidateSet,
3348 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3349 bool SuppressUserConversions = false,
3350 bool PartialOverloading = false,
3351 bool FirstArgumentIsBase = false);
3352 void AddMethodCandidate(DeclAccessPair FoundDecl,
3353 QualType ObjectType,
3354 Expr::Classification ObjectClassification,
3355 ArrayRef<Expr *> Args,
3356 OverloadCandidateSet& CandidateSet,
3357 bool SuppressUserConversion = false,
3358 OverloadCandidateParamOrder PO = {});
3359 void AddMethodCandidate(CXXMethodDecl *Method,
3360 DeclAccessPair FoundDecl,
3361 CXXRecordDecl *ActingContext, QualType ObjectType,
3362 Expr::Classification ObjectClassification,
3363 ArrayRef<Expr *> Args,
3364 OverloadCandidateSet& CandidateSet,
3365 bool SuppressUserConversions = false,
3366 bool PartialOverloading = false,
3367 ConversionSequenceList EarlyConversions = None,
3368 OverloadCandidateParamOrder PO = {});
3369 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3370 DeclAccessPair FoundDecl,
3371 CXXRecordDecl *ActingContext,
3372 TemplateArgumentListInfo *ExplicitTemplateArgs,
3373 QualType ObjectType,
3374 Expr::Classification ObjectClassification,
3375 ArrayRef<Expr *> Args,
3376 OverloadCandidateSet& CandidateSet,
3377 bool SuppressUserConversions = false,
3378 bool PartialOverloading = false,
3379 OverloadCandidateParamOrder PO = {});
3380 void AddTemplateOverloadCandidate(
3381 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3382 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3383 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3384 bool PartialOverloading = false, bool AllowExplicit = true,
3385 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3386 OverloadCandidateParamOrder PO = {});
3387 bool CheckNonDependentConversions(
3388 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3389 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3390 ConversionSequenceList &Conversions, bool SuppressUserConversions,
3391 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3392 Expr::Classification ObjectClassification = {},
3393 OverloadCandidateParamOrder PO = {});
3394 void AddConversionCandidate(
3395 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3396 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3397 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3398 bool AllowExplicit, bool AllowResultConversion = true);
3399 void AddTemplateConversionCandidate(
3400 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3401 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3402 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3403 bool AllowExplicit, bool AllowResultConversion = true);
3404 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3405 DeclAccessPair FoundDecl,
3406 CXXRecordDecl *ActingContext,
3407 const FunctionProtoType *Proto,
3408 Expr *Object, ArrayRef<Expr *> Args,
3409 OverloadCandidateSet& CandidateSet);
3410 void AddNonMemberOperatorCandidates(
3411 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3412 OverloadCandidateSet &CandidateSet,
3413 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3414 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3415 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3416 OverloadCandidateSet &CandidateSet,
3417 OverloadCandidateParamOrder PO = {});
3418 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3419 OverloadCandidateSet& CandidateSet,
3420 bool IsAssignmentOperator = false,
3421 unsigned NumContextualBoolArguments = 0);
3422 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3423 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3424 OverloadCandidateSet& CandidateSet);
3425 void AddArgumentDependentLookupCandidates(DeclarationName Name,
3426 SourceLocation Loc,
3427 ArrayRef<Expr *> Args,
3428 TemplateArgumentListInfo *ExplicitTemplateArgs,
3429 OverloadCandidateSet& CandidateSet,
3430 bool PartialOverloading = false);
3431
3432 // Emit as a 'note' the specific overload candidate
3433 void NoteOverloadCandidate(
3434 NamedDecl *Found, FunctionDecl *Fn,
3435 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3436 QualType DestType = QualType(), bool TakingAddress = false);
3437
3438 // Emit as a series of 'note's all template and non-templates identified by
3439 // the expression Expr
3440 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3441 bool TakingAddress = false);
3442
3443 /// Check the enable_if expressions on the given function. Returns the first
3444 /// failing attribute, or NULL if they were all successful.
3445 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
3446 ArrayRef<Expr *> Args,
3447 bool MissingImplicitThis = false);
3448
3449 /// Find the failed Boolean condition within a given Boolean
3450 /// constant expression, and describe it with a string.
3451 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3452
3453 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3454 /// non-ArgDependent DiagnoseIfAttrs.
3455 ///
3456 /// Argument-dependent diagnose_if attributes should be checked each time a
3457 /// function is used as a direct callee of a function call.
3458 ///
3459 /// Returns true if any errors were emitted.
3460 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3461 const Expr *ThisArg,
3462 ArrayRef<const Expr *> Args,
3463 SourceLocation Loc);
3464
3465 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3466 /// ArgDependent DiagnoseIfAttrs.
3467 ///
3468 /// Argument-independent diagnose_if attributes should be checked on every use
3469 /// of a function.
3470 ///
3471 /// Returns true if any errors were emitted.
3472 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3473 SourceLocation Loc);
3474
3475 /// Returns whether the given function's address can be taken or not,
3476 /// optionally emitting a diagnostic if the address can't be taken.
3477 ///
3478 /// Returns false if taking the address of the function is illegal.
3479 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3480 bool Complain = false,
3481 SourceLocation Loc = SourceLocation());
3482
3483 // [PossiblyAFunctionType] --> [Return]
3484 // NonFunctionType --> NonFunctionType
3485 // R (A) --> R(A)
3486 // R (*)(A) --> R (A)
3487 // R (&)(A) --> R (A)
3488 // R (S::*)(A) --> R (A)
3489 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3490
3491 FunctionDecl *
3492 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3493 QualType TargetType,
3494 bool Complain,
3495 DeclAccessPair &Found,
3496 bool *pHadMultipleCandidates = nullptr);
3497
3498 FunctionDecl *
3499 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3500
3501 bool resolveAndFixAddressOfSingleOverloadCandidate(
3502 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3503
3504 FunctionDecl *
3505 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3506 bool Complain = false,
3507 DeclAccessPair *Found = nullptr);
3508
3509 bool ResolveAndFixSingleFunctionTemplateSpecialization(
3510 ExprResult &SrcExpr,
3511 bool DoFunctionPointerConverion = false,
3512 bool Complain = false,
3513 SourceRange OpRangeForComplaining = SourceRange(),
3514 QualType DestTypeForComplaining = QualType(),
3515 unsigned DiagIDForComplaining = 0);
3516
3517
3518 Expr *FixOverloadedFunctionReference(Expr *E,
3519 DeclAccessPair FoundDecl,
3520 FunctionDecl *Fn);
3521 ExprResult FixOverloadedFunctionReference(ExprResult,
3522 DeclAccessPair FoundDecl,
3523 FunctionDecl *Fn);
3524
3525 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3526 ArrayRef<Expr *> Args,
3527 OverloadCandidateSet &CandidateSet,
3528 bool PartialOverloading = false);
3529
3530 // An enum used to represent the different possible results of building a
3531 // range-based for loop.
3532 enum ForRangeStatus {
3533 FRS_Success,
3534 FRS_NoViableFunction,
3535 FRS_DiagnosticIssued
3536 };
3537
3538 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3539 SourceLocation RangeLoc,
3540 const DeclarationNameInfo &NameInfo,
3541 LookupResult &MemberLookup,
3542 OverloadCandidateSet *CandidateSet,
3543 Expr *Range, ExprResult *CallExpr);
3544
3545 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3546 UnresolvedLookupExpr *ULE,
3547 SourceLocation LParenLoc,
3548 MultiExprArg Args,
3549 SourceLocation RParenLoc,
3550 Expr *ExecConfig,
3551 bool AllowTypoCorrection=true,
3552 bool CalleesAddressIsTaken=false);
3553
3554 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3555 MultiExprArg Args, SourceLocation RParenLoc,
3556 OverloadCandidateSet *CandidateSet,
3557 ExprResult *Result);
3558
3559 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3560 UnaryOperatorKind Opc,
3561 const UnresolvedSetImpl &Fns,
3562 Expr *input, bool RequiresADL = true);
3563
3564 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
3565 OverloadedOperatorKind Op,
3566 const UnresolvedSetImpl &Fns,
3567 ArrayRef<Expr *> Args, bool RequiresADL = true);
3568 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3569 BinaryOperatorKind Opc,
3570 const UnresolvedSetImpl &Fns,
3571 Expr *LHS, Expr *RHS,
3572 bool RequiresADL = true,
3573 bool AllowRewrittenCandidates = true,
3574 FunctionDecl *DefaultedFn = nullptr);
3575 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
3576 const UnresolvedSetImpl &Fns,
3577 Expr *LHS, Expr *RHS,
3578 FunctionDecl *DefaultedFn);
3579
3580 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3581 SourceLocation RLoc,
3582 Expr *Base,Expr *Idx);
3583
3584 ExprResult
3585 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3586 SourceLocation LParenLoc,
3587 MultiExprArg Args,
3588 SourceLocation RParenLoc);
3589 ExprResult
3590 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3591 MultiExprArg Args,
3592 SourceLocation RParenLoc);
3593
3594 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3595 SourceLocation OpLoc,
3596 bool *NoArrowOperatorFound = nullptr);
3597
3598 /// CheckCallReturnType - Checks that a call expression's return type is
3599 /// complete. Returns true on failure. The location passed in is the location
3600 /// that best represents the call.
3601 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3602 CallExpr *CE, FunctionDecl *FD);
3603
3604 /// Helpers for dealing with blocks and functions.
3605 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3606 bool CheckParameterNames);
3607 void CheckCXXDefaultArguments(FunctionDecl *FD);
3608 void CheckExtraCXXDefaultArguments(Declarator &D);
3609 Scope *getNonFieldDeclScope(Scope *S);
3610
3611 /// \name Name lookup
3612 ///
3613 /// These routines provide name lookup that is used during semantic
3614 /// analysis to resolve the various kinds of names (identifiers,
3615 /// overloaded operator names, constructor names, etc.) into zero or
3616 /// more declarations within a particular scope. The major entry
3617 /// points are LookupName, which performs unqualified name lookup,
3618 /// and LookupQualifiedName, which performs qualified name lookup.
3619 ///
3620 /// All name lookup is performed based on some specific criteria,
3621 /// which specify what names will be visible to name lookup and how
3622 /// far name lookup should work. These criteria are important both
3623 /// for capturing language semantics (certain lookups will ignore
3624 /// certain names, for example) and for performance, since name
3625 /// lookup is often a bottleneck in the compilation of C++. Name
3626 /// lookup criteria is specified via the LookupCriteria enumeration.
3627 ///
3628 /// The results of name lookup can vary based on the kind of name
3629 /// lookup performed, the current language, and the translation
3630 /// unit. In C, for example, name lookup will either return nothing
3631 /// (no entity found) or a single declaration. In C++, name lookup
3632 /// can additionally refer to a set of overloaded functions or
3633 /// result in an ambiguity. All of the possible results of name
3634 /// lookup are captured by the LookupResult class, which provides
3635 /// the ability to distinguish among them.
3636 //@{
3637
3638 /// Describes the kind of name lookup to perform.
3639 enum LookupNameKind {
3640 /// Ordinary name lookup, which finds ordinary names (functions,
3641 /// variables, typedefs, etc.) in C and most kinds of names
3642 /// (functions, variables, members, types, etc.) in C++.
3643 LookupOrdinaryName = 0,
3644 /// Tag name lookup, which finds the names of enums, classes,
3645 /// structs, and unions.
3646 LookupTagName,
3647 /// Label name lookup.
3648 LookupLabel,
3649 /// Member name lookup, which finds the names of
3650 /// class/struct/union members.
3651 LookupMemberName,
3652 /// Look up of an operator name (e.g., operator+) for use with
3653 /// operator overloading. This lookup is similar to ordinary name
3654 /// lookup, but will ignore any declarations that are class members.
3655 LookupOperatorName,
3656 /// Look up a name following ~ in a destructor name. This is an ordinary
3657 /// lookup, but prefers tags to typedefs.
3658 LookupDestructorName,
3659 /// Look up of a name that precedes the '::' scope resolution
3660 /// operator in C++. This lookup completely ignores operator, object,
3661 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3662 LookupNestedNameSpecifierName,
3663 /// Look up a namespace name within a C++ using directive or
3664 /// namespace alias definition, ignoring non-namespace names (C++
3665 /// [basic.lookup.udir]p1).
3666 LookupNamespaceName,
3667 /// Look up all declarations in a scope with the given name,
3668 /// including resolved using declarations. This is appropriate
3669 /// for checking redeclarations for a using declaration.
3670 LookupUsingDeclName,
3671 /// Look up an ordinary name that is going to be redeclared as a
3672 /// name with linkage. This lookup ignores any declarations that
3673 /// are outside of the current scope unless they have linkage. See
3674 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3675 LookupRedeclarationWithLinkage,
3676 /// Look up a friend of a local class. This lookup does not look
3677 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3678 LookupLocalFriendName,
3679 /// Look up the name of an Objective-C protocol.
3680 LookupObjCProtocolName,
3681 /// Look up implicit 'self' parameter of an objective-c method.
3682 LookupObjCImplicitSelfParam,
3683 /// Look up the name of an OpenMP user-defined reduction operation.
3684 LookupOMPReductionName,
3685 /// Look up the name of an OpenMP user-defined mapper.
3686 LookupOMPMapperName,
3687 /// Look up any declaration with any name.
3688 LookupAnyName
3689 };
3690
3691 /// Specifies whether (or how) name lookup is being performed for a
3692 /// redeclaration (vs. a reference).
3693 enum RedeclarationKind {
3694 /// The lookup is a reference to this name that is not for the
3695 /// purpose of redeclaring the name.
3696 NotForRedeclaration = 0,
3697 /// The lookup results will be used for redeclaration of a name,
3698 /// if an entity by that name already exists and is visible.
3699 ForVisibleRedeclaration,
3700 /// The lookup results will be used for redeclaration of a name
3701 /// with external linkage; non-visible lookup results with external linkage
3702 /// may also be found.
3703 ForExternalRedeclaration
3704 };
3705
3706 RedeclarationKind forRedeclarationInCurContext() {
3707 // A declaration with an owning module for linkage can never link against
3708 // anything that is not visible. We don't need to check linkage here; if
3709 // the context has internal linkage, redeclaration lookup won't find things
3710 // from other TUs, and we can't safely compute linkage yet in general.
3711 if (cast<Decl>(CurContext)
3712 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3713 return ForVisibleRedeclaration;
3714 return ForExternalRedeclaration;
3715 }
3716
3717 /// The possible outcomes of name lookup for a literal operator.
3718 enum LiteralOperatorLookupResult {
3719 /// The lookup resulted in an error.
3720 LOLR_Error,
3721 /// The lookup found no match but no diagnostic was issued.
3722 LOLR_ErrorNoDiagnostic,
3723 /// The lookup found a single 'cooked' literal operator, which
3724 /// expects a normal literal to be built and passed to it.
3725 LOLR_Cooked,
3726 /// The lookup found a single 'raw' literal operator, which expects
3727 /// a string literal containing the spelling of the literal token.
3728 LOLR_Raw,
3729 /// The lookup found an overload set of literal operator templates,
3730 /// which expect the characters of the spelling of the literal token to be
3731 /// passed as a non-type template argument pack.
3732 LOLR_Template,
3733 /// The lookup found an overload set of literal operator templates,
3734 /// which expect the character type and characters of the spelling of the
3735 /// string literal token to be passed as template arguments.
3736 LOLR_StringTemplate
3737 };
3738
3739 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3740 CXXSpecialMember SM,
3741 bool ConstArg,
3742 bool VolatileArg,
3743 bool RValueThis,
3744 bool ConstThis,
3745 bool VolatileThis);
3746
3747 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3748 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3749 TypoRecoveryCallback;
3750
3751private:
3752 bool CppLookupName(LookupResult &R, Scope *S);
3753
3754 struct TypoExprState {
3755 std::unique_ptr<TypoCorrectionConsumer> Consumer;
3756 TypoDiagnosticGenerator DiagHandler;
3757 TypoRecoveryCallback RecoveryHandler;
3758 TypoExprState();
3759 TypoExprState(TypoExprState &&other) noexcept;
3760 TypoExprState &operator=(TypoExprState &&other) noexcept;
3761 };
3762
3763 /// The set of unhandled TypoExprs and their associated state.
3764 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3765
3766 /// Creates a new TypoExpr AST node.
3767 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3768 TypoDiagnosticGenerator TDG,
3769 TypoRecoveryCallback TRC, SourceLocation TypoLoc);
3770
3771 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
3772 //
3773 // The boolean value will be true to indicate that the namespace was loaded
3774 // from an AST/PCH file, or false otherwise.
3775 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3776
3777 /// Whether we have already loaded known namespaces from an extenal
3778 /// source.
3779 bool LoadedExternalKnownNamespaces;
3780
3781 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
3782 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3783 /// should be skipped entirely.
3784 std::unique_ptr<TypoCorrectionConsumer>
3785 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3786 Sema::LookupNameKind LookupKind, Scope *S,
3787 CXXScopeSpec *SS,
3788 CorrectionCandidateCallback &CCC,
3789 DeclContext *MemberContext, bool EnteringContext,
3790 const ObjCObjectPointerType *OPT,
3791 bool ErrorRecovery);
3792
3793public:
3794 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3795
3796 /// Clears the state of the given TypoExpr.
3797 void clearDelayedTypo(TypoExpr *TE);
3798
3799 /// Look up a name, looking for a single declaration. Return
3800 /// null if the results were absent, ambiguous, or overloaded.
3801 ///
3802 /// It is preferable to use the elaborated form and explicitly handle
3803 /// ambiguity and overloaded.
3804 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3805 SourceLocation Loc,
3806 LookupNameKind NameKind,
3807 RedeclarationKind Redecl
3808 = NotForRedeclaration);
3809 bool LookupBuiltin(LookupResult &R);
3810 bool LookupName(LookupResult &R, Scope *S,
3811 bool AllowBuiltinCreation = false);
3812 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3813 bool InUnqualifiedLookup = false);
3814 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3815 CXXScopeSpec &SS);
3816 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3817 bool AllowBuiltinCreation = false,
3818 bool EnteringContext = false);
3819 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3820 RedeclarationKind Redecl
3821 = NotForRedeclaration);
3822 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3823
3824 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3825 QualType T1, QualType T2,
3826 UnresolvedSetImpl &Functions);
3827
3828 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3829 SourceLocation GnuLabelLoc = SourceLocation());
3830
3831 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3832 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3833 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3834 unsigned Quals);
3835 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3836 bool RValueThis, unsigned ThisQuals);
3837 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3838 unsigned Quals);
3839 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3840 bool RValueThis, unsigned ThisQuals);
3841 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3842
3843 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3844 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3845 ArrayRef<QualType> ArgTys,
3846 bool AllowRaw,
3847 bool AllowTemplate,
3848 bool AllowStringTemplate,
3849 bool DiagnoseMissing);
3850 bool isKnownName(StringRef name);
3851
3852 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
3853 enum class FunctionEmissionStatus {
3854 Emitted,
3855 CUDADiscarded, // Discarded due to CUDA/HIP hostness
3856 OMPDiscarded, // Discarded due to OpenMP hostness
3857 TemplateDiscarded, // Discarded due to uninstantiated templates
3858 Unknown,
3859 };
3860 FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl,
3861 bool Final = false);
3862
3863 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
3864 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
3865
3866 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3867 ArrayRef<Expr *> Args, ADLResult &Functions);
3868
3869 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3870 VisibleDeclConsumer &Consumer,
3871 bool IncludeGlobalScope = true,
3872 bool LoadExternal = true);
3873 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3874 VisibleDeclConsumer &Consumer,
3875 bool IncludeGlobalScope = true,
3876 bool IncludeDependentBases = false,
3877 bool LoadExternal = true);
3878
3879 enum CorrectTypoKind {
3880 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3881 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3882 };
3883
3884 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3885 Sema::LookupNameKind LookupKind,
3886 Scope *S, CXXScopeSpec *SS,
3887 CorrectionCandidateCallback &CCC,
3888 CorrectTypoKind Mode,
3889 DeclContext *MemberContext = nullptr,
3890 bool EnteringContext = false,
3891 const ObjCObjectPointerType *OPT = nullptr,
3892 bool RecordFailure = true);
3893
3894 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3895 Sema::LookupNameKind LookupKind, Scope *S,
3896 CXXScopeSpec *SS,
3897 CorrectionCandidateCallback &CCC,
3898 TypoDiagnosticGenerator TDG,
3899 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3900 DeclContext *MemberContext = nullptr,
3901 bool EnteringContext = false,
3902 const ObjCObjectPointerType *OPT = nullptr);
3903
3904 /// Process any TypoExprs in the given Expr and its children,
3905 /// generating diagnostics as appropriate and returning a new Expr if there
3906 /// were typos that were all successfully corrected and ExprError if one or
3907 /// more typos could not be corrected.
3908 ///
3909 /// \param E The Expr to check for TypoExprs.
3910 ///
3911 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3912 /// initializer.
3913 ///
3914 /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
3915 /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
3916 ///
3917 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3918 /// it is an acceptable/usable result from a single combination of typo
3919 /// corrections. As long as the filter returns ExprError, different
3920 /// combinations of corrections will be tried until all are exhausted.
3921 ExprResult CorrectDelayedTyposInExpr(
3922 Expr *E, VarDecl *InitDecl = nullptr,
3923 bool RecoverUncorrectedTypos = false,
3924 llvm::function_ref<ExprResult(Expr *)> Filter =
3925 [](Expr *E) -> ExprResult { return E; });
3926
3927 ExprResult CorrectDelayedTyposInExpr(
3928 ExprResult ER, VarDecl *InitDecl = nullptr,
3929 bool RecoverUncorrectedTypos = false,
3930 llvm::function_ref<ExprResult(Expr *)> Filter =
3931 [](Expr *E) -> ExprResult { return E; }) {
3932 return ER.isInvalid()
3933 ? ER
3934 : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
3935 RecoverUncorrectedTypos, Filter);
3936 }
3937
3938 void diagnoseTypo(const TypoCorrection &Correction,
3939 const PartialDiagnostic &TypoDiag,
3940 bool ErrorRecovery = true);
3941
3942 void diagnoseTypo(const TypoCorrection &Correction,
3943 const PartialDiagnostic &TypoDiag,
3944 const PartialDiagnostic &PrevNote,
3945 bool ErrorRecovery = true);
3946
3947 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3948
3949 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3950 ArrayRef<Expr *> Args,
3951 AssociatedNamespaceSet &AssociatedNamespaces,
3952 AssociatedClassSet &AssociatedClasses);
3953
3954 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3955 bool ConsiderLinkage, bool AllowInlineNamespace);
3956
3957 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3958
3959 void DiagnoseAmbiguousLookup(LookupResult &Result);
3960 //@}
3961
3962 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
3963 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
3964 ArrayRef<Expr *> SubExprs,
3965 QualType T = QualType());
3966
3967 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3968 SourceLocation IdLoc,
3969 bool TypoCorrection = false);
3970 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3971 Scope *S, bool ForRedeclaration,
3972 SourceLocation Loc);
3973 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3974 Scope *S);
3975 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
3976 FunctionDecl *FD);
3977 void AddKnownFunctionAttributes(FunctionDecl *FD);
3978
3979 // More parsing and symbol table subroutines.
3980
3981 void ProcessPragmaWeak(Scope *S, Decl *D);
3982 // Decl attributes - this routine is the top level dispatcher.
3983 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3984 // Helper for delayed processing of attributes.
3985 void ProcessDeclAttributeDelayed(Decl *D,
3986 const ParsedAttributesView &AttrList);
3987 void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
3988 bool IncludeCXX11Attributes = true);
3989 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3990 const ParsedAttributesView &AttrList);
3991
3992 void checkUnusedDeclAttributes(Declarator &D);
3993
3994 /// Determine if type T is a valid subject for a nonnull and similar
3995 /// attributes. By default, we look through references (the behavior used by
3996 /// nonnull), but if the second parameter is true, then we treat a reference
3997 /// type as valid.
3998 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3999
4000 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4001 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
4002 const FunctionDecl *FD = nullptr);
4003 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4004 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4005 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4006 StringRef &Str,
4007 SourceLocation *ArgLocation = nullptr);
4008 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4009 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4010 bool checkMSInheritanceAttrOnDefinition(
4011 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4012 MSInheritanceModel SemanticSpelling);
4013
4014 void CheckAlignasUnderalignment(Decl *D);
4015
4016 /// Adjust the calling convention of a method to be the ABI default if it
4017 /// wasn't specified explicitly. This handles method types formed from
4018 /// function type typedefs and typename template arguments.
4019 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4020 SourceLocation Loc);
4021
4022 // Check if there is an explicit attribute, but only look through parens.
4023 // The intent is to look for an attribute on the current declarator, but not
4024 // one that came from a typedef.
4025 bool hasExplicitCallingConv(QualType T);
4026
4027 /// Get the outermost AttributedType node that sets a calling convention.
4028 /// Valid types should not have multiple attributes with different CCs.
4029 const AttributedType *getCallingConvAttributedType(QualType T) const;
4030
4031 /// Stmt attributes - this routine is the top level dispatcher.
4032 StmtResult ProcessStmtAttributes(Stmt *Stmt,
4033 const ParsedAttributesView &Attrs,
4034 SourceRange Range);
4035
4036 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
4037 ObjCMethodDecl *MethodDecl,
4038 bool IsProtocolMethodDecl);
4039
4040 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
4041 ObjCMethodDecl *Overridden,
4042 bool IsProtocolMethodDecl);
4043
4044 /// WarnExactTypedMethods - This routine issues a warning if method
4045 /// implementation declaration matches exactly that of its declaration.
4046 void WarnExactTypedMethods(ObjCMethodDecl *Method,
4047 ObjCMethodDecl *MethodDecl,
4048 bool IsProtocolMethodDecl);
4049
4050 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
4051
4052 /// CheckImplementationIvars - This routine checks if the instance variables
4053 /// listed in the implelementation match those listed in the interface.
4054 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
4055 ObjCIvarDecl **Fields, unsigned nIvars,
4056 SourceLocation Loc);
4057
4058 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4059 /// remains unimplemented in the class or category \@implementation.
4060 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4061 ObjCContainerDecl* IDecl,
4062 bool IncompleteImpl = false);
4063
4064 /// DiagnoseUnimplementedProperties - This routine warns on those properties
4065 /// which must be implemented by this implementation.
4066 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
4067 ObjCContainerDecl *CDecl,
4068 bool SynthesizeProperties);
4069
4070 /// Diagnose any null-resettable synthesized setters.
4071 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
4072
4073 /// DefaultSynthesizeProperties - This routine default synthesizes all
4074 /// properties which must be synthesized in the class's \@implementation.
4075 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
4076 ObjCInterfaceDecl *IDecl,
4077 SourceLocation AtEnd);
4078 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
4079
4080 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4081 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4082 /// declared in class 'IFace'.
4083 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
4084 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4085
4086 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4087 /// backs the property is not used in the property's accessor.
4088 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4089 const ObjCImplementationDecl *ImplD);
4090
4091 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4092 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4093 /// It also returns ivar's property on success.
4094 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4095 const ObjCPropertyDecl *&PDecl) const;
4096
4097 /// Called by ActOnProperty to handle \@property declarations in
4098 /// class extensions.
4099 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
4100 SourceLocation AtLoc,
4101 SourceLocation LParenLoc,
4102 FieldDeclarator &FD,
4103 Selector GetterSel,
4104 SourceLocation GetterNameLoc,
4105 Selector SetterSel,
4106 SourceLocation SetterNameLoc,
4107 const bool isReadWrite,
4108 unsigned &Attributes,
4109 const unsigned AttributesAsWritten,
4110 QualType T,
4111 TypeSourceInfo *TSI,
4112 tok::ObjCKeywordKind MethodImplKind);
4113
4114 /// Called by ActOnProperty and HandlePropertyInClassExtension to
4115 /// handle creating the ObjcPropertyDecl for a category or \@interface.
4116 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
4117 ObjCContainerDecl *CDecl,
4118 SourceLocation AtLoc,
4119 SourceLocation LParenLoc,
4120 FieldDeclarator &FD,
4121 Selector GetterSel,
4122 SourceLocation GetterNameLoc,
4123 Selector SetterSel,
4124 SourceLocation SetterNameLoc,
4125 const bool isReadWrite,
4126 const unsigned Attributes,
4127 const unsigned AttributesAsWritten,
4128 QualType T,
4129 TypeSourceInfo *TSI,
4130 tok::ObjCKeywordKind MethodImplKind,
4131 DeclContext *lexicalDC = nullptr);
4132
4133 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4134 /// warning) when atomic property has one but not the other user-declared
4135 /// setter or getter.
4136 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
4137 ObjCInterfaceDecl* IDecl);
4138
4139 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
4140
4141 void DiagnoseMissingDesignatedInitOverrides(
4142 const ObjCImplementationDecl *ImplD,
4143 const ObjCInterfaceDecl *IFD);
4144
4145 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
4146
4147 enum MethodMatchStrategy {
4148 MMS_loose,
4149 MMS_strict
4150 };
4151
4152 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
4153 /// true, or false, accordingly.
4154 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
4155 const ObjCMethodDecl *PrevMethod,
4156 MethodMatchStrategy strategy = MMS_strict);
4157
4158 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
4159 /// or protocol against those declared in their implementations.
4160 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
4161 const SelectorSet &ClsMap,
4162 SelectorSet &InsMapSeen,
4163 SelectorSet &ClsMapSeen,
4164 ObjCImplDecl* IMPDecl,
4165 ObjCContainerDecl* IDecl,
4166 bool &IncompleteImpl,
4167 bool ImmediateClass,
4168 bool WarnCategoryMethodImpl=false);
4169
4170 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
4171 /// category matches with those implemented in its primary class and
4172 /// warns each time an exact match is found.
4173 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
4174
4175 /// Add the given method to the list of globally-known methods.
4176 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
4177
4178 /// Returns default addr space for method qualifiers.
4179 LangAS getDefaultCXXMethodAddrSpace() const;
4180
4181private:
4182 /// AddMethodToGlobalPool - Add an instance or factory method to the global
4183 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4184 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4185
4186 /// LookupMethodInGlobalPool - Returns the instance or factory method and
4187 /// optionally warns if there are multiple signatures.
4188 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4189 bool receiverIdOrClass,
4190 bool instance);
4191
4192public:
4193 /// - Returns instance or factory methods in global method pool for
4194 /// given selector. It checks the desired kind first, if none is found, and
4195 /// parameter checkTheOther is set, it then checks the other kind. If no such
4196 /// method or only one method is found, function returns false; otherwise, it
4197 /// returns true.
4198 bool
4199 CollectMultipleMethodsInGlobalPool(Selector Sel,
4200 SmallVectorImpl<ObjCMethodDecl*>& Methods,
4201 bool InstanceFirst, bool CheckTheOther,
4202 const ObjCObjectType *TypeBound = nullptr);
4203
4204 bool
4205 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4206 SourceRange R, bool receiverIdOrClass,
4207 SmallVectorImpl<ObjCMethodDecl*>& Methods);
4208
4209 void
4210 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4211 Selector Sel, SourceRange R,
4212 bool receiverIdOrClass);
4213
4214private:
4215 /// - Returns a selector which best matches given argument list or
4216 /// nullptr if none could be found
4217 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4218 bool IsInstance,
4219 SmallVectorImpl<ObjCMethodDecl*>& Methods);
4220
4221
4222 /// Record the typo correction failure and return an empty correction.
4223 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4224 bool RecordFailure = true) {
4225 if (RecordFailure)
4226 TypoCorrectionFailures[Typo].insert(TypoLoc);
4227 return TypoCorrection();
4228 }
4229
4230public:
4231 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4232 /// unit are added to a global pool. This allows us to efficiently associate
4233 /// a selector with a method declaraation for purposes of typechecking
4234 /// messages sent to "id" (where the class of the object is unknown).
4235 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4236 AddMethodToGlobalPool(Method, impl, /*instance*/true);
4237 }
4238
4239 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4240 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4241 AddMethodToGlobalPool(Method, impl, /*instance*/false);
4242 }
4243
4244 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4245 /// pool.
4246 void AddAnyMethodToGlobalPool(Decl *D);
4247
4248 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4249 /// there are multiple signatures.
4250 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4251 bool receiverIdOrClass=false) {
4252 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4253 /*instance*/true);
4254 }
4255
4256 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4257 /// there are multiple signatures.
4258 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4259 bool receiverIdOrClass=false) {
4260 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4261 /*instance*/false);
4262 }
4263
4264 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4265 QualType ObjectType=QualType());
4266 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4267 /// implementation.
4268 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4269
4270 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4271 /// initialization.
4272 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4273 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4274
4275 //===--------------------------------------------------------------------===//
4276 // Statement Parsing Callbacks: SemaStmt.cpp.
4277public:
4278 class FullExprArg {
4279 public:
4280 FullExprArg() : E(nullptr) { }
4281 FullExprArg(Sema &actions) : E(nullptr) { }
4282
4283 ExprResult release() {
4284 return E;
4285 }
4286
4287 Expr *get() const { return E; }
4288
4289 Expr *operator->() {
4290 return E;
4291 }
4292
4293 private:
4294 // FIXME: No need to make the entire Sema class a friend when it's just
4295 // Sema::MakeFullExpr that needs access to the constructor below.
4296 friend class Sema;
4297
4298 explicit FullExprArg(Expr *expr) : E(expr) {}
4299
4300 Expr *E;
4301 };
4302
4303 FullExprArg MakeFullExpr(Expr *Arg) {
4304 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4305 }
4306 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4307 return FullExprArg(
4308 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4309 }
4310 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4311 ExprResult FE =
4312 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4313 /*DiscardedValue*/ true);
4314 return FullExprArg(FE.get());
4315 }
4316
4317 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4318 StmtResult ActOnExprStmtError();
4319
4320 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4321 bool HasLeadingEmptyMacro = false);
4322
4323 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4324 void ActOnFinishOfCompoundStmt();
4325 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4326 ArrayRef<Stmt *> Elts, bool isStmtExpr);
4327
4328 /// A RAII object to enter scope of a compound statement.
4329 class CompoundScopeRAII {
4330 public:
4331 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4332 S.ActOnStartOfCompoundStmt(IsStmtExpr);
4333 }
4334
4335 ~CompoundScopeRAII() {
4336 S.ActOnFinishOfCompoundStmt();
4337 }
4338
4339 private:
4340 Sema &S;
4341 };
4342
4343 /// An RAII helper that pops function a function scope on exit.
4344 struct FunctionScopeRAII {
4345 Sema &S;
4346 bool Active;
4347 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
4348 ~FunctionScopeRAII() {
4349 if (Active)
4350 S.PopFunctionScopeInfo();
4351 }
4352 void disable() { Active = false; }
4353 };
4354
4355 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4356 SourceLocation StartLoc,
4357 SourceLocation EndLoc);
4358 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4359 StmtResult ActOnForEachLValueExpr(Expr *E);
4360 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4361 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4362 SourceLocation DotDotDotLoc, ExprResult RHS,
4363 SourceLocation ColonLoc);
4364 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4365
4366 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4367 SourceLocation ColonLoc,
4368 Stmt *SubStmt, Scope *CurScope);
4369 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4370 SourceLocation ColonLoc, Stmt *SubStmt);
4371
4372 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
4373 ArrayRef<const Attr*> Attrs,
4374 Stmt *SubStmt);
4375
4376 class ConditionResult;
4377 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4378 Stmt *InitStmt,
4379 ConditionResult Cond, Stmt *ThenVal,
4380 SourceLocation ElseLoc, Stmt *ElseVal);
4381 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4382 Stmt *InitStmt,
4383 ConditionResult Cond, Stmt *ThenVal,
4384 SourceLocation ElseLoc, Stmt *ElseVal);
4385 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4386 Stmt *InitStmt,
4387 ConditionResult Cond);
4388 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4389 Stmt *Switch, Stmt *Body);
4390 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
4391 ConditionResult Cond, SourceLocation RParenLoc,
4392 Stmt *Body);
4393 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4394 SourceLocation WhileLoc, SourceLocation CondLParen,
4395 Expr *Cond, SourceLocation CondRParen);
4396
4397 StmtResult ActOnForStmt(SourceLocation ForLoc,
4398 SourceLocation LParenLoc,
4399 Stmt *First,
4400 ConditionResult Second,
4401 FullExprArg Third,
4402 SourceLocation RParenLoc,
4403 Stmt *Body);
4404 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4405 Expr *collection);
4406 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4407 Stmt *First, Expr *collection,
4408 SourceLocation RParenLoc);
4409 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4410
4411 enum BuildForRangeKind {
4412 /// Initial building of a for-range statement.
4413 BFRK_Build,
4414 /// Instantiation or recovery rebuild of a for-range statement. Don't
4415 /// attempt any typo-correction.
4416 BFRK_Rebuild,
4417 /// Determining whether a for-range statement could be built. Avoid any
4418 /// unnecessary or irreversible actions.
4419 BFRK_Check
4420 };
4421
4422 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4423 SourceLocation CoawaitLoc,
4424 Stmt *InitStmt,
4425 Stmt *LoopVar,
4426 SourceLocation ColonLoc, Expr *Collection,
4427 SourceLocation RParenLoc,
4428 BuildForRangeKind Kind);
4429 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4430 SourceLocation CoawaitLoc,
4431 Stmt *InitStmt,
4432 SourceLocation ColonLoc,
4433 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4434 Expr *Cond, Expr *Inc,
4435 Stmt *LoopVarDecl,
4436 SourceLocation RParenLoc,
4437 BuildForRangeKind Kind);
4438 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4439
4440 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4441 SourceLocation LabelLoc,
4442 LabelDecl *TheDecl);
4443 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4444 SourceLocation StarLoc,
4445 Expr *DestExp);
4446 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4447 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4448
4449 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4450 CapturedRegionKind Kind, unsigned NumParams);
4451 typedef std::pair<StringRef, QualType> CapturedParamNameType;
4452 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4453 CapturedRegionKind Kind,
4454 ArrayRef<CapturedParamNameType> Params,
4455 unsigned OpenMPCaptureLevel = 0);
4456 StmtResult ActOnCapturedRegionEnd(Stmt *S);
4457 void ActOnCapturedRegionError();
4458 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4459 SourceLocation Loc,
4460 unsigned NumParams);
4461
4462 enum CopyElisionSemanticsKind {
4463 CES_Strict = 0,
4464 CES_AllowParameters = 1,
4465 CES_AllowDifferentTypes = 2,
4466 CES_AllowExceptionVariables = 4,
4467 CES_FormerDefault = (CES_AllowParameters),
4468 CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
4469 CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
4470 CES_AllowExceptionVariables),
4471 };
4472
4473 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
4474 CopyElisionSemanticsKind CESK);
4475 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
4476 CopyElisionSemanticsKind CESK);
4477
4478 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4479 Scope *CurScope);
4480 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4481 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4482
4483 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4484 bool IsVolatile, unsigned NumOutputs,
4485 unsigned NumInputs, IdentifierInfo **Names,
4486 MultiExprArg Constraints, MultiExprArg Exprs,
4487 Expr *AsmString, MultiExprArg Clobbers,
4488 unsigned NumLabels,
4489 SourceLocation RParenLoc);
4490
4491 void FillInlineAsmIdentifierInfo(Expr *Res,
4492 llvm::InlineAsmIdentifierInfo &Info);
4493 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4494 SourceLocation TemplateKWLoc,
4495 UnqualifiedId &Id,
4496 bool IsUnevaluatedContext);
4497 bool LookupInlineAsmField(StringRef Base, StringRef Member,
4498 unsigned &Offset, SourceLocation AsmLoc);
4499 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4500 SourceLocation AsmLoc);
4501 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4502 ArrayRef<Token> AsmToks,
4503 StringRef AsmString,
4504 unsigned NumOutputs, unsigned NumInputs,
4505 ArrayRef<StringRef> Constraints,
4506 ArrayRef<StringRef> Clobbers,
4507 ArrayRef<Expr*> Exprs,
4508 SourceLocation EndLoc);
4509 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4510 SourceLocation Location,
4511 bool AlwaysCreate);
4512
4513 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4514 SourceLocation StartLoc,
4515 SourceLocation IdLoc, IdentifierInfo *Id,
4516 bool Invalid = false);
4517
4518 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4519
4520 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4521 Decl *Parm, Stmt *Body);
4522
4523 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4524
4525 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4526 MultiStmtArg Catch, Stmt *Finally);
4527
4528 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4529 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4530 Scope *CurScope);
4531 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4532 Expr *operand);
4533 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4534 Expr *SynchExpr,
4535 Stmt *SynchBody);
4536
4537 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4538
4539 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4540 SourceLocation StartLoc,
4541 SourceLocation IdLoc,
4542 IdentifierInfo *Id);
4543
4544 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4545
4546 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4547 Decl *ExDecl, Stmt *HandlerBlock);
4548 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4549 ArrayRef<Stmt *> Handlers);
4550
4551 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4552 SourceLocation TryLoc, Stmt *TryBlock,
4553 Stmt *Handler);
4554 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4555 Expr *FilterExpr,
4556 Stmt *Block);
4557 void ActOnStartSEHFinallyBlock();
4558 void ActOnAbortSEHFinallyBlock();
4559 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4560 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4561
4562 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4563
4564 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4565
4566 /// If it's a file scoped decl that must warn if not used, keep track
4567 /// of it.
4568 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4569
4570 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4571 /// whose result is unused, warn.
4572 void DiagnoseUnusedExprResult(const Stmt *S);
4573 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4574 void DiagnoseUnusedDecl(const NamedDecl *ND);
4575
4576 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4577 /// statement as a \p Body, and it is located on the same line.
4578 ///
4579 /// This helps prevent bugs due to typos, such as:
4580 /// if (condition);
4581 /// do_stuff();
4582 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4583 const Stmt *Body,
4584 unsigned DiagID);
4585
4586 /// Warn if a for/while loop statement \p S, which is followed by
4587 /// \p PossibleBody, has a suspicious null statement as a body.
4588 void DiagnoseEmptyLoopBody(const Stmt *S,
4589 const Stmt *PossibleBody);
4590
4591 /// Warn if a value is moved to itself.
4592 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4593 SourceLocation OpLoc);
4594
4595 /// Warn if we're implicitly casting from a _Nullable pointer type to a
4596 /// _Nonnull one.
4597 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4598 SourceLocation Loc);
4599
4600 /// Warn when implicitly casting 0 to nullptr.
4601 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4602
4603 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
4604 return DelayedDiagnostics.push(pool);
4605 }
4606 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4607
4608 typedef ProcessingContextState ParsingClassState;
4609 ParsingClassState PushParsingClass() {
4610 ParsingClassDepth++;
4611 return DelayedDiagnostics.pushUndelayed();
4612 }
4613 void PopParsingClass(ParsingClassState state) {
4614 ParsingClassDepth--;
4615 DelayedDiagnostics.popUndelayed(state);
4616 }
4617
4618 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4619
4620 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4621 const ObjCInterfaceDecl *UnknownObjCClass,
4622 bool ObjCPropertyAccess,
4623 bool AvoidPartialAvailabilityChecks = false,
4624 ObjCInterfaceDecl *ClassReceiver = nullptr);
4625
4626 bool makeUnavailableInSystemHeader(SourceLocation loc,
4627 UnavailableAttr::ImplicitReason reason);
4628
4629 /// Issue any -Wunguarded-availability warnings in \c FD
4630 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4631
4632 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
4633
4634 //===--------------------------------------------------------------------===//
4635 // Expression Parsing Callbacks: SemaExpr.cpp.
4636
4637 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4638 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4639 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4640 bool ObjCPropertyAccess = false,
4641 bool AvoidPartialAvailabilityChecks = false,
4642 ObjCInterfaceDecl *ClassReciever = nullptr);
4643 void NoteDeletedFunction(FunctionDecl *FD);
4644 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4645 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4646 ObjCMethodDecl *Getter,
4647 SourceLocation Loc);
4648 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4649 ArrayRef<Expr *> Args);
4650
4651 void PushExpressionEvaluationContext(
4652 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4653 ExpressionEvaluationContextRecord::ExpressionKind Type =
4654 ExpressionEvaluationContextRecord::EK_Other);
4655 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4656 void PushExpressionEvaluationContext(
4657 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
4658 ExpressionEvaluationContextRecord::ExpressionKind Type =
4659 ExpressionEvaluationContextRecord::EK_Other);
4660 void PopExpressionEvaluationContext();
4661
4662 void DiscardCleanupsInEvaluationContext();
4663
4664 ExprResult TransformToPotentiallyEvaluated(Expr *E);
4665 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4666
4667 ExprResult CheckUnevaluatedOperand(Expr *E);
4668 void CheckUnusedVolatileAssignment(Expr *E);
4669
4670 ExprResult ActOnConstantExpression(ExprResult Res);
4671
4672 // Functions for marking a declaration referenced. These functions also
4673 // contain the relevant logic for marking if a reference to a function or
4674 // variable is an odr-use (in the C++11 sense). There are separate variants
4675 // for expressions referring to a decl; these exist because odr-use marking
4676 // needs to be delayed for some constant variables when we build one of the
4677 // named expressions.
4678 //
4679 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4680 // should usually be true. This only needs to be set to false if the lack of
4681 // odr-use cannot be determined from the current context (for instance,
4682 // because the name denotes a virtual function and was written without an
4683 // explicit nested-name-specifier).
4684 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4685 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4686 bool MightBeOdrUse = true);
4687 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4688 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4689 void MarkMemberReferenced(MemberExpr *E);
4690 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
4691 void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
4692 unsigned CapturingScopeIndex);
4693
4694 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
4695 void CleanupVarDeclMarking();
4696
4697 enum TryCaptureKind {
4698 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4699 };
4700
4701 /// Try to capture the given variable.
4702 ///
4703 /// \param Var The variable to capture.
4704 ///
4705 /// \param Loc The location at which the capture occurs.
4706 ///
4707 /// \param Kind The kind of capture, which may be implicit (for either a
4708 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4709 ///
4710 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4711 /// an explicit lambda capture.
4712 ///
4713 /// \param BuildAndDiagnose Whether we are actually supposed to add the
4714 /// captures or diagnose errors. If false, this routine merely check whether
4715 /// the capture can occur without performing the capture itself or complaining
4716 /// if the variable cannot be captured.
4717 ///
4718 /// \param CaptureType Will be set to the type of the field used to capture
4719 /// this variable in the innermost block or lambda. Only valid when the
4720 /// variable can be captured.
4721 ///
4722 /// \param DeclRefType Will be set to the type of a reference to the capture
4723 /// from within the current scope. Only valid when the variable can be
4724 /// captured.
4725 ///
4726 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4727 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4728 /// This is useful when enclosing lambdas must speculatively capture
4729 /// variables that may or may not be used in certain specializations of
4730 /// a nested generic lambda.
4731 ///
4732 /// \returns true if an error occurred (i.e., the variable cannot be
4733 /// captured) and false if the capture succeeded.
4734 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4735 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4736 QualType &CaptureType,
4737 QualType &DeclRefType,
4738 const unsigned *const FunctionScopeIndexToStopAt);
4739
4740 /// Try to capture the given variable.
4741 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4742 TryCaptureKind Kind = TryCapture_Implicit,
4743 SourceLocation EllipsisLoc = SourceLocation());
4744
4745 /// Checks if the variable must be captured.
4746 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4747
4748 /// Given a variable, determine the type that a reference to that
4749 /// variable will have in the given scope.
4750 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4751
4752 /// Mark all of the declarations referenced within a particular AST node as
4753 /// referenced. Used when template instantiation instantiates a non-dependent
4754 /// type -- entities referenced by the type are now referenced.
4755 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4756 void MarkDeclarationsReferencedInExpr(Expr *E,
4757 bool SkipLocalVariables = false);
4758
4759 /// Try to recover by turning the given expression into a
4760 /// call. Returns true if recovery was attempted or an error was
4761 /// emitted; this may also leave the ExprResult invalid.
4762 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4763 bool ForceComplain = false,
4764 bool (*IsPlausibleResult)(QualType) = nullptr);
4765
4766 /// Figure out if an expression could be turned into a call.
4767 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4768 UnresolvedSetImpl &NonTemplateOverloads);
4769
4770 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
4771 /// conversion.
4772 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
4773
4774 /// Conditionally issue a diagnostic based on the current
4775 /// evaluation context.
4776 ///
4777 /// \param Statement If Statement is non-null, delay reporting the
4778 /// diagnostic until the function body is parsed, and then do a basic
4779 /// reachability analysis to determine if the statement is reachable.
4780 /// If it is unreachable, the diagnostic will not be emitted.
4781 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4782 const PartialDiagnostic &PD);
4783 /// Similar, but diagnostic is only produced if all the specified statements
4784 /// are reachable.
4785 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
4786 const PartialDiagnostic &PD);
4787
4788 // Primary Expressions.
4789 SourceRange getExprRange(Expr *E) const;
4790
4791 ExprResult ActOnIdExpression(
4792 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4793 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4794 CorrectionCandidateCallback *CCC = nullptr,
4795 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4796
4797 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4798 TemplateArgumentListInfo &Buffer,
4799 DeclarationNameInfo &NameInfo,
4800 const TemplateArgumentListInfo *&TemplateArgs);
4801
4802 bool
4803 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4804 CorrectionCandidateCallback &CCC,
4805 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4806 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4807
4808 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
4809 IdentifierInfo *II);
4810 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
4811
4812 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4813 IdentifierInfo *II,
4814 bool AllowBuiltinCreation=false);
4815
4816 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4817 SourceLocation TemplateKWLoc,
4818 const DeclarationNameInfo &NameInfo,
4819 bool isAddressOfOperand,
4820 const TemplateArgumentListInfo *TemplateArgs);
4821
4822 /// If \p D cannot be odr-used in the current expression evaluation context,
4823 /// return a reason explaining why. Otherwise, return NOUR_None.
4824 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
4825
4826 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4827 SourceLocation Loc,
4828 const CXXScopeSpec *SS = nullptr);
4829 DeclRefExpr *
4830 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4831 const DeclarationNameInfo &NameInfo,
4832 const CXXScopeSpec *SS = nullptr,
4833 NamedDecl *FoundD = nullptr,
4834 SourceLocation TemplateKWLoc = SourceLocation(),
4835 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4836 DeclRefExpr *
4837 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4838 const DeclarationNameInfo &NameInfo,
4839 NestedNameSpecifierLoc NNS,
4840 NamedDecl *FoundD = nullptr,
4841 SourceLocation TemplateKWLoc = SourceLocation(),
4842 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4843
4844 ExprResult
4845 BuildAnonymousStructUnionMemberReference(
4846 const CXXScopeSpec &SS,
4847 SourceLocation nameLoc,
4848 IndirectFieldDecl *indirectField,
4849 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4850 Expr *baseObjectExpr = nullptr,
4851 SourceLocation opLoc = SourceLocation());
4852
4853 ExprResult BuildPossibleImplicitMemberExpr(
4854 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
4855 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
4856 UnresolvedLookupExpr *AsULE = nullptr);
4857 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4858 SourceLocation TemplateKWLoc,
4859 LookupResult &R,
4860 const TemplateArgumentListInfo *TemplateArgs,
4861 bool IsDefiniteInstance,
4862 const Scope *S);
4863 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4864 const LookupResult &R,
4865 bool HasTrailingLParen);
4866
4867 ExprResult
4868 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4869 const DeclarationNameInfo &NameInfo,
4870 bool IsAddressOfOperand, const Scope *S,
4871 TypeSourceInfo **RecoveryTSI = nullptr);
4872
4873 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4874 SourceLocation TemplateKWLoc,
4875 const DeclarationNameInfo &NameInfo,
4876 const TemplateArgumentListInfo *TemplateArgs);
4877
4878 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4879 LookupResult &R,
4880 bool NeedsADL,
4881 bool AcceptInvalidDecl = false);
4882 ExprResult BuildDeclarationNameExpr(
4883 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4884 NamedDecl *FoundD = nullptr,
4885 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4886 bool AcceptInvalidDecl = false);
4887
4888 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4889 DeclarationNameInfo &SuffixInfo,
4890 ArrayRef<Expr *> Args,
4891 SourceLocation LitEndLoc,
4892 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4893
4894 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4895 PredefinedExpr::IdentKind IK);
4896 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4897 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4898
4899 ExprResult BuildUniqueStableName(SourceLocation Loc, TypeSourceInfo *Operand);
4900 ExprResult BuildUniqueStableName(SourceLocation Loc, Expr *E);
4901 ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc,
4902 SourceLocation LParen,
4903 SourceLocation RParen, ParsedType Ty);
4904 ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc,
4905 SourceLocation LParen,
4906 SourceLocation RParen, Expr *E);
4907
4908 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4909
4910 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4911 ExprResult ActOnCharacterConstant(const Token &Tok,
4912 Scope *UDLScope = nullptr);
4913 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4914 ExprResult ActOnParenListExpr(SourceLocation L,
4915 SourceLocation R,
4916 MultiExprArg Val);
4917
4918 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4919 /// fragments (e.g. "foo" "bar" L"baz").
4920 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4921 Scope *UDLScope = nullptr);
4922
4923 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4924 SourceLocation DefaultLoc,
4925 SourceLocation RParenLoc,
4926 Expr *ControllingExpr,
4927 ArrayRef<ParsedType> ArgTypes,
4928 ArrayRef<Expr *> ArgExprs);
4929 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4930 SourceLocation DefaultLoc,
4931 SourceLocation RParenLoc,
4932 Expr *ControllingExpr,
4933 ArrayRef<TypeSourceInfo *> Types,
4934 ArrayRef<Expr *> Exprs);
4935
4936 // Binary/Unary Operators. 'Tok' is the token for the operator.
4937 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4938 Expr *InputExpr);
4939 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4940 UnaryOperatorKind Opc, Expr *Input);
4941 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4942 tok::TokenKind Op, Expr *Input);
4943
4944 bool isQualifiedMemberAccess(Expr *E);
4945 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4946
4947 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4948 SourceLocation OpLoc,
4949 UnaryExprOrTypeTrait ExprKind,
4950 SourceRange R);
4951 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4952 UnaryExprOrTypeTrait ExprKind);
4953 ExprResult
4954 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4955 UnaryExprOrTypeTrait ExprKind,
4956 bool IsType, void *TyOrEx,
4957 SourceRange ArgRange);
4958
4959 ExprResult CheckPlaceholderExpr(Expr *E);
4960 bool CheckVecStepExpr(Expr *E);
4961
4962 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4963 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4964 SourceRange ExprRange,
4965 UnaryExprOrTypeTrait ExprKind);
4966 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4967 SourceLocation OpLoc,
4968 IdentifierInfo &Name,
4969 SourceLocation NameLoc,
4970 SourceLocation RParenLoc);
4971 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4972 tok::TokenKind Kind, Expr *Input);
4973
4974 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4975 Expr *Idx, SourceLocation RLoc);
4976 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4977 Expr *Idx, SourceLocation RLoc);
4978
4979 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4980 Expr *ColumnIdx,
4981 SourceLocation RBLoc);
4982
4983 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4984 Expr *LowerBound,
4985 SourceLocation ColonLocFirst,
4986 SourceLocation ColonLocSecond,
4987 Expr *Length, Expr *Stride,
4988 SourceLocation RBLoc);
4989 ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
4990 SourceLocation RParenLoc,
4991 ArrayRef<Expr *> Dims,
4992 ArrayRef<SourceRange> Brackets);
4993
4994 /// Data structure for iterator expression.
4995 struct OMPIteratorData {
4996 IdentifierInfo *DeclIdent = nullptr;
4997 SourceLocation DeclIdentLoc;
4998 ParsedType Type;
4999 OMPIteratorExpr::IteratorRange Range;
5000 SourceLocation AssignLoc;
5001 SourceLocation ColonLoc;
5002 SourceLocation SecColonLoc;
5003 };
5004
5005 ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5006 SourceLocation LLoc, SourceLocation RLoc,
5007 ArrayRef<OMPIteratorData> Data);
5008
5009 // This struct is for use by ActOnMemberAccess to allow
5010 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
5011 // changing the access operator from a '.' to a '->' (to see if that is the
5012 // change needed to fix an error about an unknown member, e.g. when the class
5013 // defines a custom operator->).
5014 struct ActOnMemberAccessExtraArgs {
5015 Scope *S;
5016 UnqualifiedId &Id;
5017 Decl *ObjCImpDecl;
5018 };
5019
5020 ExprResult BuildMemberReferenceExpr(
5021 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
5022 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5023 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
5024 const TemplateArgumentListInfo *TemplateArgs,
5025 const Scope *S,
5026 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5027
5028 ExprResult
5029 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
5030 bool IsArrow, const CXXScopeSpec &SS,
5031 SourceLocation TemplateKWLoc,
5032 NamedDecl *FirstQualifierInScope, LookupResult &R,
5033 const TemplateArgumentListInfo *TemplateArgs,
5034 const Scope *S,
5035 bool SuppressQualifierCheck = false,
5036 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5037
5038 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
5039 SourceLocation OpLoc,
5040 const CXXScopeSpec &SS, FieldDecl *Field,
5041 DeclAccessPair FoundDecl,
5042 const DeclarationNameInfo &MemberNameInfo);
5043
5044 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
5045
5046 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
5047 const CXXScopeSpec &SS,
5048 const LookupResult &R);
5049
5050 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
5051 bool IsArrow, SourceLocation OpLoc,
5052 const CXXScopeSpec &SS,
5053 SourceLocation TemplateKWLoc,
5054 NamedDecl *FirstQualifierInScope,
5055 const DeclarationNameInfo &NameInfo,
5056 const TemplateArgumentListInfo *TemplateArgs);
5057
5058 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
5059 SourceLocation OpLoc,
5060 tok::TokenKind OpKind,
5061 CXXScopeSpec &SS,
5062 SourceLocation TemplateKWLoc,
5063 UnqualifiedId &Member,
5064 Decl *ObjCImpDecl);
5065
5066 MemberExpr *
5067 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5068 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
5069 ValueDecl *Member, DeclAccessPair FoundDecl,
5070 bool HadMultipleCandidates,
5071 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5072 ExprValueKind VK, ExprObjectKind OK,
5073 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5074 MemberExpr *
5075 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5076 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
5077 ValueDecl *Member, DeclAccessPair FoundDecl,
5078 bool HadMultipleCandidates,
5079 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5080 ExprValueKind VK, ExprObjectKind OK,
5081 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5082
5083 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
5084 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5085 FunctionDecl *FDecl,
5086 const FunctionProtoType *Proto,
5087 ArrayRef<Expr *> Args,
5088 SourceLocation RParenLoc,
5089 bool ExecConfig = false);
5090 void CheckStaticArrayArgument(SourceLocation CallLoc,
5091 ParmVarDecl *Param,
5092 const Expr *ArgExpr);
5093
5094 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5095 /// This provides the location of the left/right parens and a list of comma
5096 /// locations.
5097 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5098 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5099 Expr *ExecConfig = nullptr);
5100 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5101 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5102 Expr *ExecConfig = nullptr,
5103 bool IsExecConfig = false);
5104 enum class AtomicArgumentOrder { API, AST };
5105 ExprResult
5106 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5107 SourceLocation RParenLoc, MultiExprArg Args,
5108 AtomicExpr::AtomicOp Op,
5109 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
5110 ExprResult
5111 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
5112 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
5113 Expr *Config = nullptr, bool IsExecConfig = false,
5114 ADLCallKind UsesADL = ADLCallKind::NotADL);
5115
5116 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5117 MultiExprArg ExecConfig,
5118 SourceLocation GGGLoc);
5119
5120 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5121 Declarator &D, ParsedType &Ty,
5122 SourceLocation RParenLoc, Expr *CastExpr);
5123 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
5124 TypeSourceInfo *Ty,
5125 SourceLocation RParenLoc,
5126 Expr *Op);
5127 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
5128
5129 /// Build an altivec or OpenCL literal.
5130 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
5131 SourceLocation RParenLoc, Expr *E,
5132 TypeSourceInfo *TInfo);
5133
5134 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
5135
5136 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
5137 ParsedType Ty,
5138 SourceLocation RParenLoc,
5139 Expr *InitExpr);
5140
5141 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
5142 TypeSourceInfo *TInfo,
5143 SourceLocation RParenLoc,
5144 Expr *LiteralExpr);
5145
5146 ExprResult ActOnInitList(SourceLocation LBraceLoc,
5147 MultiExprArg InitArgList,
5148 SourceLocation RBraceLoc);
5149
5150 ExprResult BuildInitList(SourceLocation LBraceLoc,
5151 MultiExprArg InitArgList,
5152 SourceLocation RBraceLoc);
5153
5154 ExprResult ActOnDesignatedInitializer(Designation &Desig,
5155 SourceLocation EqualOrColonLoc,
5156 bool GNUSyntax,
5157 ExprResult Init);
5158
5159private:
5160 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
5161
5162public:
5163 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
5164 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
5165 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
5166 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
5167 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
5168 Expr *LHSExpr, Expr *RHSExpr);
5169
5170 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
5171
5172 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
5173 /// in the case of a the GNU conditional expr extension.
5174 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
5175 SourceLocation ColonLoc,
5176 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
5177
5178 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5179 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
5180 LabelDecl *TheDecl);
5181
5182 void ActOnStartStmtExpr();
5183 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
5184 SourceLocation RPLoc);
5185 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
5186 SourceLocation RPLoc, unsigned TemplateDepth);
5187 // Handle the final expression in a statement expression.
5188 ExprResult ActOnStmtExprResult(ExprResult E);
5189 void ActOnStmtExprError();
5190
5191 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
5192 struct OffsetOfComponent {
5193 SourceLocation LocStart, LocEnd;
5194 bool isBrackets; // true if [expr], false if .ident
5195 union {
5196 IdentifierInfo *IdentInfo;
5197 Expr *E;
5198 } U;
5199 };
5200
5201 /// __builtin_offsetof(type, a.b[123][456].c)
5202 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
5203 TypeSourceInfo *TInfo,
5204 ArrayRef<OffsetOfComponent> Components,
5205 SourceLocation RParenLoc);
5206 ExprResult ActOnBuiltinOffsetOf(Scope *S,
5207 SourceLocation BuiltinLoc,
5208 SourceLocation TypeLoc,
5209 ParsedType ParsedArgTy,
5210 ArrayRef<OffsetOfComponent> Components,
5211 SourceLocation RParenLoc);
5212
5213 // __builtin_choose_expr(constExpr, expr1, expr2)
5214 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
5215 Expr *CondExpr, Expr *LHSExpr,
5216 Expr *RHSExpr, SourceLocation RPLoc);
5217
5218 // __builtin_va_arg(expr, type)
5219 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
5220 SourceLocation RPLoc);
5221 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
5222 TypeSourceInfo *TInfo, SourceLocation RPLoc);
5223
5224 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
5225 // __builtin_COLUMN()
5226 ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
5227 SourceLocation BuiltinLoc,
5228 SourceLocation RPLoc);
5229
5230 // Build a potentially resolved SourceLocExpr.
5231 ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
5232 SourceLocation BuiltinLoc, SourceLocation RPLoc,
5233 DeclContext *ParentContext);
5234
5235 // __null
5236 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
5237
5238 bool CheckCaseExpression(Expr *E);
5239
5240 /// Describes the result of an "if-exists" condition check.
5241 enum IfExistsResult {
5242 /// The symbol exists.
5243 IER_Exists,
5244
5245 /// The symbol does not exist.
5246 IER_DoesNotExist,
5247
5248 /// The name is a dependent name, so the results will differ
5249 /// from one instantiation to the next.
5250 IER_Dependent,
5251
5252 /// An error occurred.
5253 IER_Error
5254 };
5255
5256 IfExistsResult
5257 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
5258 const DeclarationNameInfo &TargetNameInfo);
5259
5260 IfExistsResult
5261 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5262 bool IsIfExists, CXXScopeSpec &SS,
5263 UnqualifiedId &Name);
5264
5265 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
5266 bool IsIfExists,
5267 NestedNameSpecifierLoc QualifierLoc,
5268 DeclarationNameInfo NameInfo,
5269 Stmt *Nested);
5270 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
5271 bool IsIfExists,
5272 CXXScopeSpec &SS, UnqualifiedId &Name,
5273 Stmt *Nested);
5274
5275 //===------------------------- "Block" Extension ------------------------===//
5276
5277 /// ActOnBlockStart - This callback is invoked when a block literal is
5278 /// started.
5279 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
5280
5281 /// ActOnBlockArguments - This callback allows processing of block arguments.
5282 /// If there are no arguments, this is still invoked.
5283 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
5284 Scope *CurScope);
5285
5286 /// ActOnBlockError - If there is an error parsing a block, this callback
5287 /// is invoked to pop the information about the block from the action impl.
5288 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
5289
5290 /// ActOnBlockStmtExpr - This is called when the body of a block statement
5291 /// literal was successfully completed. ^(int x){...}
5292 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
5293 Scope *CurScope);
5294
5295 //===---------------------------- Clang Extensions ----------------------===//
5296
5297 /// __builtin_convertvector(...)
5298 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5299 SourceLocation BuiltinLoc,
5300 SourceLocation RParenLoc);
5301
5302 //===---------------------------- OpenCL Features -----------------------===//
5303
5304 /// __builtin_astype(...)
5305 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5306 SourceLocation BuiltinLoc,
5307 SourceLocation RParenLoc);
5308
5309 //===---------------------------- C++ Features --------------------------===//
5310
5311 // Act on C++ namespaces
5312 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5313 SourceLocation NamespaceLoc,
5314 SourceLocation IdentLoc, IdentifierInfo *Ident,
5315 SourceLocation LBrace,
5316 const ParsedAttributesView &AttrList,
5317 UsingDirectiveDecl *&UsingDecl);
5318 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5319
5320 NamespaceDecl *getStdNamespace() const;
5321 NamespaceDecl *getOrCreateStdNamespace();
5322
5323 NamespaceDecl *lookupStdExperimentalNamespace();
5324
5325 CXXRecordDecl *getStdBadAlloc() const;
5326 EnumDecl *getStdAlignValT() const;
5327
5328private:
5329 // A cache representing if we've fully checked the various comparison category
5330 // types stored in ASTContext. The bit-index corresponds to the integer value
5331 // of a ComparisonCategoryType enumerator.
5332 llvm::SmallBitVector FullyCheckedComparisonCategories;
5333
5334 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5335 CXXScopeSpec &SS,
5336 ParsedType TemplateTypeTy,
5337 IdentifierInfo *MemberOrBase);
5338
5339public:
5340 enum class ComparisonCategoryUsage {
5341 /// The '<=>' operator was used in an expression and a builtin operator
5342 /// was selected.
5343 OperatorInExpression,
5344 /// A defaulted 'operator<=>' needed the comparison category. This
5345 /// typically only applies to 'std::strong_ordering', due to the implicit
5346 /// fallback return value.
5347 DefaultedOperator,
5348 };
5349
5350 /// Lookup the specified comparison category types in the standard
5351 /// library, an check the VarDecls possibly returned by the operator<=>
5352 /// builtins for that type.
5353 ///
5354 /// \return The type of the comparison category type corresponding to the
5355 /// specified Kind, or a null type if an error occurs
5356 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5357 SourceLocation Loc,
5358 ComparisonCategoryUsage Usage);
5359
5360 /// Tests whether Ty is an instance of std::initializer_list and, if
5361 /// it is and Element is not NULL, assigns the element type to Element.
5362 bool isStdInitializerList(QualType Ty, QualType *Element);
5363
5364 /// Looks for the std::initializer_list template and instantiates it
5365 /// with Element, or emits an error if it's not found.
5366 ///
5367 /// \returns The instantiated template, or null on error.
5368 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5369
5370 /// Determine whether Ctor is an initializer-list constructor, as
5371 /// defined in [dcl.init.list]p2.
5372 bool isInitListConstructor(const FunctionDecl *Ctor);
5373
5374 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5375 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5376 SourceLocation IdentLoc,
5377 IdentifierInfo *NamespcName,
5378 const ParsedAttributesView &AttrList);
5379
5380 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5381
5382 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
5383 SourceLocation NamespaceLoc,
5384 SourceLocation AliasLoc,
5385 IdentifierInfo *Alias,
5386 CXXScopeSpec &SS,
5387 SourceLocation IdentLoc,
5388 IdentifierInfo *Ident);
5389
5390 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5391 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
5392 const LookupResult &PreviousDecls,
5393 UsingShadowDecl *&PrevShadow);
5394 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
5395 NamedDecl *Target,
5396 UsingShadowDecl *PrevDecl);
5397
5398 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5399 bool HasTypenameKeyword,
5400 const CXXScopeSpec &SS,
5401 SourceLocation NameLoc,
5402 const LookupResult &Previous);
5403 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
5404 bool HasTypename,
5405 const CXXScopeSpec &SS,
5406 const DeclarationNameInfo &NameInfo,
5407 SourceLocation NameLoc);
5408
5409 NamedDecl *BuildUsingDeclaration(
5410 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5411 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5412 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5413 const ParsedAttributesView &AttrList, bool IsInstantiation);
5414 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5415 ArrayRef<NamedDecl *> Expansions);
5416
5417 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5418
5419 /// Given a derived-class using shadow declaration for a constructor and the
5420 /// correspnding base class constructor, find or create the implicit
5421 /// synthesized derived class constructor to use for this initialization.
5422 CXXConstructorDecl *
5423 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5424 ConstructorUsingShadowDecl *DerivedShadow);
5425
5426 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5427 SourceLocation UsingLoc,
5428 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5429 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5430 const ParsedAttributesView &AttrList);
5431 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5432 MultiTemplateParamsArg TemplateParams,
5433 SourceLocation UsingLoc, UnqualifiedId &Name,
5434 const ParsedAttributesView &AttrList,
5435 TypeResult Type, Decl *DeclFromDeclSpec);
5436
5437 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5438 /// including handling of its default argument expressions.
5439 ///
5440 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5441 ExprResult
5442 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5443 NamedDecl *FoundDecl,
5444 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5445 bool HadMultipleCandidates, bool IsListInitialization,
5446 bool IsStdInitListInitialization,
5447 bool RequiresZeroInit, unsigned ConstructKind,
5448 SourceRange ParenRange);
5449
5450 /// Build a CXXConstructExpr whose constructor has already been resolved if
5451 /// it denotes an inherited constructor.
5452 ExprResult
5453 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5454 CXXConstructorDecl *Constructor, bool Elidable,
5455 MultiExprArg Exprs,
5456 bool HadMultipleCandidates, bool IsListInitialization,
5457 bool IsStdInitListInitialization,
5458 bool RequiresZeroInit, unsigned ConstructKind,
5459 SourceRange ParenRange);
5460
5461 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5462 // the constructor can be elidable?
5463 ExprResult
5464 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5465 NamedDecl *FoundDecl,
5466 CXXConstructorDecl *Constructor, bool Elidable,
5467 MultiExprArg Exprs, bool HadMultipleCandidates,
5468 bool IsListInitialization,
5469 bool IsStdInitListInitialization, bool RequiresZeroInit,
5470 unsigned ConstructKind, SourceRange ParenRange);
5471
5472 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5473
5474
5475 /// Instantiate or parse a C++ default argument expression as necessary.
5476 /// Return true on error.
5477 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5478 ParmVarDecl *Param);
5479
5480 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
5481 /// the default expr if needed.
5482 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5483 FunctionDecl *FD,
5484 ParmVarDecl *Param);
5485
5486 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5487 /// constructed variable.
5488 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
5489
5490 /// Helper class that collects exception specifications for
5491 /// implicitly-declared special member functions.
5492 class ImplicitExceptionSpecification {
5493 // Pointer to allow copying
5494 Sema *Self;
5495 // We order exception specifications thus:
5496 // noexcept is the most restrictive, but is only used in C++11.
5497 // throw() comes next.
5498 // Then a throw(collected exceptions)
5499 // Finally no specification, which is expressed as noexcept(false).
5500 // throw(...) is used instead if any called function uses it.
5501 ExceptionSpecificationType ComputedEST;
5502 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5503 SmallVector<QualType, 4> Exceptions;
5504
5505 void ClearExceptions() {
5506 ExceptionsSeen.clear();
5507 Exceptions.clear();
5508 }
5509
5510 public:
5511 explicit ImplicitExceptionSpecification(Sema &Self)
5512 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5513 if (!Self.getLangOpts().CPlusPlus11)
5514 ComputedEST = EST_DynamicNone;
5515 }
5516
5517 /// Get the computed exception specification type.
5518 ExceptionSpecificationType getExceptionSpecType() const {
5519 assert(!isComputedNoexcept(ComputedEST) &&((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 5520, __PRETTY_FUNCTION__))
5520 "noexcept(expr) should not be a possible result")((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 5520, __PRETTY_FUNCTION__))
;
5521 return ComputedEST;
5522 }
5523
5524 /// The number of exceptions in the exception specification.
5525 unsigned size() const { return Exceptions.size(); }
5526
5527 /// The set of exceptions in the exception specification.
5528 const QualType *data() const { return Exceptions.data(); }
5529
5530 /// Integrate another called method into the collected data.
5531 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5532
5533 /// Integrate an invoked expression into the collected data.
5534 void CalledExpr(Expr *E) { CalledStmt(E); }
5535
5536 /// Integrate an invoked statement into the collected data.
5537 void CalledStmt(Stmt *S);
5538
5539 /// Overwrite an EPI's exception specification with this
5540 /// computed exception specification.
5541 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5542 FunctionProtoType::ExceptionSpecInfo ESI;
5543 ESI.Type = getExceptionSpecType();
5544 if (ESI.Type == EST_Dynamic) {
5545 ESI.Exceptions = Exceptions;
5546 } else if (ESI.Type == EST_None) {
5547 /// C++11 [except.spec]p14:
5548 /// The exception-specification is noexcept(false) if the set of
5549 /// potential exceptions of the special member function contains "any"
5550 ESI.Type = EST_NoexceptFalse;
5551 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
5552 tok::kw_false).get();
5553 }
5554 return ESI;
5555 }
5556 };
5557
5558 /// Determine what sort of exception specification a defaulted
5559 /// copy constructor of a class will have.
5560 ImplicitExceptionSpecification
5561 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
5562 CXXMethodDecl *MD);
5563
5564 /// Determine what sort of exception specification a defaulted
5565 /// default constructor of a class will have, and whether the parameter
5566 /// will be const.
5567 ImplicitExceptionSpecification
5568 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
5569
5570 /// Determine what sort of exception specification a defaulted
5571 /// copy assignment operator of a class will have, and whether the
5572 /// parameter will be const.
5573 ImplicitExceptionSpecification
5574 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
5575
5576 /// Determine what sort of exception specification a defaulted move
5577 /// constructor of a class will have.
5578 ImplicitExceptionSpecification
5579 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
5580
5581 /// Determine what sort of exception specification a defaulted move
5582 /// assignment operator of a class will have.
5583 ImplicitExceptionSpecification
5584 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
5585
5586 /// Determine what sort of exception specification a defaulted
5587 /// destructor of a class will have.
5588 ImplicitExceptionSpecification
5589 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
5590
5591 /// Determine what sort of exception specification an inheriting
5592 /// constructor of a class will have.
5593 ImplicitExceptionSpecification
5594 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
5595 CXXConstructorDecl *CD);
5596
5597 /// Evaluate the implicit exception specification for a defaulted
5598 /// special member function.
5599 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5600
5601 /// Check the given noexcept-specifier, convert its expression, and compute
5602 /// the appropriate ExceptionSpecificationType.
5603 ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
5604 ExceptionSpecificationType &EST);
5605
5606 /// Check the given exception-specification and update the
5607 /// exception specification information with the results.
5608 void checkExceptionSpecification(bool IsTopLevel,
5609 ExceptionSpecificationType EST,
5610 ArrayRef<ParsedType> DynamicExceptions,
5611 ArrayRef<SourceRange> DynamicExceptionRanges,
5612 Expr *NoexceptExpr,
5613 SmallVectorImpl<QualType> &Exceptions,
5614 FunctionProtoType::ExceptionSpecInfo &ESI);
5615
5616 /// Determine if we're in a case where we need to (incorrectly) eagerly
5617 /// parse an exception specification to work around a libstdc++ bug.
5618 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
5619
5620 /// Add an exception-specification to the given member function
5621 /// (or member function template). The exception-specification was parsed
5622 /// after the method itself was declared.
5623 void actOnDelayedExceptionSpecification(Decl *Method,
5624 ExceptionSpecificationType EST,
5625 SourceRange SpecificationRange,
5626 ArrayRef<ParsedType> DynamicExceptions,
5627 ArrayRef<SourceRange> DynamicExceptionRanges,
5628 Expr *NoexceptExpr);
5629
5630 class InheritedConstructorInfo;
5631
5632 /// Determine if a special member function should have a deleted
5633 /// definition when it is defaulted.
5634 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5635 InheritedConstructorInfo *ICI = nullptr,
5636 bool Diagnose = false);
5637
5638 /// Produce notes explaining why a defaulted function was defined as deleted.
5639 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5640
5641 /// Declare the implicit default constructor for the given class.
5642 ///
5643 /// \param ClassDecl The class declaration into which the implicit
5644 /// default constructor will be added.
5645 ///
5646 /// \returns The implicitly-declared default constructor.
5647 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
5648 CXXRecordDecl *ClassDecl);
5649
5650 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5651 /// defining this constructor as the default constructor.
5652 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5653 CXXConstructorDecl *Constructor);
5654
5655 /// Declare the implicit destructor for the given class.
5656 ///
5657 /// \param ClassDecl The class declaration into which the implicit
5658 /// destructor will be added.
5659 ///
5660 /// \returns The implicitly-declared destructor.
5661 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5662
5663 /// DefineImplicitDestructor - Checks for feasibility of
5664 /// defining this destructor as the default destructor.
5665 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5666 CXXDestructorDecl *Destructor);
5667
5668 /// Build an exception spec for destructors that don't have one.
5669 ///
5670 /// C++11 says that user-defined destructors with no exception spec get one
5671 /// that looks as if the destructor was implicitly declared.
5672 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5673
5674 /// Define the specified inheriting constructor.
5675 void DefineInheritingConstructor(SourceLocation UseLoc,
5676 CXXConstructorDecl *Constructor);
5677
5678 /// Declare the implicit copy constructor for the given class.
5679 ///
5680 /// \param ClassDecl The class declaration into which the implicit
5681 /// copy constructor will be added.
5682 ///
5683 /// \returns The implicitly-declared copy constructor.
5684 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5685
5686 /// DefineImplicitCopyConstructor - Checks for feasibility of
5687 /// defining this constructor as the copy constructor.
5688 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5689 CXXConstructorDecl *Constructor);
5690
5691 /// Declare the implicit move constructor for the given class.
5692 ///
5693 /// \param ClassDecl The Class declaration into which the implicit
5694 /// move constructor will be added.
5695 ///
5696 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5697 /// declared.
5698 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5699
5700 /// DefineImplicitMoveConstructor - Checks for feasibility of
5701 /// defining this constructor as the move constructor.
5702 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5703 CXXConstructorDecl *Constructor);
5704
5705 /// Declare the implicit copy assignment operator for the given class.
5706 ///
5707 /// \param ClassDecl The class declaration into which the implicit
5708 /// copy assignment operator will be added.
5709 ///
5710 /// \returns The implicitly-declared copy assignment operator.
5711 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5712
5713 /// Defines an implicitly-declared copy assignment operator.
5714 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5715 CXXMethodDecl *MethodDecl);
5716
5717 /// Declare the implicit move assignment operator for the given class.
5718 ///
5719 /// \param ClassDecl The Class declaration into which the implicit
5720 /// move assignment operator will be added.
5721 ///
5722 /// \returns The implicitly-declared move assignment operator, or NULL if it
5723 /// wasn't declared.
5724 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5725
5726 /// Defines an implicitly-declared move assignment operator.
5727 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5728 CXXMethodDecl *MethodDecl);
5729
5730 /// Force the declaration of any implicitly-declared members of this
5731 /// class.
5732 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
5733
5734 /// Check a completed declaration of an implicit special member.
5735 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5736
5737 /// Determine whether the given function is an implicitly-deleted
5738 /// special member function.
5739 bool isImplicitlyDeleted(FunctionDecl *FD);
5740
5741 /// Check whether 'this' shows up in the type of a static member
5742 /// function after the (naturally empty) cv-qualifier-seq would be.
5743 ///
5744 /// \returns true if an error occurred.
5745 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5746
5747 /// Whether this' shows up in the exception specification of a static
5748 /// member function.
5749 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5750
5751 /// Check whether 'this' shows up in the attributes of the given
5752 /// static member function.
5753 ///
5754 /// \returns true if an error occurred.
5755 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5756
5757 /// MaybeBindToTemporary - If the passed in expression has a record type with
5758 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
5759 /// it simply returns the passed in expression.
5760 ExprResult MaybeBindToTemporary(Expr *E);
5761
5762 /// Wrap the expression in a ConstantExpr if it is a potential immediate
5763 /// invocation.
5764 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
5765
5766 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5767 MultiExprArg ArgsPtr,
5768 SourceLocation Loc,
5769 SmallVectorImpl<Expr*> &ConvertedArgs,
5770 bool AllowExplicit = false,
5771 bool IsListInitialization = false);
5772
5773 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
5774 SourceLocation NameLoc,
5775 IdentifierInfo &Name);
5776
5777 ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
5778 Scope *S, CXXScopeSpec &SS,
5779 bool EnteringContext);
5780 ParsedType getDestructorName(SourceLocation TildeLoc,
5781 IdentifierInfo &II, SourceLocation NameLoc,
5782 Scope *S, CXXScopeSpec &SS,
5783 ParsedType ObjectType,
5784 bool EnteringContext);
5785
5786 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
5787 ParsedType ObjectType);
5788
5789 // Checks that reinterpret casts don't have undefined behavior.
5790 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
5791 bool IsDereference, SourceRange Range);
5792
5793 /// ActOnCXXNamedCast - Parse
5794 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
5795 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
5796 tok::TokenKind Kind,
5797 SourceLocation LAngleBracketLoc,
5798 Declarator &D,
5799 SourceLocation RAngleBracketLoc,
5800 SourceLocation LParenLoc,
5801 Expr *E,
5802 SourceLocation RParenLoc);
5803
5804 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
5805 tok::TokenKind Kind,
5806 TypeSourceInfo *Ty,
5807 Expr *E,
5808 SourceRange AngleBrackets,
5809 SourceRange Parens);
5810
5811 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
5812 ExprResult Operand,
5813 SourceLocation RParenLoc);
5814
5815 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
5816 Expr *Operand, SourceLocation RParenLoc);
5817
5818 ExprResult BuildCXXTypeId(QualType TypeInfoType,
5819 SourceLocation TypeidLoc,
5820 TypeSourceInfo *Operand,
5821 SourceLocation RParenLoc);
5822 ExprResult BuildCXXTypeId(QualType TypeInfoType,
5823 SourceLocation TypeidLoc,
5824 Expr *Operand,
5825 SourceLocation RParenLoc);
5826
5827 /// ActOnCXXTypeid - Parse typeid( something ).
5828 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
5829 SourceLocation LParenLoc, bool isType,
5830 void *TyOrExpr,
5831 SourceLocation RParenLoc);
5832
5833 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5834 SourceLocation TypeidLoc,
5835 TypeSourceInfo *Operand,
5836 SourceLocation RParenLoc);
5837 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5838 SourceLocation TypeidLoc,
5839 Expr *Operand,
5840 SourceLocation RParenLoc);
5841
5842 /// ActOnCXXUuidof - Parse __uuidof( something ).
5843 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
5844 SourceLocation LParenLoc, bool isType,
5845 void *TyOrExpr,
5846 SourceLocation RParenLoc);
5847
5848 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
5849 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5850 tok::TokenKind Operator,
5851 SourceLocation EllipsisLoc, Expr *RHS,
5852 SourceLocation RParenLoc);
5853 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5854 BinaryOperatorKind Operator,
5855 SourceLocation EllipsisLoc, Expr *RHS,
5856 SourceLocation RParenLoc,
5857 Optional<unsigned> NumExpansions);
5858 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
5859 BinaryOperatorKind Operator);
5860
5861 //// ActOnCXXThis - Parse 'this' pointer.
5862 ExprResult ActOnCXXThis(SourceLocation loc);
5863
5864 /// Build a CXXThisExpr and mark it referenced in the current context.
5865 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
5866 void MarkThisReferenced(CXXThisExpr *This);
5867
5868 /// Try to retrieve the type of the 'this' pointer.
5869 ///
5870 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
5871 QualType getCurrentThisType();
5872
5873 /// When non-NULL, the C++ 'this' expression is allowed despite the
5874 /// current context not being a non-static member function. In such cases,
5875 /// this provides the type used for 'this'.
5876 QualType CXXThisTypeOverride;
5877
5878 /// RAII object used to temporarily allow the C++ 'this' expression
5879 /// to be used, with the given qualifiers on the current class type.
5880 class CXXThisScopeRAII {
5881 Sema &S;
5882 QualType OldCXXThisTypeOverride;
5883 bool Enabled;
5884
5885 public:
5886 /// Introduce a new scope where 'this' may be allowed (when enabled),
5887 /// using the given declaration (which is either a class template or a
5888 /// class) along with the given qualifiers.
5889 /// along with the qualifiers placed on '*this'.
5890 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
5891 bool Enabled = true);
5892
5893 ~CXXThisScopeRAII();
5894 };
5895
5896 /// Make sure the value of 'this' is actually available in the current
5897 /// context, if it is a potentially evaluated context.
5898 ///
5899 /// \param Loc The location at which the capture of 'this' occurs.
5900 ///
5901 /// \param Explicit Whether 'this' is explicitly captured in a lambda
5902 /// capture list.
5903 ///
5904 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5905 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5906 /// This is useful when enclosing lambdas must speculatively capture
5907 /// 'this' that may or may not be used in certain specializations of
5908 /// a nested generic lambda (depending on whether the name resolves to
5909 /// a non-static member function or a static function).
5910 /// \return returns 'true' if failed, 'false' if success.
5911 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5912 bool BuildAndDiagnose = true,
5913 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5914 bool ByCopy = false);
5915
5916 /// Determine whether the given type is the type of *this that is used
5917 /// outside of the body of a member function for a type that is currently
5918 /// being defined.
5919 bool isThisOutsideMemberFunctionBody(QualType BaseType);
5920
5921 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5922 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5923
5924
5925 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5926 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5927
5928 ExprResult
5929 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5930 SourceLocation AtLoc, SourceLocation RParen);
5931
5932 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5933 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5934
5935 //// ActOnCXXThrow - Parse throw expressions.
5936 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5937 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5938 bool IsThrownVarInScope);
5939 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5940
5941 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5942 /// Can be interpreted either as function-style casting ("int(x)")
5943 /// or class type construction ("ClassType(x,y,z)")
5944 /// or creation of a value-initialized type ("int()").
5945 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5946 SourceLocation LParenOrBraceLoc,
5947 MultiExprArg Exprs,
5948 SourceLocation RParenOrBraceLoc,
5949 bool ListInitialization);
5950
5951 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5952 SourceLocation LParenLoc,
5953 MultiExprArg Exprs,
5954 SourceLocation RParenLoc,
5955 bool ListInitialization);
5956
5957 /// ActOnCXXNew - Parsed a C++ 'new' expression.
5958 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5959 SourceLocation PlacementLParen,
5960 MultiExprArg PlacementArgs,
5961 SourceLocation PlacementRParen,
5962 SourceRange TypeIdParens, Declarator &D,
5963 Expr *Initializer);
5964 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5965 SourceLocation PlacementLParen,
5966 MultiExprArg PlacementArgs,
5967 SourceLocation PlacementRParen,
5968 SourceRange TypeIdParens,
5969 QualType AllocType,
5970 TypeSourceInfo *AllocTypeInfo,
5971 Optional<Expr *> ArraySize,
5972 SourceRange DirectInitRange,
5973 Expr *Initializer);
5974
5975 /// Determine whether \p FD is an aligned allocation or deallocation
5976 /// function that is unavailable.
5977 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
5978
5979 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
5980 /// function that is unavailable.
5981 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
5982 SourceLocation Loc);
5983
5984 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5985 SourceRange R);
5986
5987 /// The scope in which to find allocation functions.
5988 enum AllocationFunctionScope {
5989 /// Only look for allocation functions in the global scope.
5990 AFS_Global,
5991 /// Only look for allocation functions in the scope of the
5992 /// allocated class.
5993 AFS_Class,
5994 /// Look for allocation functions in both the global scope
5995 /// and in the scope of the allocated class.
5996 AFS_Both
5997 };
5998
5999 /// Finds the overloads of operator new and delete that are appropriate
6000 /// for the allocation.
6001 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
6002 AllocationFunctionScope NewScope,
6003 AllocationFunctionScope DeleteScope,
6004 QualType AllocType, bool IsArray,
6005 bool &PassAlignment, MultiExprArg PlaceArgs,
6006 FunctionDecl *&OperatorNew,
6007 FunctionDecl *&OperatorDelete,
6008 bool Diagnose = true);
6009 void DeclareGlobalNewDelete();
6010 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
6011 ArrayRef<QualType> Params);
6012
6013 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
6014 DeclarationName Name, FunctionDecl* &Operator,
6015 bool Diagnose = true);
6016 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
6017 bool CanProvideSize,
6018 bool Overaligned,
6019 DeclarationName Name);
6020 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
6021 CXXRecordDecl *RD);
6022
6023 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
6024 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
6025 bool UseGlobal, bool ArrayForm,
6026 Expr *Operand);
6027 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
6028 bool IsDelete, bool CallCanBeVirtual,
6029 bool WarnOnNonAbstractTypes,
6030 SourceLocation DtorLoc);
6031
6032 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
6033 Expr *Operand, SourceLocation RParen);
6034 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6035 SourceLocation RParen);
6036
6037 /// Parsed one of the type trait support pseudo-functions.
6038 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6039 ArrayRef<ParsedType> Args,
6040 SourceLocation RParenLoc);
6041 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6042 ArrayRef<TypeSourceInfo *> Args,
6043 SourceLocation RParenLoc);
6044
6045 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
6046 /// pseudo-functions.
6047 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
6048 SourceLocation KWLoc,
6049 ParsedType LhsTy,
6050 Expr *DimExpr,
6051 SourceLocation RParen);
6052
6053 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
6054 SourceLocation KWLoc,
6055 TypeSourceInfo *TSInfo,
6056 Expr *DimExpr,
6057 SourceLocation RParen);
6058
6059 /// ActOnExpressionTrait - Parsed one of the unary type trait support
6060 /// pseudo-functions.
6061 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
6062 SourceLocation KWLoc,
6063 Expr *Queried,
6064 SourceLocation RParen);
6065
6066 ExprResult BuildExpressionTrait(ExpressionTrait OET,
6067 SourceLocation KWLoc,
6068 Expr *Queried,
6069 SourceLocation RParen);
6070
6071 ExprResult ActOnStartCXXMemberReference(Scope *S,
6072 Expr *Base,
6073 SourceLocation OpLoc,
6074 tok::TokenKind OpKind,
6075 ParsedType &ObjectType,
6076 bool &MayBePseudoDestructor);
6077
6078 ExprResult BuildPseudoDestructorExpr(Expr *Base,
6079 SourceLocation OpLoc,
6080 tok::TokenKind OpKind,
6081 const CXXScopeSpec &SS,
6082 TypeSourceInfo *ScopeType,
6083 SourceLocation CCLoc,
6084 SourceLocation TildeLoc,
6085 PseudoDestructorTypeStorage DestroyedType);
6086
6087 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6088 SourceLocation OpLoc,
6089 tok::TokenKind OpKind,
6090 CXXScopeSpec &SS,
6091 UnqualifiedId &FirstTypeName,
6092 SourceLocation CCLoc,
6093 SourceLocation TildeLoc,
6094 UnqualifiedId &SecondTypeName);
6095
6096 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6097 SourceLocation OpLoc,
6098 tok::TokenKind OpKind,
6099 SourceLocation TildeLoc,
6100 const DeclSpec& DS);
6101
6102 /// MaybeCreateExprWithCleanups - If the current full-expression
6103 /// requires any cleanups, surround it with a ExprWithCleanups node.
6104 /// Otherwise, just returns the passed-in expression.
6105 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
6106 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
6107 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
6108
6109 MaterializeTemporaryExpr *
6110 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6111 bool BoundToLvalueReference);
6112
6113 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
6114 return ActOnFinishFullExpr(
6115 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
6116 }
6117 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
6118 bool DiscardedValue, bool IsConstexpr = false);
6119 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
6120
6121 // Marks SS invalid if it represents an incomplete type.
6122 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
6123
6124 DeclContext *computeDeclContext(QualType T);
6125 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
6126 bool EnteringContext = false);
6127 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
6128 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
6129
6130 /// The parser has parsed a global nested-name-specifier '::'.
6131 ///
6132 /// \param CCLoc The location of the '::'.
6133 ///
6134 /// \param SS The nested-name-specifier, which will be updated in-place
6135 /// to reflect the parsed nested-name-specifier.
6136 ///
6137 /// \returns true if an error occurred, false otherwise.
6138 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
6139
6140 /// The parser has parsed a '__super' nested-name-specifier.
6141 ///
6142 /// \param SuperLoc The location of the '__super' keyword.
6143 ///
6144 /// \param ColonColonLoc The location of the '::'.
6145 ///
6146 /// \param SS The nested-name-specifier, which will be updated in-place
6147 /// to reflect the parsed nested-name-specifier.
6148 ///
6149 /// \returns true if an error occurred, false otherwise.
6150 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
6151 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
6152
6153 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
6154 bool *CanCorrect = nullptr);
6155 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
6156
6157 /// Keeps information about an identifier in a nested-name-spec.
6158 ///
6159 struct NestedNameSpecInfo {
6160 /// The type of the object, if we're parsing nested-name-specifier in
6161 /// a member access expression.
6162 ParsedType ObjectType;
6163
6164 /// The identifier preceding the '::'.
6165 IdentifierInfo *Identifier;
6166
6167 /// The location of the identifier.
6168 SourceLocation IdentifierLoc;
6169
6170 /// The location of the '::'.
6171 SourceLocation CCLoc;
6172
6173 /// Creates info object for the most typical case.
6174 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6175 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
6176 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
6177 CCLoc(ColonColonLoc) {
6178 }
6179
6180 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6181 SourceLocation ColonColonLoc, QualType ObjectType)
6182 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
6183 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
6184 }
6185 };
6186
6187 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
6188 NestedNameSpecInfo &IdInfo);
6189
6190 bool BuildCXXNestedNameSpecifier(Scope *S,
6191 NestedNameSpecInfo &IdInfo,
6192 bool EnteringContext,
6193 CXXScopeSpec &SS,
6194 NamedDecl *ScopeLookupResult,
6195 bool ErrorRecoveryLookup,
6196 bool *IsCorrectedToColon = nullptr,
6197 bool OnlyNamespace = false);
6198
6199 /// The parser has parsed a nested-name-specifier 'identifier::'.
6200 ///
6201 /// \param S The scope in which this nested-name-specifier occurs.
6202 ///
6203 /// \param IdInfo Parser information about an identifier in the
6204 /// nested-name-spec.
6205 ///
6206 /// \param EnteringContext Whether we're entering the context nominated by
6207 /// this nested-name-specifier.
6208 ///
6209 /// \param SS The nested-name-specifier, which is both an input
6210 /// parameter (the nested-name-specifier before this type) and an
6211 /// output parameter (containing the full nested-name-specifier,
6212 /// including this new type).
6213 ///
6214 /// \param ErrorRecoveryLookup If true, then this method is called to improve
6215 /// error recovery. In this case do not emit error message.
6216 ///
6217 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
6218 /// are allowed. The bool value pointed by this parameter is set to 'true'
6219 /// if the identifier is treated as if it was followed by ':', not '::'.
6220 ///
6221 /// \param OnlyNamespace If true, only considers namespaces in lookup.
6222 ///
6223 /// \returns true if an error occurred, false otherwise.
6224 bool ActOnCXXNestedNameSpecifier(Scope *S,
6225 NestedNameSpecInfo &IdInfo,
6226 bool EnteringContext,
6227 CXXScopeSpec &SS,
6228 bool ErrorRecoveryLookup = false,
6229 bool *IsCorrectedToColon = nullptr,
6230 bool OnlyNamespace = false);
6231
6232 ExprResult ActOnDecltypeExpression(Expr *E);
6233
6234 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
6235 const DeclSpec &DS,
6236 SourceLocation ColonColonLoc);
6237
6238 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
6239 NestedNameSpecInfo &IdInfo,
6240 bool EnteringContext);
6241
6242 /// The parser has parsed a nested-name-specifier
6243 /// 'template[opt] template-name < template-args >::'.
6244 ///
6245 /// \param S The scope in which this nested-name-specifier occurs.
6246 ///
6247 /// \param SS The nested-name-specifier, which is both an input
6248 /// parameter (the nested-name-specifier before this type) and an
6249 /// output parameter (containing the full nested-name-specifier,
6250 /// including this new type).
6251 ///
6252 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
6253 /// \param TemplateName the template name.
6254 /// \param TemplateNameLoc The location of the template name.
6255 /// \param LAngleLoc The location of the opening angle bracket ('<').
6256 /// \param TemplateArgs The template arguments.
6257 /// \param RAngleLoc The location of the closing angle bracket ('>').
6258 /// \param CCLoc The location of the '::'.
6259 ///
6260 /// \param EnteringContext Whether we're entering the context of the
6261 /// nested-name-specifier.
6262 ///
6263 ///
6264 /// \returns true if an error occurred, false otherwise.
6265 bool ActOnCXXNestedNameSpecifier(Scope *S,
6266 CXXScopeSpec &SS,
6267 SourceLocation TemplateKWLoc,
6268 TemplateTy TemplateName,
6269 SourceLocation TemplateNameLoc,
6270 SourceLocation LAngleLoc,
6271 ASTTemplateArgsPtr TemplateArgs,
6272 SourceLocation RAngleLoc,
6273 SourceLocation CCLoc,
6274 bool EnteringContext);
6275
6276 /// Given a C++ nested-name-specifier, produce an annotation value
6277 /// that the parser can use later to reconstruct the given
6278 /// nested-name-specifier.
6279 ///
6280 /// \param SS A nested-name-specifier.
6281 ///
6282 /// \returns A pointer containing all of the information in the
6283 /// nested-name-specifier \p SS.
6284 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
6285
6286 /// Given an annotation pointer for a nested-name-specifier, restore
6287 /// the nested-name-specifier structure.
6288 ///
6289 /// \param Annotation The annotation pointer, produced by
6290 /// \c SaveNestedNameSpecifierAnnotation().
6291 ///
6292 /// \param AnnotationRange The source range corresponding to the annotation.
6293 ///
6294 /// \param SS The nested-name-specifier that will be updated with the contents
6295 /// of the annotation pointer.
6296 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
6297 SourceRange AnnotationRange,
6298 CXXScopeSpec &SS);
6299
6300 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6301
6302 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
6303 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
6304 /// After this method is called, according to [C++ 3.4.3p3], names should be
6305 /// looked up in the declarator-id's scope, until the declarator is parsed and
6306 /// ActOnCXXExitDeclaratorScope is called.
6307 /// The 'SS' should be a non-empty valid CXXScopeSpec.
6308 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
6309
6310 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
6311 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
6312 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
6313 /// Used to indicate that names should revert to being looked up in the
6314 /// defining scope.
6315 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6316
6317 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
6318 /// initializer for the declaration 'Dcl'.
6319 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6320 /// static data member of class X, names should be looked up in the scope of
6321 /// class X.
6322 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
6323
6324 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
6325 /// initializer for the declaration 'Dcl'.
6326 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
6327
6328 /// Create a new lambda closure type.
6329 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
6330 TypeSourceInfo *Info,
6331 bool KnownDependent,
6332 LambdaCaptureDefault CaptureDefault);
6333
6334 /// Start the definition of a lambda expression.
6335 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
6336 SourceRange IntroducerRange,
6337 TypeSourceInfo *MethodType,
6338 SourceLocation EndLoc,
6339 ArrayRef<ParmVarDecl *> Params,
6340 ConstexprSpecKind ConstexprKind,
6341 Expr *TrailingRequiresClause);
6342
6343 /// Number lambda for linkage purposes if necessary.
6344 void handleLambdaNumbering(
6345 CXXRecordDecl *Class, CXXMethodDecl *Method,
6346 Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None);
6347
6348 /// Endow the lambda scope info with the relevant properties.
6349 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
6350 CXXMethodDecl *CallOperator,
6351 SourceRange IntroducerRange,
6352 LambdaCaptureDefault CaptureDefault,
6353 SourceLocation CaptureDefaultLoc,
6354 bool ExplicitParams,
6355 bool ExplicitResultType,
6356 bool Mutable);
6357
6358 /// Perform initialization analysis of the init-capture and perform
6359 /// any implicit conversions such as an lvalue-to-rvalue conversion if
6360 /// not being used to initialize a reference.
6361 ParsedType actOnLambdaInitCaptureInitialization(
6362 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6363 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
6364 return ParsedType::make(buildLambdaInitCaptureInitialization(
6365 Loc, ByRef, EllipsisLoc, None, Id,
6366 InitKind != LambdaCaptureInitKind::CopyInit, Init));
6367 }
6368 QualType buildLambdaInitCaptureInitialization(
6369 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6370 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
6371 Expr *&Init);
6372
6373 /// Create a dummy variable within the declcontext of the lambda's
6374 /// call operator, for name lookup purposes for a lambda init capture.
6375 ///
6376 /// CodeGen handles emission of lambda captures, ignoring these dummy
6377 /// variables appropriately.
6378 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
6379 QualType InitCaptureType,
6380 SourceLocation EllipsisLoc,
6381 IdentifierInfo *Id,
6382 unsigned InitStyle, Expr *Init);
6383
6384 /// Add an init-capture to a lambda scope.
6385 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
6386
6387 /// Note that we have finished the explicit captures for the
6388 /// given lambda.
6389 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
6390
6391 /// \brief This is called after parsing the explicit template parameter list
6392 /// on a lambda (if it exists) in C++2a.
6393 void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
6394 ArrayRef<NamedDecl *> TParams,
6395 SourceLocation RAngleLoc);
6396
6397 /// Introduce the lambda parameters into scope.
6398 void addLambdaParameters(
6399 ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
6400 CXXMethodDecl *CallOperator, Scope *CurScope);
6401
6402 /// Deduce a block or lambda's return type based on the return
6403 /// statements present in the body.
6404 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
6405
6406 /// ActOnStartOfLambdaDefinition - This is called just before we start
6407 /// parsing the body of a lambda; it analyzes the explicit captures and
6408 /// arguments, and sets up various data-structures for the body of the
6409 /// lambda.
6410 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
6411 Declarator &ParamInfo, Scope *CurScope);
6412
6413 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
6414 /// is invoked to pop the information about the lambda.
6415 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
6416 bool IsInstantiation = false);
6417
6418 /// ActOnLambdaExpr - This is called when the body of a lambda expression
6419 /// was successfully completed.
6420 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
6421 Scope *CurScope);
6422
6423 /// Does copying/destroying the captured variable have side effects?
6424 bool CaptureHasSideEffects(const sema::Capture &From);
6425
6426 /// Diagnose if an explicit lambda capture is unused. Returns true if a
6427 /// diagnostic is emitted.
6428 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
6429 const sema::Capture &From);
6430
6431 /// Build a FieldDecl suitable to hold the given capture.
6432 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
6433
6434 /// Initialize the given capture with a suitable expression.
6435 ExprResult BuildCaptureInit(const sema::Capture &Capture,
6436 SourceLocation ImplicitCaptureLoc,
6437 bool IsOpenMPMapping = false);
6438
6439 /// Complete a lambda-expression having processed and attached the
6440 /// lambda body.
6441 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
6442 sema::LambdaScopeInfo *LSI);
6443
6444 /// Get the return type to use for a lambda's conversion function(s) to
6445 /// function pointer type, given the type of the call operator.
6446 QualType
6447 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
6448
6449 /// Define the "body" of the conversion from a lambda object to a
6450 /// function pointer.
6451 ///
6452 /// This routine doesn't actually define a sensible body; rather, it fills
6453 /// in the initialization expression needed to copy the lambda object into
6454 /// the block, and IR generation actually generates the real body of the
6455 /// block pointer conversion.
6456 void DefineImplicitLambdaToFunctionPointerConversion(
6457 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
6458
6459 /// Define the "body" of the conversion from a lambda object to a
6460 /// block pointer.
6461 ///
6462 /// This routine doesn't actually define a sensible body; rather, it fills
6463 /// in the initialization expression needed to copy the lambda object into
6464 /// the block, and IR generation actually generates the real body of the
6465 /// block pointer conversion.
6466 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
6467 CXXConversionDecl *Conv);
6468
6469 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
6470 SourceLocation ConvLocation,
6471 CXXConversionDecl *Conv,
6472 Expr *Src);
6473
6474 /// Check whether the given expression is a valid constraint expression.
6475 /// A diagnostic is emitted if it is not, false is returned, and
6476 /// PossibleNonPrimary will be set to true if the failure might be due to a
6477 /// non-primary expression being used as an atomic constraint.
6478 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
6479 bool *PossibleNonPrimary = nullptr,
6480 bool IsTrailingRequiresClause = false);
6481
6482private:
6483 /// Caches pairs of template-like decls whose associated constraints were
6484 /// checked for subsumption and whether or not the first's constraints did in
6485 /// fact subsume the second's.
6486 llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
6487 /// Caches the normalized associated constraints of declarations (concepts or
6488 /// constrained declarations). If an error occurred while normalizing the
6489 /// associated constraints of the template or concept, nullptr will be cached
6490 /// here.
6491 llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
6492 NormalizationCache;
6493
6494 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
6495 SatisfactionCache;
6496
6497public:
6498 const NormalizedConstraint *
6499 getNormalizedAssociatedConstraints(
6500 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
6501
6502 /// \brief Check whether the given declaration's associated constraints are
6503 /// at least as constrained than another declaration's according to the
6504 /// partial ordering of constraints.
6505 ///
6506 /// \param Result If no error occurred, receives the result of true if D1 is
6507 /// at least constrained than D2, and false otherwise.
6508 ///
6509 /// \returns true if an error occurred, false otherwise.
6510 bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
6511 NamedDecl *D2, ArrayRef<const Expr *> AC2,
6512 bool &Result);
6513
6514 /// If D1 was not at least as constrained as D2, but would've been if a pair
6515 /// of atomic constraints involved had been declared in a concept and not
6516 /// repeated in two separate places in code.
6517 /// \returns true if such a diagnostic was emitted, false otherwise.
6518 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
6519 ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
6520
6521 /// \brief Check whether the given list of constraint expressions are
6522 /// satisfied (as if in a 'conjunction') given template arguments.
6523 /// \param Template the template-like entity that triggered the constraints
6524 /// check (either a concept or a constrained entity).
6525 /// \param ConstraintExprs a list of constraint expressions, treated as if
6526 /// they were 'AND'ed together.
6527 /// \param TemplateArgs the list of template arguments to substitute into the
6528 /// constraint expression.
6529 /// \param TemplateIDRange The source range of the template id that
6530 /// caused the constraints check.
6531 /// \param Satisfaction if true is returned, will contain details of the
6532 /// satisfaction, with enough information to diagnose an unsatisfied
6533 /// expression.
6534 /// \returns true if an error occurred and satisfaction could not be checked,
6535 /// false otherwise.
6536 bool CheckConstraintSatisfaction(
6537 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
6538 ArrayRef<TemplateArgument> TemplateArgs,
6539 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
6540
6541 /// \brief Check whether the given non-dependent constraint expression is
6542 /// satisfied. Returns false and updates Satisfaction with the satisfaction
6543 /// verdict if successful, emits a diagnostic and returns true if an error
6544 /// occured and satisfaction could not be determined.
6545 ///
6546 /// \returns true if an error occurred, false otherwise.
6547 bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
6548 ConstraintSatisfaction &Satisfaction);
6549
6550 /// Check whether the given function decl's trailing requires clause is
6551 /// satisfied, if any. Returns false and updates Satisfaction with the
6552 /// satisfaction verdict if successful, emits a diagnostic and returns true if
6553 /// an error occured and satisfaction could not be determined.
6554 ///
6555 /// \returns true if an error occurred, false otherwise.
6556 bool CheckFunctionConstraints(const FunctionDecl *FD,
6557 ConstraintSatisfaction &Satisfaction,
6558 SourceLocation UsageLoc = SourceLocation());
6559
6560
6561 /// \brief Ensure that the given template arguments satisfy the constraints
6562 /// associated with the given template, emitting a diagnostic if they do not.
6563 ///
6564 /// \param Template The template to which the template arguments are being
6565 /// provided.
6566 ///
6567 /// \param TemplateArgs The converted, canonicalized template arguments.
6568 ///
6569 /// \param TemplateIDRange The source range of the template id that
6570 /// caused the constraints check.
6571 ///
6572 /// \returns true if the constrains are not satisfied or could not be checked
6573 /// for satisfaction, false if the constraints are satisfied.
6574 bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
6575 ArrayRef<TemplateArgument> TemplateArgs,
6576 SourceRange TemplateIDRange);
6577
6578 /// \brief Emit diagnostics explaining why a constraint expression was deemed
6579 /// unsatisfied.
6580 /// \param First whether this is the first time an unsatisfied constraint is
6581 /// diagnosed for this error.
6582 void
6583 DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
6584 bool First = true);
6585
6586 /// \brief Emit diagnostics explaining why a constraint expression was deemed
6587 /// unsatisfied.
6588 void
6589 DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
6590 bool First = true);
6591
6592 /// \brief Emit diagnostics explaining why a constraint expression was deemed
6593 /// unsatisfied because it was ill-formed.
6594 void DiagnoseUnsatisfiedIllFormedConstraint(SourceLocation DiagnosticLocation,
6595 StringRef Diagnostic);
6596
6597 void DiagnoseRedeclarationConstraintMismatch(SourceLocation Old,
6598 SourceLocation New);
6599
6600 // ParseObjCStringLiteral - Parse Objective-C string literals.
6601 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
6602 ArrayRef<Expr *> Strings);
6603
6604 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
6605
6606 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
6607 /// numeric literal expression. Type of the expression will be "NSNumber *"
6608 /// or "id" if NSNumber is unavailable.
6609 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
6610 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
6611 bool Value);
6612 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
6613
6614 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
6615 /// '@' prefixed parenthesized expression. The type of the expression will
6616 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
6617 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
6618 /// "const char *" or C structure with attribute 'objc_boxable'.
6619 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
6620
6621 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
6622 Expr *IndexExpr,
6623 ObjCMethodDecl *getterMethod,
6624 ObjCMethodDecl *setterMethod);
6625
6626 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
6627 MutableArrayRef<ObjCDictionaryElement> Elements);
6628
6629 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
6630 TypeSourceInfo *EncodedTypeInfo,
6631 SourceLocation RParenLoc);
6632 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
6633 CXXConversionDecl *Method,
6634 bool HadMultipleCandidates);
6635
6636 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
6637 SourceLocation EncodeLoc,
6638 SourceLocation LParenLoc,
6639 ParsedType Ty,
6640 SourceLocation RParenLoc);
6641
6642 /// ParseObjCSelectorExpression - Build selector expression for \@selector
6643 ExprResult ParseObjCSelectorExpression(Selector Sel,
6644 SourceLocation AtLoc,
6645 SourceLocation SelLoc,
6646 SourceLocation LParenLoc,
6647 SourceLocation RParenLoc,
6648 bool WarnMultipleSelectors);
6649
6650 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
6651 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
6652 SourceLocation AtLoc,
6653 SourceLocation ProtoLoc,
6654 SourceLocation LParenLoc,
6655 SourceLocation ProtoIdLoc,
6656 SourceLocation RParenLoc);
6657
6658 //===--------------------------------------------------------------------===//
6659 // C++ Declarations
6660 //
6661 Decl *ActOnStartLinkageSpecification(Scope *S,
6662 SourceLocation ExternLoc,
6663 Expr *LangStr,
6664 SourceLocation LBraceLoc);
6665 Decl *ActOnFinishLinkageSpecification(Scope *S,
6666 Decl *LinkageSpec,
6667 SourceLocation RBraceLoc);
6668
6669
6670 //===--------------------------------------------------------------------===//
6671 // C++ Classes
6672 //
6673 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
6674 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
6675 const CXXScopeSpec *SS = nullptr);
6676 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
6677
6678 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
6679 SourceLocation ColonLoc,
6680 const ParsedAttributesView &Attrs);
6681
6682 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
6683 Declarator &D,
6684 MultiTemplateParamsArg TemplateParameterLists,
6685 Expr *BitfieldWidth, const VirtSpecifiers &VS,
6686 InClassInitStyle InitStyle);
6687
6688 void ActOnStartCXXInClassMemberInitializer();
6689 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
6690 SourceLocation EqualLoc,
6691 Expr *Init);
6692
6693 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6694 Scope *S,
6695 CXXScopeSpec &SS,
6696 IdentifierInfo *MemberOrBase,
6697 ParsedType TemplateTypeTy,
6698 const DeclSpec &DS,
6699 SourceLocation IdLoc,
6700 SourceLocation LParenLoc,
6701 ArrayRef<Expr *> Args,
6702 SourceLocation RParenLoc,
6703 SourceLocation EllipsisLoc);
6704
6705 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6706 Scope *S,
6707 CXXScopeSpec &SS,
6708 IdentifierInfo *MemberOrBase,
6709 ParsedType TemplateTypeTy,
6710 const DeclSpec &DS,
6711 SourceLocation IdLoc,
6712 Expr *InitList,
6713 SourceLocation EllipsisLoc);
6714
6715 MemInitResult BuildMemInitializer(Decl *ConstructorD,
6716 Scope *S,
6717 CXXScopeSpec &SS,
6718 IdentifierInfo *MemberOrBase,
6719 ParsedType TemplateTypeTy,
6720 const DeclSpec &DS,
6721 SourceLocation IdLoc,
6722 Expr *Init,
6723 SourceLocation EllipsisLoc);
6724
6725 MemInitResult BuildMemberInitializer(ValueDecl *Member,
6726 Expr *Init,
6727 SourceLocation IdLoc);
6728
6729 MemInitResult BuildBaseInitializer(QualType BaseType,
6730 TypeSourceInfo *BaseTInfo,
6731 Expr *Init,
6732 CXXRecordDecl *ClassDecl,
6733 SourceLocation EllipsisLoc);
6734
6735 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
6736 Expr *Init,
6737 CXXRecordDecl *ClassDecl);
6738
6739 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
6740 CXXCtorInitializer *Initializer);
6741
6742 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
6743 ArrayRef<CXXCtorInitializer *> Initializers = None);
6744
6745 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
6746
6747
6748 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
6749 /// mark all the non-trivial destructors of its members and bases as
6750 /// referenced.
6751 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
6752 CXXRecordDecl *Record);
6753
6754 /// Mark destructors of virtual bases of this class referenced. In the Itanium
6755 /// C++ ABI, this is done when emitting a destructor for any non-abstract
6756 /// class. In the Microsoft C++ ABI, this is done any time a class's
6757 /// destructor is referenced.
6758 void MarkVirtualBaseDestructorsReferenced(
6759 SourceLocation Location, CXXRecordDecl *ClassDecl,
6760 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr);
6761
6762 /// Do semantic checks to allow the complete destructor variant to be emitted
6763 /// when the destructor is defined in another translation unit. In the Itanium
6764 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
6765 /// can be emitted in separate TUs. To emit the complete variant, run a subset
6766 /// of the checks performed when emitting a regular destructor.
6767 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
6768 CXXDestructorDecl *Dtor);
6769
6770 /// The list of classes whose vtables have been used within
6771 /// this translation unit, and the source locations at which the
6772 /// first use occurred.
6773 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
6774
6775 /// The list of vtables that are required but have not yet been
6776 /// materialized.
6777 SmallVector<VTableUse, 16> VTableUses;
6778
6779 /// The set of classes whose vtables have been used within
6780 /// this translation unit, and a bit that will be true if the vtable is
6781 /// required to be emitted (otherwise, it should be emitted only if needed
6782 /// by code generation).
6783 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
6784
6785 /// Load any externally-stored vtable uses.
6786 void LoadExternalVTableUses();
6787
6788 /// Note that the vtable for the given class was used at the
6789 /// given location.
6790 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6791 bool DefinitionRequired = false);
6792
6793 /// Mark the exception specifications of all virtual member functions
6794 /// in the given class as needed.
6795 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
6796 const CXXRecordDecl *RD);
6797
6798 /// MarkVirtualMembersReferenced - Will mark all members of the given
6799 /// CXXRecordDecl referenced.
6800 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
6801 bool ConstexprOnly = false);
6802
6803 /// Define all of the vtables that have been used in this
6804 /// translation unit and reference any virtual members used by those
6805 /// vtables.
6806 ///
6807 /// \returns true if any work was done, false otherwise.
6808 bool DefineUsedVTables();
6809
6810 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
6811
6812 void ActOnMemInitializers(Decl *ConstructorDecl,
6813 SourceLocation ColonLoc,
6814 ArrayRef<CXXCtorInitializer*> MemInits,
6815 bool AnyErrors);
6816
6817 /// Check class-level dllimport/dllexport attribute. The caller must
6818 /// ensure that referenceDLLExportedClassMethods is called some point later
6819 /// when all outer classes of Class are complete.
6820 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
6821 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
6822
6823 void referenceDLLExportedClassMethods();
6824
6825 void propagateDLLAttrToBaseClassTemplate(
6826 CXXRecordDecl *Class, Attr *ClassAttr,
6827 ClassTemplateSpecializationDecl *BaseTemplateSpec,
6828 SourceLocation BaseLoc);
6829
6830 /// Add gsl::Pointer attribute to std::container::iterator
6831 /// \param ND The declaration that introduces the name
6832 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
6833 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
6834
6835 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
6836 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
6837
6838 /// Add [[gsl::Pointer]] attributes for std:: types.
6839 void inferGslPointerAttribute(TypedefNameDecl *TD);
6840
6841 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
6842
6843 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6844 /// conditions that are needed for the attribute to have an effect.
6845 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
6846
6847 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6848 Decl *TagDecl, SourceLocation LBrac,
6849 SourceLocation RBrac,
6850 const ParsedAttributesView &AttrList);
6851 void ActOnFinishCXXMemberDecls();
6852 void ActOnFinishCXXNonNestedClass();
6853
6854 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6855 unsigned ActOnReenterTemplateScope(Decl *Template,
6856 llvm::function_ref<Scope *()> EnterScope);
6857 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6858 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6859 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6860 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6861 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6862 void ActOnFinishDelayedMemberInitializers(Decl *Record);
6863 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
6864 CachedTokens &Toks);
6865 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
6866 bool IsInsideALocalClassWithinATemplateFunction();
6867
6868 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6869 Expr *AssertExpr,
6870 Expr *AssertMessageExpr,
6871 SourceLocation RParenLoc);
6872 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6873 Expr *AssertExpr,
6874 StringLiteral *AssertMessageExpr,
6875 SourceLocation RParenLoc,
6876 bool Failed);
6877
6878 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
6879 SourceLocation FriendLoc,
6880 TypeSourceInfo *TSInfo);
6881 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6882 MultiTemplateParamsArg TemplateParams);
6883 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6884 MultiTemplateParamsArg TemplateParams);
6885
6886 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6887 StorageClass& SC);
6888 void CheckConstructor(CXXConstructorDecl *Constructor);
6889 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6890 StorageClass& SC);
6891 bool CheckDestructor(CXXDestructorDecl *Destructor);
6892 void CheckConversionDeclarator(Declarator &D, QualType &R,
6893 StorageClass& SC);
6894 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6895 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6896 StorageClass &SC);
6897 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
6898
6899 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
6900
6901 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6902 CXXSpecialMember CSM);
6903 void CheckDelayedMemberExceptionSpecs();
6904
6905 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
6906 DefaultedComparisonKind DCK);
6907 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
6908 FunctionDecl *Spaceship);
6909 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
6910 DefaultedComparisonKind DCK);
6911
6912 //===--------------------------------------------------------------------===//
6913 // C++ Derived Classes
6914 //
6915
6916 /// ActOnBaseSpecifier - Parsed a base specifier
6917 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6918 SourceRange SpecifierRange,
6919 bool Virtual, AccessSpecifier Access,
6920 TypeSourceInfo *TInfo,
6921 SourceLocation EllipsisLoc);
6922
6923 BaseResult ActOnBaseSpecifier(Decl *classdecl,
6924 SourceRange SpecifierRange,
6925 ParsedAttributes &Attrs,
6926 bool Virtual, AccessSpecifier Access,
6927 ParsedType basetype,
6928 SourceLocation BaseLoc,
6929 SourceLocation EllipsisLoc);
6930
6931 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6932 MutableArrayRef<CXXBaseSpecifier *> Bases);
6933 void ActOnBaseSpecifiers(Decl *ClassDecl,
6934 MutableArrayRef<CXXBaseSpecifier *> Bases);
6935
6936 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6937 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6938 CXXBasePaths &Paths);
6939
6940 // FIXME: I don't like this name.
6941 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6942
6943 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6944 SourceLocation Loc, SourceRange Range,
6945 CXXCastPath *BasePath = nullptr,
6946 bool IgnoreAccess = false);
6947 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6948 unsigned InaccessibleBaseID,
6949 unsigned AmbiguousBaseConvID,
6950 SourceLocation Loc, SourceRange Range,
6951 DeclarationName Name,
6952 CXXCastPath *BasePath,
6953 bool IgnoreAccess = false);
6954
6955 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6956
6957 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6958 const CXXMethodDecl *Old);
6959
6960 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6961 /// covariant, according to C++ [class.virtual]p5.
6962 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6963 const CXXMethodDecl *Old);
6964
6965 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6966 /// spec is a subset of base spec.
6967 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6968 const CXXMethodDecl *Old);
6969
6970 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6971
6972 /// CheckOverrideControl - Check C++11 override control semantics.
6973 void CheckOverrideControl(NamedDecl *D);
6974
6975 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6976 /// not used in the declaration of an overriding method.
6977 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
6978
6979 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
6980 /// overrides a virtual member function marked 'final', according to
6981 /// C++11 [class.virtual]p4.
6982 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6983 const CXXMethodDecl *Old);
6984
6985
6986 //===--------------------------------------------------------------------===//
6987 // C++ Access Control
6988 //
6989
6990 enum AccessResult {
6991 AR_accessible,
6992 AR_inaccessible,
6993 AR_dependent,
6994 AR_delayed
6995 };
6996
6997 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
6998 NamedDecl *PrevMemberDecl,
6999 AccessSpecifier LexicalAS);
7000
7001 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
7002 DeclAccessPair FoundDecl);
7003 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
7004 DeclAccessPair FoundDecl);
7005 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
7006 SourceRange PlacementRange,
7007 CXXRecordDecl *NamingClass,
7008 DeclAccessPair FoundDecl,
7009 bool Diagnose = true);
7010 AccessResult CheckConstructorAccess(SourceLocation Loc,
7011 CXXConstructorDecl *D,
7012 DeclAccessPair FoundDecl,
7013 const InitializedEntity &Entity,
7014 bool IsCopyBindingRefToTemp = false);
7015 AccessResult CheckConstructorAccess(SourceLocation Loc,
7016 CXXConstructorDecl *D,
7017 DeclAccessPair FoundDecl,
7018 const InitializedEntity &Entity,
7019 const PartialDiagnostic &PDiag);
7020 AccessResult CheckDestructorAccess(SourceLocation Loc,
7021 CXXDestructorDecl *Dtor,
7022 const PartialDiagnostic &PDiag,
7023 QualType objectType = QualType());
7024 AccessResult CheckFriendAccess(NamedDecl *D);
7025 AccessResult CheckMemberAccess(SourceLocation UseLoc,
7026 CXXRecordDecl *NamingClass,
7027 DeclAccessPair Found);
7028 AccessResult
7029 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
7030 CXXRecordDecl *DecomposedClass,
7031 DeclAccessPair Field);
7032 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
7033 Expr *ObjectExpr,
7034 Expr *ArgExpr,
7035 DeclAccessPair FoundDecl);
7036 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
7037 DeclAccessPair FoundDecl);
7038 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
7039 QualType Base, QualType Derived,
7040 const CXXBasePath &Path,
7041 unsigned DiagID,
7042 bool ForceCheck = false,
7043 bool ForceUnprivileged = false);
7044 void CheckLookupAccess(const LookupResult &R);
7045 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
7046 QualType BaseType);
7047 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7048 DeclAccessPair Found, QualType ObjectType,
7049 SourceLocation Loc,
7050 const PartialDiagnostic &Diag);
7051 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7052 DeclAccessPair Found,
7053 QualType ObjectType) {
7054 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
7055 SourceLocation(), PDiag());
7056 }
7057
7058 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
7059 const MultiLevelTemplateArgumentList &TemplateArgs);
7060 void PerformDependentDiagnostics(const DeclContext *Pattern,
7061 const MultiLevelTemplateArgumentList &TemplateArgs);
7062
7063 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
7064
7065 /// When true, access checking violations are treated as SFINAE
7066 /// failures rather than hard errors.
7067 bool AccessCheckingSFINAE;
7068
7069 enum AbstractDiagSelID {
7070 AbstractNone = -1,
7071 AbstractReturnType,
7072 AbstractParamType,
7073 AbstractVariableType,
7074 AbstractFieldType,
7075 AbstractIvarType,
7076 AbstractSynthesizedIvarType,
7077 AbstractArrayType
7078 };
7079
7080 bool isAbstractType(SourceLocation Loc, QualType T);
7081 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
7082 TypeDiagnoser &Diagnoser);
7083 template <typename... Ts>
7084 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
7085 const Ts &...Args) {
7086 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
7087 return RequireNonAbstractType(Loc, T, Diagnoser);
7088 }
7089
7090 void DiagnoseAbstractType(const CXXRecordDecl *RD);
7091
7092 //===--------------------------------------------------------------------===//
7093 // C++ Overloaded Operators [C++ 13.5]
7094 //
7095
7096 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
7097
7098 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
7099
7100 //===--------------------------------------------------------------------===//
7101 // C++ Templates [C++ 14]
7102 //
7103 void FilterAcceptableTemplateNames(LookupResult &R,
7104 bool AllowFunctionTemplates = true,
7105 bool AllowDependent = true);
7106 bool hasAnyAcceptableTemplateNames(LookupResult &R,
7107 bool AllowFunctionTemplates = true,
7108 bool AllowDependent = true,
7109 bool AllowNonTemplateFunctions = false);
7110 /// Try to interpret the lookup result D as a template-name.
7111 ///
7112 /// \param D A declaration found by name lookup.
7113 /// \param AllowFunctionTemplates Whether function templates should be
7114 /// considered valid results.
7115 /// \param AllowDependent Whether unresolved using declarations (that might
7116 /// name templates) should be considered valid results.
7117 NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
7118 bool AllowFunctionTemplates = true,
7119 bool AllowDependent = true);
7120
7121 enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
7122 /// Whether and why a template name is required in this lookup.
7123 class RequiredTemplateKind {
7124 public:
7125 /// Template name is required if TemplateKWLoc is valid.
7126 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
7127 : TemplateKW(TemplateKWLoc) {}
7128 /// Template name is unconditionally required.
7129 RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {}
7130
7131 SourceLocation getTemplateKeywordLoc() const {
7132 return TemplateKW.getValueOr(SourceLocation());
7133 }
7134 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
7135 bool isRequired() const { return TemplateKW != SourceLocation(); }
7136 explicit operator bool() const { return isRequired(); }
7137
7138 private:
7139 llvm::Optional<SourceLocation> TemplateKW;
7140 };
7141
7142 enum class AssumedTemplateKind {
7143 /// This is not assumed to be a template name.
7144 None,
7145 /// This is assumed to be a template name because lookup found nothing.
7146 FoundNothing,
7147 /// This is assumed to be a template name because lookup found one or more
7148 /// functions (but no function templates).
7149 FoundFunctions,
7150 };
7151 bool LookupTemplateName(
7152 LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType,
7153 bool EnteringContext, bool &MemberOfUnknownSpecialization,
7154 RequiredTemplateKind RequiredTemplate = SourceLocation(),
7155 AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true);
7156
7157 TemplateNameKind isTemplateName(Scope *S,
7158 CXXScopeSpec &SS,
7159 bool hasTemplateKeyword,
7160 const UnqualifiedId &Name,
7161 ParsedType ObjectType,
7162 bool EnteringContext,
7163 TemplateTy &Template,
7164 bool &MemberOfUnknownSpecialization,
7165 bool Disambiguation = false);
7166
7167 /// Try to resolve an undeclared template name as a type template.
7168 ///
7169 /// Sets II to the identifier corresponding to the template name, and updates
7170 /// Name to a corresponding (typo-corrected) type template name and TNK to
7171 /// the corresponding kind, if possible.
7172 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
7173 TemplateNameKind &TNK,
7174 SourceLocation NameLoc,
7175 IdentifierInfo *&II);
7176
7177 bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
7178 SourceLocation NameLoc,
7179 bool Diagnose = true);
7180
7181 /// Determine whether a particular identifier might be the name in a C++1z
7182 /// deduction-guide declaration.
7183 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
7184 SourceLocation NameLoc,
7185 ParsedTemplateTy *Template = nullptr);
7186
7187 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
7188 SourceLocation IILoc,
7189 Scope *S,
7190 const CXXScopeSpec *SS,
7191 TemplateTy &SuggestedTemplate,
7192 TemplateNameKind &SuggestedKind);
7193
7194 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
7195 NamedDecl *Instantiation,
7196 bool InstantiatedFromMember,
7197 const NamedDecl *Pattern,
7198 const NamedDecl *PatternDef,
7199 TemplateSpecializationKind TSK,
7200 bool Complain = true);
7201
7202 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
7203 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
7204
7205 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
7206 SourceLocation EllipsisLoc,
7207 SourceLocation KeyLoc,
7208 IdentifierInfo *ParamName,
7209 SourceLocation ParamNameLoc,
7210 unsigned Depth, unsigned Position,
7211 SourceLocation EqualLoc,
7212 ParsedType DefaultArg, bool HasTypeConstraint);
7213
7214 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
7215 TemplateIdAnnotation *TypeConstraint,
7216 TemplateTypeParmDecl *ConstrainedParameter,
7217 SourceLocation EllipsisLoc);
7218
7219 bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
7220 DeclarationNameInfo NameInfo,
7221 ConceptDecl *NamedConcept,
7222 const TemplateArgumentListInfo *TemplateArgs,
7223 TemplateTypeParmDecl *ConstrainedParameter,
7224 SourceLocation EllipsisLoc);
7225
7226 bool AttachTypeConstraint(AutoTypeLoc TL,
7227 NonTypeTemplateParmDecl *ConstrainedParameter,
7228 SourceLocation EllipsisLoc);
7229
7230 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
7231 SourceLocation Loc);
7232 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
7233
7234 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
7235 unsigned Depth,
7236 unsigned Position,
7237 SourceLocation EqualLoc,
7238 Expr *DefaultArg);
7239 NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
7240 SourceLocation TmpLoc,
7241 TemplateParameterList *Params,
7242 SourceLocation EllipsisLoc,
7243 IdentifierInfo *ParamName,
7244 SourceLocation ParamNameLoc,
7245 unsigned Depth,
7246 unsigned Position,
7247 SourceLocation EqualLoc,
7248 ParsedTemplateArgument DefaultArg);
7249
7250 TemplateParameterList *
7251 ActOnTemplateParameterList(unsigned Depth,
7252 SourceLocation ExportLoc,
7253 SourceLocation TemplateLoc,
7254 SourceLocation LAngleLoc,
7255 ArrayRef<NamedDecl *> Params,
7256 SourceLocation RAngleLoc,
7257 Expr *RequiresClause);
7258
7259 /// The context in which we are checking a template parameter list.
7260 enum TemplateParamListContext {
7261 TPC_ClassTemplate,
7262 TPC_VarTemplate,
7263 TPC_FunctionTemplate,
7264 TPC_ClassTemplateMember,
7265 TPC_FriendClassTemplate,
7266 TPC_FriendFunctionTemplate,
7267 TPC_FriendFunctionTemplateDefinition,
7268 TPC_TypeAliasTemplate
7269 };
7270
7271 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
7272 TemplateParameterList *OldParams,
7273 TemplateParamListContext TPC,
7274 SkipBodyInfo *SkipBody = nullptr);
7275 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
7276 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
7277 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
7278 ArrayRef<TemplateParameterList *> ParamLists,
7279 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
7280 bool SuppressDiagnostic = false);
7281
7282 DeclResult CheckClassTemplate(
7283 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7284 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
7285 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
7286 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
7287 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
7288 TemplateParameterList **OuterTemplateParamLists,
7289 SkipBodyInfo *SkipBody = nullptr);
7290
7291 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
7292 QualType NTTPType,
7293 SourceLocation Loc);
7294
7295 /// Get a template argument mapping the given template parameter to itself,
7296 /// e.g. for X in \c template<int X>, this would return an expression template
7297 /// argument referencing X.
7298 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
7299 SourceLocation Location);
7300
7301 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
7302 TemplateArgumentListInfo &Out);
7303
7304 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
7305
7306 void NoteAllFoundTemplates(TemplateName Name);
7307
7308 QualType CheckTemplateIdType(TemplateName Template,
7309 SourceLocation TemplateLoc,
7310 TemplateArgumentListInfo &TemplateArgs);
7311
7312 TypeResult
7313 ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7314 TemplateTy Template, IdentifierInfo *TemplateII,
7315 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
7316 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
7317 bool IsCtorOrDtorName = false, bool IsClassName = false);
7318
7319 /// Parsed an elaborated-type-specifier that refers to a template-id,
7320 /// such as \c class T::template apply<U>.
7321 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
7322 TypeSpecifierType TagSpec,
7323 SourceLocation TagLoc,
7324 CXXScopeSpec &SS,
7325 SourceLocation TemplateKWLoc,
7326 TemplateTy TemplateD,
7327 SourceLocation TemplateLoc,
7328 SourceLocation LAngleLoc,
7329 ASTTemplateArgsPtr TemplateArgsIn,
7330 SourceLocation RAngleLoc);
7331
7332 DeclResult ActOnVarTemplateSpecialization(
7333 Scope *S, Declarator &D, TypeSourceInfo *DI,
7334 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
7335 StorageClass SC, bool IsPartialSpecialization);
7336
7337 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
7338 SourceLocation TemplateLoc,
7339 SourceLocation TemplateNameLoc,
7340 const TemplateArgumentListInfo &TemplateArgs);
7341
7342 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
7343 const DeclarationNameInfo &NameInfo,
7344 VarTemplateDecl *Template,
7345 SourceLocation TemplateLoc,
7346 const TemplateArgumentListInfo *TemplateArgs);
7347
7348 ExprResult
7349 CheckConceptTemplateId(const CXXScopeSpec &SS,
7350 SourceLocation TemplateKWLoc,
7351 const DeclarationNameInfo &ConceptNameInfo,
7352 NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
7353 const TemplateArgumentListInfo *TemplateArgs);
7354
7355 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
7356
7357 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
7358 SourceLocation TemplateKWLoc,
7359 LookupResult &R,
7360 bool RequiresADL,
7361 const TemplateArgumentListInfo *TemplateArgs);
7362
7363 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
7364 SourceLocation TemplateKWLoc,
7365 const DeclarationNameInfo &NameInfo,
7366 const TemplateArgumentListInfo *TemplateArgs);
7367
7368 TemplateNameKind ActOnTemplateName(
7369 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7370 const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
7371 TemplateTy &Template, bool AllowInjectedClassName = false);
7372
7373 DeclResult ActOnClassTemplateSpecialization(
7374 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7375 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
7376 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
7377 MultiTemplateParamsArg TemplateParameterLists,
7378 SkipBodyInfo *SkipBody = nullptr);
7379
7380 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
7381 TemplateDecl *PrimaryTemplate,
7382 unsigned NumExplicitArgs,
7383 ArrayRef<TemplateArgument> Args);
7384 void CheckTemplatePartialSpecialization(
7385 ClassTemplatePartialSpecializationDecl *Partial);
7386 void CheckTemplatePartialSpecialization(
7387 VarTemplatePartialSpecializationDecl *Partial);
7388
7389 Decl *ActOnTemplateDeclarator(Scope *S,
7390 MultiTemplateParamsArg TemplateParameterLists,
7391 Declarator &D);
7392
7393 bool
7394 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7395 TemplateSpecializationKind NewTSK,
7396 NamedDecl *PrevDecl,
7397 TemplateSpecializationKind PrevTSK,
7398 SourceLocation PrevPtOfInstantiation,
7399 bool &SuppressNew);
7400
7401 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7402 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7403 LookupResult &Previous);
7404
7405 bool CheckFunctionTemplateSpecialization(
7406 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7407 LookupResult &Previous, bool QualifiedFriend = false);
7408 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7409 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7410
7411 DeclResult ActOnExplicitInstantiation(
7412 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
7413 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
7414 TemplateTy Template, SourceLocation TemplateNameLoc,
7415 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
7416 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
7417
7418 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
7419 SourceLocation TemplateLoc,
7420 unsigned TagSpec, SourceLocation KWLoc,
7421 CXXScopeSpec &SS, IdentifierInfo *Name,
7422 SourceLocation NameLoc,
7423 const ParsedAttributesView &Attr);
7424
7425 DeclResult ActOnExplicitInstantiation(Scope *S,
7426 SourceLocation ExternLoc,
7427 SourceLocation TemplateLoc,
7428 Declarator &D);
7429
7430 TemplateArgumentLoc
7431 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
7432 SourceLocation TemplateLoc,
7433 SourceLocation RAngleLoc,
7434 Decl *Param,
7435 SmallVectorImpl<TemplateArgument>
7436 &Converted,
7437 bool &HasDefaultArg);
7438
7439 /// Specifies the context in which a particular template
7440 /// argument is being checked.
7441 enum CheckTemplateArgumentKind {
7442 /// The template argument was specified in the code or was
7443 /// instantiated with some deduced template arguments.
7444 CTAK_Specified,
7445
7446 /// The template argument was deduced via template argument
7447 /// deduction.
7448 CTAK_Deduced,
7449
7450 /// The template argument was deduced from an array bound
7451 /// via template argument deduction.
7452 CTAK_DeducedFromArrayBound
7453 };
7454
7455 bool CheckTemplateArgument(NamedDecl *Param,
7456 TemplateArgumentLoc &Arg,
7457 NamedDecl *Template,
7458 SourceLocation TemplateLoc,
7459 SourceLocation RAngleLoc,
7460 unsigned ArgumentPackIndex,
7461 SmallVectorImpl<TemplateArgument> &Converted,
7462 CheckTemplateArgumentKind CTAK = CTAK_Specified);
7463
7464 /// Check that the given template arguments can be be provided to
7465 /// the given template, converting the arguments along the way.
7466 ///
7467 /// \param Template The template to which the template arguments are being
7468 /// provided.
7469 ///
7470 /// \param TemplateLoc The location of the template name in the source.
7471 ///
7472 /// \param TemplateArgs The list of template arguments. If the template is
7473 /// a template template parameter, this function may extend the set of
7474 /// template arguments to also include substituted, defaulted template
7475 /// arguments.
7476 ///
7477 /// \param PartialTemplateArgs True if the list of template arguments is
7478 /// intentionally partial, e.g., because we're checking just the initial
7479 /// set of template arguments.
7480 ///
7481 /// \param Converted Will receive the converted, canonicalized template
7482 /// arguments.
7483 ///
7484 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
7485 /// contain the converted forms of the template arguments as written.
7486 /// Otherwise, \p TemplateArgs will not be modified.
7487 ///
7488 /// \param ConstraintsNotSatisfied If provided, and an error occured, will
7489 /// receive true if the cause for the error is the associated constraints of
7490 /// the template not being satisfied by the template arguments.
7491 ///
7492 /// \returns true if an error occurred, false otherwise.
7493 bool CheckTemplateArgumentList(TemplateDecl *Template,
7494 SourceLocation TemplateLoc,
7495 TemplateArgumentListInfo &TemplateArgs,
7496 bool PartialTemplateArgs,
7497 SmallVectorImpl<TemplateArgument> &Converted,
7498 bool UpdateArgsWithConversions = true,
7499 bool *ConstraintsNotSatisfied = nullptr);
7500
7501 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
7502 TemplateArgumentLoc &Arg,
7503 SmallVectorImpl<TemplateArgument> &Converted);
7504
7505 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
7506 TypeSourceInfo *Arg);
7507 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
7508 QualType InstantiatedParamType, Expr *Arg,
7509 TemplateArgument &Converted,
7510 CheckTemplateArgumentKind CTAK = CTAK_Specified);
7511 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7512 TemplateParameterList *Params,
7513 TemplateArgumentLoc &Arg);
7514
7515 ExprResult
7516 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7517 QualType ParamType,
7518 SourceLocation Loc);
7519 ExprResult
7520 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7521 SourceLocation Loc);
7522
7523 /// Enumeration describing how template parameter lists are compared
7524 /// for equality.
7525 enum TemplateParameterListEqualKind {
7526 /// We are matching the template parameter lists of two templates
7527 /// that might be redeclarations.
7528 ///
7529 /// \code
7530 /// template<typename T> struct X;
7531 /// template<typename T> struct X;
7532 /// \endcode
7533 TPL_TemplateMatch,
7534
7535 /// We are matching the template parameter lists of two template
7536 /// template parameters as part of matching the template parameter lists
7537 /// of two templates that might be redeclarations.
7538 ///
7539 /// \code
7540 /// template<template<int I> class TT> struct X;
7541 /// template<template<int Value> class Other> struct X;
7542 /// \endcode
7543 TPL_TemplateTemplateParmMatch,
7544
7545 /// We are matching the template parameter lists of a template
7546 /// template argument against the template parameter lists of a template
7547 /// template parameter.
7548 ///
7549 /// \code
7550 /// template<template<int Value> class Metafun> struct X;
7551 /// template<int Value> struct integer_c;
7552 /// X<integer_c> xic;
7553 /// \endcode
7554 TPL_TemplateTemplateArgumentMatch
7555 };
7556
7557 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
7558 TemplateParameterList *Old,
7559 bool Complain,
7560 TemplateParameterListEqualKind Kind,
7561 SourceLocation TemplateArgLoc
7562 = SourceLocation());
7563
7564 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
7565
7566 /// Called when the parser has parsed a C++ typename
7567 /// specifier, e.g., "typename T::type".
7568 ///
7569 /// \param S The scope in which this typename type occurs.
7570 /// \param TypenameLoc the location of the 'typename' keyword
7571 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7572 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
7573 /// \param IdLoc the location of the identifier.
7574 TypeResult
7575 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7576 const CXXScopeSpec &SS, const IdentifierInfo &II,
7577 SourceLocation IdLoc);
7578
7579 /// Called when the parser has parsed a C++ typename
7580 /// specifier that ends in a template-id, e.g.,
7581 /// "typename MetaFun::template apply<T1, T2>".
7582 ///
7583 /// \param S The scope in which this typename type occurs.
7584 /// \param TypenameLoc the location of the 'typename' keyword
7585 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7586 /// \param TemplateLoc the location of the 'template' keyword, if any.
7587 /// \param TemplateName The template name.
7588 /// \param TemplateII The identifier used to name the template.
7589 /// \param TemplateIILoc The location of the template name.
7590 /// \param LAngleLoc The location of the opening angle bracket ('<').
7591 /// \param TemplateArgs The template arguments.
7592 /// \param RAngleLoc The location of the closing angle bracket ('>').
7593 TypeResult
7594 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7595 const CXXScopeSpec &SS,
7596 SourceLocation TemplateLoc,
7597 TemplateTy TemplateName,
7598 IdentifierInfo *TemplateII,
7599 SourceLocation TemplateIILoc,
7600 SourceLocation LAngleLoc,
7601 ASTTemplateArgsPtr TemplateArgs,
7602 SourceLocation RAngleLoc);
7603
7604 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7605 SourceLocation KeywordLoc,
7606 NestedNameSpecifierLoc QualifierLoc,
7607 const IdentifierInfo &II,
7608 SourceLocation IILoc,
7609 TypeSourceInfo **TSI,
7610 bool DeducedTSTContext);
7611
7612 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7613 SourceLocation KeywordLoc,
7614 NestedNameSpecifierLoc QualifierLoc,
7615 const IdentifierInfo &II,
7616 SourceLocation IILoc,
7617 bool DeducedTSTContext = true);
7618
7619
7620 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
7621 SourceLocation Loc,
7622 DeclarationName Name);
7623 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
7624
7625 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
7626 bool RebuildTemplateParamsInCurrentInstantiation(
7627 TemplateParameterList *Params);
7628
7629 std::string
7630 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7631 const TemplateArgumentList &Args);
7632
7633 std::string
7634 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7635 const TemplateArgument *Args,
7636 unsigned NumArgs);
7637
7638 //===--------------------------------------------------------------------===//
7639 // C++ Concepts
7640 //===--------------------------------------------------------------------===//
7641 Decl *ActOnConceptDefinition(
7642 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
7643 IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
7644
7645 RequiresExprBodyDecl *
7646 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
7647 ArrayRef<ParmVarDecl *> LocalParameters,
7648 Scope *BodyScope);
7649 void ActOnFinishRequiresExpr();
7650 concepts::Requirement *ActOnSimpleRequirement(Expr *E);
7651 concepts::Requirement *ActOnTypeRequirement(
7652 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
7653 IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
7654 concepts::Requirement *ActOnCompoundRequirement(Expr *E,
7655 SourceLocation NoexceptLoc);
7656 concepts::Requirement *
7657 ActOnCompoundRequirement(
7658 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
7659 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
7660 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
7661 concepts::ExprRequirement *
7662 BuildExprRequirement(
7663 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
7664 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
7665 concepts::ExprRequirement *
7666 BuildExprRequirement(
7667 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
7668 bool IsSatisfied, SourceLocation NoexceptLoc,
7669 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
7670 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
7671 concepts::TypeRequirement *
7672 BuildTypeRequirement(
7673 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
7674 concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
7675 concepts::NestedRequirement *
7676 BuildNestedRequirement(
7677 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
7678 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
7679 RequiresExprBodyDecl *Body,
7680 ArrayRef<ParmVarDecl *> LocalParameters,
7681 ArrayRef<concepts::Requirement *> Requirements,
7682 SourceLocation ClosingBraceLoc);
7683
7684 //===--------------------------------------------------------------------===//
7685 // C++ Variadic Templates (C++0x [temp.variadic])
7686 //===--------------------------------------------------------------------===//
7687
7688 /// Determine whether an unexpanded parameter pack might be permitted in this
7689 /// location. Useful for error recovery.
7690 bool isUnexpandedParameterPackPermitted();
7691
7692 /// The context in which an unexpanded parameter pack is
7693 /// being diagnosed.
7694 ///
7695 /// Note that the values of this enumeration line up with the first
7696 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
7697 enum UnexpandedParameterPackContext {
7698 /// An arbitrary expression.
7699 UPPC_Expression = 0,
7700
7701 /// The base type of a class type.
7702 UPPC_BaseType,
7703
7704 /// The type of an arbitrary declaration.
7705 UPPC_DeclarationType,
7706
7707 /// The type of a data member.
7708 UPPC_DataMemberType,
7709
7710 /// The size of a bit-field.
7711 UPPC_BitFieldWidth,
7712
7713 /// The expression in a static assertion.
7714 UPPC_StaticAssertExpression,
7715
7716 /// The fixed underlying type of an enumeration.
7717 UPPC_FixedUnderlyingType,
7718
7719 /// The enumerator value.
7720 UPPC_EnumeratorValue,
7721
7722 /// A using declaration.
7723 UPPC_UsingDeclaration,
7724
7725 /// A friend declaration.
7726 UPPC_FriendDeclaration,
7727
7728 /// A declaration qualifier.
7729 UPPC_DeclarationQualifier,
7730
7731 /// An initializer.
7732 UPPC_Initializer,
7733
7734 /// A default argument.
7735 UPPC_DefaultArgument,
7736
7737 /// The type of a non-type template parameter.
7738 UPPC_NonTypeTemplateParameterType,
7739
7740 /// The type of an exception.
7741 UPPC_ExceptionType,
7742
7743 /// Partial specialization.
7744 UPPC_PartialSpecialization,
7745
7746 /// Microsoft __if_exists.
7747 UPPC_IfExists,
7748
7749 /// Microsoft __if_not_exists.
7750 UPPC_IfNotExists,
7751
7752 /// Lambda expression.
7753 UPPC_Lambda,
7754
7755 /// Block expression,
7756 UPPC_Block,
7757
7758 /// A type constraint,
7759 UPPC_TypeConstraint
7760 };
7761
7762 /// Diagnose unexpanded parameter packs.
7763 ///
7764 /// \param Loc The location at which we should emit the diagnostic.
7765 ///
7766 /// \param UPPC The context in which we are diagnosing unexpanded
7767 /// parameter packs.
7768 ///
7769 /// \param Unexpanded the set of unexpanded parameter packs.
7770 ///
7771 /// \returns true if an error occurred, false otherwise.
7772 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
7773 UnexpandedParameterPackContext UPPC,
7774 ArrayRef<UnexpandedParameterPack> Unexpanded);
7775
7776 /// If the given type contains an unexpanded parameter pack,
7777 /// diagnose the error.
7778 ///
7779 /// \param Loc The source location where a diagnostc should be emitted.
7780 ///
7781 /// \param T The type that is being checked for unexpanded parameter
7782 /// packs.
7783 ///
7784 /// \returns true if an error occurred, false otherwise.
7785 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
7786 UnexpandedParameterPackContext UPPC);
7787
7788 /// If the given expression contains an unexpanded parameter
7789 /// pack, diagnose the error.
7790 ///
7791 /// \param E The expression that is being checked for unexpanded
7792 /// parameter packs.
7793 ///
7794 /// \returns true if an error occurred, false otherwise.
7795 bool DiagnoseUnexpandedParameterPack(Expr *E,
7796 UnexpandedParameterPackContext UPPC = UPPC_Expression);
7797
7798 /// If the given nested-name-specifier contains an unexpanded
7799 /// parameter pack, diagnose the error.
7800 ///
7801 /// \param SS The nested-name-specifier that is being checked for
7802 /// unexpanded parameter packs.
7803 ///
7804 /// \returns true if an error occurred, false otherwise.
7805 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
7806 UnexpandedParameterPackContext UPPC);
7807
7808 /// If the given name contains an unexpanded parameter pack,
7809 /// diagnose the error.
7810 ///
7811 /// \param NameInfo The name (with source location information) that
7812 /// is being checked for unexpanded parameter packs.
7813 ///
7814 /// \returns true if an error occurred, false otherwise.
7815 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
7816 UnexpandedParameterPackContext UPPC);
7817
7818 /// If the given template name contains an unexpanded parameter pack,
7819 /// diagnose the error.
7820 ///
7821 /// \param Loc The location of the template name.
7822 ///
7823 /// \param Template The template name that is being checked for unexpanded
7824 /// parameter packs.
7825 ///
7826 /// \returns true if an error occurred, false otherwise.
7827 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
7828 TemplateName Template,
7829 UnexpandedParameterPackContext UPPC);
7830
7831 /// If the given template argument contains an unexpanded parameter
7832 /// pack, diagnose the error.
7833 ///
7834 /// \param Arg The template argument that is being checked for unexpanded
7835 /// parameter packs.
7836 ///
7837 /// \returns true if an error occurred, false otherwise.
7838 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
7839 UnexpandedParameterPackContext UPPC);
7840
7841 /// Collect the set of unexpanded parameter packs within the given
7842 /// template argument.
7843 ///
7844 /// \param Arg The template argument that will be traversed to find
7845 /// unexpanded parameter packs.
7846 void collectUnexpandedParameterPacks(TemplateArgument Arg,
7847 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7848
7849 /// Collect the set of unexpanded parameter packs within the given
7850 /// template argument.
7851 ///
7852 /// \param Arg The template argument that will be traversed to find
7853 /// unexpanded parameter packs.
7854 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
7855 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7856
7857 /// Collect the set of unexpanded parameter packs within the given
7858 /// type.
7859 ///
7860 /// \param T The type that will be traversed to find
7861 /// unexpanded parameter packs.
7862 void collectUnexpandedParameterPacks(QualType T,
7863 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7864
7865 /// Collect the set of unexpanded parameter packs within the given
7866 /// type.
7867 ///
7868 /// \param TL The type that will be traversed to find
7869 /// unexpanded parameter packs.
7870 void collectUnexpandedParameterPacks(TypeLoc TL,
7871 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7872
7873 /// Collect the set of unexpanded parameter packs within the given
7874 /// nested-name-specifier.
7875 ///
7876 /// \param NNS The nested-name-specifier that will be traversed to find
7877 /// unexpanded parameter packs.
7878 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
7879 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7880
7881 /// Collect the set of unexpanded parameter packs within the given
7882 /// name.
7883 ///
7884 /// \param NameInfo The name that will be traversed to find
7885 /// unexpanded parameter packs.
7886 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
7887 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7888
7889 /// Invoked when parsing a template argument followed by an
7890 /// ellipsis, which creates a pack expansion.
7891 ///
7892 /// \param Arg The template argument preceding the ellipsis, which
7893 /// may already be invalid.
7894 ///
7895 /// \param EllipsisLoc The location of the ellipsis.
7896 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
7897 SourceLocation EllipsisLoc);
7898
7899 /// Invoked when parsing a type followed by an ellipsis, which
7900 /// creates a pack expansion.
7901 ///
7902 /// \param Type The type preceding the ellipsis, which will become
7903 /// the pattern of the pack expansion.
7904 ///
7905 /// \param EllipsisLoc The location of the ellipsis.
7906 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
7907
7908 /// Construct a pack expansion type from the pattern of the pack
7909 /// expansion.
7910 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
7911 SourceLocation EllipsisLoc,
7912 Optional<unsigned> NumExpansions);
7913
7914 /// Construct a pack expansion type from the pattern of the pack
7915 /// expansion.
7916 QualType CheckPackExpansion(QualType Pattern,
7917 SourceRange PatternRange,
7918 SourceLocation EllipsisLoc,
7919 Optional<unsigned> NumExpansions);
7920
7921 /// Invoked when parsing an expression followed by an ellipsis, which
7922 /// creates a pack expansion.
7923 ///
7924 /// \param Pattern The expression preceding the ellipsis, which will become
7925 /// the pattern of the pack expansion.
7926 ///
7927 /// \param EllipsisLoc The location of the ellipsis.
7928 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
7929
7930 /// Invoked when parsing an expression followed by an ellipsis, which
7931 /// creates a pack expansion.
7932 ///
7933 /// \param Pattern The expression preceding the ellipsis, which will become
7934 /// the pattern of the pack expansion.
7935 ///
7936 /// \param EllipsisLoc The location of the ellipsis.
7937 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
7938 Optional<unsigned> NumExpansions);
7939
7940 /// Determine whether we could expand a pack expansion with the
7941 /// given set of parameter packs into separate arguments by repeatedly
7942 /// transforming the pattern.
7943 ///
7944 /// \param EllipsisLoc The location of the ellipsis that identifies the
7945 /// pack expansion.
7946 ///
7947 /// \param PatternRange The source range that covers the entire pattern of
7948 /// the pack expansion.
7949 ///
7950 /// \param Unexpanded The set of unexpanded parameter packs within the
7951 /// pattern.
7952 ///
7953 /// \param ShouldExpand Will be set to \c true if the transformer should
7954 /// expand the corresponding pack expansions into separate arguments. When
7955 /// set, \c NumExpansions must also be set.
7956 ///
7957 /// \param RetainExpansion Whether the caller should add an unexpanded
7958 /// pack expansion after all of the expanded arguments. This is used
7959 /// when extending explicitly-specified template argument packs per
7960 /// C++0x [temp.arg.explicit]p9.
7961 ///
7962 /// \param NumExpansions The number of separate arguments that will be in
7963 /// the expanded form of the corresponding pack expansion. This is both an
7964 /// input and an output parameter, which can be set by the caller if the
7965 /// number of expansions is known a priori (e.g., due to a prior substitution)
7966 /// and will be set by the callee when the number of expansions is known.
7967 /// The callee must set this value when \c ShouldExpand is \c true; it may
7968 /// set this value in other cases.
7969 ///
7970 /// \returns true if an error occurred (e.g., because the parameter packs
7971 /// are to be instantiated with arguments of different lengths), false
7972 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
7973 /// must be set.
7974 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
7975 SourceRange PatternRange,
7976 ArrayRef<UnexpandedParameterPack> Unexpanded,
7977 const MultiLevelTemplateArgumentList &TemplateArgs,
7978 bool &ShouldExpand,
7979 bool &RetainExpansion,
7980 Optional<unsigned> &NumExpansions);
7981
7982 /// Determine the number of arguments in the given pack expansion
7983 /// type.
7984 ///
7985 /// This routine assumes that the number of arguments in the expansion is
7986 /// consistent across all of the unexpanded parameter packs in its pattern.
7987 ///
7988 /// Returns an empty Optional if the type can't be expanded.
7989 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
7990 const MultiLevelTemplateArgumentList &TemplateArgs);
7991
7992 /// Determine whether the given declarator contains any unexpanded
7993 /// parameter packs.
7994 ///
7995 /// This routine is used by the parser to disambiguate function declarators
7996 /// with an ellipsis prior to the ')', e.g.,
7997 ///
7998 /// \code
7999 /// void f(T...);
8000 /// \endcode
8001 ///
8002 /// To determine whether we have an (unnamed) function parameter pack or
8003 /// a variadic function.
8004 ///
8005 /// \returns true if the declarator contains any unexpanded parameter packs,
8006 /// false otherwise.
8007 bool containsUnexpandedParameterPacks(Declarator &D);
8008
8009 /// Returns the pattern of the pack expansion for a template argument.
8010 ///
8011 /// \param OrigLoc The template argument to expand.
8012 ///
8013 /// \param Ellipsis Will be set to the location of the ellipsis.
8014 ///
8015 /// \param NumExpansions Will be set to the number of expansions that will
8016 /// be generated from this pack expansion, if known a priori.
8017 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
8018 TemplateArgumentLoc OrigLoc,
8019 SourceLocation &Ellipsis,
8020 Optional<unsigned> &NumExpansions) const;
8021
8022 /// Given a template argument that contains an unexpanded parameter pack, but
8023 /// which has already been substituted, attempt to determine the number of
8024 /// elements that will be produced once this argument is fully-expanded.
8025 ///
8026 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
8027 /// avoid actually expanding the pack where possible.
8028 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
8029
8030 //===--------------------------------------------------------------------===//
8031 // C++ Template Argument Deduction (C++ [temp.deduct])
8032 //===--------------------------------------------------------------------===//
8033
8034 /// Adjust the type \p ArgFunctionType to match the calling convention,
8035 /// noreturn, and optionally the exception specification of \p FunctionType.
8036 /// Deduction often wants to ignore these properties when matching function
8037 /// types.
8038 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
8039 bool AdjustExceptionSpec = false);
8040
8041 /// Describes the result of template argument deduction.
8042 ///
8043 /// The TemplateDeductionResult enumeration describes the result of
8044 /// template argument deduction, as returned from
8045 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
8046 /// structure provides additional information about the results of
8047 /// template argument deduction, e.g., the deduced template argument
8048 /// list (if successful) or the specific template parameters or
8049 /// deduced arguments that were involved in the failure.
8050 enum TemplateDeductionResult {
8051 /// Template argument deduction was successful.
8052 TDK_Success = 0,
8053 /// The declaration was invalid; do nothing.
8054 TDK_Invalid,
8055 /// Template argument deduction exceeded the maximum template
8056 /// instantiation depth (which has already been diagnosed).
8057 TDK_InstantiationDepth,
8058 /// Template argument deduction did not deduce a value
8059 /// for every template parameter.
8060 TDK_Incomplete,
8061 /// Template argument deduction did not deduce a value for every
8062 /// expansion of an expanded template parameter pack.
8063 TDK_IncompletePack,
8064 /// Template argument deduction produced inconsistent
8065 /// deduced values for the given template parameter.
8066 TDK_Inconsistent,
8067 /// Template argument deduction failed due to inconsistent
8068 /// cv-qualifiers on a template parameter type that would
8069 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
8070 /// but were given a non-const "X".
8071 TDK_Underqualified,
8072 /// Substitution of the deduced template argument values
8073 /// resulted in an error.
8074 TDK_SubstitutionFailure,
8075 /// After substituting deduced template arguments, a dependent
8076 /// parameter type did not match the corresponding argument.
8077 TDK_DeducedMismatch,
8078 /// After substituting deduced template arguments, an element of
8079 /// a dependent parameter type did not match the corresponding element
8080 /// of the corresponding argument (when deducing from an initializer list).
8081 TDK_DeducedMismatchNested,
8082 /// A non-depnedent component of the parameter did not match the
8083 /// corresponding component of the argument.
8084 TDK_NonDeducedMismatch,
8085 /// When performing template argument deduction for a function
8086 /// template, there were too many call arguments.
8087 TDK_TooManyArguments,
8088 /// When performing template argument deduction for a function
8089 /// template, there were too few call arguments.
8090 TDK_TooFewArguments,
8091 /// The explicitly-specified template arguments were not valid
8092 /// template arguments for the given template.
8093 TDK_InvalidExplicitArguments,
8094 /// Checking non-dependent argument conversions failed.
8095 TDK_NonDependentConversionFailure,
8096 /// The deduced arguments did not satisfy the constraints associated
8097 /// with the template.
8098 TDK_ConstraintsNotSatisfied,
8099 /// Deduction failed; that's all we know.
8100 TDK_MiscellaneousDeductionFailure,
8101 /// CUDA Target attributes do not match.
8102 TDK_CUDATargetMismatch
8103 };
8104
8105 TemplateDeductionResult
8106 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
8107 const TemplateArgumentList &TemplateArgs,
8108 sema::TemplateDeductionInfo &Info);
8109
8110 TemplateDeductionResult
8111 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
8112 const TemplateArgumentList &TemplateArgs,
8113 sema::TemplateDeductionInfo &Info);
8114
8115 TemplateDeductionResult SubstituteExplicitTemplateArguments(
8116 FunctionTemplateDecl *FunctionTemplate,
8117 TemplateArgumentListInfo &ExplicitTemplateArgs,
8118 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8119 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
8120 sema::TemplateDeductionInfo &Info);
8121
8122 /// brief A function argument from which we performed template argument
8123 // deduction for a call.
8124 struct OriginalCallArg {
8125 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
8126 unsigned ArgIdx, QualType OriginalArgType)
8127 : OriginalParamType(OriginalParamType),
8128 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
8129 OriginalArgType(OriginalArgType) {}
8130
8131 QualType OriginalParamType;
8132 bool DecomposedParam;
8133 unsigned ArgIdx;
8134 QualType OriginalArgType;
8135 };
8136
8137 TemplateDeductionResult FinishTemplateArgumentDeduction(
8138 FunctionTemplateDecl *FunctionTemplate,
8139 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8140 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
8141 sema::TemplateDeductionInfo &Info,
8142 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
8143 bool PartialOverloading = false,
8144 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
8145
8146 TemplateDeductionResult DeduceTemplateArguments(
8147 FunctionTemplateDecl *FunctionTemplate,
8148 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8149 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
8150 bool PartialOverloading,
8151 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
8152
8153 TemplateDeductionResult
8154 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8155 TemplateArgumentListInfo *ExplicitTemplateArgs,
8156 QualType ArgFunctionType,
8157 FunctionDecl *&Specialization,
8158 sema::TemplateDeductionInfo &Info,
8159 bool IsAddressOfFunction = false);
8160
8161 TemplateDeductionResult
8162 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8163 QualType ToType,
8164 CXXConversionDecl *&Specialization,
8165 sema::TemplateDeductionInfo &Info);
8166
8167 TemplateDeductionResult
8168 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8169 TemplateArgumentListInfo *ExplicitTemplateArgs,
8170 FunctionDecl *&Specialization,
8171 sema::TemplateDeductionInfo &Info,
8172 bool IsAddressOfFunction = false);
8173
8174 /// Substitute Replacement for \p auto in \p TypeWithAuto
8175 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
8176 /// Substitute Replacement for auto in TypeWithAuto
8177 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8178 QualType Replacement);
8179 /// Completely replace the \c auto in \p TypeWithAuto by
8180 /// \p Replacement. This does not retain any \c auto type sugar.
8181 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
8182 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8183 QualType Replacement);
8184
8185 /// Result type of DeduceAutoType.
8186 enum DeduceAutoResult {
8187 DAR_Succeeded,
8188 DAR_Failed,
8189 DAR_FailedAlreadyDiagnosed
8190 };
8191
8192 DeduceAutoResult
8193 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
8194 Optional<unsigned> DependentDeductionDepth = None,
8195 bool IgnoreConstraints = false);
8196 DeduceAutoResult
8197 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
8198 Optional<unsigned> DependentDeductionDepth = None,
8199 bool IgnoreConstraints = false);
8200 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
8201 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
8202 bool Diagnose = true);
8203
8204 /// Declare implicit deduction guides for a class template if we've
8205 /// not already done so.
8206 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
8207 SourceLocation Loc);
8208
8209 QualType DeduceTemplateSpecializationFromInitializer(
8210 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
8211 const InitializationKind &Kind, MultiExprArg Init);
8212
8213 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
8214 QualType Type, TypeSourceInfo *TSI,
8215 SourceRange Range, bool DirectInit,
8216 Expr *Init);
8217
8218 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
8219
8220 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
8221 SourceLocation ReturnLoc,
8222 Expr *&RetExpr, AutoType *AT);
8223
8224 FunctionTemplateDecl *getMoreSpecializedTemplate(
8225 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
8226 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
8227 unsigned NumCallArguments2, bool Reversed = false);
8228 UnresolvedSetIterator
8229 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
8230 TemplateSpecCandidateSet &FailedCandidates,
8231 SourceLocation Loc,
8232 const PartialDiagnostic &NoneDiag,
8233 const PartialDiagnostic &AmbigDiag,
8234 const PartialDiagnostic &CandidateDiag,
8235 bool Complain = true, QualType TargetType = QualType());
8236
8237 ClassTemplatePartialSpecializationDecl *
8238 getMoreSpecializedPartialSpecialization(
8239 ClassTemplatePartialSpecializationDecl *PS1,
8240 ClassTemplatePartialSpecializationDecl *PS2,
8241 SourceLocation Loc);
8242
8243 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
8244 sema::TemplateDeductionInfo &Info);
8245
8246 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
8247 VarTemplatePartialSpecializationDecl *PS1,
8248 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
8249
8250 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
8251 sema::TemplateDeductionInfo &Info);
8252
8253 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
8254 TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
8255
8256 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
8257 unsigned Depth, llvm::SmallBitVector &Used);
8258
8259 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
8260 bool OnlyDeduced,
8261 unsigned Depth,
8262 llvm::SmallBitVector &Used);
8263 void MarkDeducedTemplateParameters(
8264 const FunctionTemplateDecl *FunctionTemplate,
8265 llvm::SmallBitVector &Deduced) {
8266 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
8267 }
8268 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
8269 const FunctionTemplateDecl *FunctionTemplate,
8270 llvm::SmallBitVector &Deduced);
8271
8272 //===--------------------------------------------------------------------===//
8273 // C++ Template Instantiation
8274 //
8275
8276 MultiLevelTemplateArgumentList
8277 getTemplateInstantiationArgs(NamedDecl *D,
8278 const TemplateArgumentList *Innermost = nullptr,
8279 bool RelativeToPrimary = false,
8280 const FunctionDecl *Pattern = nullptr);
8281
8282 /// A context in which code is being synthesized (where a source location
8283 /// alone is not sufficient to identify the context). This covers template
8284 /// instantiation and various forms of implicitly-generated functions.
8285 struct CodeSynthesisContext {
8286 /// The kind of template instantiation we are performing
8287 enum SynthesisKind {
8288 /// We are instantiating a template declaration. The entity is
8289 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
8290 TemplateInstantiation,
8291
8292 /// We are instantiating a default argument for a template
8293 /// parameter. The Entity is the template parameter whose argument is
8294 /// being instantiated, the Template is the template, and the
8295 /// TemplateArgs/NumTemplateArguments provide the template arguments as
8296 /// specified.
8297 DefaultTemplateArgumentInstantiation,
8298
8299 /// We are instantiating a default argument for a function.
8300 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
8301 /// provides the template arguments as specified.
8302 DefaultFunctionArgumentInstantiation,
8303
8304 /// We are substituting explicit template arguments provided for
8305 /// a function template. The entity is a FunctionTemplateDecl.
8306 ExplicitTemplateArgumentSubstitution,
8307
8308 /// We are substituting template argument determined as part of
8309 /// template argument deduction for either a class template
8310 /// partial specialization or a function template. The
8311 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
8312 /// a TemplateDecl.
8313 DeducedTemplateArgumentSubstitution,
8314
8315 /// We are substituting prior template arguments into a new
8316 /// template parameter. The template parameter itself is either a
8317 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
8318 PriorTemplateArgumentSubstitution,
8319
8320 /// We are checking the validity of a default template argument that
8321 /// has been used when naming a template-id.
8322 DefaultTemplateArgumentChecking,
8323
8324 /// We are computing the exception specification for a defaulted special
8325 /// member function.
8326 ExceptionSpecEvaluation,
8327
8328 /// We are instantiating the exception specification for a function
8329 /// template which was deferred until it was needed.
8330 ExceptionSpecInstantiation,
8331
8332 /// We are instantiating a requirement of a requires expression.
8333 RequirementInstantiation,
8334
8335 /// We are checking the satisfaction of a nested requirement of a requires
8336 /// expression.
8337 NestedRequirementConstraintsCheck,
8338
8339 /// We are declaring an implicit special member function.
8340 DeclaringSpecialMember,
8341
8342 /// We are declaring an implicit 'operator==' for a defaulted
8343 /// 'operator<=>'.
8344 DeclaringImplicitEqualityComparison,
8345
8346 /// We are defining a synthesized function (such as a defaulted special
8347 /// member).
8348 DefiningSynthesizedFunction,
8349
8350 // We are checking the constraints associated with a constrained entity or
8351 // the constraint expression of a concept. This includes the checks that
8352 // atomic constraints have the type 'bool' and that they can be constant
8353 // evaluated.
8354 ConstraintsCheck,
8355
8356 // We are substituting template arguments into a constraint expression.
8357 ConstraintSubstitution,
8358
8359 // We are normalizing a constraint expression.
8360 ConstraintNormalization,
8361
8362 // We are substituting into the parameter mapping of an atomic constraint
8363 // during normalization.
8364 ParameterMappingSubstitution,
8365
8366 /// We are rewriting a comparison operator in terms of an operator<=>.
8367 RewritingOperatorAsSpaceship,
8368
8369 /// We are initializing a structured binding.
8370 InitializingStructuredBinding,
8371
8372 /// We are marking a class as __dllexport.
8373 MarkingClassDllexported,
8374
8375 /// Added for Template instantiation observation.
8376 /// Memoization means we are _not_ instantiating a template because
8377 /// it is already instantiated (but we entered a context where we
8378 /// would have had to if it was not already instantiated).
8379 Memoization
8380 } Kind;
8381
8382 /// Was the enclosing context a non-instantiation SFINAE context?
8383 bool SavedInNonInstantiationSFINAEContext;
8384
8385 /// The point of instantiation or synthesis within the source code.
8386 SourceLocation PointOfInstantiation;
8387
8388 /// The entity that is being synthesized.
8389 Decl *Entity;
8390
8391 /// The template (or partial specialization) in which we are
8392 /// performing the instantiation, for substitutions of prior template
8393 /// arguments.
8394 NamedDecl *Template;
8395
8396 /// The list of template arguments we are substituting, if they
8397 /// are not part of the entity.
8398 const TemplateArgument *TemplateArgs;
8399
8400 // FIXME: Wrap this union around more members, or perhaps store the
8401 // kind-specific members in the RAII object owning the context.
8402 union {
8403 /// The number of template arguments in TemplateArgs.
8404 unsigned NumTemplateArgs;
8405
8406 /// The special member being declared or defined.
8407 CXXSpecialMember SpecialMember;
8408 };
8409
8410 ArrayRef<TemplateArgument> template_arguments() const {
8411 assert(Kind != DeclaringSpecialMember)((Kind != DeclaringSpecialMember) ? static_cast<void> (
0) : __assert_fail ("Kind != DeclaringSpecialMember", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 8411, __PRETTY_FUNCTION__))
;
8412 return {TemplateArgs, NumTemplateArgs};
8413 }
8414
8415 /// The template deduction info object associated with the
8416 /// substitution or checking of explicit or deduced template arguments.
8417 sema::TemplateDeductionInfo *DeductionInfo;
8418
8419 /// The source range that covers the construct that cause
8420 /// the instantiation, e.g., the template-id that causes a class
8421 /// template instantiation.
8422 SourceRange InstantiationRange;
8423
8424 CodeSynthesisContext()
8425 : Kind(TemplateInstantiation),
8426 SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
8427 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
8428 DeductionInfo(nullptr) {}
8429
8430 /// Determines whether this template is an actual instantiation
8431 /// that should be counted toward the maximum instantiation depth.
8432 bool isInstantiationRecord() const;
8433 };
8434
8435 /// List of active code synthesis contexts.
8436 ///
8437 /// This vector is treated as a stack. As synthesis of one entity requires
8438 /// synthesis of another, additional contexts are pushed onto the stack.
8439 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
8440
8441 /// Specializations whose definitions are currently being instantiated.
8442 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
8443
8444 /// Non-dependent types used in templates that have already been instantiated
8445 /// by some template instantiation.
8446 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
8447
8448 /// Extra modules inspected when performing a lookup during a template
8449 /// instantiation. Computed lazily.
8450 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
8451
8452 /// Cache of additional modules that should be used for name lookup
8453 /// within the current template instantiation. Computed lazily; use
8454 /// getLookupModules() to get a complete set.
8455 llvm::DenseSet<Module*> LookupModulesCache;
8456
8457 /// Get the set of additional modules that should be checked during
8458 /// name lookup. A module and its imports become visible when instanting a
8459 /// template defined within it.
8460 llvm::DenseSet<Module*> &getLookupModules();
8461
8462 /// Map from the most recent declaration of a namespace to the most
8463 /// recent visible declaration of that namespace.
8464 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
8465
8466 /// Whether we are in a SFINAE context that is not associated with
8467 /// template instantiation.
8468 ///
8469 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
8470 /// of a template instantiation or template argument deduction.
8471 bool InNonInstantiationSFINAEContext;
8472
8473 /// The number of \p CodeSynthesisContexts that are not template
8474 /// instantiations and, therefore, should not be counted as part of the
8475 /// instantiation depth.
8476 ///
8477 /// When the instantiation depth reaches the user-configurable limit
8478 /// \p LangOptions::InstantiationDepth we will abort instantiation.
8479 // FIXME: Should we have a similar limit for other forms of synthesis?
8480 unsigned NonInstantiationEntries;
8481
8482 /// The depth of the context stack at the point when the most recent
8483 /// error or warning was produced.
8484 ///
8485 /// This value is used to suppress printing of redundant context stacks
8486 /// when there are multiple errors or warnings in the same instantiation.
8487 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
8488 unsigned LastEmittedCodeSynthesisContextDepth = 0;
8489
8490 /// The template instantiation callbacks to trace or track
8491 /// instantiations (objects can be chained).
8492 ///
8493 /// This callbacks is used to print, trace or track template
8494 /// instantiations as they are being constructed.
8495 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
8496 TemplateInstCallbacks;
8497
8498 /// The current index into pack expansion arguments that will be
8499 /// used for substitution of parameter packs.
8500 ///
8501 /// The pack expansion index will be -1 to indicate that parameter packs
8502 /// should be instantiated as themselves. Otherwise, the index specifies
8503 /// which argument within the parameter pack will be used for substitution.
8504 int ArgumentPackSubstitutionIndex;
8505
8506 /// RAII object used to change the argument pack substitution index
8507 /// within a \c Sema object.
8508 ///
8509 /// See \c ArgumentPackSubstitutionIndex for more information.
8510 class ArgumentPackSubstitutionIndexRAII {
8511 Sema &Self;
8512 int OldSubstitutionIndex;
8513
8514 public:
8515 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
8516 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
8517 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
8518 }
8519
8520 ~ArgumentPackSubstitutionIndexRAII() {
8521 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
8522 }
8523 };
8524
8525 friend class ArgumentPackSubstitutionRAII;
8526
8527 /// For each declaration that involved template argument deduction, the
8528 /// set of diagnostics that were suppressed during that template argument
8529 /// deduction.
8530 ///
8531 /// FIXME: Serialize this structure to the AST file.
8532 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
8533 SuppressedDiagnosticsMap;
8534 SuppressedDiagnosticsMap SuppressedDiagnostics;
8535
8536 /// A stack object to be created when performing template
8537 /// instantiation.
8538 ///
8539 /// Construction of an object of type \c InstantiatingTemplate
8540 /// pushes the current instantiation onto the stack of active
8541 /// instantiations. If the size of this stack exceeds the maximum
8542 /// number of recursive template instantiations, construction
8543 /// produces an error and evaluates true.
8544 ///
8545 /// Destruction of this object will pop the named instantiation off
8546 /// the stack.
8547 struct InstantiatingTemplate {
8548 /// Note that we are instantiating a class template,
8549 /// function template, variable template, alias template,
8550 /// or a member thereof.
8551 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8552 Decl *Entity,
8553 SourceRange InstantiationRange = SourceRange());
8554
8555 struct ExceptionSpecification {};
8556 /// Note that we are instantiating an exception specification
8557 /// of a function template.
8558 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8559 FunctionDecl *Entity, ExceptionSpecification,
8560 SourceRange InstantiationRange = SourceRange());
8561
8562 /// Note that we are instantiating a default argument in a
8563 /// template-id.
8564 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8565 TemplateParameter Param, TemplateDecl *Template,
8566 ArrayRef<TemplateArgument> TemplateArgs,
8567 SourceRange InstantiationRange = SourceRange());
8568
8569 /// Note that we are substituting either explicitly-specified or
8570 /// deduced template arguments during function template argument deduction.
8571 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8572 FunctionTemplateDecl *FunctionTemplate,
8573 ArrayRef<TemplateArgument> TemplateArgs,
8574 CodeSynthesisContext::SynthesisKind Kind,
8575 sema::TemplateDeductionInfo &DeductionInfo,
8576 SourceRange InstantiationRange = SourceRange());
8577
8578 /// Note that we are instantiating as part of template
8579 /// argument deduction for a class template declaration.
8580 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8581 TemplateDecl *Template,
8582 ArrayRef<TemplateArgument> TemplateArgs,
8583 sema::TemplateDeductionInfo &DeductionInfo,
8584 SourceRange InstantiationRange = SourceRange());
8585
8586 /// Note that we are instantiating as part of template
8587 /// argument deduction for a class template partial
8588 /// specialization.
8589 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8590 ClassTemplatePartialSpecializationDecl *PartialSpec,
8591 ArrayRef<TemplateArgument> TemplateArgs,
8592 sema::TemplateDeductionInfo &DeductionInfo,
8593 SourceRange InstantiationRange = SourceRange());
8594
8595 /// Note that we are instantiating as part of template
8596 /// argument deduction for a variable template partial
8597 /// specialization.
8598 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8599 VarTemplatePartialSpecializationDecl *PartialSpec,
8600 ArrayRef<TemplateArgument> TemplateArgs,
8601 sema::TemplateDeductionInfo &DeductionInfo,
8602 SourceRange InstantiationRange = SourceRange());
8603
8604 /// Note that we are instantiating a default argument for a function
8605 /// parameter.
8606 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8607 ParmVarDecl *Param,
8608 ArrayRef<TemplateArgument> TemplateArgs,
8609 SourceRange InstantiationRange = SourceRange());
8610
8611 /// Note that we are substituting prior template arguments into a
8612 /// non-type parameter.
8613 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8614 NamedDecl *Template,
8615 NonTypeTemplateParmDecl *Param,
8616 ArrayRef<TemplateArgument> TemplateArgs,
8617 SourceRange InstantiationRange);
8618
8619 /// Note that we are substituting prior template arguments into a
8620 /// template template parameter.
8621 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8622 NamedDecl *Template,
8623 TemplateTemplateParmDecl *Param,
8624 ArrayRef<TemplateArgument> TemplateArgs,
8625 SourceRange InstantiationRange);
8626
8627 /// Note that we are checking the default template argument
8628 /// against the template parameter for a given template-id.
8629 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8630 TemplateDecl *Template,
8631 NamedDecl *Param,
8632 ArrayRef<TemplateArgument> TemplateArgs,
8633 SourceRange InstantiationRange);
8634
8635 struct ConstraintsCheck {};
8636 /// \brief Note that we are checking the constraints associated with some
8637 /// constrained entity (a concept declaration or a template with associated
8638 /// constraints).
8639 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8640 ConstraintsCheck, NamedDecl *Template,
8641 ArrayRef<TemplateArgument> TemplateArgs,
8642 SourceRange InstantiationRange);
8643
8644 struct ConstraintSubstitution {};
8645 /// \brief Note that we are checking a constraint expression associated
8646 /// with a template declaration or as part of the satisfaction check of a
8647 /// concept.
8648 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8649 ConstraintSubstitution, NamedDecl *Template,
8650 sema::TemplateDeductionInfo &DeductionInfo,
8651 SourceRange InstantiationRange);
8652
8653 struct ConstraintNormalization {};
8654 /// \brief Note that we are normalizing a constraint expression.
8655 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8656 ConstraintNormalization, NamedDecl *Template,
8657 SourceRange InstantiationRange);
8658
8659 struct ParameterMappingSubstitution {};
8660 /// \brief Note that we are subtituting into the parameter mapping of an
8661 /// atomic constraint during constraint normalization.
8662 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8663 ParameterMappingSubstitution, NamedDecl *Template,
8664 SourceRange InstantiationRange);
8665
8666 /// \brief Note that we are substituting template arguments into a part of
8667 /// a requirement of a requires expression.
8668 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8669 concepts::Requirement *Req,
8670 sema::TemplateDeductionInfo &DeductionInfo,
8671 SourceRange InstantiationRange = SourceRange());
8672
8673 /// \brief Note that we are checking the satisfaction of the constraint
8674 /// expression inside of a nested requirement.
8675 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8676 concepts::NestedRequirement *Req, ConstraintsCheck,
8677 SourceRange InstantiationRange = SourceRange());
8678
8679 /// Note that we have finished instantiating this template.
8680 void Clear();
8681
8682 ~InstantiatingTemplate() { Clear(); }
8683
8684 /// Determines whether we have exceeded the maximum
8685 /// recursive template instantiations.
8686 bool isInvalid() const { return Invalid; }
8687
8688 /// Determine whether we are already instantiating this
8689 /// specialization in some surrounding active instantiation.
8690 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
8691
8692 private:
8693 Sema &SemaRef;
8694 bool Invalid;
8695 bool AlreadyInstantiating;
8696 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
8697 SourceRange InstantiationRange);
8698
8699 InstantiatingTemplate(
8700 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
8701 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
8702 Decl *Entity, NamedDecl *Template = nullptr,
8703 ArrayRef<TemplateArgument> TemplateArgs = None,
8704 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
8705
8706 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
8707
8708 InstantiatingTemplate&
8709 operator=(const InstantiatingTemplate&) = delete;
8710 };
8711
8712 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
8713 void popCodeSynthesisContext();
8714
8715 /// Determine whether we are currently performing template instantiation.
8716 bool inTemplateInstantiation() const {
8717 return CodeSynthesisContexts.size() > NonInstantiationEntries;
8718 }
8719
8720 void PrintContextStack() {
8721 if (!CodeSynthesisContexts.empty() &&
8722 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
8723 PrintInstantiationStack();
8724 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
8725 }
8726 if (PragmaAttributeCurrentTargetDecl)
8727 PrintPragmaAttributeInstantiationPoint();
8728 }
8729 void PrintInstantiationStack();
8730
8731 void PrintPragmaAttributeInstantiationPoint();
8732
8733 /// Determines whether we are currently in a context where
8734 /// template argument substitution failures are not considered
8735 /// errors.
8736 ///
8737 /// \returns An empty \c Optional if we're not in a SFINAE context.
8738 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
8739 /// template-deduction context object, which can be used to capture
8740 /// diagnostics that will be suppressed.
8741 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
8742
8743 /// Determines whether we are currently in a context that
8744 /// is not evaluated as per C++ [expr] p5.
8745 bool isUnevaluatedContext() const {
8746 assert(!ExprEvalContexts.empty() &&((!ExprEvalContexts.empty() && "Must be in an expression evaluation context"
) ? static_cast<void> (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 8747, __PRETTY_FUNCTION__))
8747 "Must be in an expression evaluation context")((!ExprEvalContexts.empty() && "Must be in an expression evaluation context"
) ? static_cast<void> (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 8747, __PRETTY_FUNCTION__))
;
8748 return ExprEvalContexts.back().isUnevaluated();
8749 }
8750
8751 /// RAII class used to determine whether SFINAE has
8752 /// trapped any errors that occur during template argument
8753 /// deduction.
8754 class SFINAETrap {
8755 Sema &SemaRef;
8756 unsigned PrevSFINAEErrors;
8757 bool PrevInNonInstantiationSFINAEContext;
8758 bool PrevAccessCheckingSFINAE;
8759 bool PrevLastDiagnosticIgnored;
8760
8761 public:
8762 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
8763 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
8764 PrevInNonInstantiationSFINAEContext(
8765 SemaRef.InNonInstantiationSFINAEContext),
8766 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
8767 PrevLastDiagnosticIgnored(
8768 SemaRef.getDiagnostics().isLastDiagnosticIgnored())
8769 {
8770 if (!SemaRef.isSFINAEContext())
8771 SemaRef.InNonInstantiationSFINAEContext = true;
8772 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
8773 }
8774
8775 ~SFINAETrap() {
8776 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
8777 SemaRef.InNonInstantiationSFINAEContext
8778 = PrevInNonInstantiationSFINAEContext;
8779 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
8780 SemaRef.getDiagnostics().setLastDiagnosticIgnored(
8781 PrevLastDiagnosticIgnored);
8782 }
8783
8784 /// Determine whether any SFINAE errors have been trapped.
8785 bool hasErrorOccurred() const {
8786 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
8787 }
8788 };
8789
8790 /// RAII class used to indicate that we are performing provisional
8791 /// semantic analysis to determine the validity of a construct, so
8792 /// typo-correction and diagnostics in the immediate context (not within
8793 /// implicitly-instantiated templates) should be suppressed.
8794 class TentativeAnalysisScope {
8795 Sema &SemaRef;
8796 // FIXME: Using a SFINAETrap for this is a hack.
8797 SFINAETrap Trap;
8798 bool PrevDisableTypoCorrection;
8799 public:
8800 explicit TentativeAnalysisScope(Sema &SemaRef)
8801 : SemaRef(SemaRef), Trap(SemaRef, true),
8802 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
8803 SemaRef.DisableTypoCorrection = true;
8804 }
8805 ~TentativeAnalysisScope() {
8806 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
8807 }
8808 };
8809
8810 /// The current instantiation scope used to store local
8811 /// variables.
8812 LocalInstantiationScope *CurrentInstantiationScope;
8813
8814 /// Tracks whether we are in a context where typo correction is
8815 /// disabled.
8816 bool DisableTypoCorrection;
8817
8818 /// The number of typos corrected by CorrectTypo.
8819 unsigned TyposCorrected;
8820
8821 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
8822 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
8823
8824 /// A cache containing identifiers for which typo correction failed and
8825 /// their locations, so that repeated attempts to correct an identifier in a
8826 /// given location are ignored if typo correction already failed for it.
8827 IdentifierSourceLocations TypoCorrectionFailures;
8828
8829 /// Worker object for performing CFG-based warnings.
8830 sema::AnalysisBasedWarnings AnalysisWarnings;
8831 threadSafety::BeforeSet *ThreadSafetyDeclCache;
8832
8833 /// An entity for which implicit template instantiation is required.
8834 ///
8835 /// The source location associated with the declaration is the first place in
8836 /// the source code where the declaration was "used". It is not necessarily
8837 /// the point of instantiation (which will be either before or after the
8838 /// namespace-scope declaration that triggered this implicit instantiation),
8839 /// However, it is the location that diagnostics should generally refer to,
8840 /// because users will need to know what code triggered the instantiation.
8841 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
8842
8843 /// The queue of implicit template instantiations that are required
8844 /// but have not yet been performed.
8845 std::deque<PendingImplicitInstantiation> PendingInstantiations;
8846
8847 /// Queue of implicit template instantiations that cannot be performed
8848 /// eagerly.
8849 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
8850
8851 class GlobalEagerInstantiationScope {
8852 public:
8853 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
8854 : S(S), Enabled(Enabled) {
8855 if (!Enabled) return;
8856
8857 SavedPendingInstantiations.swap(S.PendingInstantiations);
8858 SavedVTableUses.swap(S.VTableUses);
8859 }
8860
8861 void perform() {
8862 if (Enabled) {
33
Assuming field 'Enabled' is true
34
Taking true branch
8863 S.DefineUsedVTables();
8864 S.PerformPendingInstantiations();
35
Calling 'Sema::PerformPendingInstantiations'
8865 }
8866 }
8867
8868 ~GlobalEagerInstantiationScope() {
8869 if (!Enabled) return;
8870
8871 // Restore the set of pending vtables.
8872 assert(S.VTableUses.empty() &&((S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 8873, __PRETTY_FUNCTION__))
8873 "VTableUses should be empty before it is discarded.")((S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 8873, __PRETTY_FUNCTION__))
;
8874 S.VTableUses.swap(SavedVTableUses);
8875
8876 // Restore the set of pending implicit instantiations.
8877 if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) {
8878 assert(S.PendingInstantiations.empty() &&((S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 8879, __PRETTY_FUNCTION__))
8879 "PendingInstantiations should be empty before it is discarded.")((S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 8879, __PRETTY_FUNCTION__))
;
8880 S.PendingInstantiations.swap(SavedPendingInstantiations);
8881 } else {
8882 // Template instantiations in the PCH may be delayed until the TU.
8883 S.PendingInstantiations.swap(SavedPendingInstantiations);
8884 S.PendingInstantiations.insert(S.PendingInstantiations.end(),
8885 SavedPendingInstantiations.begin(),
8886 SavedPendingInstantiations.end());
8887 }
8888 }
8889
8890 private:
8891 Sema &S;
8892 SmallVector<VTableUse, 16> SavedVTableUses;
8893 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
8894 bool Enabled;
8895 };
8896
8897 /// The queue of implicit template instantiations that are required
8898 /// and must be performed within the current local scope.
8899 ///
8900 /// This queue is only used for member functions of local classes in
8901 /// templates, which must be instantiated in the same scope as their
8902 /// enclosing function, so that they can reference function-local
8903 /// types, static variables, enumerators, etc.
8904 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
8905
8906 class LocalEagerInstantiationScope {
8907 public:
8908 LocalEagerInstantiationScope(Sema &S) : S(S) {
8909 SavedPendingLocalImplicitInstantiations.swap(
8910 S.PendingLocalImplicitInstantiations);
8911 }
8912
8913 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
8914
8915 ~LocalEagerInstantiationScope() {
8916 assert(S.PendingLocalImplicitInstantiations.empty() &&((S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"
) ? static_cast<void> (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 8917, __PRETTY_FUNCTION__))
8917 "there shouldn't be any pending local implicit instantiations")((S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"
) ? static_cast<void> (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 8917, __PRETTY_FUNCTION__))
;
8918 SavedPendingLocalImplicitInstantiations.swap(
8919 S.PendingLocalImplicitInstantiations);
8920 }
8921
8922 private:
8923 Sema &S;
8924 std::deque<PendingImplicitInstantiation>
8925 SavedPendingLocalImplicitInstantiations;
8926 };
8927
8928 /// A helper class for building up ExtParameterInfos.
8929 class ExtParameterInfoBuilder {
8930 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
8931 bool HasInteresting = false;
8932
8933 public:
8934 /// Set the ExtParameterInfo for the parameter at the given index,
8935 ///
8936 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
8937 assert(Infos.size() <= index)((Infos.size() <= index) ? static_cast<void> (0) : __assert_fail
("Infos.size() <= index", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 8937, __PRETTY_FUNCTION__))
;
8938 Infos.resize(index);
8939 Infos.push_back(info);
8940
8941 if (!HasInteresting)
8942 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
8943 }
8944
8945 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
8946 /// ExtParameterInfo array we've built up.
8947 const FunctionProtoType::ExtParameterInfo *
8948 getPointerOrNull(unsigned numParams) {
8949 if (!HasInteresting) return nullptr;
8950 Infos.resize(numParams);
8951 return Infos.data();
8952 }
8953 };
8954
8955 void PerformPendingInstantiations(bool LocalOnly = false);
8956
8957 TypeSourceInfo *SubstType(TypeSourceInfo *T,
8958 const MultiLevelTemplateArgumentList &TemplateArgs,
8959 SourceLocation Loc, DeclarationName Entity,
8960 bool AllowDeducedTST = false);
8961
8962 QualType SubstType(QualType T,
8963 const MultiLevelTemplateArgumentList &TemplateArgs,
8964 SourceLocation Loc, DeclarationName Entity);
8965
8966 TypeSourceInfo *SubstType(TypeLoc TL,
8967 const MultiLevelTemplateArgumentList &TemplateArgs,
8968 SourceLocation Loc, DeclarationName Entity);
8969
8970 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
8971 const MultiLevelTemplateArgumentList &TemplateArgs,
8972 SourceLocation Loc,
8973 DeclarationName Entity,
8974 CXXRecordDecl *ThisContext,
8975 Qualifiers ThisTypeQuals);
8976 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
8977 const MultiLevelTemplateArgumentList &Args);
8978 bool SubstExceptionSpec(SourceLocation Loc,
8979 FunctionProtoType::ExceptionSpecInfo &ESI,
8980 SmallVectorImpl<QualType> &ExceptionStorage,
8981 const MultiLevelTemplateArgumentList &Args);
8982 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
8983 const MultiLevelTemplateArgumentList &TemplateArgs,
8984 int indexAdjustment,
8985 Optional<unsigned> NumExpansions,
8986 bool ExpectParameterPack);
8987 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
8988 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
8989 const MultiLevelTemplateArgumentList &TemplateArgs,
8990 SmallVectorImpl<QualType> &ParamTypes,
8991 SmallVectorImpl<ParmVarDecl *> *OutParams,
8992 ExtParameterInfoBuilder &ParamInfos);
8993 ExprResult SubstExpr(Expr *E,
8994 const MultiLevelTemplateArgumentList &TemplateArgs);
8995
8996 /// Substitute the given template arguments into a list of
8997 /// expressions, expanding pack expansions if required.
8998 ///
8999 /// \param Exprs The list of expressions to substitute into.
9000 ///
9001 /// \param IsCall Whether this is some form of call, in which case
9002 /// default arguments will be dropped.
9003 ///
9004 /// \param TemplateArgs The set of template arguments to substitute.
9005 ///
9006 /// \param Outputs Will receive all of the substituted arguments.
9007 ///
9008 /// \returns true if an error occurred, false otherwise.
9009 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
9010 const MultiLevelTemplateArgumentList &TemplateArgs,
9011 SmallVectorImpl<Expr *> &Outputs);
9012
9013 StmtResult SubstStmt(Stmt *S,
9014 const MultiLevelTemplateArgumentList &TemplateArgs);
9015
9016 TemplateParameterList *
9017 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
9018 const MultiLevelTemplateArgumentList &TemplateArgs);
9019
9020 bool
9021 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
9022 const MultiLevelTemplateArgumentList &TemplateArgs,
9023 TemplateArgumentListInfo &Outputs);
9024
9025
9026 Decl *SubstDecl(Decl *D, DeclContext *Owner,
9027 const MultiLevelTemplateArgumentList &TemplateArgs);
9028
9029 /// Substitute the name and return type of a defaulted 'operator<=>' to form
9030 /// an implicit 'operator=='.
9031 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
9032 FunctionDecl *Spaceship);
9033
9034 ExprResult SubstInitializer(Expr *E,
9035 const MultiLevelTemplateArgumentList &TemplateArgs,
9036 bool CXXDirectInit);
9037
9038 bool
9039 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
9040 CXXRecordDecl *Pattern,
9041 const MultiLevelTemplateArgumentList &TemplateArgs);
9042
9043 bool
9044 InstantiateClass(SourceLocation PointOfInstantiation,
9045 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
9046 const MultiLevelTemplateArgumentList &TemplateArgs,
9047 TemplateSpecializationKind TSK,
9048 bool Complain = true);
9049
9050 bool InstantiateEnum(SourceLocation PointOfInstantiation,
9051 EnumDecl *Instantiation, EnumDecl *Pattern,
9052 const MultiLevelTemplateArgumentList &TemplateArgs,
9053 TemplateSpecializationKind TSK);
9054
9055 bool InstantiateInClassInitializer(
9056 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
9057 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
9058
9059 struct LateInstantiatedAttribute {
9060 const Attr *TmplAttr;
9061 LocalInstantiationScope *Scope;
9062 Decl *NewDecl;
9063
9064 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
9065 Decl *D)
9066 : TmplAttr(A), Scope(S), NewDecl(D)
9067 { }
9068 };
9069 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
9070
9071 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
9072 const Decl *Pattern, Decl *Inst,
9073 LateInstantiatedAttrVec *LateAttrs = nullptr,
9074 LocalInstantiationScope *OuterMostScope = nullptr);
9075
9076 void
9077 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
9078 const Decl *Pattern, Decl *Inst,
9079 LateInstantiatedAttrVec *LateAttrs = nullptr,
9080 LocalInstantiationScope *OuterMostScope = nullptr);
9081
9082 bool usesPartialOrExplicitSpecialization(
9083 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
9084
9085 bool
9086 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
9087 ClassTemplateSpecializationDecl *ClassTemplateSpec,
9088 TemplateSpecializationKind TSK,
9089 bool Complain = true);
9090
9091 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
9092 CXXRecordDecl *Instantiation,
9093 const MultiLevelTemplateArgumentList &TemplateArgs,
9094 TemplateSpecializationKind TSK);
9095
9096 void InstantiateClassTemplateSpecializationMembers(
9097 SourceLocation PointOfInstantiation,
9098 ClassTemplateSpecializationDecl *ClassTemplateSpec,
9099 TemplateSpecializationKind TSK);
9100
9101 NestedNameSpecifierLoc
9102 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
9103 const MultiLevelTemplateArgumentList &TemplateArgs);
9104
9105 DeclarationNameInfo
9106 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
9107 const MultiLevelTemplateArgumentList &TemplateArgs);
9108 TemplateName
9109 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
9110 SourceLocation Loc,
9111 const MultiLevelTemplateArgumentList &TemplateArgs);
9112 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
9113 TemplateArgumentListInfo &Result,
9114 const MultiLevelTemplateArgumentList &TemplateArgs);
9115
9116 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
9117 ParmVarDecl *Param);
9118 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
9119 FunctionDecl *Function);
9120 bool CheckInstantiatedFunctionTemplateConstraints(
9121 SourceLocation PointOfInstantiation, FunctionDecl *Decl,
9122 ArrayRef<TemplateArgument> TemplateArgs,
9123 ConstraintSatisfaction &Satisfaction);
9124 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
9125 const TemplateArgumentList *Args,
9126 SourceLocation Loc);
9127 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
9128 FunctionDecl *Function,
9129 bool Recursive = false,
9130 bool DefinitionRequired = false,
9131 bool AtEndOfTU = false);
9132 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
9133 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
9134 const TemplateArgumentList &TemplateArgList,
9135 const TemplateArgumentListInfo &TemplateArgsInfo,
9136 SmallVectorImpl<TemplateArgument> &Converted,
9137 SourceLocation PointOfInstantiation, void *InsertPos,
9138 LateInstantiatedAttrVec *LateAttrs = nullptr,
9139 LocalInstantiationScope *StartingScope = nullptr);
9140 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
9141 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
9142 const MultiLevelTemplateArgumentList &TemplateArgs);
9143 void
9144 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
9145 const MultiLevelTemplateArgumentList &TemplateArgs,
9146 LateInstantiatedAttrVec *LateAttrs,
9147 DeclContext *Owner,
9148 LocalInstantiationScope *StartingScope,
9149 bool InstantiatingVarTemplate = false,
9150 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
9151
9152 VarDecl *getVarTemplateSpecialization(
9153 VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs,
9154 const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc);
9155
9156 void InstantiateVariableInitializer(
9157 VarDecl *Var, VarDecl *OldVar,
9158 const MultiLevelTemplateArgumentList &TemplateArgs);
9159 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
9160 VarDecl *Var, bool Recursive = false,
9161 bool DefinitionRequired = false,
9162 bool AtEndOfTU = false);
9163
9164 void InstantiateMemInitializers(CXXConstructorDecl *New,
9165 const CXXConstructorDecl *Tmpl,
9166 const MultiLevelTemplateArgumentList &TemplateArgs);
9167
9168 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
9169 const MultiLevelTemplateArgumentList &TemplateArgs,
9170 bool FindingInstantiatedContext = false);
9171 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
9172 const MultiLevelTemplateArgumentList &TemplateArgs);
9173
9174 // Objective-C declarations.
9175 enum ObjCContainerKind {
9176 OCK_None = -1,
9177 OCK_Interface = 0,
9178 OCK_Protocol,
9179 OCK_Category,
9180 OCK_ClassExtension,
9181 OCK_Implementation,
9182 OCK_CategoryImplementation
9183 };
9184 ObjCContainerKind getObjCContainerKind() const;
9185
9186 DeclResult actOnObjCTypeParam(Scope *S,
9187 ObjCTypeParamVariance variance,
9188 SourceLocation varianceLoc,
9189 unsigned index,
9190 IdentifierInfo *paramName,
9191 SourceLocation paramLoc,
9192 SourceLocation colonLoc,
9193 ParsedType typeBound);
9194
9195 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
9196 ArrayRef<Decl *> typeParams,
9197 SourceLocation rAngleLoc);
9198 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
9199
9200 Decl *ActOnStartClassInterface(
9201 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9202 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9203 IdentifierInfo *SuperName, SourceLocation SuperLoc,
9204 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
9205 Decl *const *ProtoRefs, unsigned NumProtoRefs,
9206 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9207 const ParsedAttributesView &AttrList);
9208
9209 void ActOnSuperClassOfClassInterface(Scope *S,
9210 SourceLocation AtInterfaceLoc,
9211 ObjCInterfaceDecl *IDecl,
9212 IdentifierInfo *ClassName,
9213 SourceLocation ClassLoc,
9214 IdentifierInfo *SuperName,
9215 SourceLocation SuperLoc,
9216 ArrayRef<ParsedType> SuperTypeArgs,
9217 SourceRange SuperTypeArgsRange);
9218
9219 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
9220 SmallVectorImpl<SourceLocation> &ProtocolLocs,
9221 IdentifierInfo *SuperName,
9222 SourceLocation SuperLoc);
9223
9224 Decl *ActOnCompatibilityAlias(
9225 SourceLocation AtCompatibilityAliasLoc,
9226 IdentifierInfo *AliasName, SourceLocation AliasLocation,
9227 IdentifierInfo *ClassName, SourceLocation ClassLocation);
9228
9229 bool CheckForwardProtocolDeclarationForCircularDependency(
9230 IdentifierInfo *PName,
9231 SourceLocation &PLoc, SourceLocation PrevLoc,
9232 const ObjCList<ObjCProtocolDecl> &PList);
9233
9234 Decl *ActOnStartProtocolInterface(
9235 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
9236 SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
9237 unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
9238 SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
9239
9240 Decl *ActOnStartCategoryInterface(
9241 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9242 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9243 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
9244 Decl *const *ProtoRefs, unsigned NumProtoRefs,
9245 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9246 const ParsedAttributesView &AttrList);
9247
9248 Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
9249 IdentifierInfo *ClassName,
9250 SourceLocation ClassLoc,
9251 IdentifierInfo *SuperClassname,
9252 SourceLocation SuperClassLoc,
9253 const ParsedAttributesView &AttrList);
9254
9255 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
9256 IdentifierInfo *ClassName,
9257 SourceLocation ClassLoc,
9258 IdentifierInfo *CatName,
9259 SourceLocation CatLoc,
9260 const ParsedAttributesView &AttrList);
9261
9262 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
9263 ArrayRef<Decl *> Decls);
9264
9265 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
9266 IdentifierInfo **IdentList,
9267 SourceLocation *IdentLocs,
9268 ArrayRef<ObjCTypeParamList *> TypeParamLists,
9269 unsigned NumElts);
9270
9271 DeclGroupPtrTy
9272 ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
9273 ArrayRef<IdentifierLocPair> IdentList,
9274 const ParsedAttributesView &attrList);
9275
9276 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
9277 ArrayRef<IdentifierLocPair> ProtocolId,
9278 SmallVectorImpl<Decl *> &Protocols);
9279
9280 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
9281 SourceLocation ProtocolLoc,
9282 IdentifierInfo *TypeArgId,
9283 SourceLocation TypeArgLoc,
9284 bool SelectProtocolFirst = false);
9285
9286 /// Given a list of identifiers (and their locations), resolve the
9287 /// names to either Objective-C protocol qualifiers or type
9288 /// arguments, as appropriate.
9289 void actOnObjCTypeArgsOrProtocolQualifiers(
9290 Scope *S,
9291 ParsedType baseType,
9292 SourceLocation lAngleLoc,
9293 ArrayRef<IdentifierInfo *> identifiers,
9294 ArrayRef<SourceLocation> identifierLocs,
9295 SourceLocation rAngleLoc,
9296 SourceLocation &typeArgsLAngleLoc,
9297 SmallVectorImpl<ParsedType> &typeArgs,
9298 SourceLocation &typeArgsRAngleLoc,
9299 SourceLocation &protocolLAngleLoc,
9300 SmallVectorImpl<Decl *> &protocols,
9301 SourceLocation &protocolRAngleLoc,
9302 bool warnOnIncompleteProtocols);
9303
9304 /// Build a an Objective-C protocol-qualified 'id' type where no
9305 /// base type was specified.
9306 TypeResult actOnObjCProtocolQualifierType(
9307 SourceLocation lAngleLoc,
9308 ArrayRef<Decl *> protocols,
9309 ArrayRef<SourceLocation> protocolLocs,
9310 SourceLocation rAngleLoc);
9311
9312 /// Build a specialized and/or protocol-qualified Objective-C type.
9313 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
9314 Scope *S,
9315 SourceLocation Loc,
9316 ParsedType BaseType,
9317 SourceLocation TypeArgsLAngleLoc,
9318 ArrayRef<ParsedType> TypeArgs,
9319 SourceLocation TypeArgsRAngleLoc,
9320 SourceLocation ProtocolLAngleLoc,
9321 ArrayRef<Decl *> Protocols,
9322 ArrayRef<SourceLocation> ProtocolLocs,
9323 SourceLocation ProtocolRAngleLoc);
9324
9325 /// Build an Objective-C type parameter type.
9326 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
9327 SourceLocation ProtocolLAngleLoc,
9328 ArrayRef<ObjCProtocolDecl *> Protocols,
9329 ArrayRef<SourceLocation> ProtocolLocs,
9330 SourceLocation ProtocolRAngleLoc,
9331 bool FailOnError = false);
9332
9333 /// Build an Objective-C object pointer type.
9334 QualType BuildObjCObjectType(QualType BaseType,
9335 SourceLocation Loc,
9336 SourceLocation TypeArgsLAngleLoc,
9337 ArrayRef<TypeSourceInfo *> TypeArgs,
9338 SourceLocation TypeArgsRAngleLoc,
9339 SourceLocation ProtocolLAngleLoc,
9340 ArrayRef<ObjCProtocolDecl *> Protocols,
9341 ArrayRef<SourceLocation> ProtocolLocs,
9342 SourceLocation ProtocolRAngleLoc,
9343 bool FailOnError = false);
9344
9345 /// Ensure attributes are consistent with type.
9346 /// \param [in, out] Attributes The attributes to check; they will
9347 /// be modified to be consistent with \p PropertyTy.
9348 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
9349 SourceLocation Loc,
9350 unsigned &Attributes,
9351 bool propertyInPrimaryClass);
9352
9353 /// Process the specified property declaration and create decls for the
9354 /// setters and getters as needed.
9355 /// \param property The property declaration being processed
9356 void ProcessPropertyDecl(ObjCPropertyDecl *property);
9357
9358
9359 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
9360 ObjCPropertyDecl *SuperProperty,
9361 const IdentifierInfo *Name,
9362 bool OverridingProtocolProperty);
9363
9364 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
9365 ObjCInterfaceDecl *ID);
9366
9367 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
9368 ArrayRef<Decl *> allMethods = None,
9369 ArrayRef<DeclGroupPtrTy> allTUVars = None);
9370
9371 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
9372 SourceLocation LParenLoc,
9373 FieldDeclarator &FD, ObjCDeclSpec &ODS,
9374 Selector GetterSel, Selector SetterSel,
9375 tok::ObjCKeywordKind MethodImplKind,
9376 DeclContext *lexicalDC = nullptr);
9377
9378 Decl *ActOnPropertyImplDecl(Scope *S,
9379 SourceLocation AtLoc,
9380 SourceLocation PropertyLoc,
9381 bool ImplKind,
9382 IdentifierInfo *PropertyId,
9383 IdentifierInfo *PropertyIvar,
9384 SourceLocation PropertyIvarLoc,
9385 ObjCPropertyQueryKind QueryKind);
9386
9387 enum ObjCSpecialMethodKind {
9388 OSMK_None,
9389 OSMK_Alloc,
9390 OSMK_New,
9391 OSMK_Copy,
9392 OSMK_RetainingInit,
9393 OSMK_NonRetainingInit
9394 };
9395
9396 struct ObjCArgInfo {
9397 IdentifierInfo *Name;
9398 SourceLocation NameLoc;
9399 // The Type is null if no type was specified, and the DeclSpec is invalid
9400 // in this case.
9401 ParsedType Type;
9402 ObjCDeclSpec DeclSpec;
9403
9404 /// ArgAttrs - Attribute list for this argument.
9405 ParsedAttributesView ArgAttrs;
9406 };
9407
9408 Decl *ActOnMethodDeclaration(
9409 Scope *S,
9410 SourceLocation BeginLoc, // location of the + or -.
9411 SourceLocation EndLoc, // location of the ; or {.
9412 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
9413 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
9414 // optional arguments. The number of types/arguments is obtained
9415 // from the Sel.getNumArgs().
9416 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
9417 unsigned CNumArgs, // c-style args
9418 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
9419 bool isVariadic, bool MethodDefinition);
9420
9421 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
9422 const ObjCObjectPointerType *OPT,
9423 bool IsInstance);
9424 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
9425 bool IsInstance);
9426
9427 bool CheckARCMethodDecl(ObjCMethodDecl *method);
9428 bool inferObjCARCLifetime(ValueDecl *decl);
9429
9430 void deduceOpenCLAddressSpace(ValueDecl *decl);
9431
9432 ExprResult
9433 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
9434 Expr *BaseExpr,
9435 SourceLocation OpLoc,
9436 DeclarationName MemberName,
9437 SourceLocation MemberLoc,
9438 SourceLocation SuperLoc, QualType SuperType,
9439 bool Super);
9440
9441 ExprResult
9442 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
9443 IdentifierInfo &propertyName,
9444 SourceLocation receiverNameLoc,
9445 SourceLocation propertyNameLoc);
9446
9447 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
9448
9449 /// Describes the kind of message expression indicated by a message
9450 /// send that starts with an identifier.
9451 enum ObjCMessageKind {
9452 /// The message is sent to 'super'.
9453 ObjCSuperMessage,
9454 /// The message is an instance message.
9455 ObjCInstanceMessage,
9456 /// The message is a class message, and the identifier is a type
9457 /// name.
9458 ObjCClassMessage
9459 };
9460
9461 ObjCMessageKind getObjCMessageKind(Scope *S,
9462 IdentifierInfo *Name,
9463 SourceLocation NameLoc,
9464 bool IsSuper,
9465 bool HasTrailingDot,
9466 ParsedType &ReceiverType);
9467
9468 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
9469 Selector Sel,
9470 SourceLocation LBracLoc,
9471 ArrayRef<SourceLocation> SelectorLocs,
9472 SourceLocation RBracLoc,
9473 MultiExprArg Args);
9474
9475 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
9476 QualType ReceiverType,
9477 SourceLocation SuperLoc,
9478 Selector Sel,
9479 ObjCMethodDecl *Method,
9480 SourceLocation LBracLoc,
9481 ArrayRef<SourceLocation> SelectorLocs,
9482 SourceLocation RBracLoc,
9483 MultiExprArg Args,
9484 bool isImplicit = false);
9485
9486 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
9487 bool isSuperReceiver,
9488 SourceLocation Loc,
9489 Selector Sel,
9490 ObjCMethodDecl *Method,
9491 MultiExprArg Args);
9492
9493 ExprResult ActOnClassMessage(Scope *S,
9494 ParsedType Receiver,
9495 Selector Sel,
9496 SourceLocation LBracLoc,
9497 ArrayRef<SourceLocation> SelectorLocs,
9498 SourceLocation RBracLoc,
9499 MultiExprArg Args);
9500
9501 ExprResult BuildInstanceMessage(Expr *Receiver,
9502 QualType ReceiverType,
9503 SourceLocation SuperLoc,
9504 Selector Sel,
9505 ObjCMethodDecl *Method,
9506 SourceLocation LBracLoc,
9507 ArrayRef<SourceLocation> SelectorLocs,
9508 SourceLocation RBracLoc,
9509 MultiExprArg Args,
9510 bool isImplicit = false);
9511
9512 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
9513 QualType ReceiverType,
9514 SourceLocation Loc,
9515 Selector Sel,
9516 ObjCMethodDecl *Method,
9517 MultiExprArg Args);
9518
9519 ExprResult ActOnInstanceMessage(Scope *S,
9520 Expr *Receiver,
9521 Selector Sel,
9522 SourceLocation LBracLoc,
9523 ArrayRef<SourceLocation> SelectorLocs,
9524 SourceLocation RBracLoc,
9525 MultiExprArg Args);
9526
9527 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
9528 ObjCBridgeCastKind Kind,
9529 SourceLocation BridgeKeywordLoc,
9530 TypeSourceInfo *TSInfo,
9531 Expr *SubExpr);
9532
9533 ExprResult ActOnObjCBridgedCast(Scope *S,
9534 SourceLocation LParenLoc,
9535 ObjCBridgeCastKind Kind,
9536 SourceLocation BridgeKeywordLoc,
9537 ParsedType Type,
9538 SourceLocation RParenLoc,
9539 Expr *SubExpr);
9540
9541 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
9542
9543 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
9544
9545 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
9546 CastKind &Kind);
9547
9548 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
9549 QualType DestType, QualType SrcType,
9550 ObjCInterfaceDecl *&RelatedClass,
9551 ObjCMethodDecl *&ClassMethod,
9552 ObjCMethodDecl *&InstanceMethod,
9553 TypedefNameDecl *&TDNDecl,
9554 bool CfToNs, bool Diagnose = true);
9555
9556 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
9557 QualType DestType, QualType SrcType,
9558 Expr *&SrcExpr, bool Diagnose = true);
9559
9560 bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr,
9561 bool Diagnose = true);
9562
9563 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
9564
9565 /// Check whether the given new method is a valid override of the
9566 /// given overridden method, and set any properties that should be inherited.
9567 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
9568 const ObjCMethodDecl *Overridden);
9569
9570 /// Describes the compatibility of a result type with its method.
9571 enum ResultTypeCompatibilityKind {
9572 RTC_Compatible,
9573 RTC_Incompatible,
9574 RTC_Unknown
9575 };
9576
9577 void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
9578 ObjCMethodDecl *overridden);
9579
9580 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
9581 ObjCInterfaceDecl *CurrentClass,
9582 ResultTypeCompatibilityKind RTC);
9583
9584 enum PragmaOptionsAlignKind {
9585 POAK_Native, // #pragma options align=native
9586 POAK_Natural, // #pragma options align=natural
9587 POAK_Packed, // #pragma options align=packed
9588 POAK_Power, // #pragma options align=power
9589 POAK_Mac68k, // #pragma options align=mac68k
9590 POAK_Reset // #pragma options align=reset
9591 };
9592
9593 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
9594 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
9595 PragmaClangSectionAction Action,
9596 PragmaClangSectionKind SecKind, StringRef SecName);
9597
9598 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
9599 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
9600 SourceLocation PragmaLoc);
9601
9602 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
9603 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
9604 StringRef SlotLabel, Expr *Alignment);
9605
9606 enum class PragmaPackDiagnoseKind {
9607 NonDefaultStateAtInclude,
9608 ChangedStateAtExit
9609 };
9610
9611 void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
9612 SourceLocation IncludeLoc);
9613 void DiagnoseUnterminatedPragmaPack();
9614
9615 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
9616 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
9617
9618 /// ActOnPragmaMSComment - Called on well formed
9619 /// \#pragma comment(kind, "arg").
9620 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
9621 StringRef Arg);
9622
9623 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
9624 /// pointers_to_members(representation method[, general purpose
9625 /// representation]).
9626 void ActOnPragmaMSPointersToMembers(
9627 LangOptions::PragmaMSPointersToMembersKind Kind,
9628 SourceLocation PragmaLoc);
9629
9630 /// Called on well formed \#pragma vtordisp().
9631 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
9632 SourceLocation PragmaLoc,
9633 MSVtorDispMode Value);
9634
9635 enum PragmaSectionKind {
9636 PSK_DataSeg,
9637 PSK_BSSSeg,
9638 PSK_ConstSeg,
9639 PSK_CodeSeg,
9640 };
9641
9642 bool UnifySection(StringRef SectionName,
9643 int SectionFlags,
9644 DeclaratorDecl *TheDecl);
9645 bool UnifySection(StringRef SectionName,
9646 int SectionFlags,
9647 SourceLocation PragmaSectionLocation);
9648
9649 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
9650 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
9651 PragmaMsStackAction Action,
9652 llvm::StringRef StackSlotLabel,
9653 StringLiteral *SegmentName,
9654 llvm::StringRef PragmaName);
9655
9656 /// Called on well formed \#pragma section().
9657 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
9658 int SectionFlags, StringLiteral *SegmentName);
9659
9660 /// Called on well-formed \#pragma init_seg().
9661 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
9662 StringLiteral *SegmentName);
9663
9664 /// Called on #pragma clang __debug dump II
9665 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9666
9667 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
9668 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
9669 StringRef Value);
9670
9671 /// Are precise floating point semantics currently enabled?
9672 bool isPreciseFPEnabled() {
9673 return !CurFPFeatures.getAllowFPReassociate() &&
9674 !CurFPFeatures.getNoSignedZero() &&
9675 !CurFPFeatures.getAllowReciprocal() &&
9676 !CurFPFeatures.getAllowApproxFunc();
9677 }
9678
9679 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
9680 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
9681 PragmaFloatControlKind Value);
9682
9683 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
9684 void ActOnPragmaUnused(const Token &Identifier,
9685 Scope *curScope,
9686 SourceLocation PragmaLoc);
9687
9688 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
9689 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
9690 SourceLocation PragmaLoc);
9691
9692 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
9693 SourceLocation Loc);
9694 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
9695
9696 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
9697 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
9698 SourceLocation PragmaLoc,
9699 SourceLocation WeakNameLoc);
9700
9701 /// ActOnPragmaRedefineExtname - Called on well formed
9702 /// \#pragma redefine_extname oldname newname.
9703 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
9704 IdentifierInfo* AliasName,
9705 SourceLocation PragmaLoc,
9706 SourceLocation WeakNameLoc,
9707 SourceLocation AliasNameLoc);
9708
9709 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
9710 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
9711 IdentifierInfo* AliasName,
9712 SourceLocation PragmaLoc,
9713 SourceLocation WeakNameLoc,
9714 SourceLocation AliasNameLoc);
9715
9716 /// ActOnPragmaFPContract - Called on well formed
9717 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
9718 /// \#pragma clang fp contract
9719 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
9720
9721 /// Called on well formed
9722 /// \#pragma clang fp reassociate
9723 void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled);
9724
9725 /// ActOnPragmaFenvAccess - Called on well formed
9726 /// \#pragma STDC FENV_ACCESS
9727 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
9728
9729 /// Called to set rounding mode for floating point operations.
9730 void setRoundingMode(SourceLocation Loc, llvm::RoundingMode);
9731
9732 /// Called to set exception behavior for floating point operations.
9733 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
9734
9735 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
9736 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
9737 void AddAlignmentAttributesForRecord(RecordDecl *RD);
9738
9739 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
9740 void AddMsStructLayoutForRecord(RecordDecl *RD);
9741
9742 /// FreePackedContext - Deallocate and null out PackContext.
9743 void FreePackedContext();
9744
9745 /// PushNamespaceVisibilityAttr - Note that we've entered a
9746 /// namespace with a visibility attribute.
9747 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
9748 SourceLocation Loc);
9749
9750 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
9751 /// add an appropriate visibility attribute.
9752 void AddPushedVisibilityAttribute(Decl *RD);
9753
9754 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
9755 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
9756 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
9757
9758 /// FreeVisContext - Deallocate and null out VisContext.
9759 void FreeVisContext();
9760
9761 /// AddCFAuditedAttribute - Check whether we're currently within
9762 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
9763 /// the appropriate attribute.
9764 void AddCFAuditedAttribute(Decl *D);
9765
9766 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
9767 SourceLocation PragmaLoc,
9768 attr::ParsedSubjectMatchRuleSet Rules);
9769 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
9770 const IdentifierInfo *Namespace);
9771
9772 /// Called on well-formed '\#pragma clang attribute pop'.
9773 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
9774 const IdentifierInfo *Namespace);
9775
9776 /// Adds the attributes that have been specified using the
9777 /// '\#pragma clang attribute push' directives to the given declaration.
9778 void AddPragmaAttributes(Scope *S, Decl *D);
9779
9780 void DiagnoseUnterminatedPragmaAttribute();
9781
9782 /// Called on well formed \#pragma clang optimize.
9783 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
9784
9785 /// Get the location for the currently active "\#pragma clang optimize
9786 /// off". If this location is invalid, then the state of the pragma is "on".
9787 SourceLocation getOptimizeOffPragmaLocation() const {
9788 return OptimizeOffPragmaLocation;
9789 }
9790
9791 /// Only called on function definitions; if there is a pragma in scope
9792 /// with the effect of a range-based optnone, consider marking the function
9793 /// with attribute optnone.
9794 void AddRangeBasedOptnone(FunctionDecl *FD);
9795
9796 /// Adds the 'optnone' attribute to the function declaration if there
9797 /// are no conflicts; Loc represents the location causing the 'optnone'
9798 /// attribute to be added (usually because of a pragma).
9799 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
9800
9801 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
9802 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
9803 bool IsPackExpansion);
9804 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
9805 bool IsPackExpansion);
9806
9807 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
9808 /// declaration.
9809 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
9810 Expr *OE);
9811
9812 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
9813 /// declaration.
9814 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
9815 Expr *ParamExpr);
9816
9817 /// AddAlignValueAttr - Adds an align_value attribute to a particular
9818 /// declaration.
9819 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
9820
9821 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
9822 /// declaration.
9823 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
9824 Expr *MaxThreads, Expr *MinBlocks);
9825
9826 /// AddModeAttr - Adds a mode attribute to a particular declaration.
9827 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
9828 bool InInstantiation = false);
9829
9830 void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
9831 ParameterABI ABI);
9832
9833 enum class RetainOwnershipKind {NS, CF, OS};
9834 void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
9835 RetainOwnershipKind K, bool IsTemplateInstantiation);
9836
9837 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
9838 /// attribute to a particular declaration.
9839 void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
9840 Expr *Min, Expr *Max);
9841
9842 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
9843 /// particular declaration.
9844 void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
9845 Expr *Min, Expr *Max);
9846
9847 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
9848
9849 //===--------------------------------------------------------------------===//
9850 // C++ Coroutines TS
9851 //
9852 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
9853 StringRef Keyword);
9854 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
9855 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
9856 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
9857
9858 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
9859 bool IsImplicit = false);
9860 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
9861 UnresolvedLookupExpr* Lookup);
9862 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
9863 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
9864 bool IsImplicit = false);
9865 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
9866 bool buildCoroutineParameterMoves(SourceLocation Loc);
9867 VarDecl *buildCoroutinePromise(SourceLocation Loc);
9868 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
9869 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
9870 SourceLocation FuncLoc);
9871 /// Check that the expression co_await promise.final_suspend() shall not be
9872 /// potentially-throwing.
9873 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
9874
9875 //===--------------------------------------------------------------------===//
9876 // OpenCL extensions.
9877 //
9878private:
9879 std::string CurrOpenCLExtension;
9880 /// Extensions required by an OpenCL type.
9881 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
9882 /// Extensions required by an OpenCL declaration.
9883 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
9884public:
9885 llvm::StringRef getCurrentOpenCLExtension() const {
9886 return CurrOpenCLExtension;
9887 }
9888
9889 /// Check if a function declaration \p FD associates with any
9890 /// extensions present in OpenCLDeclExtMap and if so return the
9891 /// extension(s) name(s).
9892 std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD);
9893
9894 /// Check if a function type \p FT associates with any
9895 /// extensions present in OpenCLTypeExtMap and if so return the
9896 /// extension(s) name(s).
9897 std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT);
9898
9899 /// Find an extension in an appropriate extension map and return its name
9900 template<typename T, typename MapT>
9901 std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map);
9902
9903 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
9904 CurrOpenCLExtension = std::string(Ext);
9905 }
9906
9907 /// Set OpenCL extensions for a type which can only be used when these
9908 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
9909 /// \param Exts A space separated list of OpenCL extensions.
9910 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
9911
9912 /// Set OpenCL extensions for a declaration which can only be
9913 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
9914 /// nothing.
9915 /// \param Exts A space separated list of OpenCL extensions.
9916 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
9917
9918 /// Set current OpenCL extensions for a type which can only be used
9919 /// when these OpenCL extensions are enabled. If current OpenCL extension is
9920 /// empty, do nothing.
9921 void setCurrentOpenCLExtensionForType(QualType T);
9922
9923 /// Set current OpenCL extensions for a declaration which
9924 /// can only be used when these OpenCL extensions are enabled. If current
9925 /// OpenCL extension is empty, do nothing.
9926 void setCurrentOpenCLExtensionForDecl(Decl *FD);
9927
9928 bool isOpenCLDisabledDecl(Decl *FD);
9929
9930 /// Check if type \p T corresponding to declaration specifier \p DS
9931 /// is disabled due to required OpenCL extensions being disabled. If so,
9932 /// emit diagnostics.
9933 /// \return true if type is disabled.
9934 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
9935
9936 /// Check if declaration \p D used by expression \p E
9937 /// is disabled due to required OpenCL extensions being disabled. If so,
9938 /// emit diagnostics.
9939 /// \return true if type is disabled.
9940 bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
9941
9942 //===--------------------------------------------------------------------===//
9943 // OpenMP directives and clauses.
9944 //
9945private:
9946 void *VarDataSharingAttributesStack;
9947 /// Number of nested '#pragma omp declare target' directives.
9948 unsigned DeclareTargetNestingLevel = 0;
9949 /// Initialization of data-sharing attributes stack.
9950 void InitDataSharingAttributesStack();
9951 void DestroyDataSharingAttributesStack();
9952 ExprResult
9953 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
9954 bool StrictlyPositive = true);
9955 /// Returns OpenMP nesting level for current directive.
9956 unsigned getOpenMPNestingLevel() const;
9957
9958 /// Adjusts the function scopes index for the target-based regions.
9959 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
9960 unsigned Level) const;
9961
9962 /// Returns the number of scopes associated with the construct on the given
9963 /// OpenMP level.
9964 int getNumberOfConstructScopes(unsigned Level) const;
9965
9966 /// Push new OpenMP function region for non-capturing function.
9967 void pushOpenMPFunctionRegion();
9968
9969 /// Pop OpenMP function region for non-capturing function.
9970 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
9971
9972 /// Checks if a type or a declaration is disabled due to the owning extension
9973 /// being disabled, and emits diagnostic messages if it is disabled.
9974 /// \param D type or declaration to be checked.
9975 /// \param DiagLoc source location for the diagnostic message.
9976 /// \param DiagInfo information to be emitted for the diagnostic message.
9977 /// \param SrcRange source range of the declaration.
9978 /// \param Map maps type or declaration to the extensions.
9979 /// \param Selector selects diagnostic message: 0 for type and 1 for
9980 /// declaration.
9981 /// \return true if the type or declaration is disabled.
9982 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
9983 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
9984 MapT &Map, unsigned Selector = 0,
9985 SourceRange SrcRange = SourceRange());
9986
9987 /// Helper to keep information about the current `omp begin/end declare
9988 /// variant` nesting.
9989 struct OMPDeclareVariantScope {
9990 /// The associated OpenMP context selector.
9991 OMPTraitInfo *TI;
9992
9993 /// The associated OpenMP context selector mangling.
9994 std::string NameSuffix;
9995
9996 OMPDeclareVariantScope(OMPTraitInfo &TI);
9997 };
9998
9999 /// The current `omp begin/end declare variant` scopes.
10000 SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
10001
10002 /// The declarator \p D defines a function in the scope \p S which is nested
10003 /// in an `omp begin/end declare variant` scope. In this method we create a
10004 /// declaration for \p D and rename \p D according to the OpenMP context
10005 /// selector of the surrounding scope.
10006 FunctionDecl *
10007 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S,
10008 Declarator &D);
10009
10010 /// Register \p FD as specialization of \p BaseFD in the current `omp
10011 /// begin/end declare variant` scope.
10012 void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
10013 FunctionDecl *FD, FunctionDecl *BaseFD);
10014
10015public:
10016
10017 /// Can we exit a scope at the moment.
10018 bool isInOpenMPDeclareVariantScope() {
10019 return !OMPDeclareVariantScopes.empty();
10020 }
10021
10022 /// Given the potential call expression \p Call, determine if there is a
10023 /// specialization via the OpenMP declare variant mechanism available. If
10024 /// there is, return the specialized call expression, otherwise return the
10025 /// original \p Call.
10026 ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope,
10027 SourceLocation LParenLoc, MultiExprArg ArgExprs,
10028 SourceLocation RParenLoc, Expr *ExecConfig);
10029
10030 /// Handle a `omp begin declare variant`.
10031 void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI);
10032
10033 /// Handle a `omp end declare variant`.
10034 void ActOnOpenMPEndDeclareVariant();
10035
10036 /// Checks if the variant/multiversion functions are compatible.
10037 bool areMultiversionVariantFunctionsCompatible(
10038 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10039 const PartialDiagnostic &NoProtoDiagID,
10040 const PartialDiagnosticAt &NoteCausedDiagIDAt,
10041 const PartialDiagnosticAt &NoSupportDiagIDAt,
10042 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10043 bool ConstexprSupported, bool CLinkageMayDiffer);
10044
10045 /// Function tries to capture lambda's captured variables in the OpenMP region
10046 /// before the original lambda is captured.
10047 void tryCaptureOpenMPLambdas(ValueDecl *V);
10048
10049 /// Return true if the provided declaration \a VD should be captured by
10050 /// reference.
10051 /// \param Level Relative level of nested OpenMP construct for that the check
10052 /// is performed.
10053 /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
10054 bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
10055 unsigned OpenMPCaptureLevel) const;
10056
10057 /// Check if the specified variable is used in one of the private
10058 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
10059 /// constructs.
10060 VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
10061 unsigned StopAt = 0);
10062 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
10063 ExprObjectKind OK, SourceLocation Loc);
10064
10065 /// If the current region is a loop-based region, mark the start of the loop
10066 /// construct.
10067 void startOpenMPLoop();
10068
10069 /// If the current region is a range loop-based region, mark the start of the
10070 /// loop construct.
10071 void startOpenMPCXXRangeFor();
10072
10073 /// Check if the specified variable is used in 'private' clause.
10074 /// \param Level Relative level of nested OpenMP construct for that the check
10075 /// is performed.
10076 OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
10077 unsigned CapLevel) const;
10078
10079 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
10080 /// for \p FD based on DSA for the provided corresponding captured declaration
10081 /// \p D.
10082 void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
10083
10084 /// Check if the specified variable is captured by 'target' directive.
10085 /// \param Level Relative level of nested OpenMP construct for that the check
10086 /// is performed.
10087 bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
10088 unsigned CaptureLevel) const;
10089
10090 /// Check if the specified global variable must be captured by outer capture
10091 /// regions.
10092 /// \param Level Relative level of nested OpenMP construct for that
10093 /// the check is performed.
10094 bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
10095 unsigned CaptureLevel) const;
10096
10097 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
10098 Expr *Op);
10099 /// Called on start of new data sharing attribute block.
10100 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
10101 const DeclarationNameInfo &DirName, Scope *CurScope,
10102 SourceLocation Loc);
10103 /// Start analysis of clauses.
10104 void StartOpenMPClause(OpenMPClauseKind K);
10105 /// End analysis of clauses.
10106 void EndOpenMPClause();
10107 /// Called on end of data sharing attribute block.
10108 void EndOpenMPDSABlock(Stmt *CurDirective);
10109
10110 /// Check if the current region is an OpenMP loop region and if it is,
10111 /// mark loop control variable, used in \p Init for loop initialization, as
10112 /// private by default.
10113 /// \param Init First part of the for loop.
10114 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
10115
10116 // OpenMP directives and clauses.
10117 /// Called on correct id-expression from the '#pragma omp
10118 /// threadprivate'.
10119 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
10120 const DeclarationNameInfo &Id,
10121 OpenMPDirectiveKind Kind);
10122 /// Called on well-formed '#pragma omp threadprivate'.
10123 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
10124 SourceLocation Loc,
10125 ArrayRef<Expr *> VarList);
10126 /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
10127 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
10128 ArrayRef<Expr *> VarList);
10129 /// Called on well-formed '#pragma omp allocate'.
10130 DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
10131 ArrayRef<Expr *> VarList,
10132 ArrayRef<OMPClause *> Clauses,
10133 DeclContext *Owner = nullptr);
10134 /// Called on well-formed '#pragma omp requires'.
10135 DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
10136 ArrayRef<OMPClause *> ClauseList);
10137 /// Check restrictions on Requires directive
10138 OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
10139 ArrayRef<OMPClause *> Clauses);
10140 /// Check if the specified type is allowed to be used in 'omp declare
10141 /// reduction' construct.
10142 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10143 TypeResult ParsedType);
10144 /// Called on start of '#pragma omp declare reduction'.
10145 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
10146 Scope *S, DeclContext *DC, DeclarationName Name,
10147 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10148 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
10149 /// Initialize declare reduction construct initializer.
10150 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
10151 /// Finish current declare reduction construct initializer.
10152 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
10153 /// Initialize declare reduction construct initializer.
10154 /// \return omp_priv variable.
10155 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
10156 /// Finish current declare reduction construct initializer.
10157 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
10158 VarDecl *OmpPrivParm);
10159 /// Called at the end of '#pragma omp declare reduction'.
10160 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
10161 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
10162
10163 /// Check variable declaration in 'omp declare mapper' construct.
10164 TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
10165 /// Check if the specified type is allowed to be used in 'omp declare
10166 /// mapper' construct.
10167 QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
10168 TypeResult ParsedType);
10169 /// Called on start of '#pragma omp declare mapper'.
10170 OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart(
10171 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
10172 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
10173 Decl *PrevDeclInScope = nullptr);
10174 /// Build the mapper variable of '#pragma omp declare mapper'.
10175 void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
10176 Scope *S, QualType MapperType,
10177 SourceLocation StartLoc,
10178 DeclarationName VN);
10179 /// Called at the end of '#pragma omp declare mapper'.
10180 DeclGroupPtrTy
10181 ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
10182 ArrayRef<OMPClause *> ClauseList);
10183
10184 /// Called on the start of target region i.e. '#pragma omp declare target'.
10185 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
10186 /// Called at the end of target region i.e. '#pragme omp end declare target'.
10187 void ActOnFinishOpenMPDeclareTargetDirective();
10188 /// Searches for the provided declaration name for OpenMP declare target
10189 /// directive.
10190 NamedDecl *
10191 lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
10192 const DeclarationNameInfo &Id,
10193 NamedDeclSetType &SameDirectiveDecls);
10194 /// Called on correct id-expression from the '#pragma omp declare target'.
10195 void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
10196 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10197 OMPDeclareTargetDeclAttr::DevTypeTy DT);
10198 /// Check declaration inside target region.
10199 void
10200 checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
10201 SourceLocation IdLoc = SourceLocation());
10202 /// Finishes analysis of the deferred functions calls that may be declared as
10203 /// host/nohost during device/host compilation.
10204 void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
10205 const FunctionDecl *Callee,
10206 SourceLocation Loc);
10207 /// Return true inside OpenMP declare target region.
10208 bool isInOpenMPDeclareTargetContext() const {
10209 return DeclareTargetNestingLevel > 0;
10210 }
10211 /// Return true inside OpenMP target region.
10212 bool isInOpenMPTargetExecutionDirective() const;
10213
10214 /// Return the number of captured regions created for an OpenMP directive.
10215 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
10216
10217 /// Initialization of captured region for OpenMP region.
10218 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
10219 /// End of OpenMP region.
10220 ///
10221 /// \param S Statement associated with the current OpenMP region.
10222 /// \param Clauses List of clauses for the current OpenMP region.
10223 ///
10224 /// \returns Statement for finished OpenMP region.
10225 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
10226 StmtResult ActOnOpenMPExecutableDirective(
10227 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
10228 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
10229 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
10230 /// Called on well-formed '\#pragma omp parallel' after parsing
10231 /// of the associated statement.
10232 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
10233 Stmt *AStmt,
10234 SourceLocation StartLoc,
10235 SourceLocation EndLoc);
10236 using VarsWithInheritedDSAType =
10237 llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
10238 /// Called on well-formed '\#pragma omp simd' after parsing
10239 /// of the associated statement.
10240 StmtResult
10241 ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10242 SourceLocation StartLoc, SourceLocation EndLoc,
10243 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10244 /// Called on well-formed '\#pragma omp for' after parsing
10245 /// of the associated statement.
10246 StmtResult
10247 ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10248 SourceLocation StartLoc, SourceLocation EndLoc,
10249 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10250 /// Called on well-formed '\#pragma omp for simd' after parsing
10251 /// of the associated statement.
10252 StmtResult
10253 ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10254 SourceLocation StartLoc, SourceLocation EndLoc,
10255 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10256 /// Called on well-formed '\#pragma omp sections' after parsing
10257 /// of the associated statement.
10258 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
10259 Stmt *AStmt, SourceLocation StartLoc,
10260 SourceLocation EndLoc);
10261 /// Called on well-formed '\#pragma omp section' after parsing of the
10262 /// associated statement.
10263 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
10264 SourceLocation EndLoc);
10265 /// Called on well-formed '\#pragma omp single' after parsing of the
10266 /// associated statement.
10267 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
10268 Stmt *AStmt, SourceLocation StartLoc,
10269 SourceLocation EndLoc);
10270 /// Called on well-formed '\#pragma omp master' after parsing of the
10271 /// associated statement.
10272 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
10273 SourceLocation EndLoc);
10274 /// Called on well-formed '\#pragma omp critical' after parsing of the
10275 /// associated statement.
10276 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
10277 ArrayRef<OMPClause *> Clauses,
10278 Stmt *AStmt, SourceLocation StartLoc,
10279 SourceLocation EndLoc);
10280 /// Called on well-formed '\#pragma omp parallel for' after parsing
10281 /// of the associated statement.
10282 StmtResult ActOnOpenMPParallelForDirective(
10283 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10284 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10285 /// Called on well-formed '\#pragma omp parallel for simd' after
10286 /// parsing of the associated statement.
10287 StmtResult ActOnOpenMPParallelForSimdDirective(
10288 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10289 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10290 /// Called on well-formed '\#pragma omp parallel master' after
10291 /// parsing of the associated statement.
10292 StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10293 Stmt *AStmt,
10294 SourceLocation StartLoc,
10295 SourceLocation EndLoc);
10296 /// Called on well-formed '\#pragma omp parallel sections' after
10297 /// parsing of the associated statement.
10298 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10299 Stmt *AStmt,
10300 SourceLocation StartLoc,
10301 SourceLocation EndLoc);
10302 /// Called on well-formed '\#pragma omp task' after parsing of the
10303 /// associated statement.
10304 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10305 Stmt *AStmt, SourceLocation StartLoc,
10306 SourceLocation EndLoc);
10307 /// Called on well-formed '\#pragma omp taskyield'.
10308 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10309 SourceLocation EndLoc);
10310 /// Called on well-formed '\#pragma omp barrier'.
10311 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10312 SourceLocation EndLoc);
10313 /// Called on well-formed '\#pragma omp taskwait'.
10314 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
10315 SourceLocation EndLoc);
10316 /// Called on well-formed '\#pragma omp taskgroup'.
10317 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10318 Stmt *AStmt, SourceLocation StartLoc,
10319 SourceLocation EndLoc);
10320 /// Called on well-formed '\#pragma omp flush'.
10321 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10322 SourceLocation StartLoc,
10323 SourceLocation EndLoc);
10324 /// Called on well-formed '\#pragma omp depobj'.
10325 StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10326 SourceLocation StartLoc,
10327 SourceLocation EndLoc);
10328 /// Called on well-formed '\#pragma omp scan'.
10329 StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10330 SourceLocation StartLoc,
10331 SourceLocation EndLoc);
10332 /// Called on well-formed '\#pragma omp ordered' after parsing of the
10333 /// associated statement.
10334 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10335 Stmt *AStmt, SourceLocation StartLoc,
10336 SourceLocation EndLoc);
10337 /// Called on well-formed '\#pragma omp atomic' after parsing of the
10338 /// associated statement.
10339 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10340 Stmt *AStmt, SourceLocation StartLoc,
10341 SourceLocation EndLoc);
10342 /// Called on well-formed '\#pragma omp target' after parsing of the
10343 /// associated statement.
10344 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
10345 Stmt *AStmt, SourceLocation StartLoc,
10346 SourceLocation EndLoc);
10347 /// Called on well-formed '\#pragma omp target data' after parsing of
10348 /// the associated statement.
10349 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
10350 Stmt *AStmt, SourceLocation StartLoc,
10351 SourceLocation EndLoc);
10352 /// Called on well-formed '\#pragma omp target enter data' after
10353 /// parsing of the associated statement.
10354 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
10355 SourceLocation StartLoc,
10356 SourceLocation EndLoc,
10357 Stmt *AStmt);
10358 /// Called on well-formed '\#pragma omp target exit data' after
10359 /// parsing of the associated statement.
10360 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
10361 SourceLocation StartLoc,
10362 SourceLocation EndLoc,
10363 Stmt *AStmt);
10364 /// Called on well-formed '\#pragma omp target parallel' after
10365 /// parsing of the associated statement.
10366 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
10367 Stmt *AStmt,
10368 SourceLocation StartLoc,
10369 SourceLocation EndLoc);
10370 /// Called on well-formed '\#pragma omp target parallel for' after
10371 /// parsing of the associated statement.
10372 StmtResult ActOnOpenMPTargetParallelForDirective(
10373 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10374 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10375 /// Called on well-formed '\#pragma omp teams' after parsing of the
10376 /// associated statement.
10377 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
10378 Stmt *AStmt, SourceLocation StartLoc,
10379 SourceLocation EndLoc);
10380 /// Called on well-formed '\#pragma omp cancellation point'.
10381 StmtResult
10382 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
10383 SourceLocation EndLoc,
10384 OpenMPDirectiveKind CancelRegion);
10385 /// Called on well-formed '\#pragma omp cancel'.
10386 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
10387 SourceLocation StartLoc,
10388 SourceLocation EndLoc,
10389 OpenMPDirectiveKind CancelRegion);
10390 /// Called on well-formed '\#pragma omp taskloop' after parsing of the
10391 /// associated statement.
10392 StmtResult
10393 ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10394 SourceLocation StartLoc, SourceLocation EndLoc,
10395 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10396 /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
10397 /// the associated statement.
10398 StmtResult ActOnOpenMPTaskLoopSimdDirective(
10399 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10400 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10401 /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
10402 /// associated statement.
10403 StmtResult ActOnOpenMPMasterTaskLoopDirective(
10404 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10405 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10406 /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
10407 /// the associated statement.
10408 StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
10409 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10410 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10411 /// Called on well-formed '\#pragma omp parallel master taskloop' after
10412 /// parsing of the associated statement.
10413 StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
10414 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10415 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10416 /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
10417 /// parsing of the associated statement.
10418 StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
10419 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10420 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10421 /// Called on well-formed '\#pragma omp distribute' after parsing
10422 /// of the associated statement.
10423 StmtResult
10424 ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10425 SourceLocation StartLoc, SourceLocation EndLoc,
10426 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10427 /// Called on well-formed '\#pragma omp target update'.
10428 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
10429 SourceLocation StartLoc,
10430 SourceLocation EndLoc,
10431 Stmt *AStmt);
10432 /// Called on well-formed '\#pragma omp distribute parallel for' after
10433 /// parsing of the associated statement.
10434 StmtResult ActOnOpenMPDistributeParallelForDirective(
10435 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10436 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10437 /// Called on well-formed '\#pragma omp distribute parallel for simd'
10438 /// after parsing of the associated statement.
10439 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
10440 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10441 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10442 /// Called on well-formed '\#pragma omp distribute simd' after
10443 /// parsing of the associated statement.
10444 StmtResult ActOnOpenMPDistributeSimdDirective(
10445 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10446 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10447 /// Called on well-formed '\#pragma omp target parallel for simd' after
10448 /// parsing of the associated statement.
10449 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
10450 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10451 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10452 /// Called on well-formed '\#pragma omp target simd' after parsing of
10453 /// the associated statement.
10454 StmtResult
10455 ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10456 SourceLocation StartLoc, SourceLocation EndLoc,
10457 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10458 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
10459 /// the associated statement.
10460 StmtResult ActOnOpenMPTeamsDistributeDirective(
10461 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10462 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10463 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
10464 /// of the associated statement.
10465 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
10466 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10467 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10468 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
10469 /// after parsing of the associated statement.
10470 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10471 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10472 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10473 /// Called on well-formed '\#pragma omp teams distribute parallel for'
10474 /// after parsing of the associated statement.
10475 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
10476 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10477 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10478 /// Called on well-formed '\#pragma omp target teams' after parsing of the
10479 /// associated statement.
10480 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10481 Stmt *AStmt,
10482 SourceLocation StartLoc,
10483 SourceLocation EndLoc);
10484 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
10485 /// of the associated statement.
10486 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
10487 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10488 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10489 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
10490 /// after parsing of the associated statement.
10491 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10492 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10493 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10494 /// Called on well-formed '\#pragma omp target teams distribute parallel for
10495 /// simd' after parsing of the associated statement.
10496 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10497 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10498 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10499 /// Called on well-formed '\#pragma omp target teams distribute simd' after
10500 /// parsing of the associated statement.
10501 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
10502 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10503 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10504
10505 /// Checks correctness of linear modifiers.
10506 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10507 SourceLocation LinLoc);
10508 /// Checks that the specified declaration matches requirements for the linear
10509 /// decls.
10510 bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
10511 OpenMPLinearClauseKind LinKind, QualType Type,
10512 bool IsDeclareSimd = false);
10513
10514 /// Called on well-formed '\#pragma omp declare simd' after parsing of
10515 /// the associated method/function.
10516 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
10517 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
10518 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
10519 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
10520 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
10521
10522 /// Checks '\#pragma omp declare variant' variant function and original
10523 /// functions after parsing of the associated method/function.
10524 /// \param DG Function declaration to which declare variant directive is
10525 /// applied to.
10526 /// \param VariantRef Expression that references the variant function, which
10527 /// must be used instead of the original one, specified in \p DG.
10528 /// \param TI The trait info object representing the match clause.
10529 /// \returns None, if the function/variant function are not compatible with
10530 /// the pragma, pair of original function/variant ref expression otherwise.
10531 Optional<std::pair<FunctionDecl *, Expr *>>
10532 checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef,
10533 OMPTraitInfo &TI, SourceRange SR);
10534
10535 /// Called on well-formed '\#pragma omp declare variant' after parsing of
10536 /// the associated method/function.
10537 /// \param FD Function declaration to which declare variant directive is
10538 /// applied to.
10539 /// \param VariantRef Expression that references the variant function, which
10540 /// must be used instead of the original one, specified in \p DG.
10541 /// \param TI The context traits associated with the function variant.
10542 void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef,
10543 OMPTraitInfo &TI, SourceRange SR);
10544
10545 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
10546 Expr *Expr,
10547 SourceLocation StartLoc,
10548 SourceLocation LParenLoc,
10549 SourceLocation EndLoc);
10550 /// Called on well-formed 'allocator' clause.
10551 OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
10552 SourceLocation StartLoc,
10553 SourceLocation LParenLoc,
10554 SourceLocation EndLoc);
10555 /// Called on well-formed 'if' clause.
10556 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
10557 Expr *Condition, SourceLocation StartLoc,
10558 SourceLocation LParenLoc,
10559 SourceLocation NameModifierLoc,
10560 SourceLocation ColonLoc,
10561 SourceLocation EndLoc);
10562 /// Called on well-formed 'final' clause.
10563 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
10564 SourceLocation LParenLoc,
10565 SourceLocation EndLoc);
10566 /// Called on well-formed 'num_threads' clause.
10567 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
10568 SourceLocation StartLoc,
10569 SourceLocation LParenLoc,
10570 SourceLocation EndLoc);
10571 /// Called on well-formed 'safelen' clause.
10572 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
10573 SourceLocation StartLoc,
10574 SourceLocation LParenLoc,
10575 SourceLocation EndLoc);
10576 /// Called on well-formed 'simdlen' clause.
10577 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
10578 SourceLocation LParenLoc,
10579 SourceLocation EndLoc);
10580 /// Called on well-formed 'collapse' clause.
10581 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
10582 SourceLocation StartLoc,
10583 SourceLocation LParenLoc,
10584 SourceLocation EndLoc);
10585 /// Called on well-formed 'ordered' clause.
10586 OMPClause *
10587 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
10588 SourceLocation LParenLoc = SourceLocation(),
10589 Expr *NumForLoops = nullptr);
10590 /// Called on well-formed 'grainsize' clause.
10591 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
10592 SourceLocation LParenLoc,
10593 SourceLocation EndLoc);
10594 /// Called on well-formed 'num_tasks' clause.
10595 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
10596 SourceLocation LParenLoc,
10597 SourceLocation EndLoc);
10598 /// Called on well-formed 'hint' clause.
10599 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10600 SourceLocation LParenLoc,
10601 SourceLocation EndLoc);
10602 /// Called on well-formed 'detach' clause.
10603 OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
10604 SourceLocation LParenLoc,
10605 SourceLocation EndLoc);
10606
10607 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
10608 unsigned Argument,
10609 SourceLocation ArgumentLoc,
10610 SourceLocation StartLoc,
10611 SourceLocation LParenLoc,
10612 SourceLocation EndLoc);
10613 /// Called on well-formed 'default' clause.
10614 OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind,
10615 SourceLocation KindLoc,
10616 SourceLocation StartLoc,
10617 SourceLocation LParenLoc,
10618 SourceLocation EndLoc);
10619 /// Called on well-formed 'proc_bind' clause.
10620 OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
10621 SourceLocation KindLoc,
10622 SourceLocation StartLoc,
10623 SourceLocation LParenLoc,
10624 SourceLocation EndLoc);
10625 /// Called on well-formed 'order' clause.
10626 OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
10627 SourceLocation KindLoc,
10628 SourceLocation StartLoc,
10629 SourceLocation LParenLoc,
10630 SourceLocation EndLoc);
10631 /// Called on well-formed 'update' clause.
10632 OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
10633 SourceLocation KindLoc,
10634 SourceLocation StartLoc,
10635 SourceLocation LParenLoc,
10636 SourceLocation EndLoc);
10637
10638 OMPClause *ActOnOpenMPSingleExprWithArgClause(
10639 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
10640 SourceLocation StartLoc, SourceLocation LParenLoc,
10641 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
10642 SourceLocation EndLoc);
10643 /// Called on well-formed 'schedule' clause.
10644 OMPClause *ActOnOpenMPScheduleClause(
10645 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
10646 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10647 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
10648 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
10649
10650 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
10651 SourceLocation EndLoc);
10652 /// Called on well-formed 'nowait' clause.
10653 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
10654 SourceLocation EndLoc);
10655 /// Called on well-formed 'untied' clause.
10656 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
10657 SourceLocation EndLoc);
10658 /// Called on well-formed 'mergeable' clause.
10659 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
10660 SourceLocation EndLoc);
10661 /// Called on well-formed 'read' clause.
10662 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
10663 SourceLocation EndLoc);
10664 /// Called on well-formed 'write' clause.
10665 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
10666 SourceLocation EndLoc);
10667 /// Called on well-formed 'update' clause.
10668 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10669 SourceLocation EndLoc);
10670 /// Called on well-formed 'capture' clause.
10671 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10672 SourceLocation EndLoc);
10673 /// Called on well-formed 'seq_cst' clause.
10674 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10675 SourceLocation EndLoc);
10676 /// Called on well-formed 'acq_rel' clause.
10677 OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
10678 SourceLocation EndLoc);
10679 /// Called on well-formed 'acquire' clause.
10680 OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc,
10681 SourceLocation EndLoc);
10682 /// Called on well-formed 'release' clause.
10683 OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc,
10684 SourceLocation EndLoc);
10685 /// Called on well-formed 'relaxed' clause.
10686 OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
10687 SourceLocation EndLoc);
10688 /// Called on well-formed 'destroy' clause.
10689 OMPClause *ActOnOpenMPDestroyClause(SourceLocation StartLoc,
10690 SourceLocation EndLoc);
10691 /// Called on well-formed 'threads' clause.
10692 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10693 SourceLocation EndLoc);
10694 /// Called on well-formed 'simd' clause.
10695 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10696 SourceLocation EndLoc);
10697 /// Called on well-formed 'nogroup' clause.
10698 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10699 SourceLocation EndLoc);
10700 /// Called on well-formed 'unified_address' clause.
10701 OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10702 SourceLocation EndLoc);
10703
10704 /// Called on well-formed 'unified_address' clause.
10705 OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10706 SourceLocation EndLoc);
10707
10708 /// Called on well-formed 'reverse_offload' clause.
10709 OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10710 SourceLocation EndLoc);
10711
10712 /// Called on well-formed 'dynamic_allocators' clause.
10713 OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10714 SourceLocation EndLoc);
10715
10716 /// Called on well-formed 'atomic_default_mem_order' clause.
10717 OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
10718 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
10719 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
10720
10721 OMPClause *ActOnOpenMPVarListClause(
10722 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr,
10723 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10724 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10725 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
10726 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10727 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
10728 SourceLocation ExtraModifierLoc,
10729 ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
10730 ArrayRef<SourceLocation> MotionModifiersLoc);
10731 /// Called on well-formed 'inclusive' clause.
10732 OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
10733 SourceLocation StartLoc,
10734 SourceLocation LParenLoc,
10735 SourceLocation EndLoc);
10736 /// Called on well-formed 'exclusive' clause.
10737 OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
10738 SourceLocation StartLoc,
10739 SourceLocation LParenLoc,
10740 SourceLocation EndLoc);
10741 /// Called on well-formed 'allocate' clause.
10742 OMPClause *
10743 ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
10744 SourceLocation StartLoc, SourceLocation ColonLoc,
10745 SourceLocation LParenLoc, SourceLocation EndLoc);
10746 /// Called on well-formed 'private' clause.
10747 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10748 SourceLocation StartLoc,
10749 SourceLocation LParenLoc,
10750 SourceLocation EndLoc);
10751 /// Called on well-formed 'firstprivate' clause.
10752 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10753 SourceLocation StartLoc,
10754 SourceLocation LParenLoc,
10755 SourceLocation EndLoc);
10756 /// Called on well-formed 'lastprivate' clause.
10757 OMPClause *ActOnOpenMPLastprivateClause(
10758 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
10759 SourceLocation LPKindLoc, SourceLocation ColonLoc,
10760 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
10761 /// Called on well-formed 'shared' clause.
10762 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10763 SourceLocation StartLoc,
10764 SourceLocation LParenLoc,
10765 SourceLocation EndLoc);
10766 /// Called on well-formed 'reduction' clause.
10767 OMPClause *ActOnOpenMPReductionClause(
10768 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
10769 SourceLocation StartLoc, SourceLocation LParenLoc,
10770 SourceLocation ModifierLoc, SourceLocation ColonLoc,
10771 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
10772 const DeclarationNameInfo &ReductionId,
10773 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10774 /// Called on well-formed 'task_reduction' clause.
10775 OMPClause *ActOnOpenMPTaskReductionClause(
10776 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10777 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
10778 CXXScopeSpec &ReductionIdScopeSpec,
10779 const DeclarationNameInfo &ReductionId,
10780 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10781 /// Called on well-formed 'in_reduction' clause.
10782 OMPClause *ActOnOpenMPInReductionClause(
10783 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10784 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
10785 CXXScopeSpec &ReductionIdScopeSpec,
10786 const DeclarationNameInfo &ReductionId,
10787 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10788 /// Called on well-formed 'linear' clause.
10789 OMPClause *
10790 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
10791 SourceLocation StartLoc, SourceLocation LParenLoc,
10792 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
10793 SourceLocation ColonLoc, SourceLocation EndLoc);
10794 /// Called on well-formed 'aligned' clause.
10795 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
10796 Expr *Alignment,
10797 SourceLocation StartLoc,
10798 SourceLocation LParenLoc,
10799 SourceLocation ColonLoc,
10800 SourceLocation EndLoc);
10801 /// Called on well-formed 'copyin' clause.
10802 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10803 SourceLocation StartLoc,
10804 SourceLocation LParenLoc,
10805 SourceLocation EndLoc);
10806 /// Called on well-formed 'copyprivate' clause.
10807 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10808 SourceLocation StartLoc,
10809 SourceLocation LParenLoc,
10810 SourceLocation EndLoc);
10811 /// Called on well-formed 'flush' pseudo clause.
10812 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10813 SourceLocation StartLoc,
10814 SourceLocation LParenLoc,
10815 SourceLocation EndLoc);
10816 /// Called on well-formed 'depobj' pseudo clause.
10817 OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
10818 SourceLocation LParenLoc,
10819 SourceLocation EndLoc);
10820 /// Called on well-formed 'depend' clause.
10821 OMPClause *
10822 ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
10823 SourceLocation DepLoc, SourceLocation ColonLoc,
10824 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10825 SourceLocation LParenLoc, SourceLocation EndLoc);
10826 /// Called on well-formed 'device' clause.
10827 OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
10828 Expr *Device, SourceLocation StartLoc,
10829 SourceLocation LParenLoc,
10830 SourceLocation ModifierLoc,
10831 SourceLocation EndLoc);
10832 /// Called on well-formed 'map' clause.
10833 OMPClause *
10834 ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10835 ArrayRef<SourceLocation> MapTypeModifiersLoc,
10836 CXXScopeSpec &MapperIdScopeSpec,
10837 DeclarationNameInfo &MapperId,
10838 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10839 SourceLocation MapLoc, SourceLocation ColonLoc,
10840 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
10841 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10842 /// Called on well-formed 'num_teams' clause.
10843 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
10844 SourceLocation LParenLoc,
10845 SourceLocation EndLoc);
10846 /// Called on well-formed 'thread_limit' clause.
10847 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10848 SourceLocation StartLoc,
10849 SourceLocation LParenLoc,
10850 SourceLocation EndLoc);
10851 /// Called on well-formed 'priority' clause.
10852 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
10853 SourceLocation LParenLoc,
10854 SourceLocation EndLoc);
10855 /// Called on well-formed 'dist_schedule' clause.
10856 OMPClause *ActOnOpenMPDistScheduleClause(
10857 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
10858 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
10859 SourceLocation CommaLoc, SourceLocation EndLoc);
10860 /// Called on well-formed 'defaultmap' clause.
10861 OMPClause *ActOnOpenMPDefaultmapClause(
10862 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10863 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10864 SourceLocation KindLoc, SourceLocation EndLoc);
10865 /// Called on well-formed 'to' clause.
10866 OMPClause *
10867 ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
10868 ArrayRef<SourceLocation> MotionModifiersLoc,
10869 CXXScopeSpec &MapperIdScopeSpec,
10870 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
10871 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
10872 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10873 /// Called on well-formed 'from' clause.
10874 OMPClause *
10875 ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
10876 ArrayRef<SourceLocation> MotionModifiersLoc,
10877 CXXScopeSpec &MapperIdScopeSpec,
10878 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
10879 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
10880 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10881 /// Called on well-formed 'use_device_ptr' clause.
10882 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10883 const OMPVarListLocTy &Locs);
10884 /// Called on well-formed 'use_device_addr' clause.
10885 OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
10886 const OMPVarListLocTy &Locs);
10887 /// Called on well-formed 'is_device_ptr' clause.
10888 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10889 const OMPVarListLocTy &Locs);
10890 /// Called on well-formed 'nontemporal' clause.
10891 OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
10892 SourceLocation StartLoc,
10893 SourceLocation LParenLoc,
10894 SourceLocation EndLoc);
10895
10896 /// Data for list of allocators.
10897 struct UsesAllocatorsData {
10898 /// Allocator.
10899 Expr *Allocator = nullptr;
10900 /// Allocator traits.
10901 Expr *AllocatorTraits = nullptr;
10902 /// Locations of '(' and ')' symbols.
10903 SourceLocation LParenLoc, RParenLoc;
10904 };
10905 /// Called on well-formed 'uses_allocators' clause.
10906 OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc,
10907 SourceLocation LParenLoc,
10908 SourceLocation EndLoc,
10909 ArrayRef<UsesAllocatorsData> Data);
10910 /// Called on well-formed 'affinity' clause.
10911 OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc,
10912 SourceLocation LParenLoc,
10913 SourceLocation ColonLoc,
10914 SourceLocation EndLoc, Expr *Modifier,
10915 ArrayRef<Expr *> Locators);
10916
10917 /// The kind of conversion being performed.
10918 enum CheckedConversionKind {
10919 /// An implicit conversion.
10920 CCK_ImplicitConversion,
10921 /// A C-style cast.
10922 CCK_CStyleCast,
10923 /// A functional-style cast.
10924 CCK_FunctionalCast,
10925 /// A cast other than a C-style cast.
10926 CCK_OtherCast,
10927 /// A conversion for an operand of a builtin overloaded operator.
10928 CCK_ForBuiltinOverloadedOp
10929 };
10930
10931 static bool isCast(CheckedConversionKind CCK) {
10932 return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
10933 CCK == CCK_OtherCast;
10934 }
10935
10936 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
10937 /// cast. If there is already an implicit cast, merge into the existing one.
10938 /// If isLvalue, the result of the cast is an lvalue.
10939 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
10940 ExprValueKind VK = VK_RValue,
10941 const CXXCastPath *BasePath = nullptr,
10942 CheckedConversionKind CCK
10943 = CCK_ImplicitConversion);
10944
10945 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
10946 /// to the conversion from scalar type ScalarTy to the Boolean type.
10947 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
10948
10949 /// IgnoredValueConversions - Given that an expression's result is
10950 /// syntactically ignored, perform any conversions that are
10951 /// required.
10952 ExprResult IgnoredValueConversions(Expr *E);
10953
10954 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
10955 // functions and arrays to their respective pointers (C99 6.3.2.1).
10956 ExprResult UsualUnaryConversions(Expr *E);
10957
10958 /// CallExprUnaryConversions - a special case of an unary conversion
10959 /// performed on a function designator of a call expression.
10960 ExprResult CallExprUnaryConversions(Expr *E);
10961
10962 // DefaultFunctionArrayConversion - converts functions and arrays
10963 // to their respective pointers (C99 6.3.2.1).
10964 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
10965
10966 // DefaultFunctionArrayLvalueConversion - converts functions and
10967 // arrays to their respective pointers and performs the
10968 // lvalue-to-rvalue conversion.
10969 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
10970 bool Diagnose = true);
10971
10972 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
10973 // the operand. This function is a no-op if the operand has a function type
10974 // or an array type.
10975 ExprResult DefaultLvalueConversion(Expr *E);
10976
10977 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
10978 // do not have a prototype. Integer promotions are performed on each
10979 // argument, and arguments that have type float are promoted to double.
10980 ExprResult DefaultArgumentPromotion(Expr *E);
10981
10982 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
10983 /// it as an xvalue. In C++98, the result will still be a prvalue, because
10984 /// we don't have xvalues there.
10985 ExprResult TemporaryMaterializationConversion(Expr *E);
10986
10987 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
10988 enum VariadicCallType {
10989 VariadicFunction,
10990 VariadicBlock,
10991 VariadicMethod,
10992 VariadicConstructor,
10993 VariadicDoesNotApply
10994 };
10995
10996 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
10997 const FunctionProtoType *Proto,
10998 Expr *Fn);
10999
11000 // Used for determining in which context a type is allowed to be passed to a
11001 // vararg function.
11002 enum VarArgKind {
11003 VAK_Valid,
11004 VAK_ValidInCXX11,
11005 VAK_Undefined,
11006 VAK_MSVCUndefined,
11007 VAK_Invalid
11008 };
11009
11010 // Determines which VarArgKind fits an expression.
11011 VarArgKind isValidVarArgType(const QualType &Ty);
11012
11013 /// Check to see if the given expression is a valid argument to a variadic
11014 /// function, issuing a diagnostic if not.
11015 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
11016
11017 /// Check to see if a given expression could have '.c_str()' called on it.
11018 bool hasCStrMethod(const Expr *E);
11019
11020 /// GatherArgumentsForCall - Collector argument expressions for various
11021 /// form of call prototypes.
11022 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
11023 const FunctionProtoType *Proto,
11024 unsigned FirstParam, ArrayRef<Expr *> Args,
11025 SmallVectorImpl<Expr *> &AllArgs,
11026 VariadicCallType CallType = VariadicDoesNotApply,
11027 bool AllowExplicit = false,
11028 bool IsListInitialization = false);
11029
11030 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
11031 // will create a runtime trap if the resulting type is not a POD type.
11032 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
11033 FunctionDecl *FDecl);
11034
11035 /// Context in which we're performing a usual arithmetic conversion.
11036 enum ArithConvKind {
11037 /// An arithmetic operation.
11038 ACK_Arithmetic,
11039 /// A bitwise operation.
11040 ACK_BitwiseOp,
11041 /// A comparison.
11042 ACK_Comparison,
11043 /// A conditional (?:) operator.
11044 ACK_Conditional,
11045 /// A compound assignment expression.
11046 ACK_CompAssign,
11047 };
11048
11049 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
11050 // operands and then handles various conversions that are common to binary
11051 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
11052 // routine returns the first non-arithmetic type found. The client is
11053 // responsible for emitting appropriate error diagnostics.
11054 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
11055 SourceLocation Loc, ArithConvKind ACK);
11056
11057 /// AssignConvertType - All of the 'assignment' semantic checks return this
11058 /// enum to indicate whether the assignment was allowed. These checks are
11059 /// done for simple assignments, as well as initialization, return from
11060 /// function, argument passing, etc. The query is phrased in terms of a
11061 /// source and destination type.
11062 enum AssignConvertType {
11063 /// Compatible - the types are compatible according to the standard.
11064 Compatible,
11065
11066 /// PointerToInt - The assignment converts a pointer to an int, which we
11067 /// accept as an extension.
11068 PointerToInt,
11069
11070 /// IntToPointer - The assignment converts an int to a pointer, which we
11071 /// accept as an extension.
11072 IntToPointer,
11073
11074 /// FunctionVoidPointer - The assignment is between a function pointer and
11075 /// void*, which the standard doesn't allow, but we accept as an extension.
11076 FunctionVoidPointer,
11077
11078 /// IncompatiblePointer - The assignment is between two pointers types that
11079 /// are not compatible, but we accept them as an extension.
11080 IncompatiblePointer,
11081
11082 /// IncompatibleFunctionPointer - The assignment is between two function
11083 /// pointers types that are not compatible, but we accept them as an
11084 /// extension.
11085 IncompatibleFunctionPointer,
11086
11087 /// IncompatiblePointerSign - The assignment is between two pointers types
11088 /// which point to integers which have a different sign, but are otherwise
11089 /// identical. This is a subset of the above, but broken out because it's by
11090 /// far the most common case of incompatible pointers.
11091 IncompatiblePointerSign,
11092
11093 /// CompatiblePointerDiscardsQualifiers - The assignment discards
11094 /// c/v/r qualifiers, which we accept as an extension.
11095 CompatiblePointerDiscardsQualifiers,
11096
11097 /// IncompatiblePointerDiscardsQualifiers - The assignment
11098 /// discards qualifiers that we don't permit to be discarded,
11099 /// like address spaces.
11100 IncompatiblePointerDiscardsQualifiers,
11101
11102 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
11103 /// changes address spaces in nested pointer types which is not allowed.
11104 /// For instance, converting __private int ** to __generic int ** is
11105 /// illegal even though __private could be converted to __generic.
11106 IncompatibleNestedPointerAddressSpaceMismatch,
11107
11108 /// IncompatibleNestedPointerQualifiers - The assignment is between two
11109 /// nested pointer types, and the qualifiers other than the first two
11110 /// levels differ e.g. char ** -> const char **, but we accept them as an
11111 /// extension.
11112 IncompatibleNestedPointerQualifiers,
11113
11114 /// IncompatibleVectors - The assignment is between two vector types that
11115 /// have the same size, which we accept as an extension.
11116 IncompatibleVectors,
11117
11118 /// IntToBlockPointer - The assignment converts an int to a block
11119 /// pointer. We disallow this.
11120 IntToBlockPointer,
11121
11122 /// IncompatibleBlockPointer - The assignment is between two block
11123 /// pointers types that are not compatible.
11124 IncompatibleBlockPointer,
11125
11126 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
11127 /// id type and something else (that is incompatible with it). For example,
11128 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
11129 IncompatibleObjCQualifiedId,
11130
11131 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
11132 /// object with __weak qualifier.
11133 IncompatibleObjCWeakRef,
11134
11135 /// Incompatible - We reject this conversion outright, it is invalid to
11136 /// represent it in the AST.
11137 Incompatible
11138 };
11139
11140 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
11141 /// assignment conversion type specified by ConvTy. This returns true if the
11142 /// conversion was invalid or false if the conversion was accepted.
11143 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
11144 SourceLocation Loc,
11145 QualType DstType, QualType SrcType,
11146 Expr *SrcExpr, AssignmentAction Action,
11147 bool *Complained = nullptr);
11148
11149 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
11150 /// enum. If AllowMask is true, then we also allow the complement of a valid
11151 /// value, to be used as a mask.
11152 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
11153 bool AllowMask) const;
11154
11155 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11156 /// integer not in the range of enum values.
11157 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11158 Expr *SrcExpr);
11159
11160 /// CheckAssignmentConstraints - Perform type checking for assignment,
11161 /// argument passing, variable initialization, and function return values.
11162 /// C99 6.5.16.
11163 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
11164 QualType LHSType,
11165 QualType RHSType);
11166
11167 /// Check assignment constraints and optionally prepare for a conversion of
11168 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
11169 /// is true.
11170 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
11171 ExprResult &RHS,
11172 CastKind &Kind,
11173 bool ConvertRHS = true);
11174
11175 /// Check assignment constraints for an assignment of RHS to LHSType.
11176 ///
11177 /// \param LHSType The destination type for the assignment.
11178 /// \param RHS The source expression for the assignment.
11179 /// \param Diagnose If \c true, diagnostics may be produced when checking
11180 /// for assignability. If a diagnostic is produced, \p RHS will be
11181 /// set to ExprError(). Note that this function may still return
11182 /// without producing a diagnostic, even for an invalid assignment.
11183 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
11184 /// in an audited Core Foundation API and does not need to be checked
11185 /// for ARC retain issues.
11186 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
11187 /// conversions necessary to perform the assignment. If \c false,
11188 /// \p Diagnose must also be \c false.
11189 AssignConvertType CheckSingleAssignmentConstraints(
11190 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
11191 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
11192
11193 // If the lhs type is a transparent union, check whether we
11194 // can initialize the transparent union with the given expression.
11195 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
11196 ExprResult &RHS);
11197
11198 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
11199
11200 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
11201
11202 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11203 AssignmentAction Action,
11204 bool AllowExplicit = false);
11205 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11206 AssignmentAction Action,
11207 bool AllowExplicit,
11208 ImplicitConversionSequence& ICS);
11209 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11210 const ImplicitConversionSequence& ICS,
11211 AssignmentAction Action,
11212 CheckedConversionKind CCK
11213 = CCK_ImplicitConversion);
11214 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11215 const StandardConversionSequence& SCS,
11216 AssignmentAction Action,
11217 CheckedConversionKind CCK);
11218
11219 ExprResult PerformQualificationConversion(
11220 Expr *E, QualType Ty, ExprValueKind VK = VK_RValue,
11221 CheckedConversionKind CCK = CCK_ImplicitConversion);
11222
11223 /// the following "Check" methods will return a valid/converted QualType
11224 /// or a null QualType (indicating an error diagnostic was issued).
11225
11226 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
11227 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
11228 ExprResult &RHS);
11229 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
11230 ExprResult &RHS);
11231 QualType CheckPointerToMemberOperands( // C++ 5.5
11232 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
11233 SourceLocation OpLoc, bool isIndirect);
11234 QualType CheckMultiplyDivideOperands( // C99 6.5.5
11235 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
11236 bool IsDivide);
11237 QualType CheckRemainderOperands( // C99 6.5.5
11238 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11239 bool IsCompAssign = false);
11240 QualType CheckAdditionOperands( // C99 6.5.6
11241 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11242 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
11243 QualType CheckSubtractionOperands( // C99 6.5.6
11244 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11245 QualType* CompLHSTy = nullptr);
11246 QualType CheckShiftOperands( // C99 6.5.7
11247 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11248 BinaryOperatorKind Opc, bool IsCompAssign = false);
11249 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
11250 QualType CheckCompareOperands( // C99 6.5.8/9
11251 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11252 BinaryOperatorKind Opc);
11253 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
11254 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11255 BinaryOperatorKind Opc);
11256 QualType CheckLogicalOperands( // C99 6.5.[13,14]
11257 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11258 BinaryOperatorKind Opc);
11259 // CheckAssignmentOperands is used for both simple and compound assignment.
11260 // For simple assignment, pass both expressions and a null converted type.
11261 // For compound assignment, pass both expressions and the converted type.
11262 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
11263 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
11264
11265 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
11266 UnaryOperatorKind Opcode, Expr *Op);
11267 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
11268 BinaryOperatorKind Opcode,
11269 Expr *LHS, Expr *RHS);
11270 ExprResult checkPseudoObjectRValue(Expr *E);
11271 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
11272
11273 QualType CheckConditionalOperands( // C99 6.5.15
11274 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
11275 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
11276 QualType CXXCheckConditionalOperands( // C++ 5.16
11277 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
11278 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
11279 QualType CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
11280 ExprResult &RHS,
11281 SourceLocation QuestionLoc);
11282 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
11283 bool ConvertArgs = true);
11284 QualType FindCompositePointerType(SourceLocation Loc,
11285 ExprResult &E1, ExprResult &E2,
11286 bool ConvertArgs = true) {
11287 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
11288 QualType Composite =
11289 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
11290 E1 = E1Tmp;
11291 E2 = E2Tmp;
11292 return Composite;
11293 }
11294
11295 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
11296 SourceLocation QuestionLoc);
11297
11298 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
11299 SourceLocation QuestionLoc);
11300
11301 void DiagnoseAlwaysNonNullPointer(Expr *E,
11302 Expr::NullPointerConstantKind NullType,
11303 bool IsEqual, SourceRange Range);
11304
11305 /// type checking for vector binary operators.
11306 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
11307 SourceLocation Loc, bool IsCompAssign,
11308 bool AllowBothBool, bool AllowBoolConversion);
11309 QualType GetSignedVectorType(QualType V);
11310 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11311 SourceLocation Loc,
11312 BinaryOperatorKind Opc);
11313 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11314 SourceLocation Loc);
11315
11316 /// Type checking for matrix binary operators.
11317 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
11318 SourceLocation Loc,
11319 bool IsCompAssign);
11320 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
11321 SourceLocation Loc, bool IsCompAssign);
11322
11323 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
11324 bool isLaxVectorConversion(QualType srcType, QualType destType);
11325
11326 /// type checking declaration initializers (C99 6.7.8)
11327 bool CheckForConstantInitializer(Expr *e, QualType t);
11328
11329 // type checking C++ declaration initializers (C++ [dcl.init]).
11330
11331 /// ReferenceCompareResult - Expresses the result of comparing two
11332 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
11333 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
11334 enum ReferenceCompareResult {
11335 /// Ref_Incompatible - The two types are incompatible, so direct
11336 /// reference binding is not possible.
11337 Ref_Incompatible = 0,
11338 /// Ref_Related - The two types are reference-related, which means
11339 /// that their unqualified forms (T1 and T2) are either the same
11340 /// or T1 is a base class of T2.
11341 Ref_Related,
11342 /// Ref_Compatible - The two types are reference-compatible.
11343 Ref_Compatible
11344 };
11345
11346 // Fake up a scoped enumeration that still contextually converts to bool.
11347 struct ReferenceConversionsScope {
11348 /// The conversions that would be performed on an lvalue of type T2 when
11349 /// binding a reference of type T1 to it, as determined when evaluating
11350 /// whether T1 is reference-compatible with T2.
11351 enum ReferenceConversions {
11352 Qualification = 0x1,
11353 NestedQualification = 0x2,
11354 Function = 0x4,
11355 DerivedToBase = 0x8,
11356 ObjC = 0x10,
11357 ObjCLifetime = 0x20,
11358
11359 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)LLVM_BITMASK_LARGEST_ENUMERATOR = ObjCLifetime
11360 };
11361 };
11362 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
11363
11364 ReferenceCompareResult
11365 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
11366 ReferenceConversions *Conv = nullptr);
11367
11368 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11369 Expr *CastExpr, CastKind &CastKind,
11370 ExprValueKind &VK, CXXCastPath &Path);
11371
11372 /// Force an expression with unknown-type to an expression of the
11373 /// given type.
11374 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
11375
11376 /// Type-check an expression that's being passed to an
11377 /// __unknown_anytype parameter.
11378 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
11379 Expr *result, QualType &paramType);
11380
11381 // CheckVectorCast - check type constraints for vectors.
11382 // Since vectors are an extension, there are no C standard reference for this.
11383 // We allow casting between vectors and integer datatypes of the same size.
11384 // returns true if the cast is invalid
11385 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
11386 CastKind &Kind);
11387
11388 /// Prepare `SplattedExpr` for a vector splat operation, adding
11389 /// implicit casts if necessary.
11390 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
11391
11392 // CheckExtVectorCast - check type constraints for extended vectors.
11393 // Since vectors are an extension, there are no C standard reference for this.
11394 // We allow casting between vectors and integer datatypes of the same size,
11395 // or vectors and the element type of that vector.
11396 // returns the cast expr
11397 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
11398 CastKind &Kind);
11399
11400 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
11401 SourceLocation LParenLoc,
11402 Expr *CastExpr,
11403 SourceLocation RParenLoc);
11404
11405 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
11406
11407 /// Checks for invalid conversions and casts between
11408 /// retainable pointers and other pointer kinds for ARC and Weak.
11409 ARCConversionResult CheckObjCConversion(SourceRange castRange,
11410 QualType castType, Expr *&op,
11411 CheckedConversionKind CCK,
11412 bool Diagnose = true,
11413 bool DiagnoseCFAudited = false,
11414 BinaryOperatorKind Opc = BO_PtrMemD
11415 );
11416
11417 Expr *stripARCUnbridgedCast(Expr *e);
11418 void diagnoseARCUnbridgedCast(Expr *e);
11419
11420 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
11421 QualType ExprType);
11422
11423 /// checkRetainCycles - Check whether an Objective-C message send
11424 /// might create an obvious retain cycle.
11425 void checkRetainCycles(ObjCMessageExpr *msg);
11426 void checkRetainCycles(Expr *receiver, Expr *argument);
11427 void checkRetainCycles(VarDecl *Var, Expr *Init);
11428
11429 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
11430 /// to weak/__unsafe_unretained type.
11431 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
11432
11433 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
11434 /// to weak/__unsafe_unretained expression.
11435 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
11436
11437 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
11438 /// \param Method - May be null.
11439 /// \param [out] ReturnType - The return type of the send.
11440 /// \return true iff there were any incompatible types.
11441 bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
11442 MultiExprArg Args, Selector Sel,
11443 ArrayRef<SourceLocation> SelectorLocs,
11444 ObjCMethodDecl *Method, bool isClassMessage,
11445 bool isSuperMessage, SourceLocation lbrac,
11446 SourceLocation rbrac, SourceRange RecRange,
11447 QualType &ReturnType, ExprValueKind &VK);
11448
11449 /// Determine the result of a message send expression based on
11450 /// the type of the receiver, the method expected to receive the message,
11451 /// and the form of the message send.
11452 QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
11453 ObjCMethodDecl *Method, bool isClassMessage,
11454 bool isSuperMessage);
11455
11456 /// If the given expression involves a message send to a method
11457 /// with a related result type, emit a note describing what happened.
11458 void EmitRelatedResultTypeNote(const Expr *E);
11459
11460 /// Given that we had incompatible pointer types in a return
11461 /// statement, check whether we're in a method with a related result
11462 /// type, and if so, emit a note describing what happened.
11463 void EmitRelatedResultTypeNoteForReturn(QualType destType);
11464
11465 class ConditionResult {
11466 Decl *ConditionVar;
11467 FullExprArg Condition;
11468 bool Invalid;
11469 bool HasKnownValue;
11470 bool KnownValue;
11471
11472 friend class Sema;
11473 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
11474 bool IsConstexpr)
11475 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
11476 HasKnownValue(IsConstexpr && Condition.get() &&
11477 !Condition.get()->isValueDependent()),
11478 KnownValue(HasKnownValue &&
11479 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
11480 explicit ConditionResult(bool Invalid)
11481 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
11482 HasKnownValue(false), KnownValue(false) {}
11483
11484 public:
11485 ConditionResult() : ConditionResult(false) {}
11486 bool isInvalid() const { return Invalid; }
11487 std::pair<VarDecl *, Expr *> get() const {
11488 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
11489 Condition.get());
11490 }
11491 llvm::Optional<bool> getKnownValue() const {
11492 if (!HasKnownValue)
11493 return None;
11494 return KnownValue;
11495 }
11496 };
11497 static ConditionResult ConditionError() { return ConditionResult(true); }
11498
11499 enum class ConditionKind {
11500 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
11501 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
11502 Switch ///< An integral condition for a 'switch' statement.
11503 };
11504
11505 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
11506 Expr *SubExpr, ConditionKind CK);
11507
11508 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
11509 SourceLocation StmtLoc,
11510 ConditionKind CK);
11511
11512 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
11513
11514 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
11515 SourceLocation StmtLoc,
11516 ConditionKind CK);
11517 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11518
11519 /// CheckBooleanCondition - Diagnose problems involving the use of
11520 /// the given expression as a boolean condition (e.g. in an if
11521 /// statement). Also performs the standard function and array
11522 /// decays, possibly changing the input variable.
11523 ///
11524 /// \param Loc - A location associated with the condition, e.g. the
11525 /// 'if' keyword.
11526 /// \return true iff there were any errors
11527 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
11528 bool IsConstexpr = false);
11529
11530 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
11531 /// found in an explicit(bool) specifier.
11532 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
11533
11534 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
11535 /// Returns true if the explicit specifier is now resolved.
11536 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
11537
11538 /// DiagnoseAssignmentAsCondition - Given that an expression is
11539 /// being used as a boolean condition, warn if it's an assignment.
11540 void DiagnoseAssignmentAsCondition(Expr *E);
11541
11542 /// Redundant parentheses over an equality comparison can indicate
11543 /// that the user intended an assignment used as condition.
11544 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
11545
11546 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
11547 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
11548
11549 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
11550 /// the specified width and sign. If an overflow occurs, detect it and emit
11551 /// the specified diagnostic.
11552 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
11553 unsigned NewWidth, bool NewSign,
11554 SourceLocation Loc, unsigned DiagID);
11555
11556 /// Checks that the Objective-C declaration is declared in the global scope.
11557 /// Emits an error and marks the declaration as invalid if it's not declared
11558 /// in the global scope.
11559 bool CheckObjCDeclScope(Decl *D);
11560
11561 /// Abstract base class used for diagnosing integer constant
11562 /// expression violations.
11563 class VerifyICEDiagnoser {
11564 public:
11565 bool Suppress;
11566
11567 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
11568
11569 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
11570 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
11571 virtual ~VerifyICEDiagnoser() { }
11572 };
11573
11574 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
11575 /// and reports the appropriate diagnostics. Returns false on success.
11576 /// Can optionally return the value of the expression.
11577 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11578 VerifyICEDiagnoser &Diagnoser,
11579 bool AllowFold = true);
11580 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11581 unsigned DiagID,
11582 bool AllowFold = true);
11583 ExprResult VerifyIntegerConstantExpression(Expr *E,
11584 llvm::APSInt *Result = nullptr);
11585
11586 /// VerifyBitField - verifies that a bit field expression is an ICE and has
11587 /// the correct width, and that the field type is valid.
11588 /// Returns false on success.
11589 /// Can optionally return whether the bit-field is of width 0
11590 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
11591 QualType FieldTy, bool IsMsStruct,
11592 Expr *BitWidth, bool *ZeroWidth = nullptr);
11593
11594private:
11595 unsigned ForceCUDAHostDeviceDepth = 0;
11596
11597public:
11598 /// Increments our count of the number of times we've seen a pragma forcing
11599 /// functions to be __host__ __device__. So long as this count is greater
11600 /// than zero, all functions encountered will be __host__ __device__.
11601 void PushForceCUDAHostDevice();
11602
11603 /// Decrements our count of the number of times we've seen a pragma forcing
11604 /// functions to be __host__ __device__. Returns false if the count is 0
11605 /// before incrementing, so you can emit an error.
11606 bool PopForceCUDAHostDevice();
11607
11608 /// Diagnostics that are emitted only if we discover that the given function
11609 /// must be codegen'ed. Because handling these correctly adds overhead to
11610 /// compilation, this is currently only enabled for CUDA compilations.
11611 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
11612 std::vector<PartialDiagnosticAt>>
11613 DeviceDeferredDiags;
11614
11615 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
11616 /// key in a hashtable, both the FD and location are hashed.
11617 struct FunctionDeclAndLoc {
11618 CanonicalDeclPtr<FunctionDecl> FD;
11619 SourceLocation Loc;
11620 };
11621
11622 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
11623 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
11624 /// same deferred diag twice.
11625 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
11626
11627 /// An inverse call graph, mapping known-emitted functions to one of their
11628 /// known-emitted callers (plus the location of the call).
11629 ///
11630 /// Functions that we can tell a priori must be emitted aren't added to this
11631 /// map.
11632 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
11633 /* Caller = */ FunctionDeclAndLoc>
11634 DeviceKnownEmittedFns;
11635
11636 /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be
11637 /// deferred.
11638 ///
11639 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
11640 /// which are not allowed to appear inside __device__ functions and are
11641 /// allowed to appear in __host__ __device__ functions only if the host+device
11642 /// function is never codegen'ed.
11643 ///
11644 /// To handle this, we use the notion of "deferred diagnostics", where we
11645 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
11646 ///
11647 /// This class lets you emit either a regular diagnostic, a deferred
11648 /// diagnostic, or no diagnostic at all, according to an argument you pass to
11649 /// its constructor, thus simplifying the process of creating these "maybe
11650 /// deferred" diagnostics.
11651 class DeviceDiagBuilder {
11652 public:
11653 enum Kind {
11654 /// Emit no diagnostics.
11655 K_Nop,
11656 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
11657 K_Immediate,
11658 /// Emit the diagnostic immediately, and, if it's a warning or error, also
11659 /// emit a call stack showing how this function can be reached by an a
11660 /// priori known-emitted function.
11661 K_ImmediateWithCallStack,
11662 /// Create a deferred diagnostic, which is emitted only if the function
11663 /// it's attached to is codegen'ed. Also emit a call stack as with
11664 /// K_ImmediateWithCallStack.
11665 K_Deferred
11666 };
11667
11668 DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
11669 FunctionDecl *Fn, Sema &S);
11670 DeviceDiagBuilder(DeviceDiagBuilder &&D);
11671 DeviceDiagBuilder(const DeviceDiagBuilder &) = default;
11672 ~DeviceDiagBuilder();
11673
11674 /// Convertible to bool: True if we immediately emitted an error, false if
11675 /// we didn't emit an error or we created a deferred error.
11676 ///
11677 /// Example usage:
11678 ///
11679 /// if (DeviceDiagBuilder(...) << foo << bar)
11680 /// return ExprError();
11681 ///
11682 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
11683 /// want to use these instead of creating a DeviceDiagBuilder yourself.
11684 operator bool() const { return ImmediateDiag.hasValue(); }
11685
11686 template <typename T>
11687 friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag,
11688 const T &Value) {
11689 if (Diag.ImmediateDiag.hasValue())
11690 *Diag.ImmediateDiag << Value;
11691 else if (Diag.PartialDiagId.hasValue())
11692 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
11693 << Value;
11694 return Diag;
11695 }
11696
11697 private:
11698 Sema &S;
11699 SourceLocation Loc;
11700 unsigned DiagID;
11701 FunctionDecl *Fn;
11702 bool ShowCallStack;
11703
11704 // Invariant: At most one of these Optionals has a value.
11705 // FIXME: Switch these to a Variant once that exists.
11706 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
11707 llvm::Optional<unsigned> PartialDiagId;
11708 };
11709
11710 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
11711 /// is "used as device code".
11712 ///
11713 /// - If CurContext is a __host__ function, does not emit any diagnostics.
11714 /// - If CurContext is a __device__ or __global__ function, emits the
11715 /// diagnostics immediately.
11716 /// - If CurContext is a __host__ __device__ function and we are compiling for
11717 /// the device, creates a diagnostic which is emitted if and when we realize
11718 /// that the function will be codegen'ed.
11719 ///
11720 /// Example usage:
11721 ///
11722 /// // Variable-length arrays are not allowed in CUDA device code.
11723 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
11724 /// return ExprError();
11725 /// // Otherwise, continue parsing as normal.
11726 DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
11727
11728 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
11729 /// is "used as host code".
11730 ///
11731 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
11732 DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
11733
11734 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
11735 /// context is "used as device code".
11736 ///
11737 /// - If CurContext is a `declare target` function or it is known that the
11738 /// function is emitted for the device, emits the diagnostics immediately.
11739 /// - If CurContext is a non-`declare target` function and we are compiling
11740 /// for the device, creates a diagnostic which is emitted if and when we
11741 /// realize that the function will be codegen'ed.
11742 ///
11743 /// Example usage:
11744 ///
11745 /// // Variable-length arrays are not allowed in NVPTX device code.
11746 /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
11747 /// return ExprError();
11748 /// // Otherwise, continue parsing as normal.
11749 DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID);
11750
11751 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
11752 /// context is "used as host code".
11753 ///
11754 /// - If CurContext is a `declare target` function or it is known that the
11755 /// function is emitted for the host, emits the diagnostics immediately.
11756 /// - If CurContext is a non-host function, just ignore it.
11757 ///
11758 /// Example usage:
11759 ///
11760 /// // Variable-length arrays are not allowed in NVPTX device code.
11761 /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
11762 /// return ExprError();
11763 /// // Otherwise, continue parsing as normal.
11764 DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID);
11765
11766 DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
11767
11768 /// Check if the expression is allowed to be used in expressions for the
11769 /// offloading devices.
11770 void checkDeviceDecl(const ValueDecl *D, SourceLocation Loc);
11771
11772 enum CUDAFunctionTarget {
11773 CFT_Device,
11774 CFT_Global,
11775 CFT_Host,
11776 CFT_HostDevice,
11777 CFT_InvalidTarget
11778 };
11779
11780 /// Determines whether the given function is a CUDA device/host/kernel/etc.
11781 /// function.
11782 ///
11783 /// Use this rather than examining the function's attributes yourself -- you
11784 /// will get it wrong. Returns CFT_Host if D is null.
11785 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
11786 bool IgnoreImplicitHDAttr = false);
11787 CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
11788
11789 /// Gets the CUDA target for the current context.
11790 CUDAFunctionTarget CurrentCUDATarget() {
11791 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
11792 }
11793
11794 static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D);
11795
11796 // CUDA function call preference. Must be ordered numerically from
11797 // worst to best.
11798 enum CUDAFunctionPreference {
11799 CFP_Never, // Invalid caller/callee combination.
11800 CFP_WrongSide, // Calls from host-device to host or device
11801 // function that do not match current compilation
11802 // mode.
11803 CFP_HostDevice, // Any calls to host/device functions.
11804 CFP_SameSide, // Calls from host-device to host or device
11805 // function matching current compilation mode.
11806 CFP_Native, // host-to-host or device-to-device calls.
11807 };
11808
11809 /// Identifies relative preference of a given Caller/Callee
11810 /// combination, based on their host/device attributes.
11811 /// \param Caller function which needs address of \p Callee.
11812 /// nullptr in case of global context.
11813 /// \param Callee target function
11814 ///
11815 /// \returns preference value for particular Caller/Callee combination.
11816 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
11817 const FunctionDecl *Callee);
11818
11819 /// Determines whether Caller may invoke Callee, based on their CUDA
11820 /// host/device attributes. Returns false if the call is not allowed.
11821 ///
11822 /// Note: Will return true for CFP_WrongSide calls. These may appear in
11823 /// semantically correct CUDA programs, but only if they're never codegen'ed.
11824 bool IsAllowedCUDACall(const FunctionDecl *Caller,
11825 const FunctionDecl *Callee) {
11826 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
11827 }
11828
11829 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
11830 /// depending on FD and the current compilation settings.
11831 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
11832 const LookupResult &Previous);
11833
11834 /// May add implicit CUDAConstantAttr attribute to VD, depending on VD
11835 /// and current compilation settings.
11836 void MaybeAddCUDAConstantAttr(VarDecl *VD);
11837
11838public:
11839 /// Check whether we're allowed to call Callee from the current context.
11840 ///
11841 /// - If the call is never allowed in a semantically-correct program
11842 /// (CFP_Never), emits an error and returns false.
11843 ///
11844 /// - If the call is allowed in semantically-correct programs, but only if
11845 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
11846 /// be emitted if and when the caller is codegen'ed, and returns true.
11847 ///
11848 /// Will only create deferred diagnostics for a given SourceLocation once,
11849 /// so you can safely call this multiple times without generating duplicate
11850 /// deferred errors.
11851 ///
11852 /// - Otherwise, returns true without emitting any diagnostics.
11853 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
11854
11855 void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture);
11856
11857 /// Set __device__ or __host__ __device__ attributes on the given lambda
11858 /// operator() method.
11859 ///
11860 /// CUDA lambdas by default is host device function unless it has explicit
11861 /// host or device attribute.
11862 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
11863
11864 /// Finds a function in \p Matches with highest calling priority
11865 /// from \p Caller context and erases all functions with lower
11866 /// calling priority.
11867 void EraseUnwantedCUDAMatches(
11868 const FunctionDecl *Caller,
11869 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
11870
11871 /// Given a implicit special member, infer its CUDA target from the
11872 /// calls it needs to make to underlying base/field special members.
11873 /// \param ClassDecl the class for which the member is being created.
11874 /// \param CSM the kind of special member.
11875 /// \param MemberDecl the special member itself.
11876 /// \param ConstRHS true if this is a copy operation with a const object on
11877 /// its RHS.
11878 /// \param Diagnose true if this call should emit diagnostics.
11879 /// \return true if there was an error inferring.
11880 /// The result of this call is implicit CUDA target attribute(s) attached to
11881 /// the member declaration.
11882 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
11883 CXXSpecialMember CSM,
11884 CXXMethodDecl *MemberDecl,
11885 bool ConstRHS,
11886 bool Diagnose);
11887
11888 /// \return true if \p CD can be considered empty according to CUDA
11889 /// (E.2.3.1 in CUDA 7.5 Programming guide).
11890 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
11891 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
11892
11893 // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
11894 // case of error emits appropriate diagnostic and invalidates \p Var.
11895 //
11896 // \details CUDA allows only empty constructors as initializers for global
11897 // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
11898 // __shared__ variables whether they are local or not (they all are implicitly
11899 // static in CUDA). One exception is that CUDA allows constant initializers
11900 // for __constant__ and __device__ variables.
11901 void checkAllowedCUDAInitializer(VarDecl *VD);
11902
11903 /// Check whether NewFD is a valid overload for CUDA. Emits
11904 /// diagnostics and invalidates NewFD if not.
11905 void checkCUDATargetOverload(FunctionDecl *NewFD,
11906 const LookupResult &Previous);
11907 /// Copies target attributes from the template TD to the function FD.
11908 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
11909
11910 /// Returns the name of the launch configuration function. This is the name
11911 /// of the function that will be called to configure kernel call, with the
11912 /// parameters specified via <<<>>>.
11913 std::string getCudaConfigureFuncName() const;
11914
11915 /// \name Code completion
11916 //@{
11917 /// Describes the context in which code completion occurs.
11918 enum ParserCompletionContext {
11919 /// Code completion occurs at top-level or namespace context.
11920 PCC_Namespace,
11921 /// Code completion occurs within a class, struct, or union.
11922 PCC_Class,
11923 /// Code completion occurs within an Objective-C interface, protocol,
11924 /// or category.
11925 PCC_ObjCInterface,
11926 /// Code completion occurs within an Objective-C implementation or
11927 /// category implementation
11928 PCC_ObjCImplementation,
11929 /// Code completion occurs within the list of instance variables
11930 /// in an Objective-C interface, protocol, category, or implementation.
11931 PCC_ObjCInstanceVariableList,
11932 /// Code completion occurs following one or more template
11933 /// headers.
11934 PCC_Template,
11935 /// Code completion occurs following one or more template
11936 /// headers within a class.
11937 PCC_MemberTemplate,
11938 /// Code completion occurs within an expression.
11939 PCC_Expression,
11940 /// Code completion occurs within a statement, which may
11941 /// also be an expression or a declaration.
11942 PCC_Statement,
11943 /// Code completion occurs at the beginning of the
11944 /// initialization statement (or expression) in a for loop.
11945 PCC_ForInit,
11946 /// Code completion occurs within the condition of an if,
11947 /// while, switch, or for statement.
11948 PCC_Condition,
11949 /// Code completion occurs within the body of a function on a
11950 /// recovery path, where we do not have a specific handle on our position
11951 /// in the grammar.
11952 PCC_RecoveryInFunction,
11953 /// Code completion occurs where only a type is permitted.
11954 PCC_Type,
11955 /// Code completion occurs in a parenthesized expression, which
11956 /// might also be a type cast.
11957 PCC_ParenthesizedExpression,
11958 /// Code completion occurs within a sequence of declaration
11959 /// specifiers within a function, method, or block.
11960 PCC_LocalDeclarationSpecifiers
11961 };
11962
11963 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
11964 void CodeCompleteOrdinaryName(Scope *S,
11965 ParserCompletionContext CompletionContext);
11966 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
11967 bool AllowNonIdentifiers,
11968 bool AllowNestedNameSpecifiers);
11969
11970 struct CodeCompleteExpressionData;
11971 void CodeCompleteExpression(Scope *S,
11972 const CodeCompleteExpressionData &Data);
11973 void CodeCompleteExpression(Scope *S, QualType PreferredType,
11974 bool IsParenthesized = false);
11975 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
11976 SourceLocation OpLoc, bool IsArrow,
11977 bool IsBaseExprStatement,
11978 QualType PreferredType);
11979 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
11980 QualType PreferredType);
11981 void CodeCompleteTag(Scope *S, unsigned TagSpec);
11982 void CodeCompleteTypeQualifiers(DeclSpec &DS);
11983 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
11984 const VirtSpecifiers *VS = nullptr);
11985 void CodeCompleteBracketDeclarator(Scope *S);
11986 void CodeCompleteCase(Scope *S);
11987 /// Reports signatures for a call to CodeCompleteConsumer and returns the
11988 /// preferred type for the current argument. Returned type can be null.
11989 QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
11990 SourceLocation OpenParLoc);
11991 QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
11992 SourceLocation Loc,
11993 ArrayRef<Expr *> Args,
11994 SourceLocation OpenParLoc);
11995 QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
11996 CXXScopeSpec SS,
11997 ParsedType TemplateTypeTy,
11998 ArrayRef<Expr *> ArgExprs,
11999 IdentifierInfo *II,
12000 SourceLocation OpenParLoc);
12001 void CodeCompleteInitializer(Scope *S, Decl *D);
12002 /// Trigger code completion for a record of \p BaseType. \p InitExprs are
12003 /// expressions in the initializer list seen so far and \p D is the current
12004 /// Designation being parsed.
12005 void CodeCompleteDesignator(const QualType BaseType,
12006 llvm::ArrayRef<Expr *> InitExprs,
12007 const Designation &D);
12008 void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
12009
12010 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
12011 bool IsUsingDeclaration, QualType BaseType,
12012 QualType PreferredType);
12013 void CodeCompleteUsing(Scope *S);
12014 void CodeCompleteUsingDirective(Scope *S);
12015 void CodeCompleteNamespaceDecl(Scope *S);
12016 void CodeCompleteNamespaceAliasDecl(Scope *S);
12017 void CodeCompleteOperatorName(Scope *S);
12018 void CodeCompleteConstructorInitializer(
12019 Decl *Constructor,
12020 ArrayRef<CXXCtorInitializer *> Initializers);
12021
12022 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
12023 bool AfterAmpersand);
12024 void CodeCompleteAfterFunctionEquals(Declarator &D);
12025
12026 void CodeCompleteObjCAtDirective(Scope *S);
12027 void CodeCompleteObjCAtVisibility(Scope *S);
12028 void CodeCompleteObjCAtStatement(Scope *S);
12029 void CodeCompleteObjCAtExpression(Scope *S);
12030 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
12031 void CodeCompleteObjCPropertyGetter(Scope *S);
12032 void CodeCompleteObjCPropertySetter(Scope *S);
12033 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
12034 bool IsParameter);
12035 void CodeCompleteObjCMessageReceiver(Scope *S);
12036 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
12037 ArrayRef<IdentifierInfo *> SelIdents,
12038 bool AtArgumentExpression);
12039 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
12040 ArrayRef<IdentifierInfo *> SelIdents,
12041 bool AtArgumentExpression,
12042 bool IsSuper = false);
12043 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
12044 ArrayRef<IdentifierInfo *> SelIdents,
12045 bool AtArgumentExpression,
12046 ObjCInterfaceDecl *Super = nullptr);
12047 void CodeCompleteObjCForCollection(Scope *S,
12048 DeclGroupPtrTy IterationVar);
12049 void CodeCompleteObjCSelector(Scope *S,
12050 ArrayRef<IdentifierInfo *> SelIdents);
12051 void CodeCompleteObjCProtocolReferences(
12052 ArrayRef<IdentifierLocPair> Protocols);
12053 void CodeCompleteObjCProtocolDecl(Scope *S);
12054 void CodeCompleteObjCInterfaceDecl(Scope *S);
12055 void CodeCompleteObjCSuperclass(Scope *S,
12056 IdentifierInfo *ClassName,
12057 SourceLocation ClassNameLoc);
12058 void CodeCompleteObjCImplementationDecl(Scope *S);
12059 void CodeCompleteObjCInterfaceCategory(Scope *S,
12060 IdentifierInfo *ClassName,
12061 SourceLocation ClassNameLoc);
12062 void CodeCompleteObjCImplementationCategory(Scope *S,
12063 IdentifierInfo *ClassName,
12064 SourceLocation ClassNameLoc);
12065 void CodeCompleteObjCPropertyDefinition(Scope *S);
12066 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
12067 IdentifierInfo *PropertyName);
12068 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
12069 ParsedType ReturnType);
12070 void CodeCompleteObjCMethodDeclSelector(Scope *S,
12071 bool IsInstanceMethod,
12072 bool AtParameterName,
12073 ParsedType ReturnType,
12074 ArrayRef<IdentifierInfo *> SelIdents);
12075 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
12076 SourceLocation ClassNameLoc,
12077 bool IsBaseExprStatement);
12078 void CodeCompletePreprocessorDirective(bool InConditional);
12079 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
12080 void CodeCompletePreprocessorMacroName(bool IsDefinition);
12081 void CodeCompletePreprocessorExpression();
12082 void CodeCompletePreprocessorMacroArgument(Scope *S,
12083 IdentifierInfo *Macro,
12084 MacroInfo *MacroInfo,
12085 unsigned Argument);
12086 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
12087 void CodeCompleteNaturalLanguage();
12088 void CodeCompleteAvailabilityPlatformName();
12089 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
12090 CodeCompletionTUInfo &CCTUInfo,
12091 SmallVectorImpl<CodeCompletionResult> &Results);
12092 //@}
12093
12094 //===--------------------------------------------------------------------===//
12095 // Extra semantic analysis beyond the C type system
12096
12097public:
12098 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
12099 unsigned ByteNo) const;
12100
12101private:
12102 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12103 const ArraySubscriptExpr *ASE=nullptr,
12104 bool AllowOnePastEnd=true, bool IndexNegated=false);
12105 void CheckArrayAccess(const Expr *E);
12106 // Used to grab the relevant information from a FormatAttr and a
12107 // FunctionDeclaration.
12108 struct FormatStringInfo {
12109 unsigned FormatIdx;
12110 unsigned FirstDataArg;
12111 bool HasVAListArg;
12112 };
12113
12114 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
12115 FormatStringInfo *FSI);
12116 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
12117 const FunctionProtoType *Proto);
12118 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
12119 ArrayRef<const Expr *> Args);
12120 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
12121 const FunctionProtoType *Proto);
12122 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
12123 void CheckConstructorCall(FunctionDecl *FDecl,
12124 ArrayRef<const Expr *> Args,
12125 const FunctionProtoType *Proto,
12126 SourceLocation Loc);
12127
12128 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
12129 const Expr *ThisArg, ArrayRef<const Expr *> Args,
12130 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
12131 VariadicCallType CallType);
12132
12133 bool CheckObjCString(Expr *Arg);
12134 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
12135
12136 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
12137 unsigned BuiltinID, CallExpr *TheCall);
12138
12139 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12140 CallExpr *TheCall);
12141
12142 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
12143
12144 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
12145 unsigned MaxWidth);
12146 bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12147 CallExpr *TheCall);
12148 bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12149 bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12150 bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12151 CallExpr *TheCall);
12152 bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg,
12153 bool WantCDE);
12154 bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12155 CallExpr *TheCall);
12156
12157 bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12158 CallExpr *TheCall);
12159 bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12160 bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12161 bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12162 bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12163 CallExpr *TheCall);
12164 bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
12165 CallExpr *TheCall);
12166 bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12167 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12168 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
12169 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
12170 bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall);
12171 bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
12172 ArrayRef<int> ArgNums);
12173 bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, int ArgNum);
12174 bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums);
12175 bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
12176 ArrayRef<int> ArgNums);
12177 bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12178 CallExpr *TheCall);
12179 bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12180 CallExpr *TheCall);
12181 bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12182
12183 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
12184 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
12185 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
12186 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
12187 bool SemaBuiltinComplex(CallExpr *TheCall);
12188 bool SemaBuiltinVSX(CallExpr *TheCall);
12189 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
12190
12191public:
12192 // Used by C++ template instantiation.
12193 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
12194 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
12195 SourceLocation BuiltinLoc,
12196 SourceLocation RParenLoc);
12197
12198private:
12199 bool SemaBuiltinPrefetch(CallExpr *TheCall);
12200 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
12201 bool SemaBuiltinAssume(CallExpr *TheCall);
12202 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
12203 bool SemaBuiltinLongjmp(CallExpr *TheCall);
12204 bool SemaBuiltinSetjmp(CallExpr *TheCall);
12205 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
12206 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
12207 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
12208 AtomicExpr::AtomicOp Op);
12209 ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
12210 bool IsDelete);
12211 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
12212 llvm::APSInt &Result);
12213 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
12214 int High, bool RangeIsError = true);
12215 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
12216 unsigned Multiple);
12217 bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
12218 bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
12219 unsigned ArgBits);
12220 bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
12221 unsigned ArgBits);
12222 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
12223 int ArgNum, unsigned ExpectedFieldNum,
12224 bool AllowName);
12225 bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
12226
12227 // Matrix builtin handling.
12228 ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall,
12229 ExprResult CallResult);
12230 ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
12231 ExprResult CallResult);
12232 ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
12233 ExprResult CallResult);
12234
12235public:
12236 enum FormatStringType {
12237 FST_Scanf,
12238 FST_Printf,
12239 FST_NSString,
12240 FST_Strftime,
12241 FST_Strfmon,
12242 FST_Kprintf,
12243 FST_FreeBSDKPrintf,
12244 FST_OSTrace,
12245 FST_OSLog,
12246 FST_Unknown
12247 };
12248 static FormatStringType GetFormatStringType(const FormatAttr *Format);
12249
12250 bool FormatStringHasSArg(const StringLiteral *FExpr);
12251
12252 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
12253
12254private:
12255 bool CheckFormatArguments(const FormatAttr *Format,
12256 ArrayRef<const Expr *> Args,
12257 bool IsCXXMember,
12258 VariadicCallType CallType,
12259 SourceLocation Loc, SourceRange Range,
12260 llvm::SmallBitVector &CheckedVarArgs);
12261 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
12262 bool HasVAListArg, unsigned format_idx,
12263 unsigned firstDataArg, FormatStringType Type,
12264 VariadicCallType CallType,
12265 SourceLocation Loc, SourceRange range,
12266 llvm::SmallBitVector &CheckedVarArgs);
12267
12268 void CheckAbsoluteValueFunction(const CallExpr *Call,
12269 const FunctionDecl *FDecl);
12270
12271 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
12272
12273 void CheckMemaccessArguments(const CallExpr *Call,
12274 unsigned BId,
12275 IdentifierInfo *FnName);
12276
12277 void CheckStrlcpycatArguments(const CallExpr *Call,
12278 IdentifierInfo *FnName);
12279
12280 void CheckStrncatArguments(const CallExpr *Call,
12281 IdentifierInfo *FnName);
12282
12283 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
12284 SourceLocation ReturnLoc,
12285 bool isObjCMethod = false,
12286 const AttrVec *Attrs = nullptr,
12287 const FunctionDecl *FD = nullptr);
12288
12289public:
12290 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
12291
12292private:
12293 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
12294 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
12295 void CheckForIntOverflow(Expr *E);
12296 void CheckUnsequencedOperations(const Expr *E);
12297
12298 /// Perform semantic checks on a completed expression. This will either
12299 /// be a full-expression or a default argument expression.
12300 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
12301 bool IsConstexpr = false);
12302
12303 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
12304 Expr *Init);
12305
12306 /// Check if there is a field shadowing.
12307 void CheckShadowInheritedFields(const SourceLocation &Loc,
12308 DeclarationName FieldName,
12309 const CXXRecordDecl *RD,
12310 bool DeclIsField = true);
12311
12312 /// Check if the given expression contains 'break' or 'continue'
12313 /// statement that produces control flow different from GCC.
12314 void CheckBreakContinueBinding(Expr *E);
12315
12316 /// Check whether receiver is mutable ObjC container which
12317 /// attempts to add itself into the container
12318 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
12319
12320 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
12321 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
12322 bool DeleteWasArrayForm);
12323public:
12324 /// Register a magic integral constant to be used as a type tag.
12325 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12326 uint64_t MagicValue, QualType Type,
12327 bool LayoutCompatible, bool MustBeNull);
12328
12329 struct TypeTagData {
12330 TypeTagData() {}
12331
12332 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
12333 Type(Type), LayoutCompatible(LayoutCompatible),
12334 MustBeNull(MustBeNull)
12335 {}
12336
12337 QualType Type;
12338
12339 /// If true, \c Type should be compared with other expression's types for
12340 /// layout-compatibility.
12341 unsigned LayoutCompatible : 1;
12342 unsigned MustBeNull : 1;
12343 };
12344
12345 /// A pair of ArgumentKind identifier and magic value. This uniquely
12346 /// identifies the magic value.
12347 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
12348
12349private:
12350 /// A map from magic value to type information.
12351 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
12352 TypeTagForDatatypeMagicValues;
12353
12354 /// Peform checks on a call of a function with argument_with_type_tag
12355 /// or pointer_with_type_tag attributes.
12356 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12357 const ArrayRef<const Expr *> ExprArgs,
12358 SourceLocation CallSiteLoc);
12359
12360 /// Check if we are taking the address of a packed field
12361 /// as this may be a problem if the pointer value is dereferenced.
12362 void CheckAddressOfPackedMember(Expr *rhs);
12363
12364 /// The parser's current scope.
12365 ///
12366 /// The parser maintains this state here.
12367 Scope *CurScope;
12368
12369 mutable IdentifierInfo *Ident_super;
12370 mutable IdentifierInfo *Ident___float128;
12371
12372 /// Nullability type specifiers.
12373 IdentifierInfo *Ident__Nonnull = nullptr;
12374 IdentifierInfo *Ident__Nullable = nullptr;
12375 IdentifierInfo *Ident__Null_unspecified = nullptr;
12376
12377 IdentifierInfo *Ident_NSError = nullptr;
12378
12379 /// The handler for the FileChanged preprocessor events.
12380 ///
12381 /// Used for diagnostics that implement custom semantic analysis for #include
12382 /// directives, like -Wpragma-pack.
12383 sema::SemaPPCallbacks *SemaPPCallbackHandler;
12384
12385protected:
12386 friend class Parser;
12387 friend class InitializationSequence;
12388 friend class ASTReader;
12389 friend class ASTDeclReader;
12390 friend class ASTWriter;
12391
12392public:
12393 /// Retrieve the keyword associated
12394 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
12395
12396 /// The struct behind the CFErrorRef pointer.
12397 RecordDecl *CFError = nullptr;
12398
12399 /// Retrieve the identifier "NSError".
12400 IdentifierInfo *getNSErrorIdent();
12401
12402 /// Retrieve the parser's current scope.
12403 ///
12404 /// This routine must only be used when it is certain that semantic analysis
12405 /// and the parser are in precisely the same context, which is not the case
12406 /// when, e.g., we are performing any kind of template instantiation.
12407 /// Therefore, the only safe places to use this scope are in the parser
12408 /// itself and in routines directly invoked from the parser and *never* from
12409 /// template substitution or instantiation.
12410 Scope *getCurScope() const { return CurScope; }
12411
12412 void incrementMSManglingNumber() const {
12413 return CurScope->incrementMSManglingNumber();
12414 }
12415
12416 IdentifierInfo *getSuperIdentifier() const;
12417 IdentifierInfo *getFloat128Identifier() const;
12418
12419 Decl *getObjCDeclContext() const;
12420
12421 DeclContext *getCurLexicalContext() const {
12422 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
12423 }
12424
12425 const DeclContext *getCurObjCLexicalContext() const {
12426 const DeclContext *DC = getCurLexicalContext();
12427 // A category implicitly has the attribute of the interface.
12428 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
12429 DC = CatD->getClassInterface();
12430 return DC;
12431 }
12432
12433 /// Determine the number of levels of enclosing template parameters. This is
12434 /// only usable while parsing. Note that this does not include dependent
12435 /// contexts in which no template parameters have yet been declared, such as
12436 /// in a terse function template or generic lambda before the first 'auto' is
12437 /// encountered.
12438 unsigned getTemplateDepth(Scope *S) const;
12439
12440 /// To be used for checking whether the arguments being passed to
12441 /// function exceeds the number of parameters expected for it.
12442 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
12443 bool PartialOverloading = false) {
12444 // We check whether we're just after a comma in code-completion.
12445 if (NumArgs > 0 && PartialOverloading)
12446 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
12447 return NumArgs > NumParams;
12448 }
12449
12450 // Emitting members of dllexported classes is delayed until the class
12451 // (including field initializers) is fully parsed.
12452 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
12453 SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
12454
12455private:
12456 int ParsingClassDepth = 0;
12457
12458 class SavePendingParsedClassStateRAII {
12459 public:
12460 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
12461
12462 ~SavePendingParsedClassStateRAII() {
12463 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&((S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 12464, __PRETTY_FUNCTION__))
12464 "there shouldn't be any pending delayed exception spec checks")((S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 12464, __PRETTY_FUNCTION__))
;
12465 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&((S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 12466, __PRETTY_FUNCTION__))
12466 "there shouldn't be any pending delayed exception spec checks")((S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/Sema/Sema.h"
, 12466, __PRETTY_FUNCTION__))
;
12467 swapSavedState();
12468 }
12469
12470 private:
12471 Sema &S;
12472 decltype(DelayedOverridingExceptionSpecChecks)
12473 SavedOverridingExceptionSpecChecks;
12474 decltype(DelayedEquivalentExceptionSpecChecks)
12475 SavedEquivalentExceptionSpecChecks;
12476
12477 void swapSavedState() {
12478 SavedOverridingExceptionSpecChecks.swap(
12479 S.DelayedOverridingExceptionSpecChecks);
12480 SavedEquivalentExceptionSpecChecks.swap(
12481 S.DelayedEquivalentExceptionSpecChecks);
12482 }
12483 };
12484
12485 /// Helper class that collects misaligned member designations and
12486 /// their location info for delayed diagnostics.
12487 struct MisalignedMember {
12488 Expr *E;
12489 RecordDecl *RD;
12490 ValueDecl *MD;
12491 CharUnits Alignment;
12492
12493 MisalignedMember() : E(), RD(), MD(), Alignment() {}
12494 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
12495 CharUnits Alignment)
12496 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
12497 explicit MisalignedMember(Expr *E)
12498 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
12499
12500 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
12501 };
12502 /// Small set of gathered accesses to potentially misaligned members
12503 /// due to the packed attribute.
12504 SmallVector<MisalignedMember, 4> MisalignedMembers;
12505
12506 /// Adds an expression to the set of gathered misaligned members.
12507 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12508 CharUnits Alignment);
12509
12510public:
12511 /// Diagnoses the current set of gathered accesses. This typically
12512 /// happens at full expression level. The set is cleared after emitting the
12513 /// diagnostics.
12514 void DiagnoseMisalignedMembers();
12515
12516 /// This function checks if the expression is in the sef of potentially
12517 /// misaligned members and it is converted to some pointer type T with lower
12518 /// or equal alignment requirements. If so it removes it. This is used when
12519 /// we do not want to diagnose such misaligned access (e.g. in conversions to
12520 /// void*).
12521 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
12522
12523 /// This function calls Action when it determines that E designates a
12524 /// misaligned member due to the packed attribute. This is used to emit
12525 /// local diagnostics like in reference binding.
12526 void RefersToMemberWithReducedAlignment(
12527 Expr *E,
12528 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12529 Action);
12530
12531 /// Describes the reason a calling convention specification was ignored, used
12532 /// for diagnostics.
12533 enum class CallingConventionIgnoredReason {
12534 ForThisTarget = 0,
12535 VariadicFunction,
12536 ConstructorDestructor,
12537 BuiltinFunction
12538 };
12539 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
12540 /// context is "used as device code".
12541 ///
12542 /// - If CurLexicalContext is a kernel function or it is known that the
12543 /// function will be emitted for the device, emits the diagnostics
12544 /// immediately.
12545 /// - If CurLexicalContext is a function and we are compiling
12546 /// for the device, but we don't know that this function will be codegen'ed
12547 /// for devive yet, creates a diagnostic which is emitted if and when we
12548 /// realize that the function will be codegen'ed.
12549 ///
12550 /// Example usage:
12551 ///
12552 /// Diagnose __float128 type usage only from SYCL device code if the current
12553 /// target doesn't support it
12554 /// if (!S.Context.getTargetInfo().hasFloat128Type() &&
12555 /// S.getLangOpts().SYCLIsDevice)
12556 /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
12557 DeviceDiagBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
12558
12559 /// Check whether we're allowed to call Callee from the current context.
12560 ///
12561 /// - If the call is never allowed in a semantically-correct program
12562 /// emits an error and returns false.
12563 ///
12564 /// - If the call is allowed in semantically-correct programs, but only if
12565 /// it's never codegen'ed, creates a deferred diagnostic to be emitted if
12566 /// and when the caller is codegen'ed, and returns true.
12567 ///
12568 /// - Otherwise, returns true without emitting any diagnostics.
12569 ///
12570 /// Adds Callee to DeviceCallGraph if we don't know if its caller will be
12571 /// codegen'ed yet.
12572 bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee);
12573};
12574
12575/// RAII object that enters a new expression evaluation context.
12576class EnterExpressionEvaluationContext {
12577 Sema &Actions;
12578 bool Entered = true;
12579
12580public:
12581 EnterExpressionEvaluationContext(
12582 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
12583 Decl *LambdaContextDecl = nullptr,
12584 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
12585 Sema::ExpressionEvaluationContextRecord::EK_Other,
12586 bool ShouldEnter = true)
12587 : Actions(Actions), Entered(ShouldEnter) {
12588 if (Entered)
12589 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
12590 ExprContext);
12591 }
12592 EnterExpressionEvaluationContext(
12593 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
12594 Sema::ReuseLambdaContextDecl_t,
12595 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
12596 Sema::ExpressionEvaluationContextRecord::EK_Other)
12597 : Actions(Actions) {
12598 Actions.PushExpressionEvaluationContext(
12599 NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
12600 }
12601
12602 enum InitListTag { InitList };
12603 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
12604 bool ShouldEnter = true)
12605 : Actions(Actions), Entered(false) {
12606 // In C++11 onwards, narrowing checks are performed on the contents of
12607 // braced-init-lists, even when they occur within unevaluated operands.
12608 // Therefore we still need to instantiate constexpr functions used in such
12609 // a context.
12610 if (ShouldEnter && Actions.isUnevaluatedContext() &&
12611 Actions.getLangOpts().CPlusPlus11) {
12612 Actions.PushExpressionEvaluationContext(
12613 Sema::ExpressionEvaluationContext::UnevaluatedList);
12614 Entered = true;
12615 }
12616 }
12617
12618 ~EnterExpressionEvaluationContext() {
12619 if (Entered)
12620 Actions.PopExpressionEvaluationContext();
12621 }
12622};
12623
12624DeductionFailureInfo
12625MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
12626 sema::TemplateDeductionInfo &Info);
12627
12628/// Contains a late templated function.
12629/// Will be parsed at the end of the translation unit, used by Sema & Parser.
12630struct LateParsedTemplate {
12631 CachedTokens Toks;
12632 /// The template function declaration to be late parsed.
12633 Decl *D;
12634};
12635} // end namespace clang
12636
12637namespace llvm {
12638// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
12639// SourceLocation.
12640template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
12641 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
12642 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
12643
12644 static FunctionDeclAndLoc getEmptyKey() {
12645 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
12646 }
12647
12648 static FunctionDeclAndLoc getTombstoneKey() {
12649 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
12650 }
12651
12652 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
12653 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
12654 FDL.Loc.getRawEncoding());
12655 }
12656
12657 static bool isEqual(const FunctionDeclAndLoc &LHS,
12658 const FunctionDeclAndLoc &RHS) {
12659 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
12660 }
12661};
12662} // namespace llvm
12663
12664#endif