Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Warning:line 5532, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiateDecl.cpp -analyzer-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 -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -resource-dir /usr/lib/llvm-15/lib/clang/15.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-15/lib/clang/15.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

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

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Availability.h"
21#include "clang/AST/ComparisonCategories.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprConcepts.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/AST/LocInfoType.h"
31#include "clang/AST/MangleNumberingContext.h"
32#include "clang/AST/NSAPI.h"
33#include "clang/AST/PrettyPrinter.h"
34#include "clang/AST/StmtCXX.h"
35#include "clang/AST/StmtOpenMP.h"
36#include "clang/AST/TypeLoc.h"
37#include "clang/AST/TypeOrdering.h"
38#include "clang/Basic/BitmaskEnum.h"
39#include "clang/Basic/Builtins.h"
40#include "clang/Basic/DarwinSDKInfo.h"
41#include "clang/Basic/ExpressionTraits.h"
42#include "clang/Basic/Module.h"
43#include "clang/Basic/OpenCLOptions.h"
44#include "clang/Basic/OpenMPKinds.h"
45#include "clang/Basic/PragmaKinds.h"
46#include "clang/Basic/Specifiers.h"
47#include "clang/Basic/TemplateKinds.h"
48#include "clang/Basic/TypeTraits.h"
49#include "clang/Sema/AnalysisBasedWarnings.h"
50#include "clang/Sema/CleanupInfo.h"
51#include "clang/Sema/DeclSpec.h"
52#include "clang/Sema/ExternalSemaSource.h"
53#include "clang/Sema/IdentifierResolver.h"
54#include "clang/Sema/ObjCMethodList.h"
55#include "clang/Sema/Ownership.h"
56#include "clang/Sema/Scope.h"
57#include "clang/Sema/SemaConcept.h"
58#include "clang/Sema/TypoCorrection.h"
59#include "clang/Sema/Weak.h"
60#include "llvm/ADT/ArrayRef.h"
61#include "llvm/ADT/Optional.h"
62#include "llvm/ADT/SetVector.h"
63#include "llvm/ADT/SmallBitVector.h"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/ADT/SmallSet.h"
66#include "llvm/ADT/SmallVector.h"
67#include "llvm/ADT/TinyPtrVector.h"
68#include "llvm/Frontend/OpenMP/OMPConstants.h"
69#include <deque>
70#include <memory>
71#include <string>
72#include <tuple>
73#include <vector>
74
75namespace llvm {
76 class APSInt;
77 template <typename ValueT, typename ValueInfoT> class DenseSet;
78 class SmallBitVector;
79 struct InlineAsmIdentifierInfo;
80}
81
82namespace clang {
83 class ADLResult;
84 class ASTConsumer;
85 class ASTContext;
86 class ASTMutationListener;
87 class ASTReader;
88 class ASTWriter;
89 class ArrayType;
90 class ParsedAttr;
91 class BindingDecl;
92 class BlockDecl;
93 class CapturedDecl;
94 class CXXBasePath;
95 class CXXBasePaths;
96 class CXXBindTemporaryExpr;
97 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
98 class CXXConstructorDecl;
99 class CXXConversionDecl;
100 class CXXDeleteExpr;
101 class CXXDestructorDecl;
102 class CXXFieldCollector;
103 class CXXMemberCallExpr;
104 class CXXMethodDecl;
105 class CXXScopeSpec;
106 class CXXTemporary;
107 class CXXTryStmt;
108 class CallExpr;
109 class ClassTemplateDecl;
110 class ClassTemplatePartialSpecializationDecl;
111 class ClassTemplateSpecializationDecl;
112 class VarTemplatePartialSpecializationDecl;
113 class CodeCompleteConsumer;
114 class CodeCompletionAllocator;
115 class CodeCompletionTUInfo;
116 class CodeCompletionResult;
117 class CoroutineBodyStmt;
118 class Decl;
119 class DeclAccessPair;
120 class DeclContext;
121 class DeclRefExpr;
122 class DeclaratorDecl;
123 class DeducedTemplateArgument;
124 class DependentDiagnostic;
125 class DesignatedInitExpr;
126 class Designation;
127 class EnableIfAttr;
128 class EnumConstantDecl;
129 class Expr;
130 class ExtVectorType;
131 class FormatAttr;
132 class FriendDecl;
133 class FunctionDecl;
134 class FunctionProtoType;
135 class FunctionTemplateDecl;
136 class ImplicitConversionSequence;
137 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
138 class InitListExpr;
139 class InitializationKind;
140 class InitializationSequence;
141 class InitializedEntity;
142 class IntegerLiteral;
143 class LabelStmt;
144 class LambdaExpr;
145 class LangOptions;
146 class LocalInstantiationScope;
147 class LookupResult;
148 class MacroInfo;
149 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
150 class ModuleLoader;
151 class MultiLevelTemplateArgumentList;
152 class NamedDecl;
153 class ObjCCategoryDecl;
154 class ObjCCategoryImplDecl;
155 class ObjCCompatibleAliasDecl;
156 class ObjCContainerDecl;
157 class ObjCImplDecl;
158 class ObjCImplementationDecl;
159 class ObjCInterfaceDecl;
160 class ObjCIvarDecl;
161 template <class T> class ObjCList;
162 class ObjCMessageExpr;
163 class ObjCMethodDecl;
164 class ObjCPropertyDecl;
165 class ObjCProtocolDecl;
166 class OMPThreadPrivateDecl;
167 class OMPRequiresDecl;
168 class OMPDeclareReductionDecl;
169 class OMPDeclareSimdDecl;
170 class OMPClause;
171 struct OMPVarListLocTy;
172 struct OverloadCandidate;
173 enum class OverloadCandidateParamOrder : char;
174 enum OverloadCandidateRewriteKind : unsigned;
175 class OverloadCandidateSet;
176 class OverloadExpr;
177 class ParenListExpr;
178 class ParmVarDecl;
179 class Preprocessor;
180 class PseudoDestructorTypeStorage;
181 class PseudoObjectExpr;
182 class QualType;
183 class StandardConversionSequence;
184 class Stmt;
185 class StringLiteral;
186 class SwitchStmt;
187 class TemplateArgument;
188 class TemplateArgumentList;
189 class TemplateArgumentLoc;
190 class TemplateDecl;
191 class TemplateInstantiationCallback;
192 class TemplateParameterList;
193 class TemplatePartialOrderingContext;
194 class TemplateTemplateParmDecl;
195 class Token;
196 class TypeAliasDecl;
197 class TypedefDecl;
198 class TypedefNameDecl;
199 class TypeLoc;
200 class TypoCorrectionConsumer;
201 class UnqualifiedId;
202 class UnresolvedLookupExpr;
203 class UnresolvedMemberExpr;
204 class UnresolvedSetImpl;
205 class UnresolvedSetIterator;
206 class UsingDecl;
207 class UsingShadowDecl;
208 class ValueDecl;
209 class VarDecl;
210 class VarTemplateSpecializationDecl;
211 class VisibilityAttr;
212 class VisibleDeclConsumer;
213 class IndirectFieldDecl;
214 struct DeductionFailureInfo;
215 class TemplateSpecCandidateSet;
216
217namespace sema {
218 class AccessedEntity;
219 class BlockScopeInfo;
220 class Capture;
221 class CapturedRegionScopeInfo;
222 class CapturingScopeInfo;
223 class CompoundScopeInfo;
224 class DelayedDiagnostic;
225 class DelayedDiagnosticPool;
226 class FunctionScopeInfo;
227 class LambdaScopeInfo;
228 class PossiblyUnreachableDiag;
229 class SemaPPCallbacks;
230 class TemplateDeductionInfo;
231}
232
233namespace threadSafety {
234 class BeforeSet;
235 void threadSafetyCleanup(BeforeSet* Cache);
236}
237
238// FIXME: No way to easily map from TemplateTypeParmTypes to
239// TemplateTypeParmDecls, so we have this horrible PointerUnion.
240typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
241 SourceLocation> UnexpandedParameterPack;
242
243/// Describes whether we've seen any nullability information for the given
244/// file.
245struct FileNullability {
246 /// The first pointer declarator (of any pointer kind) in the file that does
247 /// not have a corresponding nullability annotation.
248 SourceLocation PointerLoc;
249
250 /// The end location for the first pointer declarator in the file. Used for
251 /// placing fix-its.
252 SourceLocation PointerEndLoc;
253
254 /// Which kind of pointer declarator we saw.
255 uint8_t PointerKind;
256
257 /// Whether we saw any type nullability annotations in the given file.
258 bool SawTypeNullability = false;
259};
260
261/// A mapping from file IDs to a record of whether we've seen nullability
262/// information in that file.
263class FileNullabilityMap {
264 /// A mapping from file IDs to the nullability information for each file ID.
265 llvm::DenseMap<FileID, FileNullability> Map;
266
267 /// A single-element cache based on the file ID.
268 struct {
269 FileID File;
270 FileNullability Nullability;
271 } Cache;
272
273public:
274 FileNullability &operator[](FileID file) {
275 // Check the single-element cache.
276 if (file == Cache.File)
277 return Cache.Nullability;
278
279 // It's not in the single-element cache; flush the cache if we have one.
280 if (!Cache.File.isInvalid()) {
281 Map[Cache.File] = Cache.Nullability;
282 }
283
284 // Pull this entry into the cache.
285 Cache.File = file;
286 Cache.Nullability = Map[file];
287 return Cache.Nullability;
288 }
289};
290
291/// Tracks expected type during expression parsing, for use in code completion.
292/// The type is tied to a particular token, all functions that update or consume
293/// the type take a start location of the token they are looking at as a
294/// parameter. This avoids updating the type on hot paths in the parser.
295class PreferredTypeBuilder {
296public:
297 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
298
299 void enterCondition(Sema &S, SourceLocation Tok);
300 void enterReturn(Sema &S, SourceLocation Tok);
301 void enterVariableInit(SourceLocation Tok, Decl *D);
302 /// Handles e.g. BaseType{ .D = Tok...
303 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
304 const Designation &D);
305 /// Computing a type for the function argument may require running
306 /// overloading, so we postpone its computation until it is actually needed.
307 ///
308 /// Clients should be very careful when using this funciton, as it stores a
309 /// function_ref, clients should make sure all calls to get() with the same
310 /// location happen while function_ref is alive.
311 ///
312 /// The callback should also emit signature help as a side-effect, but only
313 /// if the completion point has been reached.
314 void enterFunctionArgument(SourceLocation Tok,
315 llvm::function_ref<QualType()> ComputeType);
316
317 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
318 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
319 SourceLocation OpLoc);
320 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
321 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
322 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
323 /// Handles all type casts, including C-style cast, C++ casts, etc.
324 void enterTypeCast(SourceLocation Tok, QualType CastType);
325
326 /// Get the expected type associated with this location, if any.
327 ///
328 /// If the location is a function argument, determining the expected type
329 /// involves considering all function overloads and the arguments so far.
330 /// In this case, signature help for these function overloads will be reported
331 /// as a side-effect (only if the completion point has been reached).
332 QualType get(SourceLocation Tok) const {
333 if (!Enabled || Tok != ExpectedLoc)
334 return QualType();
335 if (!Type.isNull())
336 return Type;
337 if (ComputeType)
338 return ComputeType();
339 return QualType();
340 }
341
342private:
343 bool Enabled;
344 /// Start position of a token for which we store expected type.
345 SourceLocation ExpectedLoc;
346 /// Expected type for a token starting at ExpectedLoc.
347 QualType Type;
348 /// A function to compute expected type at ExpectedLoc. It is only considered
349 /// if Type is null.
350 llvm::function_ref<QualType()> ComputeType;
351};
352
353/// Sema - This implements semantic analysis and AST building for C.
354class Sema final {
355 Sema(const Sema &) = delete;
356 void operator=(const Sema &) = delete;
357
358 ///Source of additional semantic information.
359 ExternalSemaSource *ExternalSource;
360
361 ///Whether Sema has generated a multiplexer and has to delete it.
362 bool isMultiplexExternalSource;
363
364 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
365
366 bool isVisibleSlow(const NamedDecl *D);
367
368 /// Determine whether two declarations should be linked together, given that
369 /// the old declaration might not be visible and the new declaration might
370 /// not have external linkage.
371 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
372 const NamedDecl *New) {
373 if (isVisible(Old))
374 return true;
375 // See comment in below overload for why it's safe to compute the linkage
376 // of the new declaration here.
377 if (New->isExternallyDeclarable()) {
378 assert(Old->isExternallyDeclarable() &&(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "clang/include/clang/Sema/Sema.h", 379, __extension__ __PRETTY_FUNCTION__
))
379 "should not have found a non-externally-declarable previous decl")(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "clang/include/clang/Sema/Sema.h", 379, __extension__ __PRETTY_FUNCTION__
))
;
380 return true;
381 }
382 return false;
383 }
384 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
385
386 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
387 QualType ResultTy,
388 ArrayRef<QualType> Args);
389
390public:
391 /// The maximum alignment, same as in llvm::Value. We duplicate them here
392 /// because that allows us not to duplicate the constants in clang code,
393 /// which we must to since we can't directly use the llvm constants.
394 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
395 ///
396 /// This is the greatest alignment value supported by load, store, and alloca
397 /// instructions, and global values.
398 static const unsigned MaxAlignmentExponent = 32;
399 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
400
401 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
402 typedef OpaquePtr<TemplateName> TemplateTy;
403 typedef OpaquePtr<QualType> TypeTy;
404
405 OpenCLOptions OpenCLFeatures;
406 FPOptions CurFPFeatures;
407
408 const LangOptions &LangOpts;
409 Preprocessor &PP;
410 ASTContext &Context;
411 ASTConsumer &Consumer;
412 DiagnosticsEngine &Diags;
413 SourceManager &SourceMgr;
414
415 /// Flag indicating whether or not to collect detailed statistics.
416 bool CollectStats;
417
418 /// Code-completion consumer.
419 CodeCompleteConsumer *CodeCompleter;
420
421 /// CurContext - This is the current declaration context of parsing.
422 DeclContext *CurContext;
423
424 /// Generally null except when we temporarily switch decl contexts,
425 /// like in \see ActOnObjCTemporaryExitContainerContext.
426 DeclContext *OriginalLexicalContext;
427
428 /// VAListTagName - The declaration name corresponding to __va_list_tag.
429 /// This is used as part of a hack to omit that class from ADL results.
430 DeclarationName VAListTagName;
431
432 bool MSStructPragmaOn; // True when \#pragma ms_struct on
433
434 /// Controls member pointer representation format under the MS ABI.
435 LangOptions::PragmaMSPointersToMembersKind
436 MSPointerToMemberRepresentationMethod;
437
438 /// Stack of active SEH __finally scopes. Can be empty.
439 SmallVector<Scope*, 2> CurrentSEHFinally;
440
441 /// Source location for newly created implicit MSInheritanceAttrs
442 SourceLocation ImplicitMSInheritanceAttrLoc;
443
444 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
445 /// `TransformTypos` in order to keep track of any TypoExprs that are created
446 /// recursively during typo correction and wipe them away if the correction
447 /// fails.
448 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
449
450 /// pragma clang section kind
451 enum PragmaClangSectionKind {
452 PCSK_Invalid = 0,
453 PCSK_BSS = 1,
454 PCSK_Data = 2,
455 PCSK_Rodata = 3,
456 PCSK_Text = 4,
457 PCSK_Relro = 5
458 };
459
460 enum PragmaClangSectionAction {
461 PCSA_Set = 0,
462 PCSA_Clear = 1
463 };
464
465 struct PragmaClangSection {
466 std::string SectionName;
467 bool Valid = false;
468 SourceLocation PragmaLocation;
469 };
470
471 PragmaClangSection PragmaClangBSSSection;
472 PragmaClangSection PragmaClangDataSection;
473 PragmaClangSection PragmaClangRodataSection;
474 PragmaClangSection PragmaClangRelroSection;
475 PragmaClangSection PragmaClangTextSection;
476
477 enum PragmaMsStackAction {
478 PSK_Reset = 0x0, // #pragma ()
479 PSK_Set = 0x1, // #pragma (value)
480 PSK_Push = 0x2, // #pragma (push[, id])
481 PSK_Pop = 0x4, // #pragma (pop[, id])
482 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
483 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
484 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
485 };
486
487 // #pragma pack and align.
488 class AlignPackInfo {
489 public:
490 // `Native` represents default align mode, which may vary based on the
491 // platform.
492 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
493
494 // #pragma pack info constructor
495 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
496 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
497 assert(Num == PackNumber && "The pack number has been truncated.")(static_cast <bool> (Num == PackNumber && "The pack number has been truncated."
) ? void (0) : __assert_fail ("Num == PackNumber && \"The pack number has been truncated.\""
, "clang/include/clang/Sema/Sema.h", 497, __extension__ __PRETTY_FUNCTION__
))
;
498 }
499
500 // #pragma align info constructor
501 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
502 : PackAttr(false), AlignMode(M),
503 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
504
505 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
506
507 AlignPackInfo() : AlignPackInfo(Native, false) {}
508
509 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
510 // integer encoding for it. This should only be passed to
511 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
512 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
513 std::uint32_t Encoding{};
514 if (Info.IsXLStack())
515 Encoding |= IsXLMask;
516
517 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
518
519 if (Info.IsPackAttr())
520 Encoding |= PackAttrMask;
521
522 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
523
524 return Encoding;
525 }
526
527 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
528 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
529 AlignPackInfo::Mode M =
530 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
531 int PackNumber = (Encoding & PackNumMask) >> 4;
532
533 if (Encoding & PackAttrMask)
534 return AlignPackInfo(M, PackNumber, IsXL);
535
536 return AlignPackInfo(M, IsXL);
537 }
538
539 bool IsPackAttr() const { return PackAttr; }
540
541 bool IsAlignAttr() const { return !PackAttr; }
542
543 Mode getAlignMode() const { return AlignMode; }
544
545 unsigned getPackNumber() const { return PackNumber; }
546
547 bool IsPackSet() const {
548 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
549 // attriute on a decl.
550 return PackNumber != UninitPackVal && PackNumber != 0;
551 }
552
553 bool IsXLStack() const { return XLStack; }
554
555 bool operator==(const AlignPackInfo &Info) const {
556 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
557 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
558 Info.XLStack);
559 }
560
561 bool operator!=(const AlignPackInfo &Info) const {
562 return !(*this == Info);
563 }
564
565 private:
566 /// \brief True if this is a pragma pack attribute,
567 /// not a pragma align attribute.
568 bool PackAttr;
569
570 /// \brief The alignment mode that is in effect.
571 Mode AlignMode;
572
573 /// \brief The pack number of the stack.
574 unsigned char PackNumber;
575
576 /// \brief True if it is a XL #pragma align/pack stack.
577 bool XLStack;
578
579 /// \brief Uninitialized pack value.
580 static constexpr unsigned char UninitPackVal = -1;
581
582 // Masks to encode and decode an AlignPackInfo.
583 static constexpr uint32_t IsXLMask{0x0000'0001};
584 static constexpr uint32_t AlignModeMask{0x0000'0006};
585 static constexpr uint32_t PackAttrMask{0x00000'0008};
586 static constexpr uint32_t PackNumMask{0x0000'01F0};
587 };
588
589 template<typename ValueType>
590 struct PragmaStack {
591 struct Slot {
592 llvm::StringRef StackSlotLabel;
593 ValueType Value;
594 SourceLocation PragmaLocation;
595 SourceLocation PragmaPushLocation;
596 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
597 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
598 : StackSlotLabel(StackSlotLabel), Value(Value),
599 PragmaLocation(PragmaLocation),
600 PragmaPushLocation(PragmaPushLocation) {}
601 };
602
603 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
604 llvm::StringRef StackSlotLabel, ValueType Value) {
605 if (Action == PSK_Reset) {
606 CurrentValue = DefaultValue;
607 CurrentPragmaLocation = PragmaLocation;
608 return;
609 }
610 if (Action & PSK_Push)
611 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
612 PragmaLocation);
613 else if (Action & PSK_Pop) {
614 if (!StackSlotLabel.empty()) {
615 // If we've got a label, try to find it and jump there.
616 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
617 return x.StackSlotLabel == StackSlotLabel;
618 });
619 // If we found the label so pop from there.
620 if (I != Stack.rend()) {
621 CurrentValue = I->Value;
622 CurrentPragmaLocation = I->PragmaLocation;
623 Stack.erase(std::prev(I.base()), Stack.end());
624 }
625 } else if (!Stack.empty()) {
626 // We do not have a label, just pop the last entry.
627 CurrentValue = Stack.back().Value;
628 CurrentPragmaLocation = Stack.back().PragmaLocation;
629 Stack.pop_back();
630 }
631 }
632 if (Action & PSK_Set) {
633 CurrentValue = Value;
634 CurrentPragmaLocation = PragmaLocation;
635 }
636 }
637
638 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
639 // method body to restore the stacks on exit, so it works like this:
640 //
641 // struct S {
642 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
643 // void Method {}
644 // #pragma <name>(pop, InternalPragmaSlot)
645 // };
646 //
647 // It works even with #pragma vtordisp, although MSVC doesn't support
648 // #pragma vtordisp(push [, id], n)
649 // syntax.
650 //
651 // Push / pop a named sentinel slot.
652 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
653 assert((Action == PSK_Push || Action == PSK_Pop) &&(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "clang/include/clang/Sema/Sema.h", 654, __extension__ __PRETTY_FUNCTION__
))
654 "Can only push / pop #pragma stack sentinels!")(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "clang/include/clang/Sema/Sema.h", 654, __extension__ __PRETTY_FUNCTION__
))
;
655 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
656 }
657
658 // Constructors.
659 explicit PragmaStack(const ValueType &Default)
660 : DefaultValue(Default), CurrentValue(Default) {}
661
662 bool hasValue() const { return CurrentValue != DefaultValue; }
663
664 SmallVector<Slot, 2> Stack;
665 ValueType DefaultValue; // Value used for PSK_Reset action.
666 ValueType CurrentValue;
667 SourceLocation CurrentPragmaLocation;
668 };
669 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
670 // we shouldn't do so if they're in a module).
671
672 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
673 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
674 ///
675 /// 0: Suppress all vtordisps
676 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
677 /// structors
678 /// 2: Always insert vtordisps to support RTTI on partially constructed
679 /// objects
680 PragmaStack<MSVtorDispMode> VtorDispStack;
681 PragmaStack<AlignPackInfo> AlignPackStack;
682 // The current #pragma align/pack values and locations at each #include.
683 struct AlignPackIncludeState {
684 AlignPackInfo CurrentValue;
685 SourceLocation CurrentPragmaLocation;
686 bool HasNonDefaultValue, ShouldWarnOnInclude;
687 };
688 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
689 // Segment #pragmas.
690 PragmaStack<StringLiteral *> DataSegStack;
691 PragmaStack<StringLiteral *> BSSSegStack;
692 PragmaStack<StringLiteral *> ConstSegStack;
693 PragmaStack<StringLiteral *> CodeSegStack;
694
695 // This stack tracks the current state of Sema.CurFPFeatures.
696 PragmaStack<FPOptionsOverride> FpPragmaStack;
697 FPOptionsOverride CurFPFeatureOverrides() {
698 FPOptionsOverride result;
699 if (!FpPragmaStack.hasValue()) {
700 result = FPOptionsOverride();
701 } else {
702 result = FpPragmaStack.CurrentValue;
703 }
704 return result;
705 }
706
707 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
708 // Actions should be performed only if we enter / exit a C++ method body.
709 class PragmaStackSentinelRAII {
710 public:
711 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
712 ~PragmaStackSentinelRAII();
713
714 private:
715 Sema &S;
716 StringRef SlotLabel;
717 bool ShouldAct;
718 };
719
720 /// A mapping that describes the nullability we've seen in each header file.
721 FileNullabilityMap NullabilityMap;
722
723 /// Last section used with #pragma init_seg.
724 StringLiteral *CurInitSeg;
725 SourceLocation CurInitSegLoc;
726
727 /// VisContext - Manages the stack for \#pragma GCC visibility.
728 void *VisContext; // Really a "PragmaVisStack*"
729
730 /// This an attribute introduced by \#pragma clang attribute.
731 struct PragmaAttributeEntry {
732 SourceLocation Loc;
733 ParsedAttr *Attribute;
734 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
735 bool IsUsed;
736 };
737
738 /// A push'd group of PragmaAttributeEntries.
739 struct PragmaAttributeGroup {
740 /// The location of the push attribute.
741 SourceLocation Loc;
742 /// The namespace of this push group.
743 const IdentifierInfo *Namespace;
744 SmallVector<PragmaAttributeEntry, 2> Entries;
745 };
746
747 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
748
749 /// The declaration that is currently receiving an attribute from the
750 /// #pragma attribute stack.
751 const Decl *PragmaAttributeCurrentTargetDecl;
752
753 /// This represents the last location of a "#pragma clang optimize off"
754 /// directive if such a directive has not been closed by an "on" yet. If
755 /// optimizations are currently "on", this is set to an invalid location.
756 SourceLocation OptimizeOffPragmaLocation;
757
758 /// Flag indicating if Sema is building a recovery call expression.
759 ///
760 /// This flag is used to avoid building recovery call expressions
761 /// if Sema is already doing so, which would cause infinite recursions.
762 bool IsBuildingRecoveryCallExpr;
763
764 /// Used to control the generation of ExprWithCleanups.
765 CleanupInfo Cleanup;
766
767 /// ExprCleanupObjects - This is the stack of objects requiring
768 /// cleanup that are created by the current full expression.
769 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
770
771 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
772 /// to a variable (constant) that may or may not be odr-used in this Expr, and
773 /// we won't know until all lvalue-to-rvalue and discarded value conversions
774 /// have been applied to all subexpressions of the enclosing full expression.
775 /// This is cleared at the end of each full expression.
776 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
777 llvm::SmallPtrSet<Expr *, 4>>;
778 MaybeODRUseExprSet MaybeODRUseExprs;
779
780 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
781
782 /// Stack containing information about each of the nested
783 /// function, block, and method scopes that are currently active.
784 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
785
786 /// The index of the first FunctionScope that corresponds to the current
787 /// context.
788 unsigned FunctionScopesStart = 0;
789
790 /// Whether we are currently in the context of a mutable agnostic identifier
791 /// as described by CWG2569.
792 /// We are handling the unqualified-id of a decltype or noexcept expression.
793 bool InMutableAgnosticContext = false;
794
795 /// RAII object used to change the value of \c InMutableAgnosticContext
796 /// within a \c Sema object.
797 class MutableAgnosticContextRAII {
798 Sema &SemaRef;
799
800 public:
801 MutableAgnosticContextRAII(Sema &S) : SemaRef(S) {
802 SemaRef.InMutableAgnosticContext = true;
803 }
804 ~MutableAgnosticContextRAII() { SemaRef.InMutableAgnosticContext = false; }
805 };
806
807 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
808 return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
809 FunctionScopes.end());
810 }
811
812 /// Stack containing information needed when in C++2a an 'auto' is encountered
813 /// in a function declaration parameter type specifier in order to invent a
814 /// corresponding template parameter in the enclosing abbreviated function
815 /// template. This information is also present in LambdaScopeInfo, stored in
816 /// the FunctionScopes stack.
817 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
818
819 /// The index of the first InventedParameterInfo that refers to the current
820 /// context.
821 unsigned InventedParameterInfosStart = 0;
822
823 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
824 return llvm::makeArrayRef(InventedParameterInfos.begin() +
825 InventedParameterInfosStart,
826 InventedParameterInfos.end());
827 }
828
829 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
830 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
831 ExtVectorDeclsType;
832
833 /// ExtVectorDecls - This is a list all the extended vector types. This allows
834 /// us to associate a raw vector type with one of the ext_vector type names.
835 /// This is only necessary for issuing pretty diagnostics.
836 ExtVectorDeclsType ExtVectorDecls;
837
838 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
839 std::unique_ptr<CXXFieldCollector> FieldCollector;
840
841 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
842
843 /// Set containing all declared private fields that are not used.
844 NamedDeclSetType UnusedPrivateFields;
845
846 /// Set containing all typedefs that are likely unused.
847 llvm::SmallSetVector<const TypedefNameDecl *, 4>
848 UnusedLocalTypedefNameCandidates;
849
850 /// Delete-expressions to be analyzed at the end of translation unit
851 ///
852 /// This list contains class members, and locations of delete-expressions
853 /// that could not be proven as to whether they mismatch with new-expression
854 /// used in initializer of the field.
855 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
856 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
857 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
858
859 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
860
861 /// PureVirtualClassDiagSet - a set of class declarations which we have
862 /// emitted a list of pure virtual functions. Used to prevent emitting the
863 /// same list more than once.
864 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
865
866 /// ParsingInitForAutoVars - a set of declarations with auto types for which
867 /// we are currently parsing the initializer.
868 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
869
870 /// Look for a locally scoped extern "C" declaration by the given name.
871 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
872
873 typedef LazyVector<VarDecl *, ExternalSemaSource,
874 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
875 TentativeDefinitionsType;
876
877 /// All the tentative definitions encountered in the TU.
878 TentativeDefinitionsType TentativeDefinitions;
879
880 /// All the external declarations encoutered and used in the TU.
881 SmallVector<VarDecl *, 4> ExternalDeclarations;
882
883 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
884 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
885 UnusedFileScopedDeclsType;
886
887 /// The set of file scoped decls seen so far that have not been used
888 /// and must warn if not used. Only contains the first declaration.
889 UnusedFileScopedDeclsType UnusedFileScopedDecls;
890
891 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
892 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
893 DelegatingCtorDeclsType;
894
895 /// All the delegating constructors seen so far in the file, used for
896 /// cycle detection at the end of the TU.
897 DelegatingCtorDeclsType DelegatingCtorDecls;
898
899 /// All the overriding functions seen during a class definition
900 /// that had their exception spec checks delayed, plus the overridden
901 /// function.
902 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
903 DelayedOverridingExceptionSpecChecks;
904
905 /// All the function redeclarations seen during a class definition that had
906 /// their exception spec checks delayed, plus the prior declaration they
907 /// should be checked against. Except during error recovery, the new decl
908 /// should always be a friend declaration, as that's the only valid way to
909 /// redeclare a special member before its class is complete.
910 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
911 DelayedEquivalentExceptionSpecChecks;
912
913 typedef llvm::MapVector<const FunctionDecl *,
914 std::unique_ptr<LateParsedTemplate>>
915 LateParsedTemplateMapT;
916 LateParsedTemplateMapT LateParsedTemplateMap;
917
918 /// Callback to the parser to parse templated functions when needed.
919 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
920 typedef void LateTemplateParserCleanupCB(void *P);
921 LateTemplateParserCB *LateTemplateParser;
922 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
923 void *OpaqueParser;
924
925 void SetLateTemplateParser(LateTemplateParserCB *LTP,
926 LateTemplateParserCleanupCB *LTPCleanup,
927 void *P) {
928 LateTemplateParser = LTP;
929 LateTemplateParserCleanup = LTPCleanup;
930 OpaqueParser = P;
931 }
932
933 class DelayedDiagnostics;
934
935 class DelayedDiagnosticsState {
936 sema::DelayedDiagnosticPool *SavedPool;
937 friend class Sema::DelayedDiagnostics;
938 };
939 typedef DelayedDiagnosticsState ParsingDeclState;
940 typedef DelayedDiagnosticsState ProcessingContextState;
941
942 /// A class which encapsulates the logic for delaying diagnostics
943 /// during parsing and other processing.
944 class DelayedDiagnostics {
945 /// The current pool of diagnostics into which delayed
946 /// diagnostics should go.
947 sema::DelayedDiagnosticPool *CurPool;
948
949 public:
950 DelayedDiagnostics() : CurPool(nullptr) {}
951
952 /// Adds a delayed diagnostic.
953 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
954
955 /// Determines whether diagnostics should be delayed.
956 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
957
958 /// Returns the current delayed-diagnostics pool.
959 sema::DelayedDiagnosticPool *getCurrentPool() const {
960 return CurPool;
961 }
962
963 /// Enter a new scope. Access and deprecation diagnostics will be
964 /// collected in this pool.
965 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
966 DelayedDiagnosticsState state;
967 state.SavedPool = CurPool;
968 CurPool = &pool;
969 return state;
970 }
971
972 /// Leave a delayed-diagnostic state that was previously pushed.
973 /// Do not emit any of the diagnostics. This is performed as part
974 /// of the bookkeeping of popping a pool "properly".
975 void popWithoutEmitting(DelayedDiagnosticsState state) {
976 CurPool = state.SavedPool;
977 }
978
979 /// Enter a new scope where access and deprecation diagnostics are
980 /// not delayed.
981 DelayedDiagnosticsState pushUndelayed() {
982 DelayedDiagnosticsState state;
983 state.SavedPool = CurPool;
984 CurPool = nullptr;
985 return state;
986 }
987
988 /// Undo a previous pushUndelayed().
989 void popUndelayed(DelayedDiagnosticsState state) {
990 assert(CurPool == nullptr)(static_cast <bool> (CurPool == nullptr) ? void (0) : __assert_fail
("CurPool == nullptr", "clang/include/clang/Sema/Sema.h", 990
, __extension__ __PRETTY_FUNCTION__))
;
991 CurPool = state.SavedPool;
992 }
993 } DelayedDiagnostics;
994
995 /// A RAII object to temporarily push a declaration context.
996 class ContextRAII {
997 private:
998 Sema &S;
999 DeclContext *SavedContext;
1000 ProcessingContextState SavedContextState;
1001 QualType SavedCXXThisTypeOverride;
1002 unsigned SavedFunctionScopesStart;
1003 unsigned SavedInventedParameterInfosStart;
1004
1005 public:
1006 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
1007 : S(S), SavedContext(S.CurContext),
1008 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
1009 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
1010 SavedFunctionScopesStart(S.FunctionScopesStart),
1011 SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1012 {
1013 assert(ContextToPush && "pushing null context")(static_cast <bool> (ContextToPush && "pushing null context"
) ? void (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "clang/include/clang/Sema/Sema.h", 1013, __extension__ __PRETTY_FUNCTION__
))
;
1014 S.CurContext = ContextToPush;
1015 if (NewThisContext)
1016 S.CXXThisTypeOverride = QualType();
1017 // Any saved FunctionScopes do not refer to this context.
1018 S.FunctionScopesStart = S.FunctionScopes.size();
1019 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1020 }
1021
1022 void pop() {
1023 if (!SavedContext) return;
1024 S.CurContext = SavedContext;
1025 S.DelayedDiagnostics.popUndelayed(SavedContextState);
1026 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1027 S.FunctionScopesStart = SavedFunctionScopesStart;
1028 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1029 SavedContext = nullptr;
1030 }
1031
1032 ~ContextRAII() {
1033 pop();
1034 }
1035 };
1036
1037 /// Whether the AST is currently being rebuilt to correct immediate
1038 /// invocations. Immediate invocation candidates and references to consteval
1039 /// functions aren't tracked when this is set.
1040 bool RebuildingImmediateInvocation = false;
1041
1042 /// Used to change context to isConstantEvaluated without pushing a heavy
1043 /// ExpressionEvaluationContextRecord object.
1044 bool isConstantEvaluatedOverride;
1045
1046 bool isConstantEvaluated() {
1047 return ExprEvalContexts.back().isConstantEvaluated() ||
1048 isConstantEvaluatedOverride;
1049 }
1050
1051 /// RAII object to handle the state changes required to synthesize
1052 /// a function body.
1053 class SynthesizedFunctionScope {
1054 Sema &S;
1055 Sema::ContextRAII SavedContext;
1056 bool PushedCodeSynthesisContext = false;
1057
1058 public:
1059 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
1060 : S(S), SavedContext(S, DC) {
1061 S.PushFunctionScope();
1062 S.PushExpressionEvaluationContext(
1063 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1064 if (auto *FD = dyn_cast<FunctionDecl>(DC))
1065 FD->setWillHaveBody(true);
1066 else
1067 assert(isa<ObjCMethodDecl>(DC))(static_cast <bool> (isa<ObjCMethodDecl>(DC)) ? void
(0) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "clang/include/clang/Sema/Sema.h"
, 1067, __extension__ __PRETTY_FUNCTION__))
;
1068 }
1069
1070 void addContextNote(SourceLocation UseLoc) {
1071 assert(!PushedCodeSynthesisContext)(static_cast <bool> (!PushedCodeSynthesisContext) ? void
(0) : __assert_fail ("!PushedCodeSynthesisContext", "clang/include/clang/Sema/Sema.h"
, 1071, __extension__ __PRETTY_FUNCTION__))
;
1072
1073 Sema::CodeSynthesisContext Ctx;
1074 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
1075 Ctx.PointOfInstantiation = UseLoc;
1076 Ctx.Entity = cast<Decl>(S.CurContext);
1077 S.pushCodeSynthesisContext(Ctx);
1078
1079 PushedCodeSynthesisContext = true;
1080 }
1081
1082 ~SynthesizedFunctionScope() {
1083 if (PushedCodeSynthesisContext)
1084 S.popCodeSynthesisContext();
1085 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1086 FD->setWillHaveBody(false);
1087 S.PopExpressionEvaluationContext();
1088 S.PopFunctionScopeInfo();
1089 }
1090 };
1091
1092 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
1093 /// declared. Rare. May alias another identifier, declared or undeclared.
1094 ///
1095 /// For aliases, the target identifier is used as a key for eventual
1096 /// processing when the target is declared. For the single-identifier form,
1097 /// the sole identifier is used as the key. Each entry is a `SetVector`
1098 /// (ordered by parse order) of aliases (identified by the alias name) in case
1099 /// of multiple aliases to the same undeclared identifier.
1100 llvm::MapVector<
1101 IdentifierInfo *,
1102 llvm::SetVector<
1103 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
1104 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
1105 WeakUndeclaredIdentifiers;
1106
1107 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1108 /// \#pragma redefine_extname before declared. Used in Solaris system headers
1109 /// to define functions that occur in multiple standards to call the version
1110 /// in the currently selected standard.
1111 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1112
1113
1114 /// Load weak undeclared identifiers from the external source.
1115 void LoadExternalWeakUndeclaredIdentifiers();
1116
1117 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1118 /// \#pragma weak during processing of other Decls.
1119 /// I couldn't figure out a clean way to generate these in-line, so
1120 /// we store them here and handle separately -- which is a hack.
1121 /// It would be best to refactor this.
1122 SmallVector<Decl*,2> WeakTopLevelDecl;
1123
1124 IdentifierResolver IdResolver;
1125
1126 /// Translation Unit Scope - useful to Objective-C actions that need
1127 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1128 /// For example, user-defined classes, built-in "id" type, etc.
1129 Scope *TUScope;
1130
1131 /// The C++ "std" namespace, where the standard library resides.
1132 LazyDeclPtr StdNamespace;
1133
1134 /// The C++ "std::bad_alloc" class, which is defined by the C++
1135 /// standard library.
1136 LazyDeclPtr StdBadAlloc;
1137
1138 /// The C++ "std::align_val_t" enum class, which is defined by the C++
1139 /// standard library.
1140 LazyDeclPtr StdAlignValT;
1141
1142 /// The C++ "std::experimental" namespace, where the experimental parts
1143 /// of the standard library resides.
1144 NamespaceDecl *StdExperimentalNamespaceCache;
1145
1146 /// The C++ "std::initializer_list" template, which is defined in
1147 /// \<initializer_list>.
1148 ClassTemplateDecl *StdInitializerList;
1149
1150 /// The C++ "std::coroutine_traits" template, which is defined in
1151 /// \<coroutine_traits>
1152 ClassTemplateDecl *StdCoroutineTraitsCache;
1153 /// The namespace where coroutine components are defined. In standard,
1154 /// they are defined in std namespace. And in the previous implementation,
1155 /// they are defined in std::experimental namespace.
1156 NamespaceDecl *CoroTraitsNamespaceCache;
1157
1158 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1159 RecordDecl *CXXTypeInfoDecl;
1160
1161 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1162 RecordDecl *MSVCGuidDecl;
1163
1164 /// The C++ "std::source_location::__impl" struct, defined in
1165 /// \<source_location>.
1166 RecordDecl *StdSourceLocationImplDecl;
1167
1168 /// Caches identifiers/selectors for NSFoundation APIs.
1169 std::unique_ptr<NSAPI> NSAPIObj;
1170
1171 /// The declaration of the Objective-C NSNumber class.
1172 ObjCInterfaceDecl *NSNumberDecl;
1173
1174 /// The declaration of the Objective-C NSValue class.
1175 ObjCInterfaceDecl *NSValueDecl;
1176
1177 /// Pointer to NSNumber type (NSNumber *).
1178 QualType NSNumberPointer;
1179
1180 /// Pointer to NSValue type (NSValue *).
1181 QualType NSValuePointer;
1182
1183 /// The Objective-C NSNumber methods used to create NSNumber literals.
1184 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1185
1186 /// The declaration of the Objective-C NSString class.
1187 ObjCInterfaceDecl *NSStringDecl;
1188
1189 /// Pointer to NSString type (NSString *).
1190 QualType NSStringPointer;
1191
1192 /// The declaration of the stringWithUTF8String: method.
1193 ObjCMethodDecl *StringWithUTF8StringMethod;
1194
1195 /// The declaration of the valueWithBytes:objCType: method.
1196 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1197
1198 /// The declaration of the Objective-C NSArray class.
1199 ObjCInterfaceDecl *NSArrayDecl;
1200
1201 /// The declaration of the arrayWithObjects:count: method.
1202 ObjCMethodDecl *ArrayWithObjectsMethod;
1203
1204 /// The declaration of the Objective-C NSDictionary class.
1205 ObjCInterfaceDecl *NSDictionaryDecl;
1206
1207 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1208 ObjCMethodDecl *DictionaryWithObjectsMethod;
1209
1210 /// id<NSCopying> type.
1211 QualType QIDNSCopying;
1212
1213 /// will hold 'respondsToSelector:'
1214 Selector RespondsToSelectorSel;
1215
1216 /// A flag to remember whether the implicit forms of operator new and delete
1217 /// have been declared.
1218 bool GlobalNewDeleteDeclared;
1219
1220 /// Describes how the expressions currently being parsed are
1221 /// evaluated at run-time, if at all.
1222 enum class ExpressionEvaluationContext {
1223 /// The current expression and its subexpressions occur within an
1224 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1225 /// \c sizeof, where the type of the expression may be significant but
1226 /// no code will be generated to evaluate the value of the expression at
1227 /// run time.
1228 Unevaluated,
1229
1230 /// The current expression occurs within a braced-init-list within
1231 /// an unevaluated operand. This is mostly like a regular unevaluated
1232 /// context, except that we still instantiate constexpr functions that are
1233 /// referenced here so that we can perform narrowing checks correctly.
1234 UnevaluatedList,
1235
1236 /// The current expression occurs within a discarded statement.
1237 /// This behaves largely similarly to an unevaluated operand in preventing
1238 /// definitions from being required, but not in other ways.
1239 DiscardedStatement,
1240
1241 /// The current expression occurs within an unevaluated
1242 /// operand that unconditionally permits abstract references to
1243 /// fields, such as a SIZE operator in MS-style inline assembly.
1244 UnevaluatedAbstract,
1245
1246 /// The current context is "potentially evaluated" in C++11 terms,
1247 /// but the expression is evaluated at compile-time (like the values of
1248 /// cases in a switch statement).
1249 ConstantEvaluated,
1250
1251 /// In addition of being constant evaluated, the current expression
1252 /// occurs in an immediate function context - either a consteval function
1253 /// or a consteval if function.
1254 ImmediateFunctionContext,
1255
1256 /// The current expression is potentially evaluated at run time,
1257 /// which means that code may be generated to evaluate the value of the
1258 /// expression at run time.
1259 PotentiallyEvaluated,
1260
1261 /// The current expression is potentially evaluated, but any
1262 /// declarations referenced inside that expression are only used if
1263 /// in fact the current expression is used.
1264 ///
1265 /// This value is used when parsing default function arguments, for which
1266 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1267 /// through varargs) but do not want to mark declarations as "referenced"
1268 /// until the default argument is used.
1269 PotentiallyEvaluatedIfUsed
1270 };
1271
1272 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1273
1274 /// Data structure used to record current or nested
1275 /// expression evaluation contexts.
1276 struct ExpressionEvaluationContextRecord {
1277 /// The expression evaluation context.
1278 ExpressionEvaluationContext Context;
1279
1280 /// Whether the enclosing context needed a cleanup.
1281 CleanupInfo ParentCleanup;
1282
1283 /// The number of active cleanup objects when we entered
1284 /// this expression evaluation context.
1285 unsigned NumCleanupObjects;
1286
1287 /// The number of typos encountered during this expression evaluation
1288 /// context (i.e. the number of TypoExprs created).
1289 unsigned NumTypos;
1290
1291 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1292
1293 /// The lambdas that are present within this context, if it
1294 /// is indeed an unevaluated context.
1295 SmallVector<LambdaExpr *, 2> Lambdas;
1296
1297 /// The declaration that provides context for lambda expressions
1298 /// and block literals if the normal declaration context does not
1299 /// suffice, e.g., in a default function argument.
1300 Decl *ManglingContextDecl;
1301
1302 /// If we are processing a decltype type, a set of call expressions
1303 /// for which we have deferred checking the completeness of the return type.
1304 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1305
1306 /// If we are processing a decltype type, a set of temporary binding
1307 /// expressions for which we have deferred checking the destructor.
1308 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1309
1310 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1311
1312 /// Expressions appearing as the LHS of a volatile assignment in this
1313 /// context. We produce a warning for these when popping the context if
1314 /// they are not discarded-value expressions nor unevaluated operands.
1315 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1316
1317 /// Set of candidates for starting an immediate invocation.
1318 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1319
1320 /// Set of DeclRefExprs referencing a consteval function when used in a
1321 /// context not already known to be immediately invoked.
1322 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1323
1324 /// \brief Describes whether we are in an expression constext which we have
1325 /// to handle differently.
1326 enum ExpressionKind {
1327 EK_Decltype, EK_TemplateArgument, EK_Other
1328 } ExprContext;
1329
1330 // A context can be nested in both a discarded statement context and
1331 // an immediate function context, so they need to be tracked independently.
1332 bool InDiscardedStatement;
1333 bool InImmediateFunctionContext;
1334
1335 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1336 unsigned NumCleanupObjects,
1337 CleanupInfo ParentCleanup,
1338 Decl *ManglingContextDecl,
1339 ExpressionKind ExprContext)
1340 : Context(Context), ParentCleanup(ParentCleanup),
1341 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1342 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
1343 InDiscardedStatement(false), InImmediateFunctionContext(false) {}
1344
1345 bool isUnevaluated() const {
1346 return Context == ExpressionEvaluationContext::Unevaluated ||
1347 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1348 Context == ExpressionEvaluationContext::UnevaluatedList;
1349 }
1350
1351 bool isConstantEvaluated() const {
1352 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
1353 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
1354 }
1355
1356 bool isImmediateFunctionContext() const {
1357 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
1358 (Context == ExpressionEvaluationContext::DiscardedStatement &&
1359 InImmediateFunctionContext);
1360 }
1361
1362 bool isDiscardedStatementContext() const {
1363 return Context == ExpressionEvaluationContext::DiscardedStatement ||
1364 (Context ==
1365 ExpressionEvaluationContext::ImmediateFunctionContext &&
1366 InDiscardedStatement);
1367 }
1368 };
1369
1370 /// A stack of expression evaluation contexts.
1371 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1372
1373 /// Emit a warning for all pending noderef expressions that we recorded.
1374 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1375
1376 /// Compute the mangling number context for a lambda expression or
1377 /// block literal. Also return the extra mangling decl if any.
1378 ///
1379 /// \param DC - The DeclContext containing the lambda expression or
1380 /// block literal.
1381 std::tuple<MangleNumberingContext *, Decl *>
1382 getCurrentMangleNumberContext(const DeclContext *DC);
1383
1384
1385 /// SpecialMemberOverloadResult - The overloading result for a special member
1386 /// function.
1387 ///
1388 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1389 /// integer are used to determine whether overload resolution succeeded.
1390 class SpecialMemberOverloadResult {
1391 public:
1392 enum Kind {
1393 NoMemberOrDeleted,
1394 Ambiguous,
1395 Success
1396 };
1397
1398 private:
1399 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1400
1401 public:
1402 SpecialMemberOverloadResult() {}
1403 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1404 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1405
1406 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1407 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1408
1409 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1410 void setKind(Kind K) { Pair.setInt(K); }
1411 };
1412
1413 class SpecialMemberOverloadResultEntry
1414 : public llvm::FastFoldingSetNode,
1415 public SpecialMemberOverloadResult {
1416 public:
1417 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1418 : FastFoldingSetNode(ID)
1419 {}
1420 };
1421
1422 /// A cache of special member function overload resolution results
1423 /// for C++ records.
1424 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1425
1426 /// A cache of the flags available in enumerations with the flag_bits
1427 /// attribute.
1428 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1429
1430 /// The kind of translation unit we are processing.
1431 ///
1432 /// When we're processing a complete translation unit, Sema will perform
1433 /// end-of-translation-unit semantic tasks (such as creating
1434 /// initializers for tentative definitions in C) once parsing has
1435 /// completed. Modules and precompiled headers perform different kinds of
1436 /// checks.
1437 const TranslationUnitKind TUKind;
1438
1439 llvm::BumpPtrAllocator BumpAlloc;
1440
1441 /// The number of SFINAE diagnostics that have been trapped.
1442 unsigned NumSFINAEErrors;
1443
1444 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1445 UnparsedDefaultArgInstantiationsMap;
1446
1447 /// A mapping from parameters with unparsed default arguments to the
1448 /// set of instantiations of each parameter.
1449 ///
1450 /// This mapping is a temporary data structure used when parsing
1451 /// nested class templates or nested classes of class templates,
1452 /// where we might end up instantiating an inner class before the
1453 /// default arguments of its methods have been parsed.
1454 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1455
1456 // Contains the locations of the beginning of unparsed default
1457 // argument locations.
1458 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1459
1460 /// UndefinedInternals - all the used, undefined objects which require a
1461 /// definition in this translation unit.
1462 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1463
1464 /// Determine if VD, which must be a variable or function, is an external
1465 /// symbol that nonetheless can't be referenced from outside this translation
1466 /// unit because its type has no linkage and it's not extern "C".
1467 bool isExternalWithNoLinkageType(ValueDecl *VD);
1468
1469 /// Obtain a sorted list of functions that are undefined but ODR-used.
1470 void getUndefinedButUsed(
1471 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1472
1473 /// Retrieves list of suspicious delete-expressions that will be checked at
1474 /// the end of translation unit.
1475 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1476 getMismatchingDeleteExpressions() const;
1477
1478 class GlobalMethodPool {
1479 public:
1480 using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1481 using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1482 iterator begin() { return Methods.begin(); }
1483 iterator end() { return Methods.end(); }
1484 iterator find(Selector Sel) { return Methods.find(Sel); }
1485 std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1486 return Methods.insert(Val);
1487 }
1488 int count(Selector Sel) const { return Methods.count(Sel); }
1489 bool empty() const { return Methods.empty(); }
1490
1491 private:
1492 llvm::DenseMap<Selector, Lists> Methods;
1493 };
1494
1495 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1496 /// We need to maintain a list, since selectors can have differing signatures
1497 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1498 /// of selectors are "overloaded").
1499 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1500 /// methods inside categories with a particular selector.
1501 GlobalMethodPool MethodPool;
1502
1503 /// Method selectors used in a \@selector expression. Used for implementation
1504 /// of -Wselector.
1505 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1506
1507 /// List of SourceLocations where 'self' is implicitly retained inside a
1508 /// block.
1509 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1510 ImplicitlyRetainedSelfLocs;
1511
1512 /// Kinds of C++ special members.
1513 enum CXXSpecialMember {
1514 CXXDefaultConstructor,
1515 CXXCopyConstructor,
1516 CXXMoveConstructor,
1517 CXXCopyAssignment,
1518 CXXMoveAssignment,
1519 CXXDestructor,
1520 CXXInvalid
1521 };
1522
1523 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1524 SpecialMemberDecl;
1525
1526 /// The C++ special members which we are currently in the process of
1527 /// declaring. If this process recursively triggers the declaration of the
1528 /// same special member, we should act as if it is not yet declared.
1529 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1530
1531 /// Kinds of defaulted comparison operator functions.
1532 enum class DefaultedComparisonKind : unsigned char {
1533 /// This is not a defaultable comparison operator.
1534 None,
1535 /// This is an operator== that should be implemented as a series of
1536 /// subobject comparisons.
1537 Equal,
1538 /// This is an operator<=> that should be implemented as a series of
1539 /// subobject comparisons.
1540 ThreeWay,
1541 /// This is an operator!= that should be implemented as a rewrite in terms
1542 /// of a == comparison.
1543 NotEqual,
1544 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1545 /// terms of a <=> comparison.
1546 Relational,
1547 };
1548
1549 /// The function definitions which were renamed as part of typo-correction
1550 /// to match their respective declarations. We want to keep track of them
1551 /// to ensure that we don't emit a "redefinition" error if we encounter a
1552 /// correctly named definition after the renamed definition.
1553 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1554
1555 /// Stack of types that correspond to the parameter entities that are
1556 /// currently being copy-initialized. Can be empty.
1557 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1558
1559 void ReadMethodPool(Selector Sel);
1560 void updateOutOfDateSelector(Selector Sel);
1561
1562 /// Private Helper predicate to check for 'self'.
1563 bool isSelfExpr(Expr *RExpr);
1564 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1565
1566 /// Cause the active diagnostic on the DiagosticsEngine to be
1567 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1568 /// should not be used elsewhere.
1569 void EmitCurrentDiagnostic(unsigned DiagID);
1570
1571 /// Records and restores the CurFPFeatures state on entry/exit of compound
1572 /// statements.
1573 class FPFeaturesStateRAII {
1574 public:
1575 FPFeaturesStateRAII(Sema &S);
1576 ~FPFeaturesStateRAII();
1577 FPOptionsOverride getOverrides() { return OldOverrides; }
1578
1579 private:
1580 Sema& S;
1581 FPOptions OldFPFeaturesState;
1582 FPOptionsOverride OldOverrides;
1583 LangOptions::FPEvalMethodKind OldEvalMethod;
1584 SourceLocation OldFPPragmaLocation;
1585 };
1586
1587 void addImplicitTypedef(StringRef Name, QualType T);
1588
1589 bool WarnedStackExhausted = false;
1590
1591 /// Increment when we find a reference; decrement when we find an ignored
1592 /// assignment. Ultimately the value is 0 if every reference is an ignored
1593 /// assignment.
1594 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1595
1596private:
1597 Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1598
1599 bool WarnedDarwinSDKInfoMissing = false;
1600
1601public:
1602 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1603 TranslationUnitKind TUKind = TU_Complete,
1604 CodeCompleteConsumer *CompletionConsumer = nullptr);
1605 ~Sema();
1606
1607 /// Perform initialization that occurs after the parser has been
1608 /// initialized but before it parses anything.
1609 void Initialize();
1610
1611 /// This virtual key function only exists to limit the emission of debug info
1612 /// describing the Sema class. GCC and Clang only emit debug info for a class
1613 /// with a vtable when the vtable is emitted. Sema is final and not
1614 /// polymorphic, but the debug info size savings are so significant that it is
1615 /// worth adding a vtable just to take advantage of this optimization.
1616 virtual void anchor();
1617
1618 const LangOptions &getLangOpts() const { return LangOpts; }
1619 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1620 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
1621
1622 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1623 SourceManager &getSourceManager() const { return SourceMgr; }
1624 Preprocessor &getPreprocessor() const { return PP; }
1625 ASTContext &getASTContext() const { return Context; }
1626 ASTConsumer &getASTConsumer() const { return Consumer; }
1627 ASTMutationListener *getASTMutationListener() const;
1628 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1629
1630 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
1631 StringRef Platform);
1632 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
1633
1634 ///Registers an external source. If an external source already exists,
1635 /// creates a multiplex external source and appends to it.
1636 ///
1637 ///\param[in] E - A non-null external sema source.
1638 ///
1639 void addExternalSource(ExternalSemaSource *E);
1640
1641 void PrintStats() const;
1642
1643 /// Warn that the stack is nearly exhausted.
1644 void warnStackExhausted(SourceLocation Loc);
1645
1646 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1647 /// guaranteed). Produces a warning if we're low on stack space and allocates
1648 /// more in that case. Use this in code that may recurse deeply (for example,
1649 /// in template instantiation) to avoid stack overflow.
1650 void runWithSufficientStackSpace(SourceLocation Loc,
1651 llvm::function_ref<void()> Fn);
1652
1653 /// Helper class that creates diagnostics with optional
1654 /// template instantiation stacks.
1655 ///
1656 /// This class provides a wrapper around the basic DiagnosticBuilder
1657 /// class that emits diagnostics. ImmediateDiagBuilder is
1658 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1659 /// does) and, if the diagnostic comes from inside a template
1660 /// instantiation, printing the template instantiation stack as
1661 /// well.
1662 class ImmediateDiagBuilder : public DiagnosticBuilder {
1663 Sema &SemaRef;
1664 unsigned DiagID;
1665
1666 public:
1667 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1668 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1669 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1670 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1671
1672 // This is a cunning lie. DiagnosticBuilder actually performs move
1673 // construction in its copy constructor (but due to varied uses, it's not
1674 // possible to conveniently express this as actual move construction). So
1675 // the default copy ctor here is fine, because the base class disables the
1676 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1677 // in that case anwyay.
1678 ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1679
1680 ~ImmediateDiagBuilder() {
1681 // If we aren't active, there is nothing to do.
1682 if (!isActive()) return;
1683
1684 // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1685 // builder itself so it won't emit the diagnostic in its own destructor.
1686 //
1687 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1688 // do its own needless checks to see if the diagnostic needs to be
1689 // emitted. However, because we take care to ensure that the builder
1690 // objects never escape, a sufficiently smart compiler will be able to
1691 // eliminate that code.
1692 Clear();
1693
1694 // Dispatch to Sema to emit the diagnostic.
1695 SemaRef.EmitCurrentDiagnostic(DiagID);
1696 }
1697
1698 /// Teach operator<< to produce an object of the correct type.
1699 template <typename T>
1700 friend const ImmediateDiagBuilder &
1701 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1702 const DiagnosticBuilder &BaseDiag = Diag;
1703 BaseDiag << Value;
1704 return Diag;
1705 }
1706
1707 // It is necessary to limit this to rvalue reference to avoid calling this
1708 // function with a bitfield lvalue argument since non-const reference to
1709 // bitfield is not allowed.
1710 template <typename T, typename = typename std::enable_if<
1711 !std::is_lvalue_reference<T>::value>::type>
1712 const ImmediateDiagBuilder &operator<<(T &&V) const {
1713 const DiagnosticBuilder &BaseDiag = *this;
1714 BaseDiag << std::move(V);
1715 return *this;
1716 }
1717 };
1718
1719 /// A generic diagnostic builder for errors which may or may not be deferred.
1720 ///
1721 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1722 /// which are not allowed to appear inside __device__ functions and are
1723 /// allowed to appear in __host__ __device__ functions only if the host+device
1724 /// function is never codegen'ed.
1725 ///
1726 /// To handle this, we use the notion of "deferred diagnostics", where we
1727 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1728 ///
1729 /// This class lets you emit either a regular diagnostic, a deferred
1730 /// diagnostic, or no diagnostic at all, according to an argument you pass to
1731 /// its constructor, thus simplifying the process of creating these "maybe
1732 /// deferred" diagnostics.
1733 class SemaDiagnosticBuilder {
1734 public:
1735 enum Kind {
1736 /// Emit no diagnostics.
1737 K_Nop,
1738 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1739 K_Immediate,
1740 /// Emit the diagnostic immediately, and, if it's a warning or error, also
1741 /// emit a call stack showing how this function can be reached by an a
1742 /// priori known-emitted function.
1743 K_ImmediateWithCallStack,
1744 /// Create a deferred diagnostic, which is emitted only if the function
1745 /// it's attached to is codegen'ed. Also emit a call stack as with
1746 /// K_ImmediateWithCallStack.
1747 K_Deferred
1748 };
1749
1750 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1751 FunctionDecl *Fn, Sema &S);
1752 SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1753 SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1754 ~SemaDiagnosticBuilder();
1755
1756 bool isImmediate() const { return ImmediateDiag.hasValue(); }
1757
1758 /// Convertible to bool: True if we immediately emitted an error, false if
1759 /// we didn't emit an error or we created a deferred error.
1760 ///
1761 /// Example usage:
1762 ///
1763 /// if (SemaDiagnosticBuilder(...) << foo << bar)
1764 /// return ExprError();
1765 ///
1766 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1767 /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1768 operator bool() const { return isImmediate(); }
1769
1770 template <typename T>
1771 friend const SemaDiagnosticBuilder &
1772 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1773 if (Diag.ImmediateDiag.hasValue())
1774 *Diag.ImmediateDiag << Value;
1775 else if (Diag.PartialDiagId.hasValue())
1776 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1777 << Value;
1778 return Diag;
1779 }
1780
1781 // It is necessary to limit this to rvalue reference to avoid calling this
1782 // function with a bitfield lvalue argument since non-const reference to
1783 // bitfield is not allowed.
1784 template <typename T, typename = typename std::enable_if<
1785 !std::is_lvalue_reference<T>::value>::type>
1786 const SemaDiagnosticBuilder &operator<<(T &&V) const {
1787 if (ImmediateDiag.hasValue())
1788 *ImmediateDiag << std::move(V);
1789 else if (PartialDiagId.hasValue())
1790 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1791 return *this;
1792 }
1793
1794 friend const SemaDiagnosticBuilder &
1795 operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1796 if (Diag.ImmediateDiag.hasValue())
1797 PD.Emit(*Diag.ImmediateDiag);
1798 else if (Diag.PartialDiagId.hasValue())
1799 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1800 return Diag;
1801 }
1802
1803 void AddFixItHint(const FixItHint &Hint) const {
1804 if (ImmediateDiag.hasValue())
1805 ImmediateDiag->AddFixItHint(Hint);
1806 else if (PartialDiagId.hasValue())
1807 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1808 }
1809
1810 friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1811 return ExprError();
1812 }
1813 friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1814 return StmtError();
1815 }
1816 operator ExprResult() const { return ExprError(); }
1817 operator StmtResult() const { return StmtError(); }
1818 operator TypeResult() const { return TypeError(); }
1819 operator DeclResult() const { return DeclResult(true); }
1820 operator MemInitResult() const { return MemInitResult(true); }
1821
1822 private:
1823 Sema &S;
1824 SourceLocation Loc;
1825 unsigned DiagID;
1826 FunctionDecl *Fn;
1827 bool ShowCallStack;
1828
1829 // Invariant: At most one of these Optionals has a value.
1830 // FIXME: Switch these to a Variant once that exists.
1831 llvm::Optional<ImmediateDiagBuilder> ImmediateDiag;
1832 llvm::Optional<unsigned> PartialDiagId;
1833 };
1834
1835 /// Is the last error level diagnostic immediate. This is used to determined
1836 /// whether the next info diagnostic should be immediate.
1837 bool IsLastErrorImmediate = true;
1838
1839 /// Emit a diagnostic.
1840 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1841 bool DeferHint = false);
1842
1843 /// Emit a partial diagnostic.
1844 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1845 bool DeferHint = false);
1846
1847 /// Build a partial diagnostic.
1848 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1849
1850 /// Whether deferrable diagnostics should be deferred.
1851 bool DeferDiags = false;
1852
1853 /// RAII class to control scope of DeferDiags.
1854 class DeferDiagsRAII {
1855 Sema &S;
1856 bool SavedDeferDiags = false;
1857
1858 public:
1859 DeferDiagsRAII(Sema &S, bool DeferDiags)
1860 : S(S), SavedDeferDiags(S.DeferDiags) {
1861 S.DeferDiags = DeferDiags;
1862 }
1863 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1864 };
1865
1866 /// Whether uncompilable error has occurred. This includes error happens
1867 /// in deferred diagnostics.
1868 bool hasUncompilableErrorOccurred() const;
1869
1870 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1871
1872 /// Get a string to suggest for zero-initialization of a type.
1873 std::string
1874 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1875 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1876
1877 /// Calls \c Lexer::getLocForEndOfToken()
1878 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1879
1880 /// Retrieve the module loader associated with the preprocessor.
1881 ModuleLoader &getModuleLoader() const;
1882
1883 /// Invent a new identifier for parameters of abbreviated templates.
1884 IdentifierInfo *
1885 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1886 unsigned Index);
1887
1888 void emitAndClearUnusedLocalTypedefWarnings();
1889
1890 private:
1891 /// Function or variable declarations to be checked for whether the deferred
1892 /// diagnostics should be emitted.
1893 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1894
1895 public:
1896 // Emit all deferred diagnostics.
1897 void emitDeferredDiags();
1898
1899 enum TUFragmentKind {
1900 /// The global module fragment, between 'module;' and a module-declaration.
1901 Global,
1902 /// A normal translation unit fragment. For a non-module unit, this is the
1903 /// entire translation unit. Otherwise, it runs from the module-declaration
1904 /// to the private-module-fragment (if any) or the end of the TU (if not).
1905 Normal,
1906 /// The private module fragment, between 'module :private;' and the end of
1907 /// the translation unit.
1908 Private
1909 };
1910
1911 void ActOnStartOfTranslationUnit();
1912 void ActOnEndOfTranslationUnit();
1913 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1914
1915 void CheckDelegatingCtorCycles();
1916
1917 Scope *getScopeForContext(DeclContext *Ctx);
1918
1919 void PushFunctionScope();
1920 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1921 sema::LambdaScopeInfo *PushLambdaScope();
1922
1923 /// This is used to inform Sema what the current TemplateParameterDepth
1924 /// is during Parsing. Currently it is used to pass on the depth
1925 /// when parsing generic lambda 'auto' parameters.
1926 void RecordParsingTemplateParameterDepth(unsigned Depth);
1927
1928 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1929 RecordDecl *RD, CapturedRegionKind K,
1930 unsigned OpenMPCaptureLevel = 0);
1931
1932 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1933 /// time after they've been popped.
1934 class PoppedFunctionScopeDeleter {
1935 Sema *Self;
1936
1937 public:
1938 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1939 void operator()(sema::FunctionScopeInfo *Scope) const;
1940 };
1941
1942 using PoppedFunctionScopePtr =
1943 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1944
1945 PoppedFunctionScopePtr
1946 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1947 const Decl *D = nullptr,
1948 QualType BlockType = QualType());
1949
1950 sema::FunctionScopeInfo *getCurFunction() const {
1951 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1952 }
1953
1954 sema::FunctionScopeInfo *getEnclosingFunction() const;
1955
1956 void setFunctionHasBranchIntoScope();
1957 void setFunctionHasBranchProtectedScope();
1958 void setFunctionHasIndirectGoto();
1959 void setFunctionHasMustTail();
1960
1961 void PushCompoundScope(bool IsStmtExpr);
1962 void PopCompoundScope();
1963
1964 sema::CompoundScopeInfo &getCurCompoundScope() const;
1965
1966 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1967
1968 /// Retrieve the current block, if any.
1969 sema::BlockScopeInfo *getCurBlock();
1970
1971 /// Get the innermost lambda enclosing the current location, if any. This
1972 /// looks through intervening non-lambda scopes such as local functions and
1973 /// blocks.
1974 sema::LambdaScopeInfo *getEnclosingLambda() const;
1975
1976 /// Retrieve the current lambda scope info, if any.
1977 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1978 /// lambda scope info ignoring all inner capturing scopes that are not
1979 /// lambda scopes.
1980 sema::LambdaScopeInfo *
1981 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1982
1983 /// Retrieve the current generic lambda info, if any.
1984 sema::LambdaScopeInfo *getCurGenericLambda();
1985
1986 /// Retrieve the current captured region, if any.
1987 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1988
1989 /// Retrieve the current function, if any, that should be analyzed for
1990 /// potential availability violations.
1991 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
1992
1993 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1994 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1995
1996 /// Called before parsing a function declarator belonging to a function
1997 /// declaration.
1998 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
1999 unsigned TemplateParameterDepth);
2000
2001 /// Called after parsing a function declarator belonging to a function
2002 /// declaration.
2003 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
2004
2005 void ActOnComment(SourceRange Comment);
2006
2007 //===--------------------------------------------------------------------===//
2008 // Type Analysis / Processing: SemaType.cpp.
2009 //
2010
2011 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
2012 const DeclSpec *DS = nullptr);
2013 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
2014 const DeclSpec *DS = nullptr);
2015 QualType BuildPointerType(QualType T,
2016 SourceLocation Loc, DeclarationName Entity);
2017 QualType BuildReferenceType(QualType T, bool LValueRef,
2018 SourceLocation Loc, DeclarationName Entity);
2019 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2020 Expr *ArraySize, unsigned Quals,
2021 SourceRange Brackets, DeclarationName Entity);
2022 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
2023 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
2024 SourceLocation AttrLoc);
2025 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
2026 SourceLocation AttrLoc);
2027
2028 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2029 SourceLocation AttrLoc);
2030
2031 /// Same as above, but constructs the AddressSpace index if not provided.
2032 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
2033 SourceLocation AttrLoc);
2034
2035 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
2036
2037 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
2038
2039 /// Build a function type.
2040 ///
2041 /// This routine checks the function type according to C++ rules and
2042 /// under the assumption that the result type and parameter types have
2043 /// just been instantiated from a template. It therefore duplicates
2044 /// some of the behavior of GetTypeForDeclarator, but in a much
2045 /// simpler form that is only suitable for this narrow use case.
2046 ///
2047 /// \param T The return type of the function.
2048 ///
2049 /// \param ParamTypes The parameter types of the function. This array
2050 /// will be modified to account for adjustments to the types of the
2051 /// function parameters.
2052 ///
2053 /// \param Loc The location of the entity whose type involves this
2054 /// function type or, if there is no such entity, the location of the
2055 /// type that will have function type.
2056 ///
2057 /// \param Entity The name of the entity that involves the function
2058 /// type, if known.
2059 ///
2060 /// \param EPI Extra information about the function type. Usually this will
2061 /// be taken from an existing function with the same prototype.
2062 ///
2063 /// \returns A suitable function type, if there are no errors. The
2064 /// unqualified type will always be a FunctionProtoType.
2065 /// Otherwise, returns a NULL type.
2066 QualType BuildFunctionType(QualType T,
2067 MutableArrayRef<QualType> ParamTypes,
2068 SourceLocation Loc, DeclarationName Entity,
2069 const FunctionProtoType::ExtProtoInfo &EPI);
2070
2071 QualType BuildMemberPointerType(QualType T, QualType Class,
2072 SourceLocation Loc,
2073 DeclarationName Entity);
2074 QualType BuildBlockPointerType(QualType T,
2075 SourceLocation Loc, DeclarationName Entity);
2076 QualType BuildParenType(QualType T);
2077 QualType BuildAtomicType(QualType T, SourceLocation Loc);
2078 QualType BuildReadPipeType(QualType T,
2079 SourceLocation Loc);
2080 QualType BuildWritePipeType(QualType T,
2081 SourceLocation Loc);
2082 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2083
2084 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
2085 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
2086
2087 /// Package the given type and TSI into a ParsedType.
2088 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
2089 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
2090 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
2091 static QualType GetTypeFromParser(ParsedType Ty,
2092 TypeSourceInfo **TInfo = nullptr);
2093 CanThrowResult canThrow(const Stmt *E);
2094 /// Determine whether the callee of a particular function call can throw.
2095 /// E, D and Loc are all optional.
2096 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2097 SourceLocation Loc = SourceLocation());
2098 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
2099 const FunctionProtoType *FPT);
2100 void UpdateExceptionSpec(FunctionDecl *FD,
2101 const FunctionProtoType::ExceptionSpecInfo &ESI);
2102 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
2103 bool CheckDistantExceptionSpec(QualType T);
2104 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
2105 bool CheckEquivalentExceptionSpec(
2106 const FunctionProtoType *Old, SourceLocation OldLoc,
2107 const FunctionProtoType *New, SourceLocation NewLoc);
2108 bool CheckEquivalentExceptionSpec(
2109 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2110 const FunctionProtoType *Old, SourceLocation OldLoc,
2111 const FunctionProtoType *New, SourceLocation NewLoc);
2112 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2113 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2114 const PartialDiagnostic &NestedDiagID,
2115 const PartialDiagnostic &NoteID,
2116 const PartialDiagnostic &NoThrowDiagID,
2117 const FunctionProtoType *Superset,
2118 SourceLocation SuperLoc,
2119 const FunctionProtoType *Subset,
2120 SourceLocation SubLoc);
2121 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2122 const PartialDiagnostic &NoteID,
2123 const FunctionProtoType *Target,
2124 SourceLocation TargetLoc,
2125 const FunctionProtoType *Source,
2126 SourceLocation SourceLoc);
2127
2128 TypeResult ActOnTypeName(Scope *S, Declarator &D);
2129
2130 /// The parser has parsed the context-sensitive type 'instancetype'
2131 /// in an Objective-C message declaration. Return the appropriate type.
2132 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
2133
2134 /// Abstract class used to diagnose incomplete types.
2135 struct TypeDiagnoser {
2136 TypeDiagnoser() {}
2137
2138 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2139 virtual ~TypeDiagnoser() {}
2140 };
2141
2142 static int getPrintable(int I) { return I; }
2143 static unsigned getPrintable(unsigned I) { return I; }
2144 static bool getPrintable(bool B) { return B; }
2145 static const char * getPrintable(const char *S) { return S; }
2146 static StringRef getPrintable(StringRef S) { return S; }
2147 static const std::string &getPrintable(const std::string &S) { return S; }
2148 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2149 return II;
2150 }
2151 static DeclarationName getPrintable(DeclarationName N) { return N; }
2152 static QualType getPrintable(QualType T) { return T; }
2153 static SourceRange getPrintable(SourceRange R) { return R; }
2154 static SourceRange getPrintable(SourceLocation L) { return L; }
2155 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2156 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2157
2158 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2159 protected:
2160 unsigned DiagID;
2161 std::tuple<const Ts &...> Args;
2162
2163 template <std::size_t... Is>
2164 void emit(const SemaDiagnosticBuilder &DB,
2165 std::index_sequence<Is...>) const {
2166 // Apply all tuple elements to the builder in order.
2167 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2168 (void)Dummy;
2169 }
2170
2171 public:
2172 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2173 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2174 assert(DiagID != 0 && "no diagnostic for type diagnoser")(static_cast <bool> (DiagID != 0 && "no diagnostic for type diagnoser"
) ? void (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "clang/include/clang/Sema/Sema.h", 2174, __extension__ __PRETTY_FUNCTION__
))
;
2175 }
2176
2177 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2178 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2179 emit(DB, std::index_sequence_for<Ts...>());
2180 DB << T;
2181 }
2182 };
2183
2184 /// Do a check to make sure \p Name looks like a legal argument for the
2185 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2186 /// is invalid for the given declaration.
2187 ///
2188 /// \p AL is used to provide caret diagnostics in case of a malformed name.
2189 ///
2190 /// \returns true if the name is a valid swift name for \p D, false otherwise.
2191 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2192 const ParsedAttr &AL, bool IsAsync);
2193
2194 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2195 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2196 /// For example, a diagnostic with no other parameters would generally have
2197 /// the form "...%select{incomplete|sizeless}0 type %1...".
2198 template <typename... Ts>
2199 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
2200 public:
2201 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2202 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2203
2204 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2205 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2206 this->emit(DB, std::index_sequence_for<Ts...>());
2207 DB << T->isSizelessType() << T;
2208 }
2209 };
2210
2211 enum class CompleteTypeKind {
2212 /// Apply the normal rules for complete types. In particular,
2213 /// treat all sizeless types as incomplete.
2214 Normal,
2215
2216 /// Relax the normal rules for complete types so that they include
2217 /// sizeless built-in types.
2218 AcceptSizeless,
2219
2220 // FIXME: Eventually we should flip the default to Normal and opt in
2221 // to AcceptSizeless rather than opt out of it.
2222 Default = AcceptSizeless
2223 };
2224
2225private:
2226 /// Methods for marking which expressions involve dereferencing a pointer
2227 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2228 /// they are parsed, meaning that a noderef pointer may not be accessed. For
2229 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2230 /// `*p`, but need to check that `address of` is called on it. This requires
2231 /// keeping a container of all pending expressions and checking if the address
2232 /// of them are eventually taken.
2233 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2234 void CheckAddressOfNoDeref(const Expr *E);
2235 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2236
2237 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2238 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2239
2240 struct ModuleScope {
2241 SourceLocation BeginLoc;
2242 clang::Module *Module = nullptr;
2243 bool ModuleInterface = false;
2244 bool IsPartition = false;
2245 bool ImplicitGlobalModuleFragment = false;
2246 VisibleModuleSet OuterVisibleModules;
2247 };
2248 /// The modules we're currently parsing.
2249 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
2250 /// The global module fragment of the current translation unit.
2251 clang::Module *GlobalModuleFragment = nullptr;
2252
2253 /// The modules we imported directly.
2254 llvm::SmallPtrSet<clang::Module *, 8> DirectModuleImports;
2255
2256 /// Namespace definitions that we will export when they finish.
2257 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2258
2259 /// Get the module whose scope we are currently within.
2260 Module *getCurrentModule() const {
2261 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2262 }
2263
2264 /// Helper function to judge if we are in module purview.
2265 /// Return false if we are not in a module.
2266 bool isCurrentModulePurview() const {
2267 return getCurrentModule() ? getCurrentModule()->isModulePurview() : false;
2268 }
2269
2270 /// Enter the scope of the global module.
2271 Module *PushGlobalModuleFragment(SourceLocation BeginLoc, bool IsImplicit);
2272 /// Leave the scope of the global module.
2273 void PopGlobalModuleFragment();
2274
2275 VisibleModuleSet VisibleModules;
2276
2277public:
2278 /// Get the module owning an entity.
2279 Module *getOwningModule(const Decl *Entity) {
2280 return Entity->getOwningModule();
2281 }
2282
2283 bool isModuleDirectlyImported(const Module *M) {
2284 return DirectModuleImports.contains(M);
2285 }
2286
2287 /// Make a merged definition of an existing hidden definition \p ND
2288 /// visible at the specified location.
2289 void makeMergedDefinitionVisible(NamedDecl *ND);
2290
2291 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2292
2293 // When loading a non-modular PCH files, this is used to restore module
2294 // visibility.
2295 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2296 VisibleModules.setVisible(Mod, ImportLoc);
2297 }
2298
2299 /// Determine whether a declaration is visible to name lookup.
2300 bool isVisible(const NamedDecl *D) {
2301 return D->isUnconditionallyVisible() || isVisibleSlow(D);
2302 }
2303
2304 /// Determine whether any declaration of an entity is visible.
2305 bool
2306 hasVisibleDeclaration(const NamedDecl *D,
2307 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2308 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2309 }
2310 bool hasVisibleDeclarationSlow(const NamedDecl *D,
2311 llvm::SmallVectorImpl<Module *> *Modules);
2312
2313 bool hasVisibleMergedDefinition(NamedDecl *Def);
2314 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
2315
2316 /// Determine if \p D and \p Suggested have a structurally compatible
2317 /// layout as described in C11 6.2.7/1.
2318 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2319
2320 /// Determine if \p D has a visible definition. If not, suggest a declaration
2321 /// that should be made visible to expose the definition.
2322 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2323 bool OnlyNeedComplete = false);
2324 bool hasVisibleDefinition(const NamedDecl *D) {
2325 NamedDecl *Hidden;
2326 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2327 }
2328
2329 /// Determine if the template parameter \p D has a visible default argument.
2330 bool
2331 hasVisibleDefaultArgument(const NamedDecl *D,
2332 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2333
2334 /// Determine if there is a visible declaration of \p D that is an explicit
2335 /// specialization declaration for a specialization of a template. (For a
2336 /// member specialization, use hasVisibleMemberSpecialization.)
2337 bool hasVisibleExplicitSpecialization(
2338 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2339
2340 /// Determine if there is a visible declaration of \p D that is a member
2341 /// specialization declaration (as opposed to an instantiated declaration).
2342 bool hasVisibleMemberSpecialization(
2343 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2344
2345 /// Determine if \p A and \p B are equivalent internal linkage declarations
2346 /// from different modules, and thus an ambiguity error can be downgraded to
2347 /// an extension warning.
2348 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
2349 const NamedDecl *B);
2350 void diagnoseEquivalentInternalLinkageDeclarations(
2351 SourceLocation Loc, const NamedDecl *D,
2352 ArrayRef<const NamedDecl *> Equiv);
2353
2354 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
2355
2356 bool isCompleteType(SourceLocation Loc, QualType T,
2357 CompleteTypeKind Kind = CompleteTypeKind::Default) {
2358 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2359 }
2360 bool RequireCompleteType(SourceLocation Loc, QualType T,
2361 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2362 bool RequireCompleteType(SourceLocation Loc, QualType T,
2363 CompleteTypeKind Kind, unsigned DiagID);
2364
2365 bool RequireCompleteType(SourceLocation Loc, QualType T,
2366 TypeDiagnoser &Diagnoser) {
2367 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2368 }
2369 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2370 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2371 }
2372
2373 template <typename... Ts>
2374 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2375 const Ts &...Args) {
2376 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2377 return RequireCompleteType(Loc, T, Diagnoser);
2378 }
2379
2380 template <typename... Ts>
2381 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2382 const Ts &... Args) {
2383 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2384 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2385 }
2386
2387 /// Get the type of expression E, triggering instantiation to complete the
2388 /// type if necessary -- that is, if the expression refers to a templated
2389 /// static data member of incomplete array type.
2390 ///
2391 /// May still return an incomplete type if instantiation was not possible or
2392 /// if the type is incomplete for a different reason. Use
2393 /// RequireCompleteExprType instead if a diagnostic is expected for an
2394 /// incomplete expression type.
2395 QualType getCompletedType(Expr *E);
2396
2397 void completeExprArrayBound(Expr *E);
2398 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2399 TypeDiagnoser &Diagnoser);
2400 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2401
2402 template <typename... Ts>
2403 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2404 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2405 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2406 }
2407
2408 template <typename... Ts>
2409 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2410 const Ts &... Args) {
2411 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2412 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2413 }
2414
2415 bool RequireLiteralType(SourceLocation Loc, QualType T,
2416 TypeDiagnoser &Diagnoser);
2417 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2418
2419 template <typename... Ts>
2420 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2421 const Ts &...Args) {
2422 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2423 return RequireLiteralType(Loc, T, Diagnoser);
2424 }
2425
2426 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2427 const CXXScopeSpec &SS, QualType T,
2428 TagDecl *OwnedTagDecl = nullptr);
2429
2430 // Returns the underlying type of a decltype with the given expression.
2431 QualType getDecltypeForExpr(Expr *E);
2432
2433 QualType BuildTypeofExprType(Expr *E);
2434 /// If AsUnevaluated is false, E is treated as though it were an evaluated
2435 /// context, such as when building a type for decltype(auto).
2436 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2437 QualType BuildUnaryTransformType(QualType BaseType,
2438 UnaryTransformType::UTTKind UKind,
2439 SourceLocation Loc);
2440
2441 //===--------------------------------------------------------------------===//
2442 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2443 //
2444
2445 struct SkipBodyInfo {
2446 SkipBodyInfo()
2447 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
2448 New(nullptr) {}
2449 bool ShouldSkip;
2450 bool CheckSameAsPrevious;
2451 NamedDecl *Previous;
2452 NamedDecl *New;
2453 };
2454
2455 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2456
2457 void DiagnoseUseOfUnimplementedSelectors();
2458
2459 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2460
2461 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2462 Scope *S, CXXScopeSpec *SS = nullptr,
2463 bool isClassName = false, bool HasTrailingDot = false,
2464 ParsedType ObjectType = nullptr,
2465 bool IsCtorOrDtorName = false,
2466 bool WantNontrivialTypeSourceInfo = false,
2467 bool IsClassTemplateDeductionContext = true,
2468 IdentifierInfo **CorrectedII = nullptr);
2469 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2470 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2471 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2472 SourceLocation IILoc,
2473 Scope *S,
2474 CXXScopeSpec *SS,
2475 ParsedType &SuggestedType,
2476 bool IsTemplateName = false);
2477
2478 /// Attempt to behave like MSVC in situations where lookup of an unqualified
2479 /// type name has failed in a dependent context. In these situations, we
2480 /// automatically form a DependentTypeName that will retry lookup in a related
2481 /// scope during instantiation.
2482 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2483 SourceLocation NameLoc,
2484 bool IsTemplateTypeArg);
2485
2486 /// Describes the result of the name lookup and resolution performed
2487 /// by \c ClassifyName().
2488 enum NameClassificationKind {
2489 /// This name is not a type or template in this context, but might be
2490 /// something else.
2491 NC_Unknown,
2492 /// Classification failed; an error has been produced.
2493 NC_Error,
2494 /// The name has been typo-corrected to a keyword.
2495 NC_Keyword,
2496 /// The name was classified as a type.
2497 NC_Type,
2498 /// The name was classified as a specific non-type, non-template
2499 /// declaration. ActOnNameClassifiedAsNonType should be called to
2500 /// convert the declaration to an expression.
2501 NC_NonType,
2502 /// The name was classified as an ADL-only function name.
2503 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2504 /// result to an expression.
2505 NC_UndeclaredNonType,
2506 /// The name denotes a member of a dependent type that could not be
2507 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2508 /// convert the result to an expression.
2509 NC_DependentNonType,
2510 /// The name was classified as an overload set, and an expression
2511 /// representing that overload set has been formed.
2512 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2513 /// expression referencing the overload set.
2514 NC_OverloadSet,
2515 /// The name was classified as a template whose specializations are types.
2516 NC_TypeTemplate,
2517 /// The name was classified as a variable template name.
2518 NC_VarTemplate,
2519 /// The name was classified as a function template name.
2520 NC_FunctionTemplate,
2521 /// The name was classified as an ADL-only function template name.
2522 NC_UndeclaredTemplate,
2523 /// The name was classified as a concept name.
2524 NC_Concept,
2525 };
2526
2527 class NameClassification {
2528 NameClassificationKind Kind;
2529 union {
2530 ExprResult Expr;
2531 NamedDecl *NonTypeDecl;
2532 TemplateName Template;
2533 ParsedType Type;
2534 };
2535
2536 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2537
2538 public:
2539 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2540
2541 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2542
2543 static NameClassification Error() {
2544 return NameClassification(NC_Error);
2545 }
2546
2547 static NameClassification Unknown() {
2548 return NameClassification(NC_Unknown);
2549 }
2550
2551 static NameClassification OverloadSet(ExprResult E) {
2552 NameClassification Result(NC_OverloadSet);
2553 Result.Expr = E;
2554 return Result;
2555 }
2556
2557 static NameClassification NonType(NamedDecl *D) {
2558 NameClassification Result(NC_NonType);
2559 Result.NonTypeDecl = D;
2560 return Result;
2561 }
2562
2563 static NameClassification UndeclaredNonType() {
2564 return NameClassification(NC_UndeclaredNonType);
2565 }
2566
2567 static NameClassification DependentNonType() {
2568 return NameClassification(NC_DependentNonType);
2569 }
2570
2571 static NameClassification TypeTemplate(TemplateName Name) {
2572 NameClassification Result(NC_TypeTemplate);
2573 Result.Template = Name;
2574 return Result;
2575 }
2576
2577 static NameClassification VarTemplate(TemplateName Name) {
2578 NameClassification Result(NC_VarTemplate);
2579 Result.Template = Name;
2580 return Result;
2581 }
2582
2583 static NameClassification FunctionTemplate(TemplateName Name) {
2584 NameClassification Result(NC_FunctionTemplate);
2585 Result.Template = Name;
2586 return Result;
2587 }
2588
2589 static NameClassification Concept(TemplateName Name) {
2590 NameClassification Result(NC_Concept);
2591 Result.Template = Name;
2592 return Result;
2593 }
2594
2595 static NameClassification UndeclaredTemplate(TemplateName Name) {
2596 NameClassification Result(NC_UndeclaredTemplate);
2597 Result.Template = Name;
2598 return Result;
2599 }
2600
2601 NameClassificationKind getKind() const { return Kind; }
2602
2603 ExprResult getExpression() const {
2604 assert(Kind == NC_OverloadSet)(static_cast <bool> (Kind == NC_OverloadSet) ? void (0)
: __assert_fail ("Kind == NC_OverloadSet", "clang/include/clang/Sema/Sema.h"
, 2604, __extension__ __PRETTY_FUNCTION__))
;
2605 return Expr;
2606 }
2607
2608 ParsedType getType() const {
2609 assert(Kind == NC_Type)(static_cast <bool> (Kind == NC_Type) ? void (0) : __assert_fail
("Kind == NC_Type", "clang/include/clang/Sema/Sema.h", 2609,
__extension__ __PRETTY_FUNCTION__))
;
2610 return Type;
2611 }
2612
2613 NamedDecl *getNonTypeDecl() const {
2614 assert(Kind == NC_NonType)(static_cast <bool> (Kind == NC_NonType) ? void (0) : __assert_fail
("Kind == NC_NonType", "clang/include/clang/Sema/Sema.h", 2614
, __extension__ __PRETTY_FUNCTION__))
;
2615 return NonTypeDecl;
2616 }
2617
2618 TemplateName getTemplateName() const {
2619 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2621, __extension__ __PRETTY_FUNCTION__
))
2620 Kind == NC_VarTemplate || Kind == NC_Concept ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2621, __extension__ __PRETTY_FUNCTION__
))
2621 Kind == NC_UndeclaredTemplate)(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2621, __extension__ __PRETTY_FUNCTION__
))
;
2622 return Template;
2623 }
2624
2625 TemplateNameKind getTemplateNameKind() const {
2626 switch (Kind) {
2627 case NC_TypeTemplate:
2628 return TNK_Type_template;
2629 case NC_FunctionTemplate:
2630 return TNK_Function_template;
2631 case NC_VarTemplate:
2632 return TNK_Var_template;
2633 case NC_Concept:
2634 return TNK_Concept_template;
2635 case NC_UndeclaredTemplate:
2636 return TNK_Undeclared_template;
2637 default:
2638 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "clang/include/clang/Sema/Sema.h", 2638)
;
2639 }
2640 }
2641 };
2642
2643 /// Perform name lookup on the given name, classifying it based on
2644 /// the results of name lookup and the following token.
2645 ///
2646 /// This routine is used by the parser to resolve identifiers and help direct
2647 /// parsing. When the identifier cannot be found, this routine will attempt
2648 /// to correct the typo and classify based on the resulting name.
2649 ///
2650 /// \param S The scope in which we're performing name lookup.
2651 ///
2652 /// \param SS The nested-name-specifier that precedes the name.
2653 ///
2654 /// \param Name The identifier. If typo correction finds an alternative name,
2655 /// this pointer parameter will be updated accordingly.
2656 ///
2657 /// \param NameLoc The location of the identifier.
2658 ///
2659 /// \param NextToken The token following the identifier. Used to help
2660 /// disambiguate the name.
2661 ///
2662 /// \param CCC The correction callback, if typo correction is desired.
2663 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2664 IdentifierInfo *&Name, SourceLocation NameLoc,
2665 const Token &NextToken,
2666 CorrectionCandidateCallback *CCC = nullptr);
2667
2668 /// Act on the result of classifying a name as an undeclared (ADL-only)
2669 /// non-type declaration.
2670 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2671 SourceLocation NameLoc);
2672 /// Act on the result of classifying a name as an undeclared member of a
2673 /// dependent base class.
2674 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2675 IdentifierInfo *Name,
2676 SourceLocation NameLoc,
2677 bool IsAddressOfOperand);
2678 /// Act on the result of classifying a name as a specific non-type
2679 /// declaration.
2680 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2681 NamedDecl *Found,
2682 SourceLocation NameLoc,
2683 const Token &NextToken);
2684 /// Act on the result of classifying a name as an overload set.
2685 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2686
2687 /// Describes the detailed kind of a template name. Used in diagnostics.
2688 enum class TemplateNameKindForDiagnostics {
2689 ClassTemplate,
2690 FunctionTemplate,
2691 VarTemplate,
2692 AliasTemplate,
2693 TemplateTemplateParam,
2694 Concept,
2695 DependentTemplate
2696 };
2697 TemplateNameKindForDiagnostics
2698 getTemplateNameKindForDiagnostics(TemplateName Name);
2699
2700 /// Determine whether it's plausible that E was intended to be a
2701 /// template-name.
2702 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2703 if (!getLangOpts().CPlusPlus || E.isInvalid())
2704 return false;
2705 Dependent = false;
2706 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2707 return !DRE->hasExplicitTemplateArgs();
2708 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2709 return !ME->hasExplicitTemplateArgs();
2710 Dependent = true;
2711 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2712 return !DSDRE->hasExplicitTemplateArgs();
2713 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2714 return !DSME->hasExplicitTemplateArgs();
2715 // Any additional cases recognized here should also be handled by
2716 // diagnoseExprIntendedAsTemplateName.
2717 return false;
2718 }
2719 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2720 SourceLocation Less,
2721 SourceLocation Greater);
2722
2723 void warnOnReservedIdentifier(const NamedDecl *D);
2724
2725 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2726
2727 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2728 MultiTemplateParamsArg TemplateParameterLists);
2729 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
2730 QualType &T, SourceLocation Loc,
2731 unsigned FailedFoldDiagID);
2732 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2733 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2734 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2735 DeclarationName Name, SourceLocation Loc,
2736 bool IsTemplateId);
2737 void
2738 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2739 SourceLocation FallbackLoc,
2740 SourceLocation ConstQualLoc = SourceLocation(),
2741 SourceLocation VolatileQualLoc = SourceLocation(),
2742 SourceLocation RestrictQualLoc = SourceLocation(),
2743 SourceLocation AtomicQualLoc = SourceLocation(),
2744 SourceLocation UnalignedQualLoc = SourceLocation());
2745
2746 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2747 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2748 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2749 const LookupResult &R);
2750 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2751 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
2752 const LookupResult &R);
2753 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2754 const LookupResult &R);
2755 void CheckShadow(Scope *S, VarDecl *D);
2756
2757 /// Warn if 'E', which is an expression that is about to be modified, refers
2758 /// to a shadowing declaration.
2759 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2760
2761 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2762
2763private:
2764 /// Map of current shadowing declarations to shadowed declarations. Warn if
2765 /// it looks like the user is trying to modify the shadowing declaration.
2766 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2767
2768public:
2769 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2770 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2771 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2772 TypedefNameDecl *NewTD);
2773 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2774 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2775 TypeSourceInfo *TInfo,
2776 LookupResult &Previous);
2777 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2778 LookupResult &Previous, bool &Redeclaration);
2779 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2780 TypeSourceInfo *TInfo,
2781 LookupResult &Previous,
2782 MultiTemplateParamsArg TemplateParamLists,
2783 bool &AddToScope,
2784 ArrayRef<BindingDecl *> Bindings = None);
2785 NamedDecl *
2786 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2787 MultiTemplateParamsArg TemplateParamLists);
2788 // Returns true if the variable declaration is a redeclaration
2789 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2790 void CheckVariableDeclarationType(VarDecl *NewVD);
2791 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2792 Expr *Init);
2793 void CheckCompleteVariableDeclaration(VarDecl *VD);
2794 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2795 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2796
2797 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2798 TypeSourceInfo *TInfo,
2799 LookupResult &Previous,
2800 MultiTemplateParamsArg TemplateParamLists,
2801 bool &AddToScope);
2802 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2803
2804 enum class CheckConstexprKind {
2805 /// Diagnose issues that are non-constant or that are extensions.
2806 Diagnose,
2807 /// Identify whether this function satisfies the formal rules for constexpr
2808 /// functions in the current lanugage mode (with no extensions).
2809 CheckValid
2810 };
2811
2812 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2813 CheckConstexprKind Kind);
2814
2815 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2816 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2817 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2818 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2819 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2820 // Returns true if the function declaration is a redeclaration
2821 bool CheckFunctionDeclaration(Scope *S,
2822 FunctionDecl *NewFD, LookupResult &Previous,
2823 bool IsMemberSpecialization, bool DeclIsDefn);
2824 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2825 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2826 QualType NewT, QualType OldT);
2827 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2828 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2829 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2830 bool IsDefinition);
2831 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2832 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2833 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2834 SourceLocation Loc,
2835 QualType T);
2836 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2837 SourceLocation NameLoc, IdentifierInfo *Name,
2838 QualType T, TypeSourceInfo *TSInfo,
2839 StorageClass SC);
2840 void ActOnParamDefaultArgument(Decl *param,
2841 SourceLocation EqualLoc,
2842 Expr *defarg);
2843 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2844 SourceLocation ArgLoc);
2845 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2846 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2847 SourceLocation EqualLoc);
2848 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2849 SourceLocation EqualLoc);
2850
2851 // Contexts where using non-trivial C union types can be disallowed. This is
2852 // passed to err_non_trivial_c_union_in_invalid_context.
2853 enum NonTrivialCUnionContext {
2854 // Function parameter.
2855 NTCUC_FunctionParam,
2856 // Function return.
2857 NTCUC_FunctionReturn,
2858 // Default-initialized object.
2859 NTCUC_DefaultInitializedObject,
2860 // Variable with automatic storage duration.
2861 NTCUC_AutoVar,
2862 // Initializer expression that might copy from another object.
2863 NTCUC_CopyInit,
2864 // Assignment.
2865 NTCUC_Assignment,
2866 // Compound literal.
2867 NTCUC_CompoundLiteral,
2868 // Block capture.
2869 NTCUC_BlockCapture,
2870 // lvalue-to-rvalue conversion of volatile type.
2871 NTCUC_LValueToRValueVolatile,
2872 };
2873
2874 /// Emit diagnostics if the initializer or any of its explicit or
2875 /// implicitly-generated subexpressions require copying or
2876 /// default-initializing a type that is or contains a C union type that is
2877 /// non-trivial to copy or default-initialize.
2878 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2879
2880 // These flags are passed to checkNonTrivialCUnion.
2881 enum NonTrivialCUnionKind {
2882 NTCUK_Init = 0x1,
2883 NTCUK_Destruct = 0x2,
2884 NTCUK_Copy = 0x4,
2885 };
2886
2887 /// Emit diagnostics if a non-trivial C union type or a struct that contains
2888 /// a non-trivial C union is used in an invalid context.
2889 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2890 NonTrivialCUnionContext UseContext,
2891 unsigned NonTrivialKind);
2892
2893 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2894 void ActOnUninitializedDecl(Decl *dcl);
2895 void ActOnInitializerError(Decl *Dcl);
2896
2897 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2898 void ActOnCXXForRangeDecl(Decl *D);
2899 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2900 IdentifierInfo *Ident,
2901 ParsedAttributes &Attrs);
2902 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2903 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2904 void CheckStaticLocalForDllExport(VarDecl *VD);
2905 void FinalizeDeclaration(Decl *D);
2906 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2907 ArrayRef<Decl *> Group);
2908 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2909
2910 /// Should be called on all declarations that might have attached
2911 /// documentation comments.
2912 void ActOnDocumentableDecl(Decl *D);
2913 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2914
2915 enum class FnBodyKind {
2916 /// C++ [dcl.fct.def.general]p1
2917 /// function-body:
2918 /// ctor-initializer[opt] compound-statement
2919 /// function-try-block
2920 Other,
2921 /// = default ;
2922 Default,
2923 /// = delete ;
2924 Delete
2925 };
2926
2927 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2928 SourceLocation LocAfterDecls);
2929 void CheckForFunctionRedefinition(
2930 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2931 SkipBodyInfo *SkipBody = nullptr);
2932 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2933 MultiTemplateParamsArg TemplateParamLists,
2934 SkipBodyInfo *SkipBody = nullptr,
2935 FnBodyKind BodyKind = FnBodyKind::Other);
2936 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2937 SkipBodyInfo *SkipBody = nullptr,
2938 FnBodyKind BodyKind = FnBodyKind::Other);
2939 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind);
2940 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
2941 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
2942 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
2943 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2944 bool isObjCMethodDecl(Decl *D) {
2945 return D && isa<ObjCMethodDecl>(D);
2946 }
2947
2948 /// Determine whether we can delay parsing the body of a function or
2949 /// function template until it is used, assuming we don't care about emitting
2950 /// code for that function.
2951 ///
2952 /// This will be \c false if we may need the body of the function in the
2953 /// middle of parsing an expression (where it's impractical to switch to
2954 /// parsing a different function), for instance, if it's constexpr in C++11
2955 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2956 bool canDelayFunctionBody(const Declarator &D);
2957
2958 /// Determine whether we can skip parsing the body of a function
2959 /// definition, assuming we don't care about analyzing its body or emitting
2960 /// code for that function.
2961 ///
2962 /// This will be \c false only if we may need the body of the function in
2963 /// order to parse the rest of the program (for instance, if it is
2964 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2965 bool canSkipFunctionBody(Decl *D);
2966
2967 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2968 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2969 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2970 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2971 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2972
2973 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2974 /// attribute for which parsing is delayed.
2975 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2976
2977 /// Diagnose any unused parameters in the given sequence of
2978 /// ParmVarDecl pointers.
2979 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2980
2981 /// Diagnose whether the size of parameters or return value of a
2982 /// function or obj-c method definition is pass-by-value and larger than a
2983 /// specified threshold.
2984 void
2985 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2986 QualType ReturnTy, NamedDecl *D);
2987
2988 void DiagnoseInvalidJumps(Stmt *Body);
2989 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2990 SourceLocation AsmLoc,
2991 SourceLocation RParenLoc);
2992
2993 /// Handle a C++11 empty-declaration and attribute-declaration.
2994 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2995 SourceLocation SemiLoc);
2996
2997 enum class ModuleDeclKind {
2998 Interface, ///< 'export module X;'
2999 Implementation, ///< 'module X;'
3000 PartitionInterface, ///< 'export module X:Y;'
3001 PartitionImplementation, ///< 'module X:Y;'
3002 };
3003
3004 /// An enumeration to represent the transition of states in parsing module
3005 /// fragments and imports. If we are not parsing a C++20 TU, or we find
3006 /// an error in state transition, the state is set to NotACXX20Module.
3007 enum class ModuleImportState {
3008 FirstDecl, ///< Parsing the first decl in a TU.
3009 GlobalFragment, ///< after 'module;' but before 'module X;'
3010 ImportAllowed, ///< after 'module X;' but before any non-import decl.
3011 ImportFinished, ///< after any non-import decl.
3012 PrivateFragment, ///< after 'module :private;'.
3013 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
3014 };
3015
3016private:
3017 /// The parser has begun a translation unit to be compiled as a C++20
3018 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
3019 void HandleStartOfHeaderUnit();
3020
3021public:
3022 /// The parser has processed a module-declaration that begins the definition
3023 /// of a module interface or implementation.
3024 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
3025 SourceLocation ModuleLoc, ModuleDeclKind MDK,
3026 ModuleIdPath Path, ModuleIdPath Partition,
3027 ModuleImportState &ImportState);
3028
3029 /// The parser has processed a global-module-fragment declaration that begins
3030 /// the definition of the global module fragment of the current module unit.
3031 /// \param ModuleLoc The location of the 'module' keyword.
3032 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
3033
3034 /// The parser has processed a private-module-fragment declaration that begins
3035 /// the definition of the private module fragment of the current module unit.
3036 /// \param ModuleLoc The location of the 'module' keyword.
3037 /// \param PrivateLoc The location of the 'private' keyword.
3038 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
3039 SourceLocation PrivateLoc);
3040
3041 /// The parser has processed a module import declaration.
3042 ///
3043 /// \param StartLoc The location of the first token in the declaration. This
3044 /// could be the location of an '@', 'export', or 'import'.
3045 /// \param ExportLoc The location of the 'export' keyword, if any.
3046 /// \param ImportLoc The location of the 'import' keyword.
3047 /// \param Path The module toplevel name as an access path.
3048 /// \param IsPartition If the name is for a partition.
3049 DeclResult ActOnModuleImport(SourceLocation StartLoc,
3050 SourceLocation ExportLoc,
3051 SourceLocation ImportLoc, ModuleIdPath Path,
3052 bool IsPartition = false);
3053 DeclResult ActOnModuleImport(SourceLocation StartLoc,
3054 SourceLocation ExportLoc,
3055 SourceLocation ImportLoc, Module *M,
3056 ModuleIdPath Path = {});
3057
3058 /// The parser has processed a module import translated from a
3059 /// #include or similar preprocessing directive.
3060 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3061 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3062
3063 /// The parsed has entered a submodule.
3064 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
3065 /// The parser has left a submodule.
3066 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
3067
3068 /// Create an implicit import of the given module at the given
3069 /// source location, for error recovery, if possible.
3070 ///
3071 /// This routine is typically used when an entity found by name lookup
3072 /// is actually hidden within a module that we know about but the user
3073 /// has forgotten to import.
3074 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3075 Module *Mod);
3076
3077 /// Kinds of missing import. Note, the values of these enumerators correspond
3078 /// to %select values in diagnostics.
3079 enum class MissingImportKind {
3080 Declaration,
3081 Definition,
3082 DefaultArgument,
3083 ExplicitSpecialization,
3084 PartialSpecialization
3085 };
3086
3087 /// Diagnose that the specified declaration needs to be visible but
3088 /// isn't, and suggest a module import that would resolve the problem.
3089 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
3090 MissingImportKind MIK, bool Recover = true);
3091 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
3092 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3093 MissingImportKind MIK, bool Recover);
3094
3095 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
3096 SourceLocation LBraceLoc);
3097 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
3098 SourceLocation RBraceLoc);
3099
3100 /// We've found a use of a templated declaration that would trigger an
3101 /// implicit instantiation. Check that any relevant explicit specializations
3102 /// and partial specializations are visible, and diagnose if not.
3103 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
3104
3105 /// Retrieve a suitable printing policy for diagnostics.
3106 PrintingPolicy getPrintingPolicy() const {
3107 return getPrintingPolicy(Context, PP);
3108 }
3109
3110 /// Retrieve a suitable printing policy for diagnostics.
3111 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
3112 const Preprocessor &PP);
3113
3114 /// Scope actions.
3115 void ActOnPopScope(SourceLocation Loc, Scope *S);
3116 void ActOnTranslationUnitScope(Scope *S);
3117
3118 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3119 RecordDecl *&AnonRecord);
3120 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3121 MultiTemplateParamsArg TemplateParams,
3122 bool IsExplicitInstantiation,
3123 RecordDecl *&AnonRecord);
3124
3125 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3126 AccessSpecifier AS,
3127 RecordDecl *Record,
3128 const PrintingPolicy &Policy);
3129
3130 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3131 RecordDecl *Record);
3132
3133 /// Common ways to introduce type names without a tag for use in diagnostics.
3134 /// Keep in sync with err_tag_reference_non_tag.
3135 enum NonTagKind {
3136 NTK_NonStruct,
3137 NTK_NonClass,
3138 NTK_NonUnion,
3139 NTK_NonEnum,
3140 NTK_Typedef,
3141 NTK_TypeAlias,
3142 NTK_Template,
3143 NTK_TypeAliasTemplate,
3144 NTK_TemplateTemplateArgument,
3145 };
3146
3147 /// Given a non-tag type declaration, returns an enum useful for indicating
3148 /// what kind of non-tag type this is.
3149 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
3150
3151 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
3152 TagTypeKind NewTag, bool isDefinition,
3153 SourceLocation NewTagLoc,
3154 const IdentifierInfo *Name);
3155
3156 enum TagUseKind {
3157 TUK_Reference, // Reference to a tag: 'struct foo *X;'
3158 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
3159 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
3160 TUK_Friend // Friend declaration: 'friend struct foo;'
3161 };
3162
3163 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3164 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
3165 SourceLocation NameLoc, const ParsedAttributesView &Attr,
3166 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
3167 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
3168 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
3169 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3170 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3171 SkipBodyInfo *SkipBody = nullptr);
3172
3173 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
3174 unsigned TagSpec, SourceLocation TagLoc,
3175 CXXScopeSpec &SS, IdentifierInfo *Name,
3176 SourceLocation NameLoc,
3177 const ParsedAttributesView &Attr,
3178 MultiTemplateParamsArg TempParamLists);
3179
3180 TypeResult ActOnDependentTag(Scope *S,
3181 unsigned TagSpec,
3182 TagUseKind TUK,
3183 const CXXScopeSpec &SS,
3184 IdentifierInfo *Name,
3185 SourceLocation TagLoc,
3186 SourceLocation NameLoc);
3187
3188 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3189 IdentifierInfo *ClassName,
3190 SmallVectorImpl<Decl *> &Decls);
3191 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3192 Declarator &D, Expr *BitfieldWidth);
3193
3194 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3195 Declarator &D, Expr *BitfieldWidth,
3196 InClassInitStyle InitStyle,
3197 AccessSpecifier AS);
3198 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
3199 SourceLocation DeclStart, Declarator &D,
3200 Expr *BitfieldWidth,
3201 InClassInitStyle InitStyle,
3202 AccessSpecifier AS,
3203 const ParsedAttr &MSPropertyAttr);
3204
3205 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
3206 TypeSourceInfo *TInfo,
3207 RecordDecl *Record, SourceLocation Loc,
3208 bool Mutable, Expr *BitfieldWidth,
3209 InClassInitStyle InitStyle,
3210 SourceLocation TSSL,
3211 AccessSpecifier AS, NamedDecl *PrevDecl,
3212 Declarator *D = nullptr);
3213
3214 bool CheckNontrivialField(FieldDecl *FD);
3215 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3216
3217 enum TrivialABIHandling {
3218 /// The triviality of a method unaffected by "trivial_abi".
3219 TAH_IgnoreTrivialABI,
3220
3221 /// The triviality of a method affected by "trivial_abi".
3222 TAH_ConsiderTrivialABI
3223 };
3224
3225 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
3226 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
3227 bool Diagnose = false);
3228
3229 /// For a defaulted function, the kind of defaulted function that it is.
3230 class DefaultedFunctionKind {
3231 CXXSpecialMember SpecialMember : 8;
3232 DefaultedComparisonKind Comparison : 8;
3233
3234 public:
3235 DefaultedFunctionKind()
3236 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3237 }
3238 DefaultedFunctionKind(CXXSpecialMember CSM)
3239 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3240 DefaultedFunctionKind(DefaultedComparisonKind Comp)
3241 : SpecialMember(CXXInvalid), Comparison(Comp) {}
3242
3243 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3244 bool isComparison() const {
3245 return Comparison != DefaultedComparisonKind::None;
3246 }
3247
3248 explicit operator bool() const {
3249 return isSpecialMember() || isComparison();
3250 }
3251
3252 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3253 DefaultedComparisonKind asComparison() const { return Comparison; }
3254
3255 /// Get the index of this function kind for use in diagnostics.
3256 unsigned getDiagnosticIndex() const {
3257 static_assert(CXXInvalid > CXXDestructor,
3258 "invalid should have highest index");
3259 static_assert((unsigned)DefaultedComparisonKind::None == 0,
3260 "none should be equal to zero");
3261 return SpecialMember + (unsigned)Comparison;
3262 }
3263 };
3264
3265 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3266
3267 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
3268 return getDefaultedFunctionKind(MD).asSpecialMember();
3269 }
3270 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
3271 return getDefaultedFunctionKind(FD).asComparison();
3272 }
3273
3274 void ActOnLastBitfield(SourceLocation DeclStart,
3275 SmallVectorImpl<Decl *> &AllIvarDecls);
3276 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3277 Declarator &D, Expr *BitfieldWidth,
3278 tok::ObjCKeywordKind visibility);
3279
3280 // This is used for both record definitions and ObjC interface declarations.
3281 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3282 ArrayRef<Decl *> Fields, SourceLocation LBrac,
3283 SourceLocation RBrac, const ParsedAttributesView &AttrList);
3284
3285 /// ActOnTagStartDefinition - Invoked when we have entered the
3286 /// scope of a tag's definition (e.g., for an enumeration, class,
3287 /// struct, or union).
3288 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
3289
3290 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3291 /// Differently from C++, actually parse the body and reject / error out
3292 /// in case of a structural mismatch.
3293 bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3294
3295 typedef void *SkippedDefinitionContext;
3296
3297 /// Invoked when we enter a tag definition that we're skipping.
3298 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
3299
3300 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
3301
3302 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3303 /// C++ record definition's base-specifiers clause and are starting its
3304 /// member declarations.
3305 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
3306 SourceLocation FinalLoc,
3307 bool IsFinalSpelledSealed,
3308 bool IsAbstract,
3309 SourceLocation LBraceLoc);
3310
3311 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3312 /// the definition of a tag (enumeration, class, struct, or union).
3313 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
3314 SourceRange BraceRange);
3315
3316 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
3317
3318 void ActOnObjCContainerFinishDefinition();
3319
3320 /// Invoked when we must temporarily exit the objective-c container
3321 /// scope for parsing/looking-up C constructs.
3322 ///
3323 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3324 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
3325 void ActOnObjCReenterContainerContext(DeclContext *DC);
3326
3327 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3328 /// error parsing the definition of a tag.
3329 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
3330
3331 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
3332 EnumConstantDecl *LastEnumConst,
3333 SourceLocation IdLoc,
3334 IdentifierInfo *Id,
3335 Expr *val);
3336 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
3337 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3338 QualType EnumUnderlyingTy, bool IsFixed,
3339 const EnumDecl *Prev);
3340
3341 /// Determine whether the body of an anonymous enumeration should be skipped.
3342 /// \param II The name of the first enumerator.
3343 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
3344 SourceLocation IILoc);
3345
3346 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3347 SourceLocation IdLoc, IdentifierInfo *Id,
3348 const ParsedAttributesView &Attrs,
3349 SourceLocation EqualLoc, Expr *Val);
3350 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3351 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3352 const ParsedAttributesView &Attr);
3353
3354 /// Set the current declaration context until it gets popped.
3355 void PushDeclContext(Scope *S, DeclContext *DC);
3356 void PopDeclContext();
3357
3358 /// EnterDeclaratorContext - Used when we must lookup names in the context
3359 /// of a declarator's nested name specifier.
3360 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
3361 void ExitDeclaratorContext(Scope *S);
3362
3363 /// Enter a template parameter scope, after it's been associated with a particular
3364 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3365 /// in the correct order.
3366 void EnterTemplatedContext(Scope *S, DeclContext *DC);
3367
3368 /// Push the parameters of D, which must be a function, into scope.
3369 void ActOnReenterFunctionContext(Scope* S, Decl* D);
3370 void ActOnExitFunctionContext();
3371
3372 /// If \p AllowLambda is true, treat lambda as function.
3373 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false);
3374
3375 /// Returns a pointer to the innermost enclosing function, or nullptr if the
3376 /// current context is not inside a function. If \p AllowLambda is true,
3377 /// this can return the call operator of an enclosing lambda, otherwise
3378 /// lambdas are skipped when looking for an enclosing function.
3379 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false);
3380
3381 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3382 /// the method decl for the method being parsed. If we're currently
3383 /// in a 'block', this returns the containing context.
3384 ObjCMethodDecl *getCurMethodDecl();
3385
3386 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3387 /// or C function we're in, otherwise return null. If we're currently
3388 /// in a 'block', this returns the containing context.
3389 NamedDecl *getCurFunctionOrMethodDecl();
3390
3391 /// Add this decl to the scope shadowed decl chains.
3392 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3393
3394 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3395 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3396 /// true if 'D' belongs to the given declaration context.
3397 ///
3398 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3399 /// enclosing namespace set of the context, rather than contained
3400 /// directly within it.
3401 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3402 bool AllowInlineNamespace = false);
3403
3404 /// Finds the scope corresponding to the given decl context, if it
3405 /// happens to be an enclosing scope. Otherwise return NULL.
3406 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3407
3408 /// Subroutines of ActOnDeclarator().
3409 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
3410 TypeSourceInfo *TInfo);
3411 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
3412
3413 /// Describes the kind of merge to perform for availability
3414 /// attributes (including "deprecated", "unavailable", and "availability").
3415 enum AvailabilityMergeKind {
3416 /// Don't merge availability attributes at all.
3417 AMK_None,
3418 /// Merge availability attributes for a redeclaration, which requires
3419 /// an exact match.
3420 AMK_Redeclaration,
3421 /// Merge availability attributes for an override, which requires
3422 /// an exact match or a weakening of constraints.
3423 AMK_Override,
3424 /// Merge availability attributes for an implementation of
3425 /// a protocol requirement.
3426 AMK_ProtocolImplementation,
3427 /// Merge availability attributes for an implementation of
3428 /// an optional protocol requirement.
3429 AMK_OptionalProtocolImplementation
3430 };
3431
3432 /// Describes the kind of priority given to an availability attribute.
3433 ///
3434 /// The sum of priorities deteremines the final priority of the attribute.
3435 /// The final priority determines how the attribute will be merged.
3436 /// An attribute with a lower priority will always remove higher priority
3437 /// attributes for the specified platform when it is being applied. An
3438 /// attribute with a higher priority will not be applied if the declaration
3439 /// already has an availability attribute with a lower priority for the
3440 /// specified platform. The final prirority values are not expected to match
3441 /// the values in this enumeration, but instead should be treated as a plain
3442 /// integer value. This enumeration just names the priority weights that are
3443 /// used to calculate that final vaue.
3444 enum AvailabilityPriority : int {
3445 /// The availability attribute was specified explicitly next to the
3446 /// declaration.
3447 AP_Explicit = 0,
3448
3449 /// The availability attribute was applied using '#pragma clang attribute'.
3450 AP_PragmaClangAttribute = 1,
3451
3452 /// The availability attribute for a specific platform was inferred from
3453 /// an availability attribute for another platform.
3454 AP_InferredFromOtherPlatform = 2
3455 };
3456
3457 /// Attribute merging methods. Return true if a new attribute was added.
3458 AvailabilityAttr *
3459 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3460 IdentifierInfo *Platform, bool Implicit,
3461 VersionTuple Introduced, VersionTuple Deprecated,
3462 VersionTuple Obsoleted, bool IsUnavailable,
3463 StringRef Message, bool IsStrict, StringRef Replacement,
3464 AvailabilityMergeKind AMK, int Priority);
3465 TypeVisibilityAttr *
3466 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3467 TypeVisibilityAttr::VisibilityType Vis);
3468 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3469 VisibilityAttr::VisibilityType Vis);
3470 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3471 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3472 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3473 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3474 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3475 const AttributeCommonInfo &CI,
3476 bool BestCase,
3477 MSInheritanceModel Model);
3478 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3479 StringRef NewUserDiagnostic);
3480 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3481 IdentifierInfo *Format, int FormatIdx,
3482 int FirstArg);
3483 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3484 StringRef Name);
3485 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3486 StringRef Name);
3487 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3488 const AttributeCommonInfo &CI,
3489 const IdentifierInfo *Ident);
3490 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3491 SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3492 StringRef Name);
3493 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3494 const AttributeCommonInfo &CI);
3495 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3496 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3497 const InternalLinkageAttr &AL);
3498 WebAssemblyImportNameAttr *mergeImportNameAttr(
3499 Decl *D, const WebAssemblyImportNameAttr &AL);
3500 WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3501 Decl *D, const WebAssemblyImportModuleAttr &AL);
3502 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3503 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3504 const EnforceTCBLeafAttr &AL);
3505 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3506 HLSLNumThreadsAttr *mergeHLSLNumThreadsAttr(Decl *D,
3507 const AttributeCommonInfo &AL,
3508 int X, int Y, int Z);
3509
3510 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3511 AvailabilityMergeKind AMK = AMK_Redeclaration);
3512 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
3513 LookupResult &OldDecls);
3514 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3515 bool MergeTypeWithOld, bool NewDeclIsDefn);
3516 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3517 Scope *S, bool MergeTypeWithOld);
3518 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
3519 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
3520 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3521 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3522 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3523 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3524 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3525
3526 // AssignmentAction - This is used by all the assignment diagnostic functions
3527 // to represent what is actually causing the operation
3528 enum AssignmentAction {
3529 AA_Assigning,
3530 AA_Passing,
3531 AA_Returning,
3532 AA_Converting,
3533 AA_Initializing,
3534 AA_Sending,
3535 AA_Casting,
3536 AA_Passing_CFAudited
3537 };
3538
3539 /// C++ Overloading.
3540 enum OverloadKind {
3541 /// This is a legitimate overload: the existing declarations are
3542 /// functions or function templates with different signatures.
3543 Ovl_Overload,
3544
3545 /// This is not an overload because the signature exactly matches
3546 /// an existing declaration.
3547 Ovl_Match,
3548
3549 /// This is not an overload because the lookup results contain a
3550 /// non-function.
3551 Ovl_NonFunction
3552 };
3553 OverloadKind CheckOverload(Scope *S,
3554 FunctionDecl *New,
3555 const LookupResult &OldDecls,
3556 NamedDecl *&OldDecl,
3557 bool IsForUsingDecl);
3558 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
3559 bool ConsiderCudaAttrs = true,
3560 bool ConsiderRequiresClauses = true);
3561
3562 enum class AllowedExplicit {
3563 /// Allow no explicit functions to be used.
3564 None,
3565 /// Allow explicit conversion functions but not explicit constructors.
3566 Conversions,
3567 /// Allow both explicit conversion functions and explicit constructors.
3568 All
3569 };
3570
3571 ImplicitConversionSequence
3572 TryImplicitConversion(Expr *From, QualType ToType,
3573 bool SuppressUserConversions,
3574 AllowedExplicit AllowExplicit,
3575 bool InOverloadResolution,
3576 bool CStyle,
3577 bool AllowObjCWritebackConversion);
3578
3579 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3580 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3581 bool IsComplexPromotion(QualType FromType, QualType ToType);
3582 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3583 bool InOverloadResolution,
3584 QualType& ConvertedType, bool &IncompatibleObjC);
3585 bool isObjCPointerConversion(QualType FromType, QualType ToType,
3586 QualType& ConvertedType, bool &IncompatibleObjC);
3587 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3588 QualType &ConvertedType);
3589 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3590 QualType& ConvertedType);
3591 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3592 const FunctionProtoType *NewType,
3593 unsigned *ArgPos = nullptr);
3594 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3595 QualType FromType, QualType ToType);
3596
3597 void maybeExtendBlockObject(ExprResult &E);
3598 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
3599 bool CheckPointerConversion(Expr *From, QualType ToType,
3600 CastKind &Kind,
3601 CXXCastPath& BasePath,
3602 bool IgnoreBaseAccess,
3603 bool Diagnose = true);
3604 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3605 bool InOverloadResolution,
3606 QualType &ConvertedType);
3607 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3608 CastKind &Kind,
3609 CXXCastPath &BasePath,
3610 bool IgnoreBaseAccess);
3611 bool IsQualificationConversion(QualType FromType, QualType ToType,
3612 bool CStyle, bool &ObjCLifetimeConversion);
3613 bool IsFunctionConversion(QualType FromType, QualType ToType,
3614 QualType &ResultTy);
3615 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3616 bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
3617
3618 bool CanPerformAggregateInitializationForOverloadResolution(
3619 const InitializedEntity &Entity, InitListExpr *From);
3620
3621 bool IsStringInit(Expr *Init, const ArrayType *AT);
3622
3623 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3624 ExprResult Init);
3625 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3626 SourceLocation EqualLoc,
3627 ExprResult Init,
3628 bool TopLevelOfInitList = false,
3629 bool AllowExplicit = false);
3630 ExprResult PerformObjectArgumentInitialization(Expr *From,
3631 NestedNameSpecifier *Qualifier,
3632 NamedDecl *FoundDecl,
3633 CXXMethodDecl *Method);
3634
3635 /// Check that the lifetime of the initializer (and its subobjects) is
3636 /// sufficient for initializing the entity, and perform lifetime extension
3637 /// (when permitted) if not.
3638 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3639
3640 ExprResult PerformContextuallyConvertToBool(Expr *From);
3641 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3642
3643 /// Contexts in which a converted constant expression is required.
3644 enum CCEKind {
3645 CCEK_CaseValue, ///< Expression in a case label.
3646 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
3647 CCEK_TemplateArg, ///< Value of a non-type template parameter.
3648 CCEK_ArrayBound, ///< Array bound in array declarator or new-expression.
3649 CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier.
3650 CCEK_Noexcept ///< Condition in a noexcept(bool) specifier.
3651 };
3652 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3653 llvm::APSInt &Value, CCEKind CCE);
3654 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3655 APValue &Value, CCEKind CCE,
3656 NamedDecl *Dest = nullptr);
3657
3658 /// Abstract base class used to perform a contextual implicit
3659 /// conversion from an expression to any type passing a filter.
3660 class ContextualImplicitConverter {
3661 public:
3662 bool Suppress;
3663 bool SuppressConversion;
3664
3665 ContextualImplicitConverter(bool Suppress = false,
3666 bool SuppressConversion = false)
3667 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3668
3669 /// Determine whether the specified type is a valid destination type
3670 /// for this conversion.
3671 virtual bool match(QualType T) = 0;
3672
3673 /// Emits a diagnostic complaining that the expression does not have
3674 /// integral or enumeration type.
3675 virtual SemaDiagnosticBuilder
3676 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3677
3678 /// Emits a diagnostic when the expression has incomplete class type.
3679 virtual SemaDiagnosticBuilder
3680 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3681
3682 /// Emits a diagnostic when the only matching conversion function
3683 /// is explicit.
3684 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3685 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3686
3687 /// Emits a note for the explicit conversion function.
3688 virtual SemaDiagnosticBuilder
3689 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3690
3691 /// Emits a diagnostic when there are multiple possible conversion
3692 /// functions.
3693 virtual SemaDiagnosticBuilder
3694 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3695
3696 /// Emits a note for one of the candidate conversions.
3697 virtual SemaDiagnosticBuilder
3698 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3699
3700 /// Emits a diagnostic when we picked a conversion function
3701 /// (for cases when we are not allowed to pick a conversion function).
3702 virtual SemaDiagnosticBuilder diagnoseConversion(
3703 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3704
3705 virtual ~ContextualImplicitConverter() {}
3706 };
3707
3708 class ICEConvertDiagnoser : public ContextualImplicitConverter {
3709 bool AllowScopedEnumerations;
3710
3711 public:
3712 ICEConvertDiagnoser(bool AllowScopedEnumerations,
3713 bool Suppress, bool SuppressConversion)
3714 : ContextualImplicitConverter(Suppress, SuppressConversion),
3715 AllowScopedEnumerations(AllowScopedEnumerations) {}
3716
3717 /// Match an integral or (possibly scoped) enumeration type.
3718 bool match(QualType T) override;
3719
3720 SemaDiagnosticBuilder
3721 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3722 return diagnoseNotInt(S, Loc, T);
3723 }
3724
3725 /// Emits a diagnostic complaining that the expression does not have
3726 /// integral or enumeration type.
3727 virtual SemaDiagnosticBuilder
3728 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3729 };
3730
3731 /// Perform a contextual implicit conversion.
3732 ExprResult PerformContextualImplicitConversion(
3733 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3734
3735
3736 enum ObjCSubscriptKind {
3737 OS_Array,
3738 OS_Dictionary,
3739 OS_Error
3740 };
3741 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3742
3743 // Note that LK_String is intentionally after the other literals, as
3744 // this is used for diagnostics logic.
3745 enum ObjCLiteralKind {
3746 LK_Array,
3747 LK_Dictionary,
3748 LK_Numeric,
3749 LK_Boxed,
3750 LK_String,
3751 LK_Block,
3752 LK_None
3753 };
3754 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3755
3756 ExprResult PerformObjectMemberConversion(Expr *From,
3757 NestedNameSpecifier *Qualifier,
3758 NamedDecl *FoundDecl,
3759 NamedDecl *Member);
3760
3761 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3762 // TODO: make this is a typesafe union.
3763 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
3764 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3765
3766 using ADLCallKind = CallExpr::ADLCallKind;
3767
3768 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3769 ArrayRef<Expr *> Args,
3770 OverloadCandidateSet &CandidateSet,
3771 bool SuppressUserConversions = false,
3772 bool PartialOverloading = false,
3773 bool AllowExplicit = true,
3774 bool AllowExplicitConversion = false,
3775 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3776 ConversionSequenceList EarlyConversions = None,
3777 OverloadCandidateParamOrder PO = {});
3778 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3779 ArrayRef<Expr *> Args,
3780 OverloadCandidateSet &CandidateSet,
3781 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3782 bool SuppressUserConversions = false,
3783 bool PartialOverloading = false,
3784 bool FirstArgumentIsBase = false);
3785 void AddMethodCandidate(DeclAccessPair FoundDecl,
3786 QualType ObjectType,
3787 Expr::Classification ObjectClassification,
3788 ArrayRef<Expr *> Args,
3789 OverloadCandidateSet& CandidateSet,
3790 bool SuppressUserConversion = false,
3791 OverloadCandidateParamOrder PO = {});
3792 void AddMethodCandidate(CXXMethodDecl *Method,
3793 DeclAccessPair FoundDecl,
3794 CXXRecordDecl *ActingContext, QualType ObjectType,
3795 Expr::Classification ObjectClassification,
3796 ArrayRef<Expr *> Args,
3797 OverloadCandidateSet& CandidateSet,
3798 bool SuppressUserConversions = false,
3799 bool PartialOverloading = false,
3800 ConversionSequenceList EarlyConversions = None,
3801 OverloadCandidateParamOrder PO = {});
3802 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3803 DeclAccessPair FoundDecl,
3804 CXXRecordDecl *ActingContext,
3805 TemplateArgumentListInfo *ExplicitTemplateArgs,
3806 QualType ObjectType,
3807 Expr::Classification ObjectClassification,
3808 ArrayRef<Expr *> Args,
3809 OverloadCandidateSet& CandidateSet,
3810 bool SuppressUserConversions = false,
3811 bool PartialOverloading = false,
3812 OverloadCandidateParamOrder PO = {});
3813 void AddTemplateOverloadCandidate(
3814 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3815 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3816 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3817 bool PartialOverloading = false, bool AllowExplicit = true,
3818 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3819 OverloadCandidateParamOrder PO = {});
3820 bool CheckNonDependentConversions(
3821 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3822 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3823 ConversionSequenceList &Conversions, bool SuppressUserConversions,
3824 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3825 Expr::Classification ObjectClassification = {},
3826 OverloadCandidateParamOrder PO = {});
3827 void AddConversionCandidate(
3828 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3829 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3830 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3831 bool AllowExplicit, bool AllowResultConversion = true);
3832 void AddTemplateConversionCandidate(
3833 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3834 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3835 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3836 bool AllowExplicit, bool AllowResultConversion = true);
3837 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3838 DeclAccessPair FoundDecl,
3839 CXXRecordDecl *ActingContext,
3840 const FunctionProtoType *Proto,
3841 Expr *Object, ArrayRef<Expr *> Args,
3842 OverloadCandidateSet& CandidateSet);
3843 void AddNonMemberOperatorCandidates(
3844 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3845 OverloadCandidateSet &CandidateSet,
3846 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3847 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3848 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3849 OverloadCandidateSet &CandidateSet,
3850 OverloadCandidateParamOrder PO = {});
3851 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3852 OverloadCandidateSet& CandidateSet,
3853 bool IsAssignmentOperator = false,
3854 unsigned NumContextualBoolArguments = 0);
3855 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3856 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3857 OverloadCandidateSet& CandidateSet);
3858 void AddArgumentDependentLookupCandidates(DeclarationName Name,
3859 SourceLocation Loc,
3860 ArrayRef<Expr *> Args,
3861 TemplateArgumentListInfo *ExplicitTemplateArgs,
3862 OverloadCandidateSet& CandidateSet,
3863 bool PartialOverloading = false);
3864
3865 // Emit as a 'note' the specific overload candidate
3866 void NoteOverloadCandidate(
3867 NamedDecl *Found, FunctionDecl *Fn,
3868 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3869 QualType DestType = QualType(), bool TakingAddress = false);
3870
3871 // Emit as a series of 'note's all template and non-templates identified by
3872 // the expression Expr
3873 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3874 bool TakingAddress = false);
3875
3876 /// Check the enable_if expressions on the given function. Returns the first
3877 /// failing attribute, or NULL if they were all successful.
3878 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
3879 ArrayRef<Expr *> Args,
3880 bool MissingImplicitThis = false);
3881
3882 /// Find the failed Boolean condition within a given Boolean
3883 /// constant expression, and describe it with a string.
3884 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3885
3886 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3887 /// non-ArgDependent DiagnoseIfAttrs.
3888 ///
3889 /// Argument-dependent diagnose_if attributes should be checked each time a
3890 /// function is used as a direct callee of a function call.
3891 ///
3892 /// Returns true if any errors were emitted.
3893 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3894 const Expr *ThisArg,
3895 ArrayRef<const Expr *> Args,
3896 SourceLocation Loc);
3897
3898 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3899 /// ArgDependent DiagnoseIfAttrs.
3900 ///
3901 /// Argument-independent diagnose_if attributes should be checked on every use
3902 /// of a function.
3903 ///
3904 /// Returns true if any errors were emitted.
3905 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3906 SourceLocation Loc);
3907
3908 /// Returns whether the given function's address can be taken or not,
3909 /// optionally emitting a diagnostic if the address can't be taken.
3910 ///
3911 /// Returns false if taking the address of the function is illegal.
3912 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3913 bool Complain = false,
3914 SourceLocation Loc = SourceLocation());
3915
3916 // [PossiblyAFunctionType] --> [Return]
3917 // NonFunctionType --> NonFunctionType
3918 // R (A) --> R(A)
3919 // R (*)(A) --> R (A)
3920 // R (&)(A) --> R (A)
3921 // R (S::*)(A) --> R (A)
3922 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3923
3924 FunctionDecl *
3925 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3926 QualType TargetType,
3927 bool Complain,
3928 DeclAccessPair &Found,
3929 bool *pHadMultipleCandidates = nullptr);
3930
3931 FunctionDecl *
3932 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3933
3934 bool resolveAndFixAddressOfSingleOverloadCandidate(
3935 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3936
3937 FunctionDecl *
3938 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3939 bool Complain = false,
3940 DeclAccessPair *Found = nullptr);
3941
3942 bool ResolveAndFixSingleFunctionTemplateSpecialization(
3943 ExprResult &SrcExpr,
3944 bool DoFunctionPointerConverion = false,
3945 bool Complain = false,
3946 SourceRange OpRangeForComplaining = SourceRange(),
3947 QualType DestTypeForComplaining = QualType(),
3948 unsigned DiagIDForComplaining = 0);
3949
3950
3951 Expr *FixOverloadedFunctionReference(Expr *E,
3952 DeclAccessPair FoundDecl,
3953 FunctionDecl *Fn);
3954 ExprResult FixOverloadedFunctionReference(ExprResult,
3955 DeclAccessPair FoundDecl,
3956 FunctionDecl *Fn);
3957
3958 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3959 ArrayRef<Expr *> Args,
3960 OverloadCandidateSet &CandidateSet,
3961 bool PartialOverloading = false);
3962 void AddOverloadedCallCandidates(
3963 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
3964 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
3965
3966 // An enum used to represent the different possible results of building a
3967 // range-based for loop.
3968 enum ForRangeStatus {
3969 FRS_Success,
3970 FRS_NoViableFunction,
3971 FRS_DiagnosticIssued
3972 };
3973
3974 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3975 SourceLocation RangeLoc,
3976 const DeclarationNameInfo &NameInfo,
3977 LookupResult &MemberLookup,
3978 OverloadCandidateSet *CandidateSet,
3979 Expr *Range, ExprResult *CallExpr);
3980
3981 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3982 UnresolvedLookupExpr *ULE,
3983 SourceLocation LParenLoc,
3984 MultiExprArg Args,
3985 SourceLocation RParenLoc,
3986 Expr *ExecConfig,
3987 bool AllowTypoCorrection=true,
3988 bool CalleesAddressIsTaken=false);
3989
3990 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3991 MultiExprArg Args, SourceLocation RParenLoc,
3992 OverloadCandidateSet *CandidateSet,
3993 ExprResult *Result);
3994
3995 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
3996 NestedNameSpecifierLoc NNSLoc,
3997 DeclarationNameInfo DNI,
3998 const UnresolvedSetImpl &Fns,
3999 bool PerformADL = true);
4000
4001 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
4002 UnaryOperatorKind Opc,
4003 const UnresolvedSetImpl &Fns,
4004 Expr *input, bool RequiresADL = true);
4005
4006 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
4007 OverloadedOperatorKind Op,
4008 const UnresolvedSetImpl &Fns,
4009 ArrayRef<Expr *> Args, bool RequiresADL = true);
4010 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
4011 BinaryOperatorKind Opc,
4012 const UnresolvedSetImpl &Fns,
4013 Expr *LHS, Expr *RHS,
4014 bool RequiresADL = true,
4015 bool AllowRewrittenCandidates = true,
4016 FunctionDecl *DefaultedFn = nullptr);
4017 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
4018 const UnresolvedSetImpl &Fns,
4019 Expr *LHS, Expr *RHS,
4020 FunctionDecl *DefaultedFn);
4021
4022 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
4023 SourceLocation RLoc, Expr *Base,
4024 MultiExprArg Args);
4025
4026 ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
4027 SourceLocation LParenLoc,
4028 MultiExprArg Args,
4029 SourceLocation RParenLoc,
4030 Expr *ExecConfig = nullptr,
4031 bool IsExecConfig = false,
4032 bool AllowRecovery = false);
4033 ExprResult
4034 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
4035 MultiExprArg Args,
4036 SourceLocation RParenLoc);
4037
4038 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
4039 SourceLocation OpLoc,
4040 bool *NoArrowOperatorFound = nullptr);
4041
4042 /// CheckCallReturnType - Checks that a call expression's return type is
4043 /// complete. Returns true on failure. The location passed in is the location
4044 /// that best represents the call.
4045 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
4046 CallExpr *CE, FunctionDecl *FD);
4047
4048 /// Helpers for dealing with blocks and functions.
4049 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
4050 bool CheckParameterNames);
4051 void CheckCXXDefaultArguments(FunctionDecl *FD);
4052 void CheckExtraCXXDefaultArguments(Declarator &D);
4053 Scope *getNonFieldDeclScope(Scope *S);
4054
4055 /// \name Name lookup
4056 ///
4057 /// These routines provide name lookup that is used during semantic
4058 /// analysis to resolve the various kinds of names (identifiers,
4059 /// overloaded operator names, constructor names, etc.) into zero or
4060 /// more declarations within a particular scope. The major entry
4061 /// points are LookupName, which performs unqualified name lookup,
4062 /// and LookupQualifiedName, which performs qualified name lookup.
4063 ///
4064 /// All name lookup is performed based on some specific criteria,
4065 /// which specify what names will be visible to name lookup and how
4066 /// far name lookup should work. These criteria are important both
4067 /// for capturing language semantics (certain lookups will ignore
4068 /// certain names, for example) and for performance, since name
4069 /// lookup is often a bottleneck in the compilation of C++. Name
4070 /// lookup criteria is specified via the LookupCriteria enumeration.
4071 ///
4072 /// The results of name lookup can vary based on the kind of name
4073 /// lookup performed, the current language, and the translation
4074 /// unit. In C, for example, name lookup will either return nothing
4075 /// (no entity found) or a single declaration. In C++, name lookup
4076 /// can additionally refer to a set of overloaded functions or
4077 /// result in an ambiguity. All of the possible results of name
4078 /// lookup are captured by the LookupResult class, which provides
4079 /// the ability to distinguish among them.
4080 //@{
4081
4082 /// Describes the kind of name lookup to perform.
4083 enum LookupNameKind {
4084 /// Ordinary name lookup, which finds ordinary names (functions,
4085 /// variables, typedefs, etc.) in C and most kinds of names
4086 /// (functions, variables, members, types, etc.) in C++.
4087 LookupOrdinaryName = 0,
4088 /// Tag name lookup, which finds the names of enums, classes,
4089 /// structs, and unions.
4090 LookupTagName,
4091 /// Label name lookup.
4092 LookupLabel,
4093 /// Member name lookup, which finds the names of
4094 /// class/struct/union members.
4095 LookupMemberName,
4096 /// Look up of an operator name (e.g., operator+) for use with
4097 /// operator overloading. This lookup is similar to ordinary name
4098 /// lookup, but will ignore any declarations that are class members.
4099 LookupOperatorName,
4100 /// Look up a name following ~ in a destructor name. This is an ordinary
4101 /// lookup, but prefers tags to typedefs.
4102 LookupDestructorName,
4103 /// Look up of a name that precedes the '::' scope resolution
4104 /// operator in C++. This lookup completely ignores operator, object,
4105 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
4106 LookupNestedNameSpecifierName,
4107 /// Look up a namespace name within a C++ using directive or
4108 /// namespace alias definition, ignoring non-namespace names (C++
4109 /// [basic.lookup.udir]p1).
4110 LookupNamespaceName,
4111 /// Look up all declarations in a scope with the given name,
4112 /// including resolved using declarations. This is appropriate
4113 /// for checking redeclarations for a using declaration.
4114 LookupUsingDeclName,
4115 /// Look up an ordinary name that is going to be redeclared as a
4116 /// name with linkage. This lookup ignores any declarations that
4117 /// are outside of the current scope unless they have linkage. See
4118 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
4119 LookupRedeclarationWithLinkage,
4120 /// Look up a friend of a local class. This lookup does not look
4121 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
4122 LookupLocalFriendName,
4123 /// Look up the name of an Objective-C protocol.
4124 LookupObjCProtocolName,
4125 /// Look up implicit 'self' parameter of an objective-c method.
4126 LookupObjCImplicitSelfParam,
4127 /// Look up the name of an OpenMP user-defined reduction operation.
4128 LookupOMPReductionName,
4129 /// Look up the name of an OpenMP user-defined mapper.
4130 LookupOMPMapperName,
4131 /// Look up any declaration with any name.
4132 LookupAnyName
4133 };
4134
4135 /// Specifies whether (or how) name lookup is being performed for a
4136 /// redeclaration (vs. a reference).
4137 enum RedeclarationKind {
4138 /// The lookup is a reference to this name that is not for the
4139 /// purpose of redeclaring the name.
4140 NotForRedeclaration = 0,
4141 /// The lookup results will be used for redeclaration of a name,
4142 /// if an entity by that name already exists and is visible.
4143 ForVisibleRedeclaration,
4144 /// The lookup results will be used for redeclaration of a name
4145 /// with external linkage; non-visible lookup results with external linkage
4146 /// may also be found.
4147 ForExternalRedeclaration
4148 };
4149
4150 RedeclarationKind forRedeclarationInCurContext() {
4151 // A declaration with an owning module for linkage can never link against
4152 // anything that is not visible. We don't need to check linkage here; if
4153 // the context has internal linkage, redeclaration lookup won't find things
4154 // from other TUs, and we can't safely compute linkage yet in general.
4155 if (cast<Decl>(CurContext)
4156 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
4157 return ForVisibleRedeclaration;
4158 return ForExternalRedeclaration;
4159 }
4160
4161 /// The possible outcomes of name lookup for a literal operator.
4162 enum LiteralOperatorLookupResult {
4163 /// The lookup resulted in an error.
4164 LOLR_Error,
4165 /// The lookup found no match but no diagnostic was issued.
4166 LOLR_ErrorNoDiagnostic,
4167 /// The lookup found a single 'cooked' literal operator, which
4168 /// expects a normal literal to be built and passed to it.
4169 LOLR_Cooked,
4170 /// The lookup found a single 'raw' literal operator, which expects
4171 /// a string literal containing the spelling of the literal token.
4172 LOLR_Raw,
4173 /// The lookup found an overload set of literal operator templates,
4174 /// which expect the characters of the spelling of the literal token to be
4175 /// passed as a non-type template argument pack.
4176 LOLR_Template,
4177 /// The lookup found an overload set of literal operator templates,
4178 /// which expect the character type and characters of the spelling of the
4179 /// string literal token to be passed as template arguments.
4180 LOLR_StringTemplatePack,
4181 };
4182
4183 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
4184 CXXSpecialMember SM,
4185 bool ConstArg,
4186 bool VolatileArg,
4187 bool RValueThis,
4188 bool ConstThis,
4189 bool VolatileThis);
4190
4191 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
4192 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
4193 TypoRecoveryCallback;
4194
4195private:
4196 bool CppLookupName(LookupResult &R, Scope *S);
4197
4198 struct TypoExprState {
4199 std::unique_ptr<TypoCorrectionConsumer> Consumer;
4200 TypoDiagnosticGenerator DiagHandler;
4201 TypoRecoveryCallback RecoveryHandler;
4202 TypoExprState();
4203 TypoExprState(TypoExprState &&other) noexcept;
4204 TypoExprState &operator=(TypoExprState &&other) noexcept;
4205 };
4206
4207 /// The set of unhandled TypoExprs and their associated state.
4208 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
4209
4210 /// Creates a new TypoExpr AST node.
4211 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4212 TypoDiagnosticGenerator TDG,
4213 TypoRecoveryCallback TRC, SourceLocation TypoLoc);
4214
4215 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
4216 //
4217 // The boolean value will be true to indicate that the namespace was loaded
4218 // from an AST/PCH file, or false otherwise.
4219 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
4220
4221 /// Whether we have already loaded known namespaces from an extenal
4222 /// source.
4223 bool LoadedExternalKnownNamespaces;
4224
4225 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
4226 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
4227 /// should be skipped entirely.
4228 std::unique_ptr<TypoCorrectionConsumer>
4229 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
4230 Sema::LookupNameKind LookupKind, Scope *S,
4231 CXXScopeSpec *SS,
4232 CorrectionCandidateCallback &CCC,
4233 DeclContext *MemberContext, bool EnteringContext,
4234 const ObjCObjectPointerType *OPT,
4235 bool ErrorRecovery);
4236
4237public:
4238 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
4239
4240 /// Clears the state of the given TypoExpr.
4241 void clearDelayedTypo(TypoExpr *TE);
4242
4243 /// Look up a name, looking for a single declaration. Return
4244 /// null if the results were absent, ambiguous, or overloaded.
4245 ///
4246 /// It is preferable to use the elaborated form and explicitly handle
4247 /// ambiguity and overloaded.
4248 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
4249 SourceLocation Loc,
4250 LookupNameKind NameKind,
4251 RedeclarationKind Redecl
4252 = NotForRedeclaration);
4253 bool LookupBuiltin(LookupResult &R);
4254 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
4255 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
4256 bool ForceNoCPlusPlus = false);
4257 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4258 bool InUnqualifiedLookup = false);
4259 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4260 CXXScopeSpec &SS);
4261 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
4262 bool AllowBuiltinCreation = false,
4263 bool EnteringContext = false);
4264 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
4265 RedeclarationKind Redecl
4266 = NotForRedeclaration);
4267 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
4268
4269 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
4270 UnresolvedSetImpl &Functions);
4271
4272 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
4273 SourceLocation GnuLabelLoc = SourceLocation());
4274
4275 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
4276 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
4277 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
4278 unsigned Quals);
4279 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
4280 bool RValueThis, unsigned ThisQuals);
4281 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
4282 unsigned Quals);
4283 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
4284 bool RValueThis, unsigned ThisQuals);
4285 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
4286
4287 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
4288 bool IsUDSuffix);
4289 LiteralOperatorLookupResult
4290 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
4291 bool AllowRaw, bool AllowTemplate,
4292 bool AllowStringTemplate, bool DiagnoseMissing,
4293 StringLiteral *StringLit = nullptr);
4294 bool isKnownName(StringRef name);
4295
4296 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4297 enum class FunctionEmissionStatus {
4298 Emitted,
4299 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4300 OMPDiscarded, // Discarded due to OpenMP hostness
4301 TemplateDiscarded, // Discarded due to uninstantiated templates
4302 Unknown,
4303 };
4304 FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl,
4305 bool Final = false);
4306
4307 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4308 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4309
4310 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
4311 ArrayRef<Expr *> Args, ADLResult &Functions);
4312
4313 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4314 VisibleDeclConsumer &Consumer,
4315 bool IncludeGlobalScope = true,
4316 bool LoadExternal = true);
4317 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4318 VisibleDeclConsumer &Consumer,
4319 bool IncludeGlobalScope = true,
4320 bool IncludeDependentBases = false,
4321 bool LoadExternal = true);
4322
4323 enum CorrectTypoKind {
4324 CTK_NonError, // CorrectTypo used in a non error recovery situation.
4325 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4326 };
4327
4328 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
4329 Sema::LookupNameKind LookupKind,
4330 Scope *S, CXXScopeSpec *SS,
4331 CorrectionCandidateCallback &CCC,
4332 CorrectTypoKind Mode,
4333 DeclContext *MemberContext = nullptr,
4334 bool EnteringContext = false,
4335 const ObjCObjectPointerType *OPT = nullptr,
4336 bool RecordFailure = true);
4337
4338 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
4339 Sema::LookupNameKind LookupKind, Scope *S,
4340 CXXScopeSpec *SS,
4341 CorrectionCandidateCallback &CCC,
4342 TypoDiagnosticGenerator TDG,
4343 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
4344 DeclContext *MemberContext = nullptr,
4345 bool EnteringContext = false,
4346 const ObjCObjectPointerType *OPT = nullptr);
4347
4348 /// Process any TypoExprs in the given Expr and its children,
4349 /// generating diagnostics as appropriate and returning a new Expr if there
4350 /// were typos that were all successfully corrected and ExprError if one or
4351 /// more typos could not be corrected.
4352 ///
4353 /// \param E The Expr to check for TypoExprs.
4354 ///
4355 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4356 /// initializer.
4357 ///
4358 /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4359 /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4360 ///
4361 /// \param Filter A function applied to a newly rebuilt Expr to determine if
4362 /// it is an acceptable/usable result from a single combination of typo
4363 /// corrections. As long as the filter returns ExprError, different
4364 /// combinations of corrections will be tried until all are exhausted.
4365 ExprResult CorrectDelayedTyposInExpr(
4366 Expr *E, VarDecl *InitDecl = nullptr,
4367 bool RecoverUncorrectedTypos = false,
4368 llvm::function_ref<ExprResult(Expr *)> Filter =
4369 [](Expr *E) -> ExprResult { return E; });
4370
4371 ExprResult CorrectDelayedTyposInExpr(
4372 ExprResult ER, VarDecl *InitDecl = nullptr,
4373 bool RecoverUncorrectedTypos = false,
4374 llvm::function_ref<ExprResult(Expr *)> Filter =
4375 [](Expr *E) -> ExprResult { return E; }) {
4376 return ER.isInvalid()
4377 ? ER
4378 : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4379 RecoverUncorrectedTypos, Filter);
4380 }
4381
4382 void diagnoseTypo(const TypoCorrection &Correction,
4383 const PartialDiagnostic &TypoDiag,
4384 bool ErrorRecovery = true);
4385
4386 void diagnoseTypo(const TypoCorrection &Correction,
4387 const PartialDiagnostic &TypoDiag,
4388 const PartialDiagnostic &PrevNote,
4389 bool ErrorRecovery = true);
4390
4391 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4392
4393 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4394 ArrayRef<Expr *> Args,
4395 AssociatedNamespaceSet &AssociatedNamespaces,
4396 AssociatedClassSet &AssociatedClasses);
4397
4398 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4399 bool ConsiderLinkage, bool AllowInlineNamespace);
4400
4401 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4402 bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4403 bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4404
4405 void DiagnoseAmbiguousLookup(LookupResult &Result);
4406 //@}
4407
4408 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4409 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4410 ArrayRef<Expr *> SubExprs,
4411 QualType T = QualType());
4412
4413 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4414 SourceLocation IdLoc,
4415 bool TypoCorrection = false);
4416 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4417 SourceLocation Loc);
4418 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
4419 Scope *S, bool ForRedeclaration,
4420 SourceLocation Loc);
4421 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4422 Scope *S);
4423 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4424 FunctionDecl *FD);
4425 void AddKnownFunctionAttributes(FunctionDecl *FD);
4426
4427 // More parsing and symbol table subroutines.
4428
4429 void ProcessPragmaWeak(Scope *S, Decl *D);
4430 // Decl attributes - this routine is the top level dispatcher.
4431 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
4432 // Helper for delayed processing of attributes.
4433 void ProcessDeclAttributeDelayed(Decl *D,
4434 const ParsedAttributesView &AttrList);
4435 void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
4436 bool IncludeCXX11Attributes = true);
4437 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4438 const ParsedAttributesView &AttrList);
4439
4440 void checkUnusedDeclAttributes(Declarator &D);
4441
4442 /// Handles semantic checking for features that are common to all attributes,
4443 /// such as checking whether a parameter was properly specified, or the
4444 /// correct number of arguments were passed, etc. Returns true if the
4445 /// attribute has been diagnosed.
4446 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
4447 bool SkipArgCountCheck = false);
4448 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
4449 bool SkipArgCountCheck = false);
4450
4451 /// Determine if type T is a valid subject for a nonnull and similar
4452 /// attributes. By default, we look through references (the behavior used by
4453 /// nonnull), but if the second parameter is true, then we treat a reference
4454 /// type as valid.
4455 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4456
4457 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4458 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
4459 const FunctionDecl *FD = nullptr);
4460 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4461 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4462 bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
4463 const Expr *E, StringRef &Str,
4464 SourceLocation *ArgLocation = nullptr);
4465 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4466 StringRef &Str,
4467 SourceLocation *ArgLocation = nullptr);
4468 llvm::Error isValidSectionSpecifier(StringRef Str);
4469 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4470 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4471 bool checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str,
4472 const StringLiteral *Literal,
4473 bool &HasDefault, bool &HasCommas,
4474 SmallVectorImpl<StringRef> &Strings);
4475 bool checkMSInheritanceAttrOnDefinition(
4476 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4477 MSInheritanceModel SemanticSpelling);
4478
4479 void CheckAlignasUnderalignment(Decl *D);
4480
4481 /// Adjust the calling convention of a method to be the ABI default if it
4482 /// wasn't specified explicitly. This handles method types formed from
4483 /// function type typedefs and typename template arguments.
4484 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4485 SourceLocation Loc);
4486
4487 // Check if there is an explicit attribute, but only look through parens.
4488 // The intent is to look for an attribute on the current declarator, but not
4489 // one that came from a typedef.
4490 bool hasExplicitCallingConv(QualType T);
4491
4492 /// Get the outermost AttributedType node that sets a calling convention.
4493 /// Valid types should not have multiple attributes with different CCs.
4494 const AttributedType *getCallingConvAttributedType(QualType T) const;
4495
4496 /// Process the attributes before creating an attributed statement. Returns
4497 /// the semantic attributes that have been processed.
4498 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
4499 SmallVectorImpl<const Attr *> &OutAttrs);
4500
4501 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
4502 ObjCMethodDecl *MethodDecl,
4503 bool IsProtocolMethodDecl);
4504
4505 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
4506 ObjCMethodDecl *Overridden,
4507 bool IsProtocolMethodDecl);
4508
4509 /// WarnExactTypedMethods - This routine issues a warning if method
4510 /// implementation declaration matches exactly that of its declaration.
4511 void WarnExactTypedMethods(ObjCMethodDecl *Method,
4512 ObjCMethodDecl *MethodDecl,
4513 bool IsProtocolMethodDecl);
4514
4515 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
4516
4517 /// CheckImplementationIvars - This routine checks if the instance variables
4518 /// listed in the implelementation match those listed in the interface.
4519 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
4520 ObjCIvarDecl **Fields, unsigned nIvars,
4521 SourceLocation Loc);
4522
4523 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4524 /// remains unimplemented in the class or category \@implementation.
4525 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4526 ObjCContainerDecl* IDecl,
4527 bool IncompleteImpl = false);
4528
4529 /// DiagnoseUnimplementedProperties - This routine warns on those properties
4530 /// which must be implemented by this implementation.
4531 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
4532 ObjCContainerDecl *CDecl,
4533 bool SynthesizeProperties);
4534
4535 /// Diagnose any null-resettable synthesized setters.
4536 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
4537
4538 /// DefaultSynthesizeProperties - This routine default synthesizes all
4539 /// properties which must be synthesized in the class's \@implementation.
4540 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
4541 ObjCInterfaceDecl *IDecl,
4542 SourceLocation AtEnd);
4543 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
4544
4545 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4546 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4547 /// declared in class 'IFace'.
4548 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
4549 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4550
4551 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4552 /// backs the property is not used in the property's accessor.
4553 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4554 const ObjCImplementationDecl *ImplD);
4555
4556 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4557 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4558 /// It also returns ivar's property on success.
4559 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4560 const ObjCPropertyDecl *&PDecl) const;
4561
4562 /// Called by ActOnProperty to handle \@property declarations in
4563 /// class extensions.
4564 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
4565 SourceLocation AtLoc,
4566 SourceLocation LParenLoc,
4567 FieldDeclarator &FD,
4568 Selector GetterSel,
4569 SourceLocation GetterNameLoc,
4570 Selector SetterSel,
4571 SourceLocation SetterNameLoc,
4572 const bool isReadWrite,
4573 unsigned &Attributes,
4574 const unsigned AttributesAsWritten,
4575 QualType T,
4576 TypeSourceInfo *TSI,
4577 tok::ObjCKeywordKind MethodImplKind);
4578
4579 /// Called by ActOnProperty and HandlePropertyInClassExtension to
4580 /// handle creating the ObjcPropertyDecl for a category or \@interface.
4581 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
4582 ObjCContainerDecl *CDecl,
4583 SourceLocation AtLoc,
4584 SourceLocation LParenLoc,
4585 FieldDeclarator &FD,
4586 Selector GetterSel,
4587 SourceLocation GetterNameLoc,
4588 Selector SetterSel,
4589 SourceLocation SetterNameLoc,
4590 const bool isReadWrite,
4591 const unsigned Attributes,
4592 const unsigned AttributesAsWritten,
4593 QualType T,
4594 TypeSourceInfo *TSI,
4595 tok::ObjCKeywordKind MethodImplKind,
4596 DeclContext *lexicalDC = nullptr);
4597
4598 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4599 /// warning) when atomic property has one but not the other user-declared
4600 /// setter or getter.
4601 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
4602 ObjCInterfaceDecl* IDecl);
4603
4604 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
4605
4606 void DiagnoseMissingDesignatedInitOverrides(
4607 const ObjCImplementationDecl *ImplD,
4608 const ObjCInterfaceDecl *IFD);
4609
4610 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
4611
4612 enum MethodMatchStrategy {
4613 MMS_loose,
4614 MMS_strict
4615 };
4616
4617 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
4618 /// true, or false, accordingly.
4619 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
4620 const ObjCMethodDecl *PrevMethod,
4621 MethodMatchStrategy strategy = MMS_strict);
4622
4623 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
4624 /// or protocol against those declared in their implementations.
4625 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
4626 const SelectorSet &ClsMap,
4627 SelectorSet &InsMapSeen,
4628 SelectorSet &ClsMapSeen,
4629 ObjCImplDecl* IMPDecl,
4630 ObjCContainerDecl* IDecl,
4631 bool &IncompleteImpl,
4632 bool ImmediateClass,
4633 bool WarnCategoryMethodImpl=false);
4634
4635 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
4636 /// category matches with those implemented in its primary class and
4637 /// warns each time an exact match is found.
4638 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
4639
4640 /// Add the given method to the list of globally-known methods.
4641 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
4642
4643 /// Returns default addr space for method qualifiers.
4644 LangAS getDefaultCXXMethodAddrSpace() const;
4645
4646private:
4647 /// AddMethodToGlobalPool - Add an instance or factory method to the global
4648 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4649 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4650
4651 /// LookupMethodInGlobalPool - Returns the instance or factory method and
4652 /// optionally warns if there are multiple signatures.
4653 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4654 bool receiverIdOrClass,
4655 bool instance);
4656
4657public:
4658 /// - Returns instance or factory methods in global method pool for
4659 /// given selector. It checks the desired kind first, if none is found, and
4660 /// parameter checkTheOther is set, it then checks the other kind. If no such
4661 /// method or only one method is found, function returns false; otherwise, it
4662 /// returns true.
4663 bool
4664 CollectMultipleMethodsInGlobalPool(Selector Sel,
4665 SmallVectorImpl<ObjCMethodDecl*>& Methods,
4666 bool InstanceFirst, bool CheckTheOther,
4667 const ObjCObjectType *TypeBound = nullptr);
4668
4669 bool
4670 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4671 SourceRange R, bool receiverIdOrClass,
4672 SmallVectorImpl<ObjCMethodDecl*>& Methods);
4673
4674 void
4675 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4676 Selector Sel, SourceRange R,
4677 bool receiverIdOrClass);
4678
4679private:
4680 /// - Returns a selector which best matches given argument list or
4681 /// nullptr if none could be found
4682 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4683 bool IsInstance,
4684 SmallVectorImpl<ObjCMethodDecl*>& Methods);
4685
4686
4687 /// Record the typo correction failure and return an empty correction.
4688 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4689 bool RecordFailure = true) {
4690 if (RecordFailure)
4691 TypoCorrectionFailures[Typo].insert(TypoLoc);
4692 return TypoCorrection();
4693 }
4694
4695public:
4696 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4697 /// unit are added to a global pool. This allows us to efficiently associate
4698 /// a selector with a method declaraation for purposes of typechecking
4699 /// messages sent to "id" (where the class of the object is unknown).
4700 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4701 AddMethodToGlobalPool(Method, impl, /*instance*/true);
4702 }
4703
4704 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4705 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4706 AddMethodToGlobalPool(Method, impl, /*instance*/false);
4707 }
4708
4709 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4710 /// pool.
4711 void AddAnyMethodToGlobalPool(Decl *D);
4712
4713 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4714 /// there are multiple signatures.
4715 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4716 bool receiverIdOrClass=false) {
4717 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4718 /*instance*/true);
4719 }
4720
4721 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4722 /// there are multiple signatures.
4723 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4724 bool receiverIdOrClass=false) {
4725 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4726 /*instance*/false);
4727 }
4728
4729 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4730 QualType ObjectType=QualType());
4731 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4732 /// implementation.
4733 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4734
4735 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4736 /// initialization.
4737 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4738 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4739
4740 //===--------------------------------------------------------------------===//
4741 // Statement Parsing Callbacks: SemaStmt.cpp.
4742public:
4743 class FullExprArg {
4744 public:
4745 FullExprArg() : E(nullptr) { }
4746 FullExprArg(Sema &actions) : E(nullptr) { }
4747
4748 ExprResult release() {
4749 return E;
4750 }
4751
4752 Expr *get() const { return E; }
4753
4754 Expr *operator->() {
4755 return E;
4756 }
4757
4758 private:
4759 // FIXME: No need to make the entire Sema class a friend when it's just
4760 // Sema::MakeFullExpr that needs access to the constructor below.
4761 friend class Sema;
4762
4763 explicit FullExprArg(Expr *expr) : E(expr) {}
4764
4765 Expr *E;
4766 };
4767
4768 FullExprArg MakeFullExpr(Expr *Arg) {
4769 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4770 }
4771 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4772 return FullExprArg(
4773 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4774 }
4775 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4776 ExprResult FE =
4777 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4778 /*DiscardedValue*/ true);
4779 return FullExprArg(FE.get());
4780 }
4781
4782 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4783 StmtResult ActOnExprStmtError();
4784
4785 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4786 bool HasLeadingEmptyMacro = false);
4787
4788 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4789 void ActOnAfterCompoundStatementLeadingPragmas();
4790 void ActOnFinishOfCompoundStmt();
4791 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4792 ArrayRef<Stmt *> Elts, bool isStmtExpr);
4793
4794 /// A RAII object to enter scope of a compound statement.
4795 class CompoundScopeRAII {
4796 public:
4797 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4798 S.ActOnStartOfCompoundStmt(IsStmtExpr);
4799 }
4800
4801 ~CompoundScopeRAII() {
4802 S.ActOnFinishOfCompoundStmt();
4803 }
4804
4805 private:
4806 Sema &S;
4807 };
4808
4809 /// An RAII helper that pops function a function scope on exit.
4810 struct FunctionScopeRAII {
4811 Sema &S;
4812 bool Active;
4813 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
4814 ~FunctionScopeRAII() {
4815 if (Active)
4816 S.PopFunctionScopeInfo();
4817 }
4818 void disable() { Active = false; }
4819 };
4820
4821 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4822 SourceLocation StartLoc,
4823 SourceLocation EndLoc);
4824 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4825 StmtResult ActOnForEachLValueExpr(Expr *E);
4826 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4827 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4828 SourceLocation DotDotDotLoc, ExprResult RHS,
4829 SourceLocation ColonLoc);
4830 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4831
4832 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4833 SourceLocation ColonLoc,
4834 Stmt *SubStmt, Scope *CurScope);
4835 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4836 SourceLocation ColonLoc, Stmt *SubStmt);
4837
4838 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
4839 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
4840 StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
4841 Stmt *SubStmt);
4842
4843 class ConditionResult;
4844
4845 StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
4846 SourceLocation LParenLoc, Stmt *InitStmt,
4847 ConditionResult Cond, SourceLocation RParenLoc,
4848 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4849 StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
4850 SourceLocation LParenLoc, Stmt *InitStmt,
4851 ConditionResult Cond, SourceLocation RParenLoc,
4852 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4853 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4854 SourceLocation LParenLoc, Stmt *InitStmt,
4855 ConditionResult Cond,
4856 SourceLocation RParenLoc);
4857 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4858 Stmt *Switch, Stmt *Body);
4859 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
4860 ConditionResult Cond, SourceLocation RParenLoc,
4861 Stmt *Body);
4862 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4863 SourceLocation WhileLoc, SourceLocation CondLParen,
4864 Expr *Cond, SourceLocation CondRParen);
4865
4866 StmtResult ActOnForStmt(SourceLocation ForLoc,
4867 SourceLocation LParenLoc,
4868 Stmt *First,
4869 ConditionResult Second,
4870 FullExprArg Third,
4871 SourceLocation RParenLoc,
4872 Stmt *Body);
4873 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4874 Expr *collection);
4875 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4876 Stmt *First, Expr *collection,
4877 SourceLocation RParenLoc);
4878 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4879
4880 enum BuildForRangeKind {
4881 /// Initial building of a for-range statement.
4882 BFRK_Build,
4883 /// Instantiation or recovery rebuild of a for-range statement. Don't
4884 /// attempt any typo-correction.
4885 BFRK_Rebuild,
4886 /// Determining whether a for-range statement could be built. Avoid any
4887 /// unnecessary or irreversible actions.
4888 BFRK_Check
4889 };
4890
4891 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4892 SourceLocation CoawaitLoc,
4893 Stmt *InitStmt,
4894 Stmt *LoopVar,
4895 SourceLocation ColonLoc, Expr *Collection,
4896 SourceLocation RParenLoc,
4897 BuildForRangeKind Kind);
4898 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4899 SourceLocation CoawaitLoc,
4900 Stmt *InitStmt,
4901 SourceLocation ColonLoc,
4902 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4903 Expr *Cond, Expr *Inc,
4904 Stmt *LoopVarDecl,
4905 SourceLocation RParenLoc,
4906 BuildForRangeKind Kind);
4907 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4908
4909 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4910 SourceLocation LabelLoc,
4911 LabelDecl *TheDecl);
4912 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4913 SourceLocation StarLoc,
4914 Expr *DestExp);
4915 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4916 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4917
4918 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4919 CapturedRegionKind Kind, unsigned NumParams);
4920 typedef std::pair<StringRef, QualType> CapturedParamNameType;
4921 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4922 CapturedRegionKind Kind,
4923 ArrayRef<CapturedParamNameType> Params,
4924 unsigned OpenMPCaptureLevel = 0);
4925 StmtResult ActOnCapturedRegionEnd(Stmt *S);
4926 void ActOnCapturedRegionError();
4927 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4928 SourceLocation Loc,
4929 unsigned NumParams);
4930
4931 struct NamedReturnInfo {
4932 const VarDecl *Candidate;
4933
4934 enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
4935 Status S;
4936
4937 bool isMoveEligible() const { return S != None; };
4938 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
4939 };
4940 enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
4941 NamedReturnInfo getNamedReturnInfo(
4942 Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
4943 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
4944 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
4945 QualType ReturnType);
4946
4947 ExprResult
4948 PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
4949 const NamedReturnInfo &NRInfo, Expr *Value,
4950 bool SupressSimplerImplicitMoves = false);
4951
4952 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4953 Scope *CurScope);
4954 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4955 bool AllowRecovery = false);
4956 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4957 NamedReturnInfo &NRInfo,
4958 bool SupressSimplerImplicitMoves);
4959
4960 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4961 bool IsVolatile, unsigned NumOutputs,
4962 unsigned NumInputs, IdentifierInfo **Names,
4963 MultiExprArg Constraints, MultiExprArg Exprs,
4964 Expr *AsmString, MultiExprArg Clobbers,
4965 unsigned NumLabels,
4966 SourceLocation RParenLoc);
4967
4968 void FillInlineAsmIdentifierInfo(Expr *Res,
4969 llvm::InlineAsmIdentifierInfo &Info);
4970 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4971 SourceLocation TemplateKWLoc,
4972 UnqualifiedId &Id,
4973 bool IsUnevaluatedContext);
4974 bool LookupInlineAsmField(StringRef Base, StringRef Member,
4975 unsigned &Offset, SourceLocation AsmLoc);
4976 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4977 SourceLocation AsmLoc);
4978 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4979 ArrayRef<Token> AsmToks,
4980 StringRef AsmString,
4981 unsigned NumOutputs, unsigned NumInputs,
4982 ArrayRef<StringRef> Constraints,
4983 ArrayRef<StringRef> Clobbers,
4984 ArrayRef<Expr*> Exprs,
4985 SourceLocation EndLoc);
4986 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4987 SourceLocation Location,
4988 bool AlwaysCreate);
4989
4990 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4991 SourceLocation StartLoc,
4992 SourceLocation IdLoc, IdentifierInfo *Id,
4993 bool Invalid = false);
4994
4995 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4996
4997 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4998 Decl *Parm, Stmt *Body);
4999
5000 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
5001
5002 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
5003 MultiStmtArg Catch, Stmt *Finally);
5004
5005 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
5006 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
5007 Scope *CurScope);
5008 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
5009 Expr *operand);
5010 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
5011 Expr *SynchExpr,
5012 Stmt *SynchBody);
5013
5014 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
5015
5016 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
5017 SourceLocation StartLoc,
5018 SourceLocation IdLoc,
5019 IdentifierInfo *Id);
5020
5021 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
5022
5023 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
5024 Decl *ExDecl, Stmt *HandlerBlock);
5025 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
5026 ArrayRef<Stmt *> Handlers);
5027
5028 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
5029 SourceLocation TryLoc, Stmt *TryBlock,
5030 Stmt *Handler);
5031 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
5032 Expr *FilterExpr,
5033 Stmt *Block);
5034 void ActOnStartSEHFinallyBlock();
5035 void ActOnAbortSEHFinallyBlock();
5036 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
5037 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
5038
5039 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
5040
5041 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
5042
5043 /// If it's a file scoped decl that must warn if not used, keep track
5044 /// of it.
5045 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
5046
5047 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
5048 /// whose result is unused, warn.
5049 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
5050 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
5051 void DiagnoseUnusedDecl(const NamedDecl *ND);
5052
5053 /// If VD is set but not otherwise used, diagnose, for a parameter or a
5054 /// variable.
5055 void DiagnoseUnusedButSetDecl(const VarDecl *VD);
5056
5057 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
5058 /// statement as a \p Body, and it is located on the same line.
5059 ///
5060 /// This helps prevent bugs due to typos, such as:
5061 /// if (condition);
5062 /// do_stuff();
5063 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5064 const Stmt *Body,
5065 unsigned DiagID);
5066
5067 /// Warn if a for/while loop statement \p S, which is followed by
5068 /// \p PossibleBody, has a suspicious null statement as a body.
5069 void DiagnoseEmptyLoopBody(const Stmt *S,
5070 const Stmt *PossibleBody);
5071
5072 /// Warn if a value is moved to itself.
5073 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
5074 SourceLocation OpLoc);
5075
5076 /// Warn if we're implicitly casting from a _Nullable pointer type to a
5077 /// _Nonnull one.
5078 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
5079 SourceLocation Loc);
5080
5081 /// Warn when implicitly casting 0 to nullptr.
5082 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
5083
5084 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
5085 return DelayedDiagnostics.push(pool);
5086 }
5087 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5088
5089 typedef ProcessingContextState ParsingClassState;
5090 ParsingClassState PushParsingClass() {
5091 ParsingClassDepth++;
5092 return DelayedDiagnostics.pushUndelayed();
5093 }
5094 void PopParsingClass(ParsingClassState state) {
5095 ParsingClassDepth--;
5096 DelayedDiagnostics.popUndelayed(state);
5097 }
5098
5099 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5100
5101 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
5102 const ObjCInterfaceDecl *UnknownObjCClass,
5103 bool ObjCPropertyAccess,
5104 bool AvoidPartialAvailabilityChecks = false,
5105 ObjCInterfaceDecl *ClassReceiver = nullptr);
5106
5107 bool makeUnavailableInSystemHeader(SourceLocation loc,
5108 UnavailableAttr::ImplicitReason reason);
5109
5110 /// Issue any -Wunguarded-availability warnings in \c FD
5111 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
5112
5113 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5114
5115 //===--------------------------------------------------------------------===//
5116 // Expression Parsing Callbacks: SemaExpr.cpp.
5117
5118 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
5119 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
5120 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
5121 bool ObjCPropertyAccess = false,
5122 bool AvoidPartialAvailabilityChecks = false,
5123 ObjCInterfaceDecl *ClassReciever = nullptr);
5124 void NoteDeletedFunction(FunctionDecl *FD);
5125 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
5126 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
5127 ObjCMethodDecl *Getter,
5128 SourceLocation Loc);
5129 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
5130 ArrayRef<Expr *> Args);
5131
5132 void PushExpressionEvaluationContext(
5133 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
5134 ExpressionEvaluationContextRecord::ExpressionKind Type =
5135 ExpressionEvaluationContextRecord::EK_Other);
5136 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
5137 void PushExpressionEvaluationContext(
5138 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
5139 ExpressionEvaluationContextRecord::ExpressionKind Type =
5140 ExpressionEvaluationContextRecord::EK_Other);
5141 void PopExpressionEvaluationContext();
5142
5143 void DiscardCleanupsInEvaluationContext();
5144
5145 ExprResult TransformToPotentiallyEvaluated(Expr *E);
5146 TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
5147 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
5148
5149 ExprResult CheckUnevaluatedOperand(Expr *E);
5150 void CheckUnusedVolatileAssignment(Expr *E);
5151
5152 ExprResult ActOnConstantExpression(ExprResult Res);
5153
5154 // Functions for marking a declaration referenced. These functions also
5155 // contain the relevant logic for marking if a reference to a function or
5156 // variable is an odr-use (in the C++11 sense). There are separate variants
5157 // for expressions referring to a decl; these exist because odr-use marking
5158 // needs to be delayed for some constant variables when we build one of the
5159 // named expressions.
5160 //
5161 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
5162 // should usually be true. This only needs to be set to false if the lack of
5163 // odr-use cannot be determined from the current context (for instance,
5164 // because the name denotes a virtual function and was written without an
5165 // explicit nested-name-specifier).
5166 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
5167 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
5168 bool MightBeOdrUse = true);
5169 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
5170 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
5171 void MarkMemberReferenced(MemberExpr *E);
5172 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
5173 void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
5174 unsigned CapturingScopeIndex);
5175
5176 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
5177 void CleanupVarDeclMarking();
5178
5179 enum TryCaptureKind {
5180 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
5181 };
5182
5183 /// Try to capture the given variable.
5184 ///
5185 /// \param Var The variable to capture.
5186 ///
5187 /// \param Loc The location at which the capture occurs.
5188 ///
5189 /// \param Kind The kind of capture, which may be implicit (for either a
5190 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
5191 ///
5192 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
5193 /// an explicit lambda capture.
5194 ///
5195 /// \param BuildAndDiagnose Whether we are actually supposed to add the
5196 /// captures or diagnose errors. If false, this routine merely check whether
5197 /// the capture can occur without performing the capture itself or complaining
5198 /// if the variable cannot be captured.
5199 ///
5200 /// \param CaptureType Will be set to the type of the field used to capture
5201 /// this variable in the innermost block or lambda. Only valid when the
5202 /// variable can be captured.
5203 ///
5204 /// \param DeclRefType Will be set to the type of a reference to the capture
5205 /// from within the current scope. Only valid when the variable can be
5206 /// captured.
5207 ///
5208 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5209 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5210 /// This is useful when enclosing lambdas must speculatively capture
5211 /// variables that may or may not be used in certain specializations of
5212 /// a nested generic lambda.
5213 ///
5214 /// \returns true if an error occurred (i.e., the variable cannot be
5215 /// captured) and false if the capture succeeded.
5216 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
5217 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
5218 QualType &CaptureType,
5219 QualType &DeclRefType,
5220 const unsigned *const FunctionScopeIndexToStopAt);
5221
5222 /// Try to capture the given variable.
5223 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
5224 TryCaptureKind Kind = TryCapture_Implicit,
5225 SourceLocation EllipsisLoc = SourceLocation());
5226
5227 /// Checks if the variable must be captured.
5228 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
5229
5230 /// Given a variable, determine the type that a reference to that
5231 /// variable will have in the given scope.
5232 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
5233
5234 /// Mark all of the declarations referenced within a particular AST node as
5235 /// referenced. Used when template instantiation instantiates a non-dependent
5236 /// type -- entities referenced by the type are now referenced.
5237 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
5238 void MarkDeclarationsReferencedInExpr(Expr *E,
5239 bool SkipLocalVariables = false,
5240 ArrayRef<const Expr *> StopAt = None);
5241
5242 /// Try to recover by turning the given expression into a
5243 /// call. Returns true if recovery was attempted or an error was
5244 /// emitted; this may also leave the ExprResult invalid.
5245 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
5246 bool ForceComplain = false,
5247 bool (*IsPlausibleResult)(QualType) = nullptr);
5248
5249 /// Figure out if an expression could be turned into a call.
5250 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
5251 UnresolvedSetImpl &NonTemplateOverloads);
5252
5253 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
5254 /// conversion.
5255 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
5256
5257 /// Conditionally issue a diagnostic based on the statements's reachability
5258 /// analysis.
5259 ///
5260 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
5261 /// the function body is parsed, and then do a basic reachability analysis to
5262 /// determine if the statement is reachable. If it is unreachable, the
5263 /// diagnostic will not be emitted.
5264 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
5265 const PartialDiagnostic &PD);
5266
5267 /// Conditionally issue a diagnostic based on the current
5268 /// evaluation context.
5269 ///
5270 /// \param Statement If Statement is non-null, delay reporting the
5271 /// diagnostic until the function body is parsed, and then do a basic
5272 /// reachability analysis to determine if the statement is reachable.
5273 /// If it is unreachable, the diagnostic will not be emitted.
5274 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
5275 const PartialDiagnostic &PD);
5276 /// Similar, but diagnostic is only produced if all the specified statements
5277 /// are reachable.
5278 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
5279 const PartialDiagnostic &PD);
5280
5281 // Primary Expressions.
5282 SourceRange getExprRange(Expr *E) const;
5283
5284 ExprResult ActOnIdExpression(
5285 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5286 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
5287 CorrectionCandidateCallback *CCC = nullptr,
5288 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
5289
5290 ExprResult ActOnMutableAgnosticIdExpression(Scope *S, CXXScopeSpec &SS,
5291 UnqualifiedId &Id);
5292
5293 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
5294 TemplateArgumentListInfo &Buffer,
5295 DeclarationNameInfo &NameInfo,
5296 const TemplateArgumentListInfo *&TemplateArgs);
5297
5298 bool DiagnoseDependentMemberLookup(LookupResult &R);
5299
5300 bool
5301 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
5302 CorrectionCandidateCallback &CCC,
5303 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
5304 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
5305
5306 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
5307 IdentifierInfo *II);
5308 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
5309
5310 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
5311 IdentifierInfo *II,
5312 bool AllowBuiltinCreation=false);
5313
5314 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
5315 SourceLocation TemplateKWLoc,
5316 const DeclarationNameInfo &NameInfo,
5317 bool isAddressOfOperand,
5318 const TemplateArgumentListInfo *TemplateArgs);
5319
5320 /// If \p D cannot be odr-used in the current expression evaluation context,
5321 /// return a reason explaining why. Otherwise, return NOUR_None.
5322 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
5323
5324 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5325 SourceLocation Loc,
5326 const CXXScopeSpec *SS = nullptr);
5327 DeclRefExpr *
5328 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5329 const DeclarationNameInfo &NameInfo,
5330 const CXXScopeSpec *SS = nullptr,
5331 NamedDecl *FoundD = nullptr,
5332 SourceLocation TemplateKWLoc = SourceLocation(),
5333 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5334 DeclRefExpr *
5335 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5336 const DeclarationNameInfo &NameInfo,
5337 NestedNameSpecifierLoc NNS,
5338 NamedDecl *FoundD = nullptr,
5339 SourceLocation TemplateKWLoc = SourceLocation(),
5340 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5341
5342 ExprResult
5343 BuildAnonymousStructUnionMemberReference(
5344 const CXXScopeSpec &SS,
5345 SourceLocation nameLoc,
5346 IndirectFieldDecl *indirectField,
5347 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
5348 Expr *baseObjectExpr = nullptr,
5349 SourceLocation opLoc = SourceLocation());
5350
5351 ExprResult BuildPossibleImplicitMemberExpr(
5352 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
5353 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
5354 UnresolvedLookupExpr *AsULE = nullptr);
5355 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
5356 SourceLocation TemplateKWLoc,
5357 LookupResult &R,
5358 const TemplateArgumentListInfo *TemplateArgs,
5359 bool IsDefiniteInstance,
5360 const Scope *S);
5361 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
5362 const LookupResult &R,
5363 bool HasTrailingLParen);
5364
5365 ExprResult
5366 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
5367 const DeclarationNameInfo &NameInfo,
5368 bool IsAddressOfOperand, const Scope *S,
5369 TypeSourceInfo **RecoveryTSI = nullptr);
5370
5371 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
5372 SourceLocation TemplateKWLoc,
5373 const DeclarationNameInfo &NameInfo,
5374 const TemplateArgumentListInfo *TemplateArgs);
5375
5376 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
5377 LookupResult &R,
5378 bool NeedsADL,
5379 bool AcceptInvalidDecl = false);
5380 ExprResult BuildDeclarationNameExpr(
5381 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
5382 NamedDecl *FoundD = nullptr,
5383 const TemplateArgumentListInfo *TemplateArgs = nullptr,
5384 bool AcceptInvalidDecl = false);
5385
5386 ExprResult BuildLiteralOperatorCall(LookupResult &R,
5387 DeclarationNameInfo &SuffixInfo,
5388 ArrayRef<Expr *> Args,
5389 SourceLocation LitEndLoc,
5390 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
5391
5392 ExprResult BuildPredefinedExpr(SourceLocation Loc,
5393 PredefinedExpr::IdentKind IK);
5394 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
5395 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
5396
5397 ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5398 SourceLocation LParen,
5399 SourceLocation RParen,
5400 TypeSourceInfo *TSI);
5401 ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5402 SourceLocation LParen,
5403 SourceLocation RParen,
5404 ParsedType ParsedTy);
5405
5406 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
5407
5408 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
5409 ExprResult ActOnCharacterConstant(const Token &Tok,
5410 Scope *UDLScope = nullptr);
5411 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
5412 ExprResult ActOnParenListExpr(SourceLocation L,
5413 SourceLocation R,
5414 MultiExprArg Val);
5415
5416 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
5417 /// fragments (e.g. "foo" "bar" L"baz").
5418 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
5419 Scope *UDLScope = nullptr);
5420
5421 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
5422 SourceLocation DefaultLoc,
5423 SourceLocation RParenLoc,
5424 Expr *ControllingExpr,
5425 ArrayRef<ParsedType> ArgTypes,
5426 ArrayRef<Expr *> ArgExprs);
5427 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
5428 SourceLocation DefaultLoc,
5429 SourceLocation RParenLoc,
5430 Expr *ControllingExpr,
5431 ArrayRef<TypeSourceInfo *> Types,
5432 ArrayRef<Expr *> Exprs);
5433
5434 // Binary/Unary Operators. 'Tok' is the token for the operator.
5435 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
5436 Expr *InputExpr);
5437 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5438 UnaryOperatorKind Opc, Expr *Input);
5439 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5440 tok::TokenKind Op, Expr *Input);
5441
5442 bool isQualifiedMemberAccess(Expr *E);
5443 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
5444
5445 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
5446 SourceLocation OpLoc,
5447 UnaryExprOrTypeTrait ExprKind,
5448 SourceRange R);
5449 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
5450 UnaryExprOrTypeTrait ExprKind);
5451 ExprResult
5452 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
5453 UnaryExprOrTypeTrait ExprKind,
5454 bool IsType, void *TyOrEx,
5455 SourceRange ArgRange);
5456
5457 ExprResult CheckPlaceholderExpr(Expr *E);
5458 bool CheckVecStepExpr(Expr *E);
5459
5460 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
5461 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
5462 SourceRange ExprRange,
5463 UnaryExprOrTypeTrait ExprKind);
5464 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
5465 SourceLocation OpLoc,
5466 IdentifierInfo &Name,
5467 SourceLocation NameLoc,
5468 SourceLocation RParenLoc);
5469 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
5470 tok::TokenKind Kind, Expr *Input);
5471
5472 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
5473 MultiExprArg ArgExprs,
5474 SourceLocation RLoc);
5475 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5476 Expr *Idx, SourceLocation RLoc);
5477
5478 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5479 Expr *ColumnIdx,
5480 SourceLocation RBLoc);
5481
5482 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5483 Expr *LowerBound,
5484 SourceLocation ColonLocFirst,
5485 SourceLocation ColonLocSecond,
5486 Expr *Length, Expr *Stride,
5487 SourceLocation RBLoc);
5488 ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5489 SourceLocation RParenLoc,
5490 ArrayRef<Expr *> Dims,
5491 ArrayRef<SourceRange> Brackets);
5492
5493 /// Data structure for iterator expression.
5494 struct OMPIteratorData {
5495 IdentifierInfo *DeclIdent = nullptr;
5496 SourceLocation DeclIdentLoc;
5497 ParsedType Type;
5498 OMPIteratorExpr::IteratorRange Range;
5499 SourceLocation AssignLoc;
5500 SourceLocation ColonLoc;
5501 SourceLocation SecColonLoc;
5502 };
5503
5504 ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5505 SourceLocation LLoc, SourceLocation RLoc,
5506 ArrayRef<OMPIteratorData> Data);
5507
5508 // This struct is for use by ActOnMemberAccess to allow
5509 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
5510 // changing the access operator from a '.' to a '->' (to see if that is the
5511 // change needed to fix an error about an unknown member, e.g. when the class
5512 // defines a custom operator->).
5513 struct ActOnMemberAccessExtraArgs {
5514 Scope *S;
5515 UnqualifiedId &Id;
5516 Decl *ObjCImpDecl;
5517 };
5518
5519 ExprResult BuildMemberReferenceExpr(
5520 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
5521 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5522 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
5523 const TemplateArgumentListInfo *TemplateArgs,
5524 const Scope *S,
5525 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5526
5527 ExprResult
5528 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
5529 bool IsArrow, const CXXScopeSpec &SS,
5530 SourceLocation TemplateKWLoc,
5531 NamedDecl *FirstQualifierInScope, LookupResult &R,
5532 const TemplateArgumentListInfo *TemplateArgs,
5533 const Scope *S,
5534 bool SuppressQualifierCheck = false,
5535 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5536
5537 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
5538 SourceLocation OpLoc,
5539 const CXXScopeSpec &SS, FieldDecl *Field,
5540 DeclAccessPair FoundDecl,
5541 const DeclarationNameInfo &MemberNameInfo);
5542
5543 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
5544
5545 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
5546 const CXXScopeSpec &SS,
5547 const LookupResult &R);
5548
5549 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
5550 bool IsArrow, SourceLocation OpLoc,
5551 const CXXScopeSpec &SS,
5552 SourceLocation TemplateKWLoc,
5553 NamedDecl *FirstQualifierInScope,
5554 const DeclarationNameInfo &NameInfo,
5555 const TemplateArgumentListInfo *TemplateArgs);
5556
5557 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
5558 SourceLocation OpLoc,
5559 tok::TokenKind OpKind,
5560 CXXScopeSpec &SS,
5561 SourceLocation TemplateKWLoc,
5562 UnqualifiedId &Member,
5563 Decl *ObjCImpDecl);
5564
5565 MemberExpr *
5566 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5567 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
5568 ValueDecl *Member, DeclAccessPair FoundDecl,
5569 bool HadMultipleCandidates,
5570 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5571 ExprValueKind VK, ExprObjectKind OK,
5572 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5573 MemberExpr *
5574 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5575 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
5576 ValueDecl *Member, DeclAccessPair FoundDecl,
5577 bool HadMultipleCandidates,
5578 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5579 ExprValueKind VK, ExprObjectKind OK,
5580 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5581
5582 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
5583 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5584 FunctionDecl *FDecl,
5585 const FunctionProtoType *Proto,
5586 ArrayRef<Expr *> Args,
5587 SourceLocation RParenLoc,
5588 bool ExecConfig = false);
5589 void CheckStaticArrayArgument(SourceLocation CallLoc,
5590 ParmVarDecl *Param,
5591 const Expr *ArgExpr);
5592
5593 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5594 /// This provides the location of the left/right parens and a list of comma
5595 /// locations.
5596 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5597 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5598 Expr *ExecConfig = nullptr);
5599 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5600 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5601 Expr *ExecConfig = nullptr,
5602 bool IsExecConfig = false,
5603 bool AllowRecovery = false);
5604 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
5605 MultiExprArg CallArgs);
5606 enum class AtomicArgumentOrder { API, AST };
5607 ExprResult
5608 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5609 SourceLocation RParenLoc, MultiExprArg Args,
5610 AtomicExpr::AtomicOp Op,
5611 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
5612 ExprResult
5613 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
5614 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
5615 Expr *Config = nullptr, bool IsExecConfig = false,
5616 ADLCallKind UsesADL = ADLCallKind::NotADL);
5617
5618 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5619 MultiExprArg ExecConfig,
5620 SourceLocation GGGLoc);
5621
5622 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5623 Declarator &D, ParsedType &Ty,
5624 SourceLocation RParenLoc, Expr *CastExpr);
5625 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
5626 TypeSourceInfo *Ty,
5627 SourceLocation RParenLoc,
5628 Expr *Op);
5629 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
5630
5631 /// Build an altivec or OpenCL literal.
5632 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
5633 SourceLocation RParenLoc, Expr *E,
5634 TypeSourceInfo *TInfo);
5635
5636 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
5637
5638 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
5639 ParsedType Ty,
5640 SourceLocation RParenLoc,
5641 Expr *InitExpr);
5642
5643 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
5644 TypeSourceInfo *TInfo,
5645 SourceLocation RParenLoc,
5646 Expr *LiteralExpr);
5647
5648 ExprResult ActOnInitList(SourceLocation LBraceLoc,
5649 MultiExprArg InitArgList,
5650 SourceLocation RBraceLoc);
5651
5652 ExprResult BuildInitList(SourceLocation LBraceLoc,
5653 MultiExprArg InitArgList,
5654 SourceLocation RBraceLoc);
5655
5656 ExprResult ActOnDesignatedInitializer(Designation &Desig,
5657 SourceLocation EqualOrColonLoc,
5658 bool GNUSyntax,
5659 ExprResult Init);
5660
5661private:
5662 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
5663
5664public:
5665 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
5666 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
5667 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
5668 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
5669 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
5670 Expr *LHSExpr, Expr *RHSExpr);
5671 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
5672 UnresolvedSetImpl &Functions);
5673
5674 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
5675
5676 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
5677 /// in the case of a the GNU conditional expr extension.
5678 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
5679 SourceLocation ColonLoc,
5680 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
5681
5682 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5683 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
5684 LabelDecl *TheDecl);
5685
5686 void ActOnStartStmtExpr();
5687 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
5688 SourceLocation RPLoc);
5689 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
5690 SourceLocation RPLoc, unsigned TemplateDepth);
5691 // Handle the final expression in a statement expression.
5692 ExprResult ActOnStmtExprResult(ExprResult E);
5693 void ActOnStmtExprError();
5694
5695 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
5696 struct OffsetOfComponent {
5697 SourceLocation LocStart, LocEnd;
5698 bool isBrackets; // true if [expr], false if .ident
5699 union {
5700 IdentifierInfo *IdentInfo;
5701 Expr *E;
5702 } U;
5703 };
5704
5705 /// __builtin_offsetof(type, a.b[123][456].c)
5706 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
5707 TypeSourceInfo *TInfo,
5708 ArrayRef<OffsetOfComponent> Components,
5709 SourceLocation RParenLoc);
5710 ExprResult ActOnBuiltinOffsetOf(Scope *S,
5711 SourceLocation BuiltinLoc,
5712 SourceLocation TypeLoc,
5713 ParsedType ParsedArgTy,
5714 ArrayRef<OffsetOfComponent> Components,
5715 SourceLocation RParenLoc);
5716
5717 // __builtin_choose_expr(constExpr, expr1, expr2)
5718 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
5719 Expr *CondExpr, Expr *LHSExpr,
5720 Expr *RHSExpr, SourceLocation RPLoc);
5721
5722 // __builtin_va_arg(expr, type)
5723 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
5724 SourceLocation RPLoc);
5725 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
5726 TypeSourceInfo *TInfo, SourceLocation RPLoc);
5727
5728 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
5729 // __builtin_COLUMN(), __builtin_source_location()
5730 ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
5731 SourceLocation BuiltinLoc,
5732 SourceLocation RPLoc);
5733
5734 // Build a potentially resolved SourceLocExpr.
5735 ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
5736 QualType ResultTy, SourceLocation BuiltinLoc,
5737 SourceLocation RPLoc,
5738 DeclContext *ParentContext);
5739
5740 // __null
5741 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
5742
5743 bool CheckCaseExpression(Expr *E);
5744
5745 /// Describes the result of an "if-exists" condition check.
5746 enum IfExistsResult {
5747 /// The symbol exists.
5748 IER_Exists,
5749
5750 /// The symbol does not exist.
5751 IER_DoesNotExist,
5752
5753 /// The name is a dependent name, so the results will differ
5754 /// from one instantiation to the next.
5755 IER_Dependent,
5756
5757 /// An error occurred.
5758 IER_Error
5759 };
5760
5761 IfExistsResult
5762 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
5763 const DeclarationNameInfo &TargetNameInfo);
5764
5765 IfExistsResult
5766 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5767 bool IsIfExists, CXXScopeSpec &SS,
5768 UnqualifiedId &Name);
5769
5770 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
5771 bool IsIfExists,
5772 NestedNameSpecifierLoc QualifierLoc,
5773 DeclarationNameInfo NameInfo,
5774 Stmt *Nested);
5775 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
5776 bool IsIfExists,
5777 CXXScopeSpec &SS, UnqualifiedId &Name,
5778 Stmt *Nested);
5779
5780 //===------------------------- "Block" Extension ------------------------===//
5781
5782 /// ActOnBlockStart - This callback is invoked when a block literal is
5783 /// started.
5784 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
5785
5786 /// ActOnBlockArguments - This callback allows processing of block arguments.
5787 /// If there are no arguments, this is still invoked.
5788 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
5789 Scope *CurScope);
5790
5791 /// ActOnBlockError - If there is an error parsing a block, this callback
5792 /// is invoked to pop the information about the block from the action impl.
5793 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
5794
5795 /// ActOnBlockStmtExpr - This is called when the body of a block statement
5796 /// literal was successfully completed. ^(int x){...}
5797 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
5798 Scope *CurScope);
5799
5800 //===---------------------------- Clang Extensions ----------------------===//
5801
5802 /// __builtin_convertvector(...)
5803 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5804 SourceLocation BuiltinLoc,
5805 SourceLocation RParenLoc);
5806
5807 //===---------------------------- OpenCL Features -----------------------===//
5808
5809 /// __builtin_astype(...)
5810 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5811 SourceLocation BuiltinLoc,
5812 SourceLocation RParenLoc);
5813 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
5814 SourceLocation BuiltinLoc,
5815 SourceLocation RParenLoc);
5816
5817 //===---------------------------- C++ Features --------------------------===//
5818
5819 // Act on C++ namespaces
5820 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5821 SourceLocation NamespaceLoc,
5822 SourceLocation IdentLoc, IdentifierInfo *Ident,
5823 SourceLocation LBrace,
5824 const ParsedAttributesView &AttrList,
5825 UsingDirectiveDecl *&UsingDecl);
5826 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5827
5828 NamespaceDecl *getStdNamespace() const;
5829 NamespaceDecl *getOrCreateStdNamespace();
5830
5831 NamespaceDecl *lookupStdExperimentalNamespace();
5832 NamespaceDecl *getCachedCoroNamespace() { return CoroTraitsNamespaceCache; }
5833
5834 CXXRecordDecl *getStdBadAlloc() const;
5835 EnumDecl *getStdAlignValT() const;
5836
5837private:
5838 // A cache representing if we've fully checked the various comparison category
5839 // types stored in ASTContext. The bit-index corresponds to the integer value
5840 // of a ComparisonCategoryType enumerator.
5841 llvm::SmallBitVector FullyCheckedComparisonCategories;
5842
5843 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5844 CXXScopeSpec &SS,
5845 ParsedType TemplateTypeTy,
5846 IdentifierInfo *MemberOrBase);
5847
5848public:
5849 enum class ComparisonCategoryUsage {
5850 /// The '<=>' operator was used in an expression and a builtin operator
5851 /// was selected.
5852 OperatorInExpression,
5853 /// A defaulted 'operator<=>' needed the comparison category. This
5854 /// typically only applies to 'std::strong_ordering', due to the implicit
5855 /// fallback return value.
5856 DefaultedOperator,
5857 };
5858
5859 /// Lookup the specified comparison category types in the standard
5860 /// library, an check the VarDecls possibly returned by the operator<=>
5861 /// builtins for that type.
5862 ///
5863 /// \return The type of the comparison category type corresponding to the
5864 /// specified Kind, or a null type if an error occurs
5865 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5866 SourceLocation Loc,
5867 ComparisonCategoryUsage Usage);
5868
5869 /// Tests whether Ty is an instance of std::initializer_list and, if
5870 /// it is and Element is not NULL, assigns the element type to Element.
5871 bool isStdInitializerList(QualType Ty, QualType *Element);
5872
5873 /// Looks for the std::initializer_list template and instantiates it
5874 /// with Element, or emits an error if it's not found.
5875 ///
5876 /// \returns The instantiated template, or null on error.
5877 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5878
5879 /// Determine whether Ctor is an initializer-list constructor, as
5880 /// defined in [dcl.init.list]p2.
5881 bool isInitListConstructor(const FunctionDecl *Ctor);
5882
5883 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5884 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5885 SourceLocation IdentLoc,
5886 IdentifierInfo *NamespcName,
5887 const ParsedAttributesView &AttrList);
5888
5889 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5890
5891 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
5892 SourceLocation NamespaceLoc,
5893 SourceLocation AliasLoc,
5894 IdentifierInfo *Alias,
5895 CXXScopeSpec &SS,
5896 SourceLocation IdentLoc,
5897 IdentifierInfo *Ident);
5898
5899 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5900 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5901 bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
5902 const LookupResult &PreviousDecls,
5903 UsingShadowDecl *&PrevShadow);
5904 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
5905 NamedDecl *Target,
5906 UsingShadowDecl *PrevDecl);
5907
5908 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5909 bool HasTypenameKeyword,
5910 const CXXScopeSpec &SS,
5911 SourceLocation NameLoc,
5912 const LookupResult &Previous);
5913 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5914 const CXXScopeSpec &SS,
5915 const DeclarationNameInfo &NameInfo,
5916 SourceLocation NameLoc,
5917 const LookupResult *R = nullptr,
5918 const UsingDecl *UD = nullptr);
5919
5920 NamedDecl *BuildUsingDeclaration(
5921 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5922 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5923 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5924 const ParsedAttributesView &AttrList, bool IsInstantiation,
5925 bool IsUsingIfExists);
5926 NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
5927 SourceLocation UsingLoc,
5928 SourceLocation EnumLoc,
5929 SourceLocation NameLoc, EnumDecl *ED);
5930 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5931 ArrayRef<NamedDecl *> Expansions);
5932
5933 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5934
5935 /// Given a derived-class using shadow declaration for a constructor and the
5936 /// correspnding base class constructor, find or create the implicit
5937 /// synthesized derived class constructor to use for this initialization.
5938 CXXConstructorDecl *
5939 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5940 ConstructorUsingShadowDecl *DerivedShadow);
5941
5942 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5943 SourceLocation UsingLoc,
5944 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5945 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5946 const ParsedAttributesView &AttrList);
5947 Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
5948 SourceLocation UsingLoc,
5949 SourceLocation EnumLoc, const DeclSpec &);
5950 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5951 MultiTemplateParamsArg TemplateParams,
5952 SourceLocation UsingLoc, UnqualifiedId &Name,
5953 const ParsedAttributesView &AttrList,
5954 TypeResult Type, Decl *DeclFromDeclSpec);
5955
5956 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5957 /// including handling of its default argument expressions.
5958 ///
5959 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5960 ExprResult
5961 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5962 NamedDecl *FoundDecl,
5963 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5964 bool HadMultipleCandidates, bool IsListInitialization,
5965 bool IsStdInitListInitialization,
5966 bool RequiresZeroInit, unsigned ConstructKind,
5967 SourceRange ParenRange);
5968
5969 /// Build a CXXConstructExpr whose constructor has already been resolved if
5970 /// it denotes an inherited constructor.
5971 ExprResult
5972 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5973 CXXConstructorDecl *Constructor, bool Elidable,
5974 MultiExprArg Exprs,
5975 bool HadMultipleCandidates, bool IsListInitialization,
5976 bool IsStdInitListInitialization,
5977 bool RequiresZeroInit, unsigned ConstructKind,
5978 SourceRange ParenRange);
5979
5980 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5981 // the constructor can be elidable?
5982 ExprResult
5983 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5984 NamedDecl *FoundDecl,
5985 CXXConstructorDecl *Constructor, bool Elidable,
5986 MultiExprArg Exprs, bool HadMultipleCandidates,
5987 bool IsListInitialization,
5988 bool IsStdInitListInitialization, bool RequiresZeroInit,
5989 unsigned ConstructKind, SourceRange ParenRange);
5990
5991 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5992
5993
5994 /// Instantiate or parse a C++ default argument expression as necessary.
5995 /// Return true on error.
5996 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5997 ParmVarDecl *Param);
5998
5999 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
6000 /// the default expr if needed.
6001 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
6002 FunctionDecl *FD,
6003 ParmVarDecl *Param);
6004
6005 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
6006 /// constructed variable.
6007 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
6008
6009 /// Helper class that collects exception specifications for
6010 /// implicitly-declared special member functions.
6011 class ImplicitExceptionSpecification {
6012 // Pointer to allow copying
6013 Sema *Self;
6014 // We order exception specifications thus:
6015 // noexcept is the most restrictive, but is only used in C++11.
6016 // throw() comes next.
6017 // Then a throw(collected exceptions)
6018 // Finally no specification, which is expressed as noexcept(false).
6019 // throw(...) is used instead if any called function uses it.
6020 ExceptionSpecificationType ComputedEST;
6021 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
6022 SmallVector<QualType, 4> Exceptions;
6023
6024 void ClearExceptions() {
6025 ExceptionsSeen.clear();
6026 Exceptions.clear();
6027 }
6028
6029 public:
6030 explicit ImplicitExceptionSpecification(Sema &Self)
6031 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
6032 if (!Self.getLangOpts().CPlusPlus11)
6033 ComputedEST = EST_DynamicNone;
6034 }
6035
6036 /// Get the computed exception specification type.
6037 ExceptionSpecificationType getExceptionSpecType() const {
6038 assert(!isComputedNoexcept(ComputedEST) &&(static_cast <bool> (!isComputedNoexcept(ComputedEST) &&
"noexcept(expr) should not be a possible result") ? void (0)
: __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "clang/include/clang/Sema/Sema.h", 6039, __extension__ __PRETTY_FUNCTION__
))
6039 "noexcept(expr) should not be a possible result")(static_cast <bool> (!isComputedNoexcept(ComputedEST) &&
"noexcept(expr) should not be a possible result") ? void (0)
: __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "clang/include/clang/Sema/Sema.h", 6039, __extension__ __PRETTY_FUNCTION__
))
;
6040 return ComputedEST;
6041 }
6042
6043 /// The number of exceptions in the exception specification.
6044 unsigned size() const { return Exceptions.size(); }
6045
6046 /// The set of exceptions in the exception specification.
6047 const QualType *data() const { return Exceptions.data(); }
6048
6049 /// Integrate another called method into the collected data.
6050 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
6051
6052 /// Integrate an invoked expression into the collected data.
6053 void CalledExpr(Expr *E) { CalledStmt(E); }
6054
6055 /// Integrate an invoked statement into the collected data.
6056 void CalledStmt(Stmt *S);
6057
6058 /// Overwrite an EPI's exception specification with this
6059 /// computed exception specification.
6060 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
6061 FunctionProtoType::ExceptionSpecInfo ESI;
6062 ESI.Type = getExceptionSpecType();
6063 if (ESI.Type == EST_Dynamic) {
6064 ESI.Exceptions = Exceptions;
6065 } else if (ESI.Type == EST_None) {
6066 /// C++11 [except.spec]p14:
6067 /// The exception-specification is noexcept(false) if the set of
6068 /// potential exceptions of the special member function contains "any"
6069 ESI.Type = EST_NoexceptFalse;
6070 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
6071 tok::kw_false).get();
6072 }
6073 return ESI;
6074 }
6075 };
6076
6077 /// Evaluate the implicit exception specification for a defaulted
6078 /// special member function.
6079 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
6080
6081 /// Check the given noexcept-specifier, convert its expression, and compute
6082 /// the appropriate ExceptionSpecificationType.
6083 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6084 ExceptionSpecificationType &EST);
6085
6086 /// Check the given exception-specification and update the
6087 /// exception specification information with the results.
6088 void checkExceptionSpecification(bool IsTopLevel,
6089 ExceptionSpecificationType EST,
6090 ArrayRef<ParsedType> DynamicExceptions,
6091 ArrayRef<SourceRange> DynamicExceptionRanges,
6092 Expr *NoexceptExpr,
6093 SmallVectorImpl<QualType> &Exceptions,
6094 FunctionProtoType::ExceptionSpecInfo &ESI);
6095
6096 /// Determine if we're in a case where we need to (incorrectly) eagerly
6097 /// parse an exception specification to work around a libstdc++ bug.
6098 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6099
6100 /// Add an exception-specification to the given member function
6101 /// (or member function template). The exception-specification was parsed
6102 /// after the method itself was declared.
6103 void actOnDelayedExceptionSpecification(Decl *Method,
6104 ExceptionSpecificationType EST,
6105 SourceRange SpecificationRange,
6106 ArrayRef<ParsedType> DynamicExceptions,
6107 ArrayRef<SourceRange> DynamicExceptionRanges,
6108 Expr *NoexceptExpr);
6109
6110 class InheritedConstructorInfo;
6111
6112 /// Determine if a special member function should have a deleted
6113 /// definition when it is defaulted.
6114 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6115 InheritedConstructorInfo *ICI = nullptr,
6116 bool Diagnose = false);
6117
6118 /// Produce notes explaining why a defaulted function was defined as deleted.
6119 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
6120
6121 /// Declare the implicit default constructor for the given class.
6122 ///
6123 /// \param ClassDecl The class declaration into which the implicit
6124 /// default constructor will be added.
6125 ///
6126 /// \returns The implicitly-declared default constructor.
6127 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
6128 CXXRecordDecl *ClassDecl);
6129
6130 /// DefineImplicitDefaultConstructor - Checks for feasibility of
6131 /// defining this constructor as the default constructor.
6132 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6133 CXXConstructorDecl *Constructor);
6134
6135 /// Declare the implicit destructor for the given class.
6136 ///
6137 /// \param ClassDecl The class declaration into which the implicit
6138 /// destructor will be added.
6139 ///
6140 /// \returns The implicitly-declared destructor.
6141 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
6142
6143 /// DefineImplicitDestructor - Checks for feasibility of
6144 /// defining this destructor as the default destructor.
6145 void DefineImplicitDestructor(SourceLocation CurrentLocation,
6146 CXXDestructorDecl *Destructor);
6147
6148 /// Build an exception spec for destructors that don't have one.
6149 ///
6150 /// C++11 says that user-defined destructors with no exception spec get one
6151 /// that looks as if the destructor was implicitly declared.
6152 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
6153
6154 /// Define the specified inheriting constructor.
6155 void DefineInheritingConstructor(SourceLocation UseLoc,
6156 CXXConstructorDecl *Constructor);
6157
6158 /// Declare the implicit copy constructor for the given class.
6159 ///
6160 /// \param ClassDecl The class declaration into which the implicit
6161 /// copy constructor will be added.
6162 ///
6163 /// \returns The implicitly-declared copy constructor.
6164 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
6165
6166 /// DefineImplicitCopyConstructor - Checks for feasibility of
6167 /// defining this constructor as the copy constructor.
6168 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6169 CXXConstructorDecl *Constructor);
6170
6171 /// Declare the implicit move constructor for the given class.
6172 ///
6173 /// \param ClassDecl The Class declaration into which the implicit
6174 /// move constructor will be added.
6175 ///
6176 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
6177 /// declared.
6178 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
6179
6180 /// DefineImplicitMoveConstructor - Checks for feasibility of
6181 /// defining this constructor as the move constructor.
6182 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
6183 CXXConstructorDecl *Constructor);
6184
6185 /// Declare the implicit copy assignment operator for the given class.
6186 ///
6187 /// \param ClassDecl The class declaration into which the implicit
6188 /// copy assignment operator will be added.
6189 ///
6190 /// \returns The implicitly-declared copy assignment operator.
6191 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
6192
6193 /// Defines an implicitly-declared copy assignment operator.
6194 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6195 CXXMethodDecl *MethodDecl);
6196
6197 /// Declare the implicit move assignment operator for the given class.
6198 ///
6199 /// \param ClassDecl The Class declaration into which the implicit
6200 /// move assignment operator will be added.
6201 ///
6202 /// \returns The implicitly-declared move assignment operator, or NULL if it
6203 /// wasn't declared.
6204 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
6205
6206 /// Defines an implicitly-declared move assignment operator.
6207 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
6208 CXXMethodDecl *MethodDecl);
6209
6210 /// Force the declaration of any implicitly-declared members of this
6211 /// class.
6212 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
6213
6214 /// Check a completed declaration of an implicit special member.
6215 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
6216
6217 /// Determine whether the given function is an implicitly-deleted
6218 /// special member function.
6219 bool isImplicitlyDeleted(FunctionDecl *FD);
6220
6221 /// Check whether 'this' shows up in the type of a static member
6222 /// function after the (naturally empty) cv-qualifier-seq would be.
6223 ///
6224 /// \returns true if an error occurred.
6225 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
6226
6227 /// Whether this' shows up in the exception specification of a static
6228 /// member function.
6229 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
6230
6231 /// Check whether 'this' shows up in the attributes of the given
6232 /// static member function.
6233 ///
6234 /// \returns true if an error occurred.
6235 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
6236
6237 /// MaybeBindToTemporary - If the passed in expression has a record type with
6238 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
6239 /// it simply returns the passed in expression.
6240 ExprResult MaybeBindToTemporary(Expr *E);
6241
6242 /// Wrap the expression in a ConstantExpr if it is a potential immediate
6243 /// invocation.
6244 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
6245
6246 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
6247 QualType DeclInitType, MultiExprArg ArgsPtr,
6248 SourceLocation Loc,
6249 SmallVectorImpl<Expr *> &ConvertedArgs,
6250 bool AllowExplicit = false,
6251 bool IsListInitialization = false);
6252
6253 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
6254 SourceLocation NameLoc,
6255 IdentifierInfo &Name);
6256
6257 ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
6258 Scope *S, CXXScopeSpec &SS,
6259 bool EnteringContext);
6260 ParsedType getDestructorName(SourceLocation TildeLoc,
6261 IdentifierInfo &II, SourceLocation NameLoc,
6262 Scope *S, CXXScopeSpec &SS,
6263 ParsedType ObjectType,
6264 bool EnteringContext);
6265
6266 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
6267 ParsedType ObjectType);
6268
6269 // Checks that reinterpret casts don't have undefined behavior.
6270 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
6271 bool IsDereference, SourceRange Range);
6272
6273 // Checks that the vector type should be initialized from a scalar
6274 // by splatting the value rather than populating a single element.
6275 // This is the case for AltiVecVector types as well as with
6276 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
6277 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
6278
6279 // Checks if the -faltivec-src-compat=gcc option is specified.
6280 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
6281 // treated the same way as they are when trying to initialize
6282 // these vectors on gcc (an error is emitted).
6283 bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
6284 QualType SrcTy);
6285
6286 /// ActOnCXXNamedCast - Parse
6287 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
6288 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
6289 tok::TokenKind Kind,
6290 SourceLocation LAngleBracketLoc,
6291 Declarator &D,
6292 SourceLocation RAngleBracketLoc,
6293 SourceLocation LParenLoc,
6294 Expr *E,
6295 SourceLocation RParenLoc);
6296
6297 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
6298 tok::TokenKind Kind,
6299 TypeSourceInfo *Ty,
6300 Expr *E,
6301 SourceRange AngleBrackets,
6302 SourceRange Parens);
6303
6304 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
6305 ExprResult Operand,
6306 SourceLocation RParenLoc);
6307
6308 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
6309 Expr *Operand, SourceLocation RParenLoc);
6310
6311 ExprResult BuildCXXTypeId(QualType TypeInfoType,
6312 SourceLocation TypeidLoc,
6313 TypeSourceInfo *Operand,
6314 SourceLocation RParenLoc);
6315 ExprResult BuildCXXTypeId(QualType TypeInfoType,
6316 SourceLocation TypeidLoc,
6317 Expr *Operand,
6318 SourceLocation RParenLoc);
6319
6320 /// ActOnCXXTypeid - Parse typeid( something ).
6321 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
6322 SourceLocation LParenLoc, bool isType,
6323 void *TyOrExpr,
6324 SourceLocation RParenLoc);
6325
6326 ExprResult BuildCXXUuidof(QualType TypeInfoType,
6327 SourceLocation TypeidLoc,
6328 TypeSourceInfo *Operand,
6329 SourceLocation RParenLoc);
6330 ExprResult BuildCXXUuidof(QualType TypeInfoType,
6331 SourceLocation TypeidLoc,
6332 Expr *Operand,
6333 SourceLocation RParenLoc);
6334
6335 /// ActOnCXXUuidof - Parse __uuidof( something ).
6336 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
6337 SourceLocation LParenLoc, bool isType,
6338 void *TyOrExpr,
6339 SourceLocation RParenLoc);
6340
6341 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
6342 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
6343 tok::TokenKind Operator,
6344 SourceLocation EllipsisLoc, Expr *RHS,
6345 SourceLocation RParenLoc);
6346 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
6347 SourceLocation LParenLoc, Expr *LHS,
6348 BinaryOperatorKind Operator,
6349 SourceLocation EllipsisLoc, Expr *RHS,
6350 SourceLocation RParenLoc,
6351 Optional<unsigned> NumExpansions);
6352 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
6353 BinaryOperatorKind Operator);
6354
6355 //// ActOnCXXThis - Parse 'this' pointer.
6356 ExprResult ActOnCXXThis(SourceLocation loc);
6357
6358 /// Build a CXXThisExpr and mark it referenced in the current context.
6359 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
6360 void MarkThisReferenced(CXXThisExpr *This);
6361
6362 /// Try to retrieve the type of the 'this' pointer.
6363 ///
6364 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
6365 QualType getCurrentThisType();
6366
6367 /// When non-NULL, the C++ 'this' expression is allowed despite the
6368 /// current context not being a non-static member function. In such cases,
6369 /// this provides the type used for 'this'.
6370 QualType CXXThisTypeOverride;
6371
6372 /// RAII object used to temporarily allow the C++ 'this' expression
6373 /// to be used, with the given qualifiers on the current class type.
6374 class CXXThisScopeRAII {
6375 Sema &S;
6376 QualType OldCXXThisTypeOverride;
6377 bool Enabled;
6378
6379 public:
6380 /// Introduce a new scope where 'this' may be allowed (when enabled),
6381 /// using the given declaration (which is either a class template or a
6382 /// class) along with the given qualifiers.
6383 /// along with the qualifiers placed on '*this'.
6384 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
6385 bool Enabled = true);
6386
6387 ~CXXThisScopeRAII();
6388 };
6389
6390 /// Make sure the value of 'this' is actually available in the current
6391 /// context, if it is a potentially evaluated context.
6392 ///
6393 /// \param Loc The location at which the capture of 'this' occurs.
6394 ///
6395 /// \param Explicit Whether 'this' is explicitly captured in a lambda
6396 /// capture list.
6397 ///
6398 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
6399 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
6400 /// This is useful when enclosing lambdas must speculatively capture
6401 /// 'this' that may or may not be used in certain specializations of
6402 /// a nested generic lambda (depending on whether the name resolves to
6403 /// a non-static member function or a static function).
6404 /// \return returns 'true' if failed, 'false' if success.
6405 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
6406 bool BuildAndDiagnose = true,
6407 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
6408 bool ByCopy = false);
6409
6410 /// Determine whether the given type is the type of *this that is used
6411 /// outside of the body of a member function for a type that is currently
6412 /// being defined.
6413 bool isThisOutsideMemberFunctionBody(QualType BaseType);
6414
6415 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
6416 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6417
6418
6419 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
6420 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6421
6422 ExprResult
6423 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
6424 SourceLocation AtLoc, SourceLocation RParen);
6425
6426 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
6427 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
6428
6429 //// ActOnCXXThrow - Parse throw expressions.
6430 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
6431 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
6432 bool IsThrownVarInScope);
6433 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
6434
6435 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
6436 /// Can be interpreted either as function-style casting ("int(x)")
6437 /// or class type construction ("ClassType(x,y,z)")
6438 /// or creation of a value-initialized type ("int()").
6439 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
6440 SourceLocation LParenOrBraceLoc,
6441 MultiExprArg Exprs,
6442 SourceLocation RParenOrBraceLoc,
6443 bool ListInitialization);
6444
6445 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
6446 SourceLocation LParenLoc,
6447 MultiExprArg Exprs,
6448 SourceLocation RParenLoc,
6449 bool ListInitialization);
6450
6451 /// ActOnCXXNew - Parsed a C++ 'new' expression.
6452 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
6453 SourceLocation PlacementLParen,
6454 MultiExprArg PlacementArgs,
6455 SourceLocation PlacementRParen,
6456 SourceRange TypeIdParens, Declarator &D,
6457 Expr *Initializer);
6458 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
6459 SourceLocation PlacementLParen,
6460 MultiExprArg PlacementArgs,
6461 SourceLocation PlacementRParen,
6462 SourceRange TypeIdParens,
6463 QualType AllocType,
6464 TypeSourceInfo *AllocTypeInfo,
6465 Optional<Expr *> ArraySize,
6466 SourceRange DirectInitRange,
6467 Expr *Initializer);
6468
6469 /// Determine whether \p FD is an aligned allocation or deallocation
6470 /// function that is unavailable.
6471 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
6472
6473 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
6474 /// function that is unavailable.
6475 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
6476 SourceLocation Loc);
6477
6478 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
6479 SourceRange R);
6480
6481 /// The scope in which to find allocation functions.
6482 enum AllocationFunctionScope {
6483 /// Only look for allocation functions in the global scope.
6484 AFS_Global,
6485 /// Only look for allocation functions in the scope of the
6486 /// allocated class.
6487 AFS_Class,
6488 /// Look for allocation functions in both the global scope
6489 /// and in the scope of the allocated class.
6490 AFS_Both
6491 };
6492
6493 /// Finds the overloads of operator new and delete that are appropriate
6494 /// for the allocation.
6495 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
6496 AllocationFunctionScope NewScope,
6497 AllocationFunctionScope DeleteScope,
6498 QualType AllocType, bool IsArray,
6499 bool &PassAlignment, MultiExprArg PlaceArgs,
6500 FunctionDecl *&OperatorNew,
6501 FunctionDecl *&OperatorDelete,
6502 bool Diagnose = true);
6503 void DeclareGlobalNewDelete();
6504 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
6505 ArrayRef<QualType> Params);
6506
6507 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
6508 DeclarationName Name, FunctionDecl* &Operator,
6509 bool Diagnose = true);
6510 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
6511 bool CanProvideSize,
6512 bool Overaligned,
6513 DeclarationName Name);
6514 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
6515 CXXRecordDecl *RD);
6516
6517 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
6518 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
6519 bool UseGlobal, bool ArrayForm,
6520 Expr *Operand);
6521 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
6522 bool IsDelete, bool CallCanBeVirtual,
6523 bool WarnOnNonAbstractTypes,
6524 SourceLocation DtorLoc);
6525
6526 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
6527 Expr *Operand, SourceLocation RParen);
6528 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6529 SourceLocation RParen);
6530
6531 /// Parsed one of the type trait support pseudo-functions.
6532 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6533 ArrayRef<ParsedType> Args,
6534 SourceLocation RParenLoc);
6535 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6536 ArrayRef<TypeSourceInfo *> Args,
6537 SourceLocation RParenLoc);
6538
6539 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
6540 /// pseudo-functions.
6541 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
6542 SourceLocation KWLoc,
6543 ParsedType LhsTy,
6544 Expr *DimExpr,
6545 SourceLocation RParen);
6546
6547 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
6548 SourceLocation KWLoc,
6549 TypeSourceInfo *TSInfo,
6550 Expr *DimExpr,
6551 SourceLocation RParen);
6552
6553 /// ActOnExpressionTrait - Parsed one of the unary type trait support
6554 /// pseudo-functions.
6555 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
6556 SourceLocation KWLoc,
6557 Expr *Queried,
6558 SourceLocation RParen);
6559
6560 ExprResult BuildExpressionTrait(ExpressionTrait OET,
6561 SourceLocation KWLoc,
6562 Expr *Queried,
6563 SourceLocation RParen);
6564
6565 ExprResult ActOnStartCXXMemberReference(Scope *S,
6566 Expr *Base,
6567 SourceLocation OpLoc,
6568 tok::TokenKind OpKind,
6569 ParsedType &ObjectType,
6570 bool &MayBePseudoDestructor);
6571
6572 ExprResult BuildPseudoDestructorExpr(Expr *Base,
6573 SourceLocation OpLoc,
6574 tok::TokenKind OpKind,
6575 const CXXScopeSpec &SS,
6576 TypeSourceInfo *ScopeType,
6577 SourceLocation CCLoc,
6578 SourceLocation TildeLoc,
6579 PseudoDestructorTypeStorage DestroyedType);
6580
6581 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6582 SourceLocation OpLoc,
6583 tok::TokenKind OpKind,
6584 CXXScopeSpec &SS,
6585 UnqualifiedId &FirstTypeName,
6586 SourceLocation CCLoc,
6587 SourceLocation TildeLoc,
6588 UnqualifiedId &SecondTypeName);
6589
6590 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6591 SourceLocation OpLoc,
6592 tok::TokenKind OpKind,
6593 SourceLocation TildeLoc,
6594 const DeclSpec& DS);
6595
6596 /// MaybeCreateExprWithCleanups - If the current full-expression
6597 /// requires any cleanups, surround it with a ExprWithCleanups node.
6598 /// Otherwise, just returns the passed-in expression.
6599 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
6600 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
6601 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
6602
6603 MaterializeTemporaryExpr *
6604 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6605 bool BoundToLvalueReference);
6606
6607 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
6608 return ActOnFinishFullExpr(
6609 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
6610 }
6611 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
6612 bool DiscardedValue, bool IsConstexpr = false);
6613 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
6614
6615 // Marks SS invalid if it represents an incomplete type.
6616 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
6617 // Complete an enum decl, maybe without a scope spec.
6618 bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
6619 CXXScopeSpec *SS = nullptr);
6620
6621 DeclContext *computeDeclContext(QualType T);
6622 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
6623 bool EnteringContext = false);
6624 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
6625 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
6626
6627 /// The parser has parsed a global nested-name-specifier '::'.
6628 ///
6629 /// \param CCLoc The location of the '::'.
6630 ///
6631 /// \param SS The nested-name-specifier, which will be updated in-place
6632 /// to reflect the parsed nested-name-specifier.
6633 ///
6634 /// \returns true if an error occurred, false otherwise.
6635 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
6636
6637 /// The parser has parsed a '__super' nested-name-specifier.
6638 ///
6639 /// \param SuperLoc The location of the '__super' keyword.
6640 ///
6641 /// \param ColonColonLoc The location of the '::'.
6642 ///
6643 /// \param SS The nested-name-specifier, which will be updated in-place
6644 /// to reflect the parsed nested-name-specifier.
6645 ///
6646 /// \returns true if an error occurred, false otherwise.
6647 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
6648 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
6649
6650 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
6651 bool *CanCorrect = nullptr);
6652 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
6653
6654 /// Keeps information about an identifier in a nested-name-spec.
6655 ///
6656 struct NestedNameSpecInfo {
6657 /// The type of the object, if we're parsing nested-name-specifier in
6658 /// a member access expression.
6659 ParsedType ObjectType;
6660
6661 /// The identifier preceding the '::'.
6662 IdentifierInfo *Identifier;
6663
6664 /// The location of the identifier.
6665 SourceLocation IdentifierLoc;
6666
6667 /// The location of the '::'.
6668 SourceLocation CCLoc;
6669
6670 /// Creates info object for the most typical case.
6671 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6672 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
6673 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
6674 CCLoc(ColonColonLoc) {
6675 }
6676
6677 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6678 SourceLocation ColonColonLoc, QualType ObjectType)
6679 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
6680 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
6681 }
6682 };
6683
6684 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
6685 NestedNameSpecInfo &IdInfo);
6686
6687 bool BuildCXXNestedNameSpecifier(Scope *S,
6688 NestedNameSpecInfo &IdInfo,
6689 bool EnteringContext,
6690 CXXScopeSpec &SS,
6691 NamedDecl *ScopeLookupResult,
6692 bool ErrorRecoveryLookup,
6693 bool *IsCorrectedToColon = nullptr,
6694 bool OnlyNamespace = false);
6695
6696 /// The parser has parsed a nested-name-specifier 'identifier::'.
6697 ///
6698 /// \param S The scope in which this nested-name-specifier occurs.
6699 ///
6700 /// \param IdInfo Parser information about an identifier in the
6701 /// nested-name-spec.
6702 ///
6703 /// \param EnteringContext Whether we're entering the context nominated by
6704 /// this nested-name-specifier.
6705 ///
6706 /// \param SS The nested-name-specifier, which is both an input
6707 /// parameter (the nested-name-specifier before this type) and an
6708 /// output parameter (containing the full nested-name-specifier,
6709 /// including this new type).
6710 ///
6711 /// \param ErrorRecoveryLookup If true, then this method is called to improve
6712 /// error recovery. In this case do not emit error message.
6713 ///
6714 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
6715 /// are allowed. The bool value pointed by this parameter is set to 'true'
6716 /// if the identifier is treated as if it was followed by ':', not '::'.
6717 ///
6718 /// \param OnlyNamespace If true, only considers namespaces in lookup.
6719 ///
6720 /// \returns true if an error occurred, false otherwise.
6721 bool ActOnCXXNestedNameSpecifier(Scope *S,
6722 NestedNameSpecInfo &IdInfo,
6723 bool EnteringContext,
6724 CXXScopeSpec &SS,
6725 bool ErrorRecoveryLookup = false,
6726 bool *IsCorrectedToColon = nullptr,
6727 bool OnlyNamespace = false);
6728
6729 ExprResult ActOnDecltypeExpression(Expr *E);
6730
6731 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
6732 const DeclSpec &DS,
6733 SourceLocation ColonColonLoc);
6734
6735 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
6736 NestedNameSpecInfo &IdInfo,
6737 bool EnteringContext);
6738
6739 /// The parser has parsed a nested-name-specifier
6740 /// 'template[opt] template-name < template-args >::'.
6741 ///
6742 /// \param S The scope in which this nested-name-specifier occurs.
6743 ///
6744 /// \param SS The nested-name-specifier, which is both an input
6745 /// parameter (the nested-name-specifier before this type) and an
6746 /// output parameter (containing the full nested-name-specifier,
6747 /// including this new type).
6748 ///
6749 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
6750 /// \param TemplateName the template name.
6751 /// \param TemplateNameLoc The location of the template name.
6752 /// \param LAngleLoc The location of the opening angle bracket ('<').
6753 /// \param TemplateArgs The template arguments.
6754 /// \param RAngleLoc The location of the closing angle bracket ('>').
6755 /// \param CCLoc The location of the '::'.
6756 ///
6757 /// \param EnteringContext Whether we're entering the context of the
6758 /// nested-name-specifier.
6759 ///
6760 ///
6761 /// \returns true if an error occurred, false otherwise.
6762 bool ActOnCXXNestedNameSpecifier(Scope *S,
6763 CXXScopeSpec &SS,
6764 SourceLocation TemplateKWLoc,
6765 TemplateTy TemplateName,
6766 SourceLocation TemplateNameLoc,
6767 SourceLocation LAngleLoc,
6768 ASTTemplateArgsPtr TemplateArgs,
6769 SourceLocation RAngleLoc,
6770 SourceLocation CCLoc,
6771 bool EnteringContext);
6772
6773 /// Given a C++ nested-name-specifier, produce an annotation value
6774 /// that the parser can use later to reconstruct the given
6775 /// nested-name-specifier.
6776 ///
6777 /// \param SS A nested-name-specifier.
6778 ///
6779 /// \returns A pointer containing all of the information in the
6780 /// nested-name-specifier \p SS.
6781 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
6782
6783 /// Given an annotation pointer for a nested-name-specifier, restore
6784 /// the nested-name-specifier structure.
6785 ///
6786 /// \param Annotation The annotation pointer, produced by
6787 /// \c SaveNestedNameSpecifierAnnotation().
6788 ///
6789 /// \param AnnotationRange The source range corresponding to the annotation.
6790 ///
6791 /// \param SS The nested-name-specifier that will be updated with the contents
6792 /// of the annotation pointer.
6793 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
6794 SourceRange AnnotationRange,
6795 CXXScopeSpec &SS);
6796
6797 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6798
6799 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
6800 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
6801 /// After this method is called, according to [C++ 3.4.3p3], names should be
6802 /// looked up in the declarator-id's scope, until the declarator is parsed and
6803 /// ActOnCXXExitDeclaratorScope is called.
6804 /// The 'SS' should be a non-empty valid CXXScopeSpec.
6805 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
6806
6807 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
6808 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
6809 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
6810 /// Used to indicate that names should revert to being looked up in the
6811 /// defining scope.
6812 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6813
6814 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
6815 /// initializer for the declaration 'Dcl'.
6816 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6817 /// static data member of class X, names should be looked up in the scope of
6818 /// class X.
6819 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
6820
6821 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
6822 /// initializer for the declaration 'Dcl'.
6823 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
6824
6825 /// Create a new lambda closure type.
6826 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
6827 TypeSourceInfo *Info,
6828 unsigned LambdaDependencyKind,
6829 LambdaCaptureDefault CaptureDefault);
6830
6831 /// Start the definition of a lambda expression.
6832 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
6833 SourceRange IntroducerRange,
6834 TypeSourceInfo *MethodType,
6835 SourceLocation EndLoc,
6836 ArrayRef<ParmVarDecl *> Params,
6837 ConstexprSpecKind ConstexprKind,
6838 Expr *TrailingRequiresClause);
6839
6840 /// Number lambda for linkage purposes if necessary.
6841 void handleLambdaNumbering(
6842 CXXRecordDecl *Class, CXXMethodDecl *Method,
6843 Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = None);
6844
6845 /// Endow the lambda scope info with the relevant properties.
6846 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
6847 CXXMethodDecl *CallOperator,
6848 SourceRange IntroducerRange,
6849 LambdaCaptureDefault CaptureDefault,
6850 SourceLocation CaptureDefaultLoc,
6851 bool ExplicitParams,
6852 bool ExplicitResultType,
6853 bool Mutable);
6854
6855 /// Perform initialization analysis of the init-capture and perform
6856 /// any implicit conversions such as an lvalue-to-rvalue conversion if
6857 /// not being used to initialize a reference.
6858 ParsedType actOnLambdaInitCaptureInitialization(
6859 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6860 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
6861 return ParsedType::make(buildLambdaInitCaptureInitialization(
6862 Loc, ByRef, EllipsisLoc, None, Id,
6863 InitKind != LambdaCaptureInitKind::CopyInit, Init));
6864 }
6865 QualType buildLambdaInitCaptureInitialization(
6866 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6867 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
6868 Expr *&Init);
6869
6870 /// Create a dummy variable within the declcontext of the lambda's
6871 /// call operator, for name lookup purposes for a lambda init capture.
6872 ///
6873 /// CodeGen handles emission of lambda captures, ignoring these dummy
6874 /// variables appropriately.
6875 VarDecl *createLambdaInitCaptureVarDecl(
6876 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
6877 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
6878
6879 /// Add an init-capture to a lambda scope.
6880 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
6881
6882 /// Note that we have finished the explicit captures for the
6883 /// given lambda.
6884 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
6885
6886 /// Deduce a block or lambda's return type based on the return
6887 /// statements present in the body.
6888 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
6889
6890 /// Once the Lambdas capture are known, we can
6891 /// start to create the closure, call operator method,
6892 /// and keep track of the captures.
6893 /// We do the capture lookup here, but they are not actually captured
6894 /// until after we know what the qualifiers of the call operator are.
6895 void ActOnLambdaIntroducer(LambdaIntroducer &Intro, Scope *CurContext);
6896
6897 /// This is called after parsing the explicit template parameter list
6898 /// on a lambda (if it exists) in C++2a.
6899 void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro,
6900 SourceLocation LAngleLoc,
6901 ArrayRef<NamedDecl *> TParams,
6902 SourceLocation RAngleLoc,
6903 ExprResult RequiresClause);
6904
6905 void ActOnLambdaClosureQualifiers(
6906 LambdaIntroducer &Intro, SourceLocation MutableLoc, SourceLocation EndLoc,
6907 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo,
6908 const DeclSpec &DS);
6909
6910 /// ActOnStartOfLambdaDefinition - This is called just before we start
6911 /// parsing the body of a lambda; it analyzes the explicit captures and
6912 /// arguments, and sets up various data-structures for the body of the
6913 /// lambda.
6914 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
6915 Declarator &ParamInfo, Scope *CurScope);
6916
6917 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
6918 /// is invoked to pop the information about the lambda.
6919 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
6920 bool IsInstantiation = false);
6921
6922 /// ActOnLambdaExpr - This is called when the body of a lambda expression
6923 /// was successfully completed.
6924 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
6925 Scope *CurScope);
6926
6927 /// Does copying/destroying the captured variable have side effects?
6928 bool CaptureHasSideEffects(const sema::Capture &From);
6929
6930 /// Diagnose if an explicit lambda capture is unused. Returns true if a
6931 /// diagnostic is emitted.
6932 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
6933 const sema::Capture &From);
6934
6935 /// Build a FieldDecl suitable to hold the given capture.
6936 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
6937
6938 /// Initialize the given capture with a suitable expression.
6939 ExprResult BuildCaptureInit(const sema::Capture &Capture,
6940 SourceLocation ImplicitCaptureLoc,
6941 bool IsOpenMPMapping = false);
6942
6943 /// Complete a lambda-expression having processed and attached the
6944 /// lambda body.
6945 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
6946 sema::LambdaScopeInfo *LSI);
6947
6948 /// Get the return type to use for a lambda's conversion function(s) to
6949 /// function pointer type, given the type of the call operator.
6950 QualType
6951 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
6952 CallingConv CC);
6953
6954 /// Define the "body" of the conversion from a lambda object to a
6955 /// function pointer.
6956 ///
6957 /// This routine doesn't actually define a sensible body; rather, it fills
6958 /// in the initialization expression needed to copy the lambda object into
6959 /// the block, and IR generation actually generates the real body of the
6960 /// block pointer conversion.
6961 void DefineImplicitLambdaToFunctionPointerConversion(
6962 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
6963
6964 /// Define the "body" of the conversion from a lambda object to a
6965 /// block pointer.
6966 ///
6967 /// This routine doesn't actually define a sensible body; rather, it fills
6968 /// in the initialization expression needed to copy the lambda object into
6969 /// the block, and IR generation actually generates the real body of the
6970 /// block pointer conversion.
6971 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
6972 CXXConversionDecl *Conv);
6973
6974 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
6975 SourceLocation ConvLocation,
6976 CXXConversionDecl *Conv,
6977 Expr *Src);
6978
6979 /// Check whether the given expression is a valid constraint expression.
6980 /// A diagnostic is emitted if it is not, false is returned, and
6981 /// PossibleNonPrimary will be set to true if the failure might be due to a
6982 /// non-primary expression being used as an atomic constraint.
6983 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
6984 bool *PossibleNonPrimary = nullptr,
6985 bool IsTrailingRequiresClause = false);
6986
6987private:
6988 /// Caches pairs of template-like decls whose associated constraints were
6989 /// checked for subsumption and whether or not the first's constraints did in
6990 /// fact subsume the second's.
6991 llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
6992 /// Caches the normalized associated constraints of declarations (concepts or
6993 /// constrained declarations). If an error occurred while normalizing the
6994 /// associated constraints of the template or concept, nullptr will be cached
6995 /// here.
6996 llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
6997 NormalizationCache;
6998
6999 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
7000 SatisfactionCache;
7001
7002 /// Introduce the instantiated function parameters into the local
7003 /// instantiation scope, and set the parameter names to those used
7004 /// in the template.
7005 bool addInstantiatedParametersToScope(
7006 FunctionDecl *Function, const FunctionDecl *PatternDecl,
7007 LocalInstantiationScope &Scope,
7008 const MultiLevelTemplateArgumentList &TemplateArgs);
7009
7010public:
7011 const NormalizedConstraint *
7012 getNormalizedAssociatedConstraints(
7013 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
7014
7015 /// \brief Check whether the given declaration's associated constraints are
7016 /// at least as constrained than another declaration's according to the
7017 /// partial ordering of constraints.
7018 ///
7019 /// \param Result If no error occurred, receives the result of true if D1 is
7020 /// at least constrained than D2, and false otherwise.
7021 ///
7022 /// \returns true if an error occurred, false otherwise.
7023 bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
7024 NamedDecl *D2, ArrayRef<const Expr *> AC2,
7025 bool &Result);
7026
7027 /// If D1 was not at least as constrained as D2, but would've been if a pair
7028 /// of atomic constraints involved had been declared in a concept and not
7029 /// repeated in two separate places in code.
7030 /// \returns true if such a diagnostic was emitted, false otherwise.
7031 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
7032 ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
7033
7034 /// \brief Check whether the given list of constraint expressions are
7035 /// satisfied (as if in a 'conjunction') given template arguments.
7036 /// \param Template the template-like entity that triggered the constraints
7037 /// check (either a concept or a constrained entity).
7038 /// \param ConstraintExprs a list of constraint expressions, treated as if
7039 /// they were 'AND'ed together.
7040 /// \param TemplateArgs the list of template arguments to substitute into the
7041 /// constraint expression.
7042 /// \param TemplateIDRange The source range of the template id that
7043 /// caused the constraints check.
7044 /// \param Satisfaction if true is returned, will contain details of the
7045 /// satisfaction, with enough information to diagnose an unsatisfied
7046 /// expression.
7047 /// \returns true if an error occurred and satisfaction could not be checked,
7048 /// false otherwise.
7049 bool CheckConstraintSatisfaction(
7050 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
7051 ArrayRef<TemplateArgument> TemplateArgs,
7052 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
7053
7054 /// \brief Check whether the given non-dependent constraint expression is
7055 /// satisfied. Returns false and updates Satisfaction with the satisfaction
7056 /// verdict if successful, emits a diagnostic and returns true if an error
7057 /// occurred and satisfaction could not be determined.
7058 ///
7059 /// \returns true if an error occurred, false otherwise.
7060 bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
7061 ConstraintSatisfaction &Satisfaction);
7062
7063 /// Check whether the given function decl's trailing requires clause is
7064 /// satisfied, if any. Returns false and updates Satisfaction with the
7065 /// satisfaction verdict if successful, emits a diagnostic and returns true if
7066 /// an error occurred and satisfaction could not be determined.
7067 ///
7068 /// \returns true if an error occurred, false otherwise.
7069 bool CheckFunctionConstraints(const FunctionDecl *FD,
7070 ConstraintSatisfaction &Satisfaction,
7071 SourceLocation UsageLoc = SourceLocation());
7072
7073
7074 /// \brief Ensure that the given template arguments satisfy the constraints
7075 /// associated with the given template, emitting a diagnostic if they do not.
7076 ///
7077 /// \param Template The template to which the template arguments are being
7078 /// provided.
7079 ///
7080 /// \param TemplateArgs The converted, canonicalized template arguments.
7081 ///
7082 /// \param TemplateIDRange The source range of the template id that
7083 /// caused the constraints check.
7084 ///
7085 /// \returns true if the constrains are not satisfied or could not be checked
7086 /// for satisfaction, false if the constraints are satisfied.
7087 bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
7088 ArrayRef<TemplateArgument> TemplateArgs,
7089 SourceRange TemplateIDRange);
7090
7091 /// \brief Emit diagnostics explaining why a constraint expression was deemed
7092 /// unsatisfied.
7093 /// \param First whether this is the first time an unsatisfied constraint is
7094 /// diagnosed for this error.
7095 void
7096 DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
7097 bool First = true);
7098
7099 /// \brief Emit diagnostics explaining why a constraint expression was deemed
7100 /// unsatisfied.
7101 void
7102 DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
7103 bool First = true);
7104
7105 // ParseObjCStringLiteral - Parse Objective-C string literals.
7106 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
7107 ArrayRef<Expr *> Strings);
7108
7109 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
7110
7111 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
7112 /// numeric literal expression. Type of the expression will be "NSNumber *"
7113 /// or "id" if NSNumber is unavailable.
7114 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
7115 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
7116 bool Value);
7117 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
7118
7119 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
7120 /// '@' prefixed parenthesized expression. The type of the expression will
7121 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
7122 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
7123 /// "const char *" or C structure with attribute 'objc_boxable'.
7124 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
7125
7126 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
7127 Expr *IndexExpr,
7128 ObjCMethodDecl *getterMethod,
7129 ObjCMethodDecl *setterMethod);
7130
7131 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
7132 MutableArrayRef<ObjCDictionaryElement> Elements);
7133
7134 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
7135 TypeSourceInfo *EncodedTypeInfo,
7136 SourceLocation RParenLoc);
7137 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
7138 CXXConversionDecl *Method,
7139 bool HadMultipleCandidates);
7140
7141 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
7142 SourceLocation EncodeLoc,
7143 SourceLocation LParenLoc,
7144 ParsedType Ty,
7145 SourceLocation RParenLoc);
7146
7147 /// ParseObjCSelectorExpression - Build selector expression for \@selector
7148 ExprResult ParseObjCSelectorExpression(Selector Sel,
7149 SourceLocation AtLoc,
7150 SourceLocation SelLoc,
7151 SourceLocation LParenLoc,
7152 SourceLocation RParenLoc,
7153 bool WarnMultipleSelectors);
7154
7155 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
7156 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
7157 SourceLocation AtLoc,
7158 SourceLocation ProtoLoc,
7159 SourceLocation LParenLoc,
7160 SourceLocation ProtoIdLoc,
7161 SourceLocation RParenLoc);
7162
7163 //===--------------------------------------------------------------------===//
7164 // C++ Declarations
7165 //
7166 Decl *ActOnStartLinkageSpecification(Scope *S,
7167 SourceLocation ExternLoc,
7168 Expr *LangStr,
7169 SourceLocation LBraceLoc);
7170 Decl *ActOnFinishLinkageSpecification(Scope *S,
7171 Decl *LinkageSpec,
7172 SourceLocation RBraceLoc);
7173
7174
7175 //===--------------------------------------------------------------------===//
7176 // C++ Classes
7177 //
7178 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
7179 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
7180 const CXXScopeSpec *SS = nullptr);
7181 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
7182
7183 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
7184 SourceLocation ColonLoc,
7185 const ParsedAttributesView &Attrs);
7186
7187 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
7188 Declarator &D,
7189 MultiTemplateParamsArg TemplateParameterLists,
7190 Expr *BitfieldWidth, const VirtSpecifiers &VS,
7191 InClassInitStyle InitStyle);
7192
7193 void ActOnStartCXXInClassMemberInitializer();
7194 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
7195 SourceLocation EqualLoc,
7196 Expr *Init);
7197
7198 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7199 Scope *S,
7200 CXXScopeSpec &SS,
7201 IdentifierInfo *MemberOrBase,
7202 ParsedType TemplateTypeTy,
7203 const DeclSpec &DS,
7204 SourceLocation IdLoc,
7205 SourceLocation LParenLoc,
7206 ArrayRef<Expr *> Args,
7207 SourceLocation RParenLoc,
7208 SourceLocation EllipsisLoc);
7209
7210 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7211 Scope *S,
7212 CXXScopeSpec &SS,
7213 IdentifierInfo *MemberOrBase,
7214 ParsedType TemplateTypeTy,
7215 const DeclSpec &DS,
7216 SourceLocation IdLoc,
7217 Expr *InitList,
7218 SourceLocation EllipsisLoc);
7219
7220 MemInitResult BuildMemInitializer(Decl *ConstructorD,
7221 Scope *S,
7222 CXXScopeSpec &SS,
7223 IdentifierInfo *MemberOrBase,
7224 ParsedType TemplateTypeTy,
7225 const DeclSpec &DS,
7226 SourceLocation IdLoc,
7227 Expr *Init,
7228 SourceLocation EllipsisLoc);
7229
7230 MemInitResult BuildMemberInitializer(ValueDecl *Member,
7231 Expr *Init,
7232 SourceLocation IdLoc);
7233
7234 MemInitResult BuildBaseInitializer(QualType BaseType,
7235 TypeSourceInfo *BaseTInfo,
7236 Expr *Init,
7237 CXXRecordDecl *ClassDecl,
7238 SourceLocation EllipsisLoc);
7239
7240 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
7241 Expr *Init,
7242 CXXRecordDecl *ClassDecl);
7243
7244 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
7245 CXXCtorInitializer *Initializer);
7246
7247 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
7248 ArrayRef<CXXCtorInitializer *> Initializers = None);
7249
7250 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
7251
7252
7253 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
7254 /// mark all the non-trivial destructors of its members and bases as
7255 /// referenced.
7256 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
7257 CXXRecordDecl *Record);
7258
7259 /// Mark destructors of virtual bases of this class referenced. In the Itanium
7260 /// C++ ABI, this is done when emitting a destructor for any non-abstract
7261 /// class. In the Microsoft C++ ABI, this is done any time a class's
7262 /// destructor is referenced.
7263 void MarkVirtualBaseDestructorsReferenced(
7264 SourceLocation Location, CXXRecordDecl *ClassDecl,
7265 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr);
7266
7267 /// Do semantic checks to allow the complete destructor variant to be emitted
7268 /// when the destructor is defined in another translation unit. In the Itanium
7269 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
7270 /// can be emitted in separate TUs. To emit the complete variant, run a subset
7271 /// of the checks performed when emitting a regular destructor.
7272 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
7273 CXXDestructorDecl *Dtor);
7274
7275 /// The list of classes whose vtables have been used within
7276 /// this translation unit, and the source locations at which the
7277 /// first use occurred.
7278 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
7279
7280 /// The list of vtables that are required but have not yet been
7281 /// materialized.
7282 SmallVector<VTableUse, 16> VTableUses;
7283
7284 /// The set of classes whose vtables have been used within
7285 /// this translation unit, and a bit that will be true if the vtable is
7286 /// required to be emitted (otherwise, it should be emitted only if needed
7287 /// by code generation).
7288 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
7289
7290 /// Load any externally-stored vtable uses.
7291 void LoadExternalVTableUses();
7292
7293 /// Note that the vtable for the given class was used at the
7294 /// given location.
7295 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7296 bool DefinitionRequired = false);
7297
7298 /// Mark the exception specifications of all virtual member functions
7299 /// in the given class as needed.
7300 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
7301 const CXXRecordDecl *RD);
7302
7303 /// MarkVirtualMembersReferenced - Will mark all members of the given
7304 /// CXXRecordDecl referenced.
7305 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
7306 bool ConstexprOnly = false);
7307
7308 /// Define all of the vtables that have been used in this
7309 /// translation unit and reference any virtual members used by those
7310 /// vtables.
7311 ///
7312 /// \returns true if any work was done, false otherwise.
7313 bool DefineUsedVTables();
7314
7315 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
7316
7317 void ActOnMemInitializers(Decl *ConstructorDecl,
7318 SourceLocation ColonLoc,
7319 ArrayRef<CXXCtorInitializer*> MemInits,
7320 bool AnyErrors);
7321
7322 /// Check class-level dllimport/dllexport attribute. The caller must
7323 /// ensure that referenceDLLExportedClassMethods is called some point later
7324 /// when all outer classes of Class are complete.
7325 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
7326 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
7327
7328 void referenceDLLExportedClassMethods();
7329
7330 void propagateDLLAttrToBaseClassTemplate(
7331 CXXRecordDecl *Class, Attr *ClassAttr,
7332 ClassTemplateSpecializationDecl *BaseTemplateSpec,
7333 SourceLocation BaseLoc);
7334
7335 /// Add gsl::Pointer attribute to std::container::iterator
7336 /// \param ND The declaration that introduces the name
7337 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
7338 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
7339
7340 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
7341 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
7342
7343 /// Add [[gsl::Pointer]] attributes for std:: types.
7344 void inferGslPointerAttribute(TypedefNameDecl *TD);
7345
7346 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
7347
7348 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
7349 /// conditions that are needed for the attribute to have an effect.
7350 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
7351
7352 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
7353 Decl *TagDecl, SourceLocation LBrac,
7354 SourceLocation RBrac,
7355 const ParsedAttributesView &AttrList);
7356 void ActOnFinishCXXMemberDecls();
7357 void ActOnFinishCXXNonNestedClass();
7358
7359 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
7360 unsigned ActOnReenterTemplateScope(Decl *Template,
7361 llvm::function_ref<Scope *()> EnterScope);
7362 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
7363 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7364 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
7365 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
7366 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7367 void ActOnFinishDelayedMemberInitializers(Decl *Record);
7368 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
7369 CachedTokens &Toks);
7370 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
7371 bool IsInsideALocalClassWithinATemplateFunction();
7372
7373 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7374 Expr *AssertExpr,
7375 Expr *AssertMessageExpr,
7376 SourceLocation RParenLoc);
7377 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7378 Expr *AssertExpr,
7379 StringLiteral *AssertMessageExpr,
7380 SourceLocation RParenLoc,
7381 bool Failed);
7382
7383 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
7384 SourceLocation FriendLoc,
7385 TypeSourceInfo *TSInfo);
7386 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
7387 MultiTemplateParamsArg TemplateParams);
7388 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
7389 MultiTemplateParamsArg TemplateParams);
7390
7391 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
7392 StorageClass& SC);
7393 void CheckConstructor(CXXConstructorDecl *Constructor);
7394 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
7395 StorageClass& SC);
7396 bool CheckDestructor(CXXDestructorDecl *Destructor);
7397 void CheckConversionDeclarator(Declarator &D, QualType &R,
7398 StorageClass& SC);
7399 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
7400 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
7401 StorageClass &SC);
7402 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
7403
7404 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
7405
7406 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7407 CXXSpecialMember CSM);
7408 void CheckDelayedMemberExceptionSpecs();
7409
7410 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
7411 DefaultedComparisonKind DCK);
7412 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
7413 FunctionDecl *Spaceship);
7414 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
7415 DefaultedComparisonKind DCK);
7416
7417 //===--------------------------------------------------------------------===//
7418 // C++ Derived Classes
7419 //
7420
7421 /// ActOnBaseSpecifier - Parsed a base specifier
7422 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
7423 SourceRange SpecifierRange,
7424 bool Virtual, AccessSpecifier Access,
7425 TypeSourceInfo *TInfo,
7426 SourceLocation EllipsisLoc);
7427
7428 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
7429 const ParsedAttributesView &Attrs, bool Virtual,
7430 AccessSpecifier Access, ParsedType basetype,
7431 SourceLocation BaseLoc,
7432 SourceLocation EllipsisLoc);
7433
7434 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
7435 MutableArrayRef<CXXBaseSpecifier *> Bases);
7436 void ActOnBaseSpecifiers(Decl *ClassDecl,
7437 MutableArrayRef<CXXBaseSpecifier *> Bases);
7438
7439 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
7440 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
7441 CXXBasePaths &Paths);
7442
7443 // FIXME: I don't like this name.
7444 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
7445
7446 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7447 SourceLocation Loc, SourceRange Range,
7448 CXXCastPath *BasePath = nullptr,
7449 bool IgnoreAccess = false);
7450 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7451 unsigned InaccessibleBaseID,
7452 unsigned AmbiguousBaseConvID,
7453 SourceLocation Loc, SourceRange Range,
7454 DeclarationName Name,
7455 CXXCastPath *BasePath,
7456 bool IgnoreAccess = false);
7457
7458 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
7459
7460 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
7461 const CXXMethodDecl *Old);
7462
7463 /// CheckOverridingFunctionReturnType - Checks whether the return types are
7464 /// covariant, according to C++ [class.virtual]p5.
7465 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
7466 const CXXMethodDecl *Old);
7467
7468 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
7469 /// spec is a subset of base spec.
7470 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
7471 const CXXMethodDecl *Old);
7472
7473 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
7474
7475 /// CheckOverrideControl - Check C++11 override control semantics.
7476 void CheckOverrideControl(NamedDecl *D);
7477
7478 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
7479 /// not used in the declaration of an overriding method.
7480 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
7481
7482 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
7483 /// overrides a virtual member function marked 'final', according to
7484 /// C++11 [class.virtual]p4.
7485 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
7486 const CXXMethodDecl *Old);
7487
7488
7489 //===--------------------------------------------------------------------===//
7490 // C++ Access Control
7491 //
7492
7493 enum AccessResult {
7494 AR_accessible,
7495 AR_inaccessible,
7496 AR_dependent,
7497 AR_delayed
7498 };
7499
7500 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
7501 NamedDecl *PrevMemberDecl,
7502 AccessSpecifier LexicalAS);
7503
7504 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
7505 DeclAccessPair FoundDecl);
7506 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
7507 DeclAccessPair FoundDecl);
7508 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
7509 SourceRange PlacementRange,
7510 CXXRecordDecl *NamingClass,
7511 DeclAccessPair FoundDecl,
7512 bool Diagnose = true);
7513 AccessResult CheckConstructorAccess(SourceLocation Loc,
7514 CXXConstructorDecl *D,
7515 DeclAccessPair FoundDecl,
7516 const InitializedEntity &Entity,
7517 bool IsCopyBindingRefToTemp = false);
7518 AccessResult CheckConstructorAccess(SourceLocation Loc,
7519 CXXConstructorDecl *D,
7520 DeclAccessPair FoundDecl,
7521 const InitializedEntity &Entity,
7522 const PartialDiagnostic &PDiag);
7523 AccessResult CheckDestructorAccess(SourceLocation Loc,
7524 CXXDestructorDecl *Dtor,
7525 const PartialDiagnostic &PDiag,
7526 QualType objectType = QualType());
7527 AccessResult CheckFriendAccess(NamedDecl *D);
7528 AccessResult CheckMemberAccess(SourceLocation UseLoc,
7529 CXXRecordDecl *NamingClass,
7530 DeclAccessPair Found);
7531 AccessResult
7532 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
7533 CXXRecordDecl *DecomposedClass,
7534 DeclAccessPair Field);
7535 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
7536 const SourceRange &,
7537 DeclAccessPair FoundDecl);
7538 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
7539 Expr *ObjectExpr,
7540 Expr *ArgExpr,
7541 DeclAccessPair FoundDecl);
7542 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
7543 ArrayRef<Expr *> ArgExprs,
7544 DeclAccessPair FoundDecl);
7545 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
7546 DeclAccessPair FoundDecl);
7547 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
7548 QualType Base, QualType Derived,
7549 const CXXBasePath &Path,
7550 unsigned DiagID,
7551 bool ForceCheck = false,
7552 bool ForceUnprivileged = false);
7553 void CheckLookupAccess(const LookupResult &R);
7554 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
7555 QualType BaseType);
7556 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7557 DeclAccessPair Found, QualType ObjectType,
7558 SourceLocation Loc,
7559 const PartialDiagnostic &Diag);
7560 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7561 DeclAccessPair Found,
7562 QualType ObjectType) {
7563 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
7564 SourceLocation(), PDiag());
7565 }
7566
7567 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
7568 const MultiLevelTemplateArgumentList &TemplateArgs);
7569 void PerformDependentDiagnostics(const DeclContext *Pattern,
7570 const MultiLevelTemplateArgumentList &TemplateArgs);
7571
7572 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
7573
7574 /// When true, access checking violations are treated as SFINAE
7575 /// failures rather than hard errors.
7576 bool AccessCheckingSFINAE;
7577
7578 enum AbstractDiagSelID {
7579 AbstractNone = -1,
7580 AbstractReturnType,
7581 AbstractParamType,
7582 AbstractVariableType,
7583 AbstractFieldType,
7584 AbstractIvarType,
7585 AbstractSynthesizedIvarType,
7586 AbstractArrayType
7587 };
7588
7589 bool isAbstractType(SourceLocation Loc, QualType T);
7590 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
7591 TypeDiagnoser &Diagnoser);
7592 template <typename... Ts>
7593 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
7594 const Ts &...Args) {
7595 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
7596 return RequireNonAbstractType(Loc, T, Diagnoser);
7597 }
7598
7599 void DiagnoseAbstractType(const CXXRecordDecl *RD);
7600
7601 //===--------------------------------------------------------------------===//
7602 // C++ Overloaded Operators [C++ 13.5]
7603 //
7604
7605 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
7606
7607 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
7608
7609 //===--------------------------------------------------------------------===//
7610 // C++ Templates [C++ 14]
7611 //
7612 void FilterAcceptableTemplateNames(LookupResult &R,
7613 bool AllowFunctionTemplates = true,
7614 bool AllowDependent = true);
7615 bool hasAnyAcceptableTemplateNames(LookupResult &R,
7616 bool AllowFunctionTemplates = true,
7617 bool AllowDependent = true,
7618 bool AllowNonTemplateFunctions = false);
7619 /// Try to interpret the lookup result D as a template-name.
7620 ///
7621 /// \param D A declaration found by name lookup.
7622 /// \param AllowFunctionTemplates Whether function templates should be
7623 /// considered valid results.
7624 /// \param AllowDependent Whether unresolved using declarations (that might
7625 /// name templates) should be considered valid results.
7626 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
7627 bool AllowFunctionTemplates = true,
7628 bool AllowDependent = true);
7629
7630 enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
7631 /// Whether and why a template name is required in this lookup.
7632 class RequiredTemplateKind {
7633 public:
7634 /// Template name is required if TemplateKWLoc is valid.
7635 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
7636 : TemplateKW(TemplateKWLoc) {}
7637 /// Template name is unconditionally required.
7638 RequiredTemplateKind(TemplateNameIsRequiredTag) {}
7639
7640 SourceLocation getTemplateKeywordLoc() const {
7641 return TemplateKW.getValueOr(SourceLocation());
7642 }
7643 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
7644 bool isRequired() const { return TemplateKW != SourceLocation(); }
7645 explicit operator bool() const { return isRequired(); }
7646
7647 private:
7648 llvm::Optional<SourceLocation> TemplateKW;
7649 };
7650
7651 enum class AssumedTemplateKind {
7652 /// This is not assumed to be a template name.
7653 None,
7654 /// This is assumed to be a template name because lookup found nothing.
7655 FoundNothing,
7656 /// This is assumed to be a template name because lookup found one or more
7657 /// functions (but no function templates).
7658 FoundFunctions,
7659 };
7660 bool LookupTemplateName(
7661 LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType,
7662 bool EnteringContext, bool &MemberOfUnknownSpecialization,
7663 RequiredTemplateKind RequiredTemplate = SourceLocation(),
7664 AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true);
7665
7666 TemplateNameKind isTemplateName(Scope *S,
7667 CXXScopeSpec &SS,
7668 bool hasTemplateKeyword,
7669 const UnqualifiedId &Name,
7670 ParsedType ObjectType,
7671 bool EnteringContext,
7672 TemplateTy &Template,
7673 bool &MemberOfUnknownSpecialization,
7674 bool Disambiguation = false);
7675
7676 /// Try to resolve an undeclared template name as a type template.
7677 ///
7678 /// Sets II to the identifier corresponding to the template name, and updates
7679 /// Name to a corresponding (typo-corrected) type template name and TNK to
7680 /// the corresponding kind, if possible.
7681 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
7682 TemplateNameKind &TNK,
7683 SourceLocation NameLoc,
7684 IdentifierInfo *&II);
7685
7686 bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
7687 SourceLocation NameLoc,
7688 bool Diagnose = true);
7689
7690 /// Determine whether a particular identifier might be the name in a C++1z
7691 /// deduction-guide declaration.
7692 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
7693 SourceLocation NameLoc,
7694 ParsedTemplateTy *Template = nullptr);
7695
7696 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
7697 SourceLocation IILoc,
7698 Scope *S,
7699 const CXXScopeSpec *SS,
7700 TemplateTy &SuggestedTemplate,
7701 TemplateNameKind &SuggestedKind);
7702
7703 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
7704 NamedDecl *Instantiation,
7705 bool InstantiatedFromMember,
7706 const NamedDecl *Pattern,
7707 const NamedDecl *PatternDef,
7708 TemplateSpecializationKind TSK,
7709 bool Complain = true);
7710
7711 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
7712 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
7713
7714 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
7715 SourceLocation EllipsisLoc,
7716 SourceLocation KeyLoc,
7717 IdentifierInfo *ParamName,
7718 SourceLocation ParamNameLoc,
7719 unsigned Depth, unsigned Position,
7720 SourceLocation EqualLoc,
7721 ParsedType DefaultArg, bool HasTypeConstraint);
7722
7723 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
7724 TemplateIdAnnotation *TypeConstraint,
7725 TemplateTypeParmDecl *ConstrainedParameter,
7726 SourceLocation EllipsisLoc);
7727 bool BuildTypeConstraint(const CXXScopeSpec &SS,
7728 TemplateIdAnnotation *TypeConstraint,
7729 TemplateTypeParmDecl *ConstrainedParameter,
7730 SourceLocation EllipsisLoc,
7731 bool AllowUnexpandedPack);
7732
7733 bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
7734 DeclarationNameInfo NameInfo,
7735 ConceptDecl *NamedConcept,
7736 const TemplateArgumentListInfo *TemplateArgs,
7737 TemplateTypeParmDecl *ConstrainedParameter,
7738 SourceLocation EllipsisLoc);
7739
7740 bool AttachTypeConstraint(AutoTypeLoc TL,
7741 NonTypeTemplateParmDecl *ConstrainedParameter,
7742 SourceLocation EllipsisLoc);
7743
7744 bool RequireStructuralType(QualType T, SourceLocation Loc);
7745
7746 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
7747 SourceLocation Loc);
7748 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
7749
7750 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
7751 unsigned Depth,
7752 unsigned Position,
7753 SourceLocation EqualLoc,
7754 Expr *DefaultArg);
7755 NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
7756 SourceLocation TmpLoc,
7757 TemplateParameterList *Params,
7758 SourceLocation EllipsisLoc,
7759 IdentifierInfo *ParamName,
7760 SourceLocation ParamNameLoc,
7761 unsigned Depth,
7762 unsigned Position,
7763 SourceLocation EqualLoc,
7764 ParsedTemplateArgument DefaultArg);
7765
7766 TemplateParameterList *
7767 ActOnTemplateParameterList(unsigned Depth,
7768 SourceLocation ExportLoc,
7769 SourceLocation TemplateLoc,
7770 SourceLocation LAngleLoc,
7771 ArrayRef<NamedDecl *> Params,
7772 SourceLocation RAngleLoc,
7773 Expr *RequiresClause);
7774
7775 /// The context in which we are checking a template parameter list.
7776 enum TemplateParamListContext {
7777 TPC_ClassTemplate,
7778 TPC_VarTemplate,
7779 TPC_FunctionTemplate,
7780 TPC_ClassTemplateMember,
7781 TPC_FriendClassTemplate,
7782 TPC_FriendFunctionTemplate,
7783 TPC_FriendFunctionTemplateDefinition,
7784 TPC_TypeAliasTemplate
7785 };
7786
7787 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
7788 TemplateParameterList *OldParams,
7789 TemplateParamListContext TPC,
7790 SkipBodyInfo *SkipBody = nullptr);
7791 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
7792 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
7793 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
7794 ArrayRef<TemplateParameterList *> ParamLists,
7795 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
7796 bool SuppressDiagnostic = false);
7797
7798 DeclResult CheckClassTemplate(
7799 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7800 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
7801 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
7802 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
7803 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
7804 TemplateParameterList **OuterTemplateParamLists,
7805 SkipBodyInfo *SkipBody = nullptr);
7806
7807 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
7808 QualType NTTPType,
7809 SourceLocation Loc);
7810
7811 /// Get a template argument mapping the given template parameter to itself,
7812 /// e.g. for X in \c template<int X>, this would return an expression template
7813 /// argument referencing X.
7814 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
7815 SourceLocation Location);
7816
7817 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
7818 TemplateArgumentListInfo &Out);
7819
7820 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
7821
7822 void NoteAllFoundTemplates(TemplateName Name);
7823
7824 QualType CheckTemplateIdType(TemplateName Template,
7825 SourceLocation TemplateLoc,
7826 TemplateArgumentListInfo &TemplateArgs);
7827
7828 TypeResult
7829 ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7830 TemplateTy Template, IdentifierInfo *TemplateII,
7831 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
7832 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
7833 bool IsCtorOrDtorName = false, bool IsClassName = false);
7834
7835 /// Parsed an elaborated-type-specifier that refers to a template-id,
7836 /// such as \c class T::template apply<U>.
7837 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
7838 TypeSpecifierType TagSpec,
7839 SourceLocation TagLoc,
7840 CXXScopeSpec &SS,
7841 SourceLocation TemplateKWLoc,
7842 TemplateTy TemplateD,
7843 SourceLocation TemplateLoc,
7844 SourceLocation LAngleLoc,
7845 ASTTemplateArgsPtr TemplateArgsIn,
7846 SourceLocation RAngleLoc);
7847
7848 DeclResult ActOnVarTemplateSpecialization(
7849 Scope *S, Declarator &D, TypeSourceInfo *DI,
7850 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
7851 StorageClass SC, bool IsPartialSpecialization);
7852
7853 /// Get the specialization of the given variable template corresponding to
7854 /// the specified argument list, or a null-but-valid result if the arguments
7855 /// are dependent.
7856 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
7857 SourceLocation TemplateLoc,
7858 SourceLocation TemplateNameLoc,
7859 const TemplateArgumentListInfo &TemplateArgs);
7860
7861 /// Form a reference to the specialization of the given variable template
7862 /// corresponding to the specified argument list, or a null-but-valid result
7863 /// if the arguments are dependent.
7864 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
7865 const DeclarationNameInfo &NameInfo,
7866 VarTemplateDecl *Template,
7867 SourceLocation TemplateLoc,
7868 const TemplateArgumentListInfo *TemplateArgs);
7869
7870 ExprResult
7871 CheckConceptTemplateId(const CXXScopeSpec &SS,
7872 SourceLocation TemplateKWLoc,
7873 const DeclarationNameInfo &ConceptNameInfo,
7874 NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
7875 const TemplateArgumentListInfo *TemplateArgs);
7876
7877 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
7878
7879 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
7880 SourceLocation TemplateKWLoc,
7881 LookupResult &R,
7882 bool RequiresADL,
7883 const TemplateArgumentListInfo *TemplateArgs);
7884
7885 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
7886 SourceLocation TemplateKWLoc,
7887 const DeclarationNameInfo &NameInfo,
7888 const TemplateArgumentListInfo *TemplateArgs);
7889
7890 TemplateNameKind ActOnTemplateName(
7891 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7892 const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
7893 TemplateTy &Template, bool AllowInjectedClassName = false);
7894
7895 DeclResult ActOnClassTemplateSpecialization(
7896 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7897 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
7898 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
7899 MultiTemplateParamsArg TemplateParameterLists,
7900 SkipBodyInfo *SkipBody = nullptr);
7901
7902 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
7903 TemplateDecl *PrimaryTemplate,
7904 unsigned NumExplicitArgs,
7905 ArrayRef<TemplateArgument> Args);
7906 void CheckTemplatePartialSpecialization(
7907 ClassTemplatePartialSpecializationDecl *Partial);
7908 void CheckTemplatePartialSpecialization(
7909 VarTemplatePartialSpecializationDecl *Partial);
7910
7911 Decl *ActOnTemplateDeclarator(Scope *S,
7912 MultiTemplateParamsArg TemplateParameterLists,
7913 Declarator &D);
7914
7915 bool
7916 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7917 TemplateSpecializationKind NewTSK,
7918 NamedDecl *PrevDecl,
7919 TemplateSpecializationKind PrevTSK,
7920 SourceLocation PrevPtOfInstantiation,
7921 bool &SuppressNew);
7922
7923 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7924 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7925 LookupResult &Previous);
7926
7927 bool CheckFunctionTemplateSpecialization(
7928 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7929 LookupResult &Previous, bool QualifiedFriend = false);
7930 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7931 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7932
7933 DeclResult ActOnExplicitInstantiation(
7934 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
7935 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
7936 TemplateTy Template, SourceLocation TemplateNameLoc,
7937 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
7938 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
7939
7940 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
7941 SourceLocation TemplateLoc,
7942 unsigned TagSpec, SourceLocation KWLoc,
7943 CXXScopeSpec &SS, IdentifierInfo *Name,
7944 SourceLocation NameLoc,
7945 const ParsedAttributesView &Attr);
7946
7947 DeclResult ActOnExplicitInstantiation(Scope *S,
7948 SourceLocation ExternLoc,
7949 SourceLocation TemplateLoc,
7950 Declarator &D);
7951
7952 TemplateArgumentLoc
7953 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
7954 SourceLocation TemplateLoc,
7955 SourceLocation RAngleLoc,
7956 Decl *Param,
7957 SmallVectorImpl<TemplateArgument>
7958 &Converted,
7959 bool &HasDefaultArg);
7960
7961 /// Specifies the context in which a particular template
7962 /// argument is being checked.
7963 enum CheckTemplateArgumentKind {
7964 /// The template argument was specified in the code or was
7965 /// instantiated with some deduced template arguments.
7966 CTAK_Specified,
7967
7968 /// The template argument was deduced via template argument
7969 /// deduction.
7970 CTAK_Deduced,
7971
7972 /// The template argument was deduced from an array bound
7973 /// via template argument deduction.
7974 CTAK_DeducedFromArrayBound
7975 };
7976
7977 bool CheckTemplateArgument(NamedDecl *Param,
7978 TemplateArgumentLoc &Arg,
7979 NamedDecl *Template,
7980 SourceLocation TemplateLoc,
7981 SourceLocation RAngleLoc,
7982 unsigned ArgumentPackIndex,
7983 SmallVectorImpl<TemplateArgument> &Converted,
7984 CheckTemplateArgumentKind CTAK = CTAK_Specified);
7985
7986 /// Check that the given template arguments can be be provided to
7987 /// the given template, converting the arguments along the way.
7988 ///
7989 /// \param Template The template to which the template arguments are being
7990 /// provided.
7991 ///
7992 /// \param TemplateLoc The location of the template name in the source.
7993 ///
7994 /// \param TemplateArgs The list of template arguments. If the template is
7995 /// a template template parameter, this function may extend the set of
7996 /// template arguments to also include substituted, defaulted template
7997 /// arguments.
7998 ///
7999 /// \param PartialTemplateArgs True if the list of template arguments is
8000 /// intentionally partial, e.g., because we're checking just the initial
8001 /// set of template arguments.
8002 ///
8003 /// \param Converted Will receive the converted, canonicalized template
8004 /// arguments.
8005 ///
8006 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
8007 /// contain the converted forms of the template arguments as written.
8008 /// Otherwise, \p TemplateArgs will not be modified.
8009 ///
8010 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
8011 /// receive true if the cause for the error is the associated constraints of
8012 /// the template not being satisfied by the template arguments.
8013 ///
8014 /// \returns true if an error occurred, false otherwise.
8015 bool CheckTemplateArgumentList(TemplateDecl *Template,
8016 SourceLocation TemplateLoc,
8017 TemplateArgumentListInfo &TemplateArgs,
8018 bool PartialTemplateArgs,
8019 SmallVectorImpl<TemplateArgument> &Converted,
8020 bool UpdateArgsWithConversions = true,
8021 bool *ConstraintsNotSatisfied = nullptr);
8022
8023 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
8024 TemplateArgumentLoc &Arg,
8025 SmallVectorImpl<TemplateArgument> &Converted);
8026
8027 bool CheckTemplateArgument(TypeSourceInfo *Arg);
8028 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
8029 QualType InstantiatedParamType, Expr *Arg,
8030 TemplateArgument &Converted,
8031 CheckTemplateArgumentKind CTAK = CTAK_Specified);
8032 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
8033 TemplateParameterList *Params,
8034 TemplateArgumentLoc &Arg);
8035
8036 ExprResult
8037 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
8038 QualType ParamType,
8039 SourceLocation Loc);
8040 ExprResult
8041 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
8042 SourceLocation Loc);
8043
8044 /// Enumeration describing how template parameter lists are compared
8045 /// for equality.
8046 enum TemplateParameterListEqualKind {
8047 /// We are matching the template parameter lists of two templates
8048 /// that might be redeclarations.
8049 ///
8050 /// \code
8051 /// template<typename T> struct X;
8052 /// template<typename T> struct X;
8053 /// \endcode
8054 TPL_TemplateMatch,
8055
8056 /// We are matching the template parameter lists of two template
8057 /// template parameters as part of matching the template parameter lists
8058 /// of two templates that might be redeclarations.
8059 ///
8060 /// \code
8061 /// template<template<int I> class TT> struct X;
8062 /// template<template<int Value> class Other> struct X;
8063 /// \endcode
8064 TPL_TemplateTemplateParmMatch,
8065
8066 /// We are matching the template parameter lists of a template
8067 /// template argument against the template parameter lists of a template
8068 /// template parameter.
8069 ///
8070 /// \code
8071 /// template<template<int Value> class Metafun> struct X;
8072 /// template<int Value> struct integer_c;
8073 /// X<integer_c> xic;
8074 /// \endcode
8075 TPL_TemplateTemplateArgumentMatch
8076 };
8077
8078 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
8079 TemplateParameterList *Old,
8080 bool Complain,
8081 TemplateParameterListEqualKind Kind,
8082 SourceLocation TemplateArgLoc
8083 = SourceLocation());
8084
8085 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
8086
8087 /// Called when the parser has parsed a C++ typename
8088 /// specifier, e.g., "typename T::type".
8089 ///
8090 /// \param S The scope in which this typename type occurs.
8091 /// \param TypenameLoc the location of the 'typename' keyword
8092 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
8093 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
8094 /// \param IdLoc the location of the identifier.
8095 TypeResult
8096 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8097 const CXXScopeSpec &SS, const IdentifierInfo &II,
8098 SourceLocation IdLoc);
8099
8100 /// Called when the parser has parsed a C++ typename
8101 /// specifier that ends in a template-id, e.g.,
8102 /// "typename MetaFun::template apply<T1, T2>".
8103 ///
8104 /// \param S The scope in which this typename type occurs.
8105 /// \param TypenameLoc the location of the 'typename' keyword
8106 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
8107 /// \param TemplateLoc the location of the 'template' keyword, if any.
8108 /// \param TemplateName The template name.
8109 /// \param TemplateII The identifier used to name the template.
8110 /// \param TemplateIILoc The location of the template name.
8111 /// \param LAngleLoc The location of the opening angle bracket ('<').
8112 /// \param TemplateArgs The template arguments.
8113 /// \param RAngleLoc The location of the closing angle bracket ('>').
8114 TypeResult
8115 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8116 const CXXScopeSpec &SS,
8117 SourceLocation TemplateLoc,
8118 TemplateTy TemplateName,
8119 IdentifierInfo *TemplateII,
8120 SourceLocation TemplateIILoc,
8121 SourceLocation LAngleLoc,
8122 ASTTemplateArgsPtr TemplateArgs,
8123 SourceLocation RAngleLoc);
8124
8125 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
8126 SourceLocation KeywordLoc,
8127 NestedNameSpecifierLoc QualifierLoc,
8128 const IdentifierInfo &II,
8129 SourceLocation IILoc,
8130 TypeSourceInfo **TSI,
8131 bool DeducedTSTContext);
8132
8133 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
8134 SourceLocation KeywordLoc,
8135 NestedNameSpecifierLoc QualifierLoc,
8136 const IdentifierInfo &II,
8137 SourceLocation IILoc,
8138 bool DeducedTSTContext = true);
8139
8140
8141 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8142 SourceLocation Loc,
8143 DeclarationName Name);
8144 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
8145
8146 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
8147 bool RebuildTemplateParamsInCurrentInstantiation(
8148 TemplateParameterList *Params);
8149
8150 std::string
8151 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8152 const TemplateArgumentList &Args);
8153
8154 std::string
8155 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8156 const TemplateArgument *Args,
8157 unsigned NumArgs);
8158
8159 //===--------------------------------------------------------------------===//
8160 // C++ Concepts
8161 //===--------------------------------------------------------------------===//
8162 Decl *ActOnConceptDefinition(
8163 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8164 IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
8165
8166 RequiresExprBodyDecl *
8167 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8168 ArrayRef<ParmVarDecl *> LocalParameters,
8169 Scope *BodyScope);
8170 void ActOnFinishRequiresExpr();
8171 concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8172 concepts::Requirement *ActOnTypeRequirement(
8173 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
8174 IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
8175 concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8176 SourceLocation NoexceptLoc);
8177 concepts::Requirement *
8178 ActOnCompoundRequirement(
8179 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8180 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8181 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8182 concepts::ExprRequirement *
8183 BuildExprRequirement(
8184 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8185 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8186 concepts::ExprRequirement *
8187 BuildExprRequirement(
8188 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8189 bool IsSatisfied, SourceLocation NoexceptLoc,
8190 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8191 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8192 concepts::TypeRequirement *
8193 BuildTypeRequirement(
8194 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8195 concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8196 concepts::NestedRequirement *
8197 BuildNestedRequirement(
8198 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8199 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8200 RequiresExprBodyDecl *Body,
8201 ArrayRef<ParmVarDecl *> LocalParameters,
8202 ArrayRef<concepts::Requirement *> Requirements,
8203 SourceLocation ClosingBraceLoc);
8204
8205 //===--------------------------------------------------------------------===//
8206 // C++ Variadic Templates (C++0x [temp.variadic])
8207 //===--------------------------------------------------------------------===//
8208
8209 /// Determine whether an unexpanded parameter pack might be permitted in this
8210 /// location. Useful for error recovery.
8211 bool isUnexpandedParameterPackPermitted();
8212
8213 /// The context in which an unexpanded parameter pack is
8214 /// being diagnosed.
8215 ///
8216 /// Note that the values of this enumeration line up with the first
8217 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
8218 enum UnexpandedParameterPackContext {
8219 /// An arbitrary expression.
8220 UPPC_Expression = 0,
8221
8222 /// The base type of a class type.
8223 UPPC_BaseType,
8224
8225 /// The type of an arbitrary declaration.
8226 UPPC_DeclarationType,
8227
8228 /// The type of a data member.
8229 UPPC_DataMemberType,
8230
8231 /// The size of a bit-field.
8232 UPPC_BitFieldWidth,
8233
8234 /// The expression in a static assertion.
8235 UPPC_StaticAssertExpression,
8236
8237 /// The fixed underlying type of an enumeration.
8238 UPPC_FixedUnderlyingType,
8239
8240 /// The enumerator value.
8241 UPPC_EnumeratorValue,
8242
8243 /// A using declaration.
8244 UPPC_UsingDeclaration,
8245
8246 /// A friend declaration.
8247 UPPC_FriendDeclaration,
8248
8249 /// A declaration qualifier.
8250 UPPC_DeclarationQualifier,
8251
8252 /// An initializer.
8253 UPPC_Initializer,
8254
8255 /// A default argument.
8256 UPPC_DefaultArgument,
8257
8258 /// The type of a non-type template parameter.
8259 UPPC_NonTypeTemplateParameterType,
8260
8261 /// The type of an exception.
8262 UPPC_ExceptionType,
8263
8264 /// Partial specialization.
8265 UPPC_PartialSpecialization,
8266
8267 /// Microsoft __if_exists.
8268 UPPC_IfExists,
8269
8270 /// Microsoft __if_not_exists.
8271 UPPC_IfNotExists,
8272
8273 /// Lambda expression.
8274 UPPC_Lambda,
8275
8276 /// Block expression.
8277 UPPC_Block,
8278
8279 /// A type constraint.
8280 UPPC_TypeConstraint,
8281
8282 // A requirement in a requires-expression.
8283 UPPC_Requirement,
8284
8285 // A requires-clause.
8286 UPPC_RequiresClause,
8287 };
8288
8289 /// Diagnose unexpanded parameter packs.
8290 ///
8291 /// \param Loc The location at which we should emit the diagnostic.
8292 ///
8293 /// \param UPPC The context in which we are diagnosing unexpanded
8294 /// parameter packs.
8295 ///
8296 /// \param Unexpanded the set of unexpanded parameter packs.
8297 ///
8298 /// \returns true if an error occurred, false otherwise.
8299 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
8300 UnexpandedParameterPackContext UPPC,
8301 ArrayRef<UnexpandedParameterPack> Unexpanded);
8302
8303 /// If the given type contains an unexpanded parameter pack,
8304 /// diagnose the error.
8305 ///
8306 /// \param Loc The source location where a diagnostc should be emitted.
8307 ///
8308 /// \param T The type that is being checked for unexpanded parameter
8309 /// packs.
8310 ///
8311 /// \returns true if an error occurred, false otherwise.
8312 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
8313 UnexpandedParameterPackContext UPPC);
8314
8315 /// If the given expression contains an unexpanded parameter
8316 /// pack, diagnose the error.
8317 ///
8318 /// \param E The expression that is being checked for unexpanded
8319 /// parameter packs.
8320 ///
8321 /// \returns true if an error occurred, false otherwise.
8322 bool DiagnoseUnexpandedParameterPack(Expr *E,
8323 UnexpandedParameterPackContext UPPC = UPPC_Expression);
8324
8325 /// If the given requirees-expression contains an unexpanded reference to one
8326 /// of its own parameter packs, diagnose the error.
8327 ///
8328 /// \param RE The requiress-expression that is being checked for unexpanded
8329 /// parameter packs.
8330 ///
8331 /// \returns true if an error occurred, false otherwise.
8332 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
8333
8334 /// If the given nested-name-specifier contains an unexpanded
8335 /// parameter pack, diagnose the error.
8336 ///
8337 /// \param SS The nested-name-specifier that is being checked for
8338 /// unexpanded parameter packs.
8339 ///
8340 /// \returns true if an error occurred, false otherwise.
8341 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
8342 UnexpandedParameterPackContext UPPC);
8343
8344 /// If the given name contains an unexpanded parameter pack,
8345 /// diagnose the error.
8346 ///
8347 /// \param NameInfo The name (with source location information) that
8348 /// is being checked for unexpanded parameter packs.
8349 ///
8350 /// \returns true if an error occurred, false otherwise.
8351 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
8352 UnexpandedParameterPackContext UPPC);
8353
8354 /// If the given template name contains an unexpanded parameter pack,
8355 /// diagnose the error.
8356 ///
8357 /// \param Loc The location of the template name.
8358 ///
8359 /// \param Template The template name that is being checked for unexpanded
8360 /// parameter packs.
8361 ///
8362 /// \returns true if an error occurred, false otherwise.
8363 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
8364 TemplateName Template,
8365 UnexpandedParameterPackContext UPPC);
8366
8367 /// If the given template argument contains an unexpanded parameter
8368 /// pack, diagnose the error.
8369 ///
8370 /// \param Arg The template argument that is being checked for unexpanded
8371 /// parameter packs.
8372 ///
8373 /// \returns true if an error occurred, false otherwise.
8374 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
8375 UnexpandedParameterPackContext UPPC);
8376
8377 /// Collect the set of unexpanded parameter packs within the given
8378 /// template argument.
8379 ///
8380 /// \param Arg The template argument that will be traversed to find
8381 /// unexpanded parameter packs.
8382 void collectUnexpandedParameterPacks(TemplateArgument Arg,
8383 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8384
8385 /// Collect the set of unexpanded parameter packs within the given
8386 /// template argument.
8387 ///
8388 /// \param Arg The template argument that will be traversed to find
8389 /// unexpanded parameter packs.
8390 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
8391 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8392
8393 /// Collect the set of unexpanded parameter packs within the given
8394 /// type.
8395 ///
8396 /// \param T The type that will be traversed to find
8397 /// unexpanded parameter packs.
8398 void collectUnexpandedParameterPacks(QualType T,
8399 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8400
8401 /// Collect the set of unexpanded parameter packs within the given
8402 /// type.
8403 ///
8404 /// \param TL The type that will be traversed to find
8405 /// unexpanded parameter packs.
8406 void collectUnexpandedParameterPacks(TypeLoc TL,
8407 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8408
8409 /// Collect the set of unexpanded parameter packs within the given
8410 /// nested-name-specifier.
8411 ///
8412 /// \param NNS The nested-name-specifier that will be traversed to find
8413 /// unexpanded parameter packs.
8414 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
8415 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8416
8417 /// Collect the set of unexpanded parameter packs within the given
8418 /// name.
8419 ///
8420 /// \param NameInfo The name that will be traversed to find
8421 /// unexpanded parameter packs.
8422 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
8423 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8424
8425 /// Invoked when parsing a template argument followed by an
8426 /// ellipsis, which creates a pack expansion.
8427 ///
8428 /// \param Arg The template argument preceding the ellipsis, which
8429 /// may already be invalid.
8430 ///
8431 /// \param EllipsisLoc The location of the ellipsis.
8432 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
8433 SourceLocation EllipsisLoc);
8434
8435 /// Invoked when parsing a type followed by an ellipsis, which
8436 /// creates a pack expansion.
8437 ///
8438 /// \param Type The type preceding the ellipsis, which will become
8439 /// the pattern of the pack expansion.
8440 ///
8441 /// \param EllipsisLoc The location of the ellipsis.
8442 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
8443
8444 /// Construct a pack expansion type from the pattern of the pack
8445 /// expansion.
8446 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
8447 SourceLocation EllipsisLoc,
8448 Optional<unsigned> NumExpansions);
8449
8450 /// Construct a pack expansion type from the pattern of the pack
8451 /// expansion.
8452 QualType CheckPackExpansion(QualType Pattern,
8453 SourceRange PatternRange,
8454 SourceLocation EllipsisLoc,
8455 Optional<unsigned> NumExpansions);
8456
8457 /// Invoked when parsing an expression followed by an ellipsis, which
8458 /// creates a pack expansion.
8459 ///
8460 /// \param Pattern The expression preceding the ellipsis, which will become
8461 /// the pattern of the pack expansion.
8462 ///
8463 /// \param EllipsisLoc The location of the ellipsis.
8464 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
8465
8466 /// Invoked when parsing an expression followed by an ellipsis, which
8467 /// creates a pack expansion.
8468 ///
8469 /// \param Pattern The expression preceding the ellipsis, which will become
8470 /// the pattern of the pack expansion.
8471 ///
8472 /// \param EllipsisLoc The location of the ellipsis.
8473 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
8474 Optional<unsigned> NumExpansions);
8475
8476 /// Determine whether we could expand a pack expansion with the
8477 /// given set of parameter packs into separate arguments by repeatedly
8478 /// transforming the pattern.
8479 ///
8480 /// \param EllipsisLoc The location of the ellipsis that identifies the
8481 /// pack expansion.
8482 ///
8483 /// \param PatternRange The source range that covers the entire pattern of
8484 /// the pack expansion.
8485 ///
8486 /// \param Unexpanded The set of unexpanded parameter packs within the
8487 /// pattern.
8488 ///
8489 /// \param ShouldExpand Will be set to \c true if the transformer should
8490 /// expand the corresponding pack expansions into separate arguments. When
8491 /// set, \c NumExpansions must also be set.
8492 ///
8493 /// \param RetainExpansion Whether the caller should add an unexpanded
8494 /// pack expansion after all of the expanded arguments. This is used
8495 /// when extending explicitly-specified template argument packs per
8496 /// C++0x [temp.arg.explicit]p9.
8497 ///
8498 /// \param NumExpansions The number of separate arguments that will be in
8499 /// the expanded form of the corresponding pack expansion. This is both an
8500 /// input and an output parameter, which can be set by the caller if the
8501 /// number of expansions is known a priori (e.g., due to a prior substitution)
8502 /// and will be set by the callee when the number of expansions is known.
8503 /// The callee must set this value when \c ShouldExpand is \c true; it may
8504 /// set this value in other cases.
8505 ///
8506 /// \returns true if an error occurred (e.g., because the parameter packs
8507 /// are to be instantiated with arguments of different lengths), false
8508 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
8509 /// must be set.
8510 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
8511 SourceRange PatternRange,
8512 ArrayRef<UnexpandedParameterPack> Unexpanded,
8513 const MultiLevelTemplateArgumentList &TemplateArgs,
8514 bool &ShouldExpand,
8515 bool &RetainExpansion,
8516 Optional<unsigned> &NumExpansions);
8517
8518 /// Determine the number of arguments in the given pack expansion
8519 /// type.
8520 ///
8521 /// This routine assumes that the number of arguments in the expansion is
8522 /// consistent across all of the unexpanded parameter packs in its pattern.
8523 ///
8524 /// Returns an empty Optional if the type can't be expanded.
8525 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
8526 const MultiLevelTemplateArgumentList &TemplateArgs);
8527
8528 /// Determine whether the given declarator contains any unexpanded
8529 /// parameter packs.
8530 ///
8531 /// This routine is used by the parser to disambiguate function declarators
8532 /// with an ellipsis prior to the ')', e.g.,
8533 ///
8534 /// \code
8535 /// void f(T...);
8536 /// \endcode
8537 ///
8538 /// To determine whether we have an (unnamed) function parameter pack or
8539 /// a variadic function.
8540 ///
8541 /// \returns true if the declarator contains any unexpanded parameter packs,
8542 /// false otherwise.
8543 bool containsUnexpandedParameterPacks(Declarator &D);
8544
8545 /// Returns the pattern of the pack expansion for a template argument.
8546 ///
8547 /// \param OrigLoc The template argument to expand.
8548 ///
8549 /// \param Ellipsis Will be set to the location of the ellipsis.
8550 ///
8551 /// \param NumExpansions Will be set to the number of expansions that will
8552 /// be generated from this pack expansion, if known a priori.
8553 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
8554 TemplateArgumentLoc OrigLoc,
8555 SourceLocation &Ellipsis,
8556 Optional<unsigned> &NumExpansions) const;
8557
8558 /// Given a template argument that contains an unexpanded parameter pack, but
8559 /// which has already been substituted, attempt to determine the number of
8560 /// elements that will be produced once this argument is fully-expanded.
8561 ///
8562 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
8563 /// avoid actually expanding the pack where possible.
8564 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
8565
8566 //===--------------------------------------------------------------------===//
8567 // C++ Template Argument Deduction (C++ [temp.deduct])
8568 //===--------------------------------------------------------------------===//
8569
8570 /// Adjust the type \p ArgFunctionType to match the calling convention,
8571 /// noreturn, and optionally the exception specification of \p FunctionType.
8572 /// Deduction often wants to ignore these properties when matching function
8573 /// types.
8574 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
8575 bool AdjustExceptionSpec = false);
8576
8577 /// Describes the result of template argument deduction.
8578 ///
8579 /// The TemplateDeductionResult enumeration describes the result of
8580 /// template argument deduction, as returned from
8581 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
8582 /// structure provides additional information about the results of
8583 /// template argument deduction, e.g., the deduced template argument
8584 /// list (if successful) or the specific template parameters or
8585 /// deduced arguments that were involved in the failure.
8586 enum TemplateDeductionResult {
8587 /// Template argument deduction was successful.
8588 TDK_Success = 0,
8589 /// The declaration was invalid; do nothing.
8590 TDK_Invalid,
8591 /// Template argument deduction exceeded the maximum template
8592 /// instantiation depth (which has already been diagnosed).
8593 TDK_InstantiationDepth,
8594 /// Template argument deduction did not deduce a value
8595 /// for every template parameter.
8596 TDK_Incomplete,
8597 /// Template argument deduction did not deduce a value for every
8598 /// expansion of an expanded template parameter pack.
8599 TDK_IncompletePack,
8600 /// Template argument deduction produced inconsistent
8601 /// deduced values for the given template parameter.
8602 TDK_Inconsistent,
8603 /// Template argument deduction failed due to inconsistent
8604 /// cv-qualifiers on a template parameter type that would
8605 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
8606 /// but were given a non-const "X".
8607 TDK_Underqualified,
8608 /// Substitution of the deduced template argument values
8609 /// resulted in an error.
8610 TDK_SubstitutionFailure,
8611 /// After substituting deduced template arguments, a dependent
8612 /// parameter type did not match the corresponding argument.
8613 TDK_DeducedMismatch,
8614 /// After substituting deduced template arguments, an element of
8615 /// a dependent parameter type did not match the corresponding element
8616 /// of the corresponding argument (when deducing from an initializer list).
8617 TDK_DeducedMismatchNested,
8618 /// A non-depnedent component of the parameter did not match the
8619 /// corresponding component of the argument.
8620 TDK_NonDeducedMismatch,
8621 /// When performing template argument deduction for a function
8622 /// template, there were too many call arguments.
8623 TDK_TooManyArguments,
8624 /// When performing template argument deduction for a function
8625 /// template, there were too few call arguments.
8626 TDK_TooFewArguments,
8627 /// The explicitly-specified template arguments were not valid
8628 /// template arguments for the given template.
8629 TDK_InvalidExplicitArguments,
8630 /// Checking non-dependent argument conversions failed.
8631 TDK_NonDependentConversionFailure,
8632 /// The deduced arguments did not satisfy the constraints associated
8633 /// with the template.
8634 TDK_ConstraintsNotSatisfied,
8635 /// Deduction failed; that's all we know.
8636 TDK_MiscellaneousDeductionFailure,
8637 /// CUDA Target attributes do not match.
8638 TDK_CUDATargetMismatch
8639 };
8640
8641 TemplateDeductionResult
8642 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
8643 const TemplateArgumentList &TemplateArgs,
8644 sema::TemplateDeductionInfo &Info);
8645
8646 TemplateDeductionResult
8647 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
8648 const TemplateArgumentList &TemplateArgs,
8649 sema::TemplateDeductionInfo &Info);
8650
8651 TemplateDeductionResult SubstituteExplicitTemplateArguments(
8652 FunctionTemplateDecl *FunctionTemplate,
8653 TemplateArgumentListInfo &ExplicitTemplateArgs,
8654 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8655 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
8656 sema::TemplateDeductionInfo &Info);
8657
8658 /// brief A function argument from which we performed template argument
8659 // deduction for a call.
8660 struct OriginalCallArg {
8661 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
8662 unsigned ArgIdx, QualType OriginalArgType)
8663 : OriginalParamType(OriginalParamType),
8664 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
8665 OriginalArgType(OriginalArgType) {}
8666
8667 QualType OriginalParamType;
8668 bool DecomposedParam;
8669 unsigned ArgIdx;
8670 QualType OriginalArgType;
8671 };
8672
8673 TemplateDeductionResult FinishTemplateArgumentDeduction(
8674 FunctionTemplateDecl *FunctionTemplate,
8675 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8676 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
8677 sema::TemplateDeductionInfo &Info,
8678 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
8679 bool PartialOverloading = false,
8680 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
8681
8682 TemplateDeductionResult DeduceTemplateArguments(
8683 FunctionTemplateDecl *FunctionTemplate,
8684 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8685 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
8686 bool PartialOverloading,
8687 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
8688
8689 TemplateDeductionResult
8690 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8691 TemplateArgumentListInfo *ExplicitTemplateArgs,
8692 QualType ArgFunctionType,
8693 FunctionDecl *&Specialization,
8694 sema::TemplateDeductionInfo &Info,
8695 bool IsAddressOfFunction = false);
8696
8697 TemplateDeductionResult
8698 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8699 QualType ToType,
8700 CXXConversionDecl *&Specialization,
8701 sema::TemplateDeductionInfo &Info);
8702
8703 TemplateDeductionResult
8704 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8705 TemplateArgumentListInfo *ExplicitTemplateArgs,
8706 FunctionDecl *&Specialization,
8707 sema::TemplateDeductionInfo &Info,
8708 bool IsAddressOfFunction = false);
8709
8710 /// Substitute Replacement for \p auto in \p TypeWithAuto
8711 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
8712 /// Substitute Replacement for auto in TypeWithAuto
8713 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8714 QualType Replacement);
8715
8716 // Substitute auto in TypeWithAuto for a Dependent auto type
8717 QualType SubstAutoTypeDependent(QualType TypeWithAuto);
8718
8719 // Substitute auto in TypeWithAuto for a Dependent auto type
8720 TypeSourceInfo *
8721 SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
8722
8723 /// Completely replace the \c auto in \p TypeWithAuto by
8724 /// \p Replacement. This does not retain any \c auto type sugar.
8725 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
8726 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8727 QualType Replacement);
8728
8729 /// Result type of DeduceAutoType.
8730 enum DeduceAutoResult {
8731 DAR_Succeeded,
8732 DAR_Failed,
8733 DAR_FailedAlreadyDiagnosed
8734 };
8735
8736 DeduceAutoResult
8737 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
8738 Optional<unsigned> DependentDeductionDepth = None,
8739 bool IgnoreConstraints = false);
8740 DeduceAutoResult
8741 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
8742 Optional<unsigned> DependentDeductionDepth = None,
8743 bool IgnoreConstraints = false);
8744 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
8745 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
8746 bool Diagnose = true);
8747
8748 /// Declare implicit deduction guides for a class template if we've
8749 /// not already done so.
8750 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
8751 SourceLocation Loc);
8752
8753 QualType DeduceTemplateSpecializationFromInitializer(
8754 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
8755 const InitializationKind &Kind, MultiExprArg Init);
8756
8757 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
8758 QualType Type, TypeSourceInfo *TSI,
8759 SourceRange Range, bool DirectInit,
8760 Expr *Init);
8761
8762 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
8763
8764 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
8765 SourceLocation ReturnLoc,
8766 Expr *&RetExpr, const AutoType *AT);
8767
8768 FunctionTemplateDecl *getMoreSpecializedTemplate(
8769 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
8770 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
8771 unsigned NumCallArguments2, bool Reversed = false);
8772 UnresolvedSetIterator
8773 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
8774 TemplateSpecCandidateSet &FailedCandidates,
8775 SourceLocation Loc,
8776 const PartialDiagnostic &NoneDiag,
8777 const PartialDiagnostic &AmbigDiag,
8778 const PartialDiagnostic &CandidateDiag,
8779 bool Complain = true, QualType TargetType = QualType());
8780
8781 ClassTemplatePartialSpecializationDecl *
8782 getMoreSpecializedPartialSpecialization(
8783 ClassTemplatePartialSpecializationDecl *PS1,
8784 ClassTemplatePartialSpecializationDecl *PS2,
8785 SourceLocation Loc);
8786
8787 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
8788 sema::TemplateDeductionInfo &Info);
8789
8790 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
8791 VarTemplatePartialSpecializationDecl *PS1,
8792 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
8793
8794 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
8795 sema::TemplateDeductionInfo &Info);
8796
8797 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
8798 TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
8799
8800 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
8801 unsigned Depth, llvm::SmallBitVector &Used);
8802
8803 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
8804 bool OnlyDeduced,
8805 unsigned Depth,
8806 llvm::SmallBitVector &Used);
8807 void MarkDeducedTemplateParameters(
8808 const FunctionTemplateDecl *FunctionTemplate,
8809 llvm::SmallBitVector &Deduced) {
8810 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
8811 }
8812 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
8813 const FunctionTemplateDecl *FunctionTemplate,
8814 llvm::SmallBitVector &Deduced);
8815
8816 //===--------------------------------------------------------------------===//
8817 // C++ Template Instantiation
8818 //
8819
8820 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
8821 const NamedDecl *D, const TemplateArgumentList *Innermost = nullptr,
8822 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr);
8823
8824 /// A context in which code is being synthesized (where a source location
8825 /// alone is not sufficient to identify the context). This covers template
8826 /// instantiation and various forms of implicitly-generated functions.
8827 struct CodeSynthesisContext {
8828 /// The kind of template instantiation we are performing
8829 enum SynthesisKind {
8830 /// We are instantiating a template declaration. The entity is
8831 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
8832 TemplateInstantiation,
8833
8834 /// We are instantiating a default argument for a template
8835 /// parameter. The Entity is the template parameter whose argument is
8836 /// being instantiated, the Template is the template, and the
8837 /// TemplateArgs/NumTemplateArguments provide the template arguments as
8838 /// specified.
8839 DefaultTemplateArgumentInstantiation,
8840
8841 /// We are instantiating a default argument for a function.
8842 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
8843 /// provides the template arguments as specified.
8844 DefaultFunctionArgumentInstantiation,
8845
8846 /// We are substituting explicit template arguments provided for
8847 /// a function template. The entity is a FunctionTemplateDecl.
8848 ExplicitTemplateArgumentSubstitution,
8849
8850 /// We are substituting template argument determined as part of
8851 /// template argument deduction for either a class template
8852 /// partial specialization or a function template. The
8853 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
8854 /// a TemplateDecl.
8855 DeducedTemplateArgumentSubstitution,
8856
8857 /// We are substituting prior template arguments into a new
8858 /// template parameter. The template parameter itself is either a
8859 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
8860 PriorTemplateArgumentSubstitution,
8861
8862 /// We are checking the validity of a default template argument that
8863 /// has been used when naming a template-id.
8864 DefaultTemplateArgumentChecking,
8865
8866 /// We are computing the exception specification for a defaulted special
8867 /// member function.
8868 ExceptionSpecEvaluation,
8869
8870 /// We are instantiating the exception specification for a function
8871 /// template which was deferred until it was needed.
8872 ExceptionSpecInstantiation,
8873
8874 /// We are instantiating a requirement of a requires expression.
8875 RequirementInstantiation,
8876
8877 /// We are checking the satisfaction of a nested requirement of a requires
8878 /// expression.
8879 NestedRequirementConstraintsCheck,
8880
8881 /// We are declaring an implicit special member function.
8882 DeclaringSpecialMember,
8883
8884 /// We are declaring an implicit 'operator==' for a defaulted
8885 /// 'operator<=>'.
8886 DeclaringImplicitEqualityComparison,
8887
8888 /// We are defining a synthesized function (such as a defaulted special
8889 /// member).
8890 DefiningSynthesizedFunction,
8891
8892 // We are checking the constraints associated with a constrained entity or
8893 // the constraint expression of a concept. This includes the checks that
8894 // atomic constraints have the type 'bool' and that they can be constant
8895 // evaluated.
8896 ConstraintsCheck,
8897
8898 // We are substituting template arguments into a constraint expression.
8899 ConstraintSubstitution,
8900
8901 // We are normalizing a constraint expression.
8902 ConstraintNormalization,
8903
8904 // We are substituting into the parameter mapping of an atomic constraint
8905 // during normalization.
8906 ParameterMappingSubstitution,
8907
8908 /// We are rewriting a comparison operator in terms of an operator<=>.
8909 RewritingOperatorAsSpaceship,
8910
8911 /// We are initializing a structured binding.
8912 InitializingStructuredBinding,
8913
8914 /// We are marking a class as __dllexport.
8915 MarkingClassDllexported,
8916
8917 /// Added for Template instantiation observation.
8918 /// Memoization means we are _not_ instantiating a template because
8919 /// it is already instantiated (but we entered a context where we
8920 /// would have had to if it was not already instantiated).
8921 Memoization
8922 } Kind;
8923
8924 /// Was the enclosing context a non-instantiation SFINAE context?
8925 bool SavedInNonInstantiationSFINAEContext;
8926
8927 /// The point of instantiation or synthesis within the source code.
8928 SourceLocation PointOfInstantiation;
8929
8930 /// The entity that is being synthesized.
8931 Decl *Entity;
8932
8933 /// The template (or partial specialization) in which we are
8934 /// performing the instantiation, for substitutions of prior template
8935 /// arguments.
8936 NamedDecl *Template;
8937
8938 /// The list of template arguments we are substituting, if they
8939 /// are not part of the entity.
8940 const TemplateArgument *TemplateArgs;
8941
8942 // FIXME: Wrap this union around more members, or perhaps store the
8943 // kind-specific members in the RAII object owning the context.
8944 union {
8945 /// The number of template arguments in TemplateArgs.
8946 unsigned NumTemplateArgs;
8947
8948 /// The special member being declared or defined.
8949 CXXSpecialMember SpecialMember;
8950 };
8951
8952 ArrayRef<TemplateArgument> template_arguments() const {
8953 assert(Kind != DeclaringSpecialMember)(static_cast <bool> (Kind != DeclaringSpecialMember) ? void
(0) : __assert_fail ("Kind != DeclaringSpecialMember", "clang/include/clang/Sema/Sema.h"
, 8953, __extension__ __PRETTY_FUNCTION__))
;
8954 return {TemplateArgs, NumTemplateArgs};
8955 }
8956
8957 /// The template deduction info object associated with the
8958 /// substitution or checking of explicit or deduced template arguments.
8959 sema::TemplateDeductionInfo *DeductionInfo;
8960
8961 /// The source range that covers the construct that cause
8962 /// the instantiation, e.g., the template-id that causes a class
8963 /// template instantiation.
8964 SourceRange InstantiationRange;
8965
8966 CodeSynthesisContext()
8967 : Kind(TemplateInstantiation),
8968 SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
8969 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
8970 DeductionInfo(nullptr) {}
8971
8972 /// Determines whether this template is an actual instantiation
8973 /// that should be counted toward the maximum instantiation depth.
8974 bool isInstantiationRecord() const;
8975 };
8976
8977 /// List of active code synthesis contexts.
8978 ///
8979 /// This vector is treated as a stack. As synthesis of one entity requires
8980 /// synthesis of another, additional contexts are pushed onto the stack.
8981 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
8982
8983 /// Specializations whose definitions are currently being instantiated.
8984 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
8985
8986 /// Non-dependent types used in templates that have already been instantiated
8987 /// by some template instantiation.
8988 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
8989
8990 /// Extra modules inspected when performing a lookup during a template
8991 /// instantiation. Computed lazily.
8992 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
8993
8994 /// Cache of additional modules that should be used for name lookup
8995 /// within the current template instantiation. Computed lazily; use
8996 /// getLookupModules() to get a complete set.
8997 llvm::DenseSet<Module*> LookupModulesCache;
8998
8999 /// Get the set of additional modules that should be checked during
9000 /// name lookup. A module and its imports become visible when instanting a
9001 /// template defined within it.
9002 llvm::DenseSet<Module*> &getLookupModules();
9003
9004 /// Map from the most recent declaration of a namespace to the most
9005 /// recent visible declaration of that namespace.
9006 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
9007
9008 /// Whether we are in a SFINAE context that is not associated with
9009 /// template instantiation.
9010 ///
9011 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
9012 /// of a template instantiation or template argument deduction.
9013 bool InNonInstantiationSFINAEContext;
9014
9015 /// The number of \p CodeSynthesisContexts that are not template
9016 /// instantiations and, therefore, should not be counted as part of the
9017 /// instantiation depth.
9018 ///
9019 /// When the instantiation depth reaches the user-configurable limit
9020 /// \p LangOptions::InstantiationDepth we will abort instantiation.
9021 // FIXME: Should we have a similar limit for other forms of synthesis?
9022 unsigned NonInstantiationEntries;
9023
9024 /// The depth of the context stack at the point when the most recent
9025 /// error or warning was produced.
9026 ///
9027 /// This value is used to suppress printing of redundant context stacks
9028 /// when there are multiple errors or warnings in the same instantiation.
9029 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
9030 unsigned LastEmittedCodeSynthesisContextDepth = 0;
9031
9032 /// The template instantiation callbacks to trace or track
9033 /// instantiations (objects can be chained).
9034 ///
9035 /// This callbacks is used to print, trace or track template
9036 /// instantiations as they are being constructed.
9037 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
9038 TemplateInstCallbacks;
9039
9040 /// The current index into pack expansion arguments that will be
9041 /// used for substitution of parameter packs.
9042 ///
9043 /// The pack expansion index will be -1 to indicate that parameter packs
9044 /// should be instantiated as themselves. Otherwise, the index specifies
9045 /// which argument within the parameter pack will be used for substitution.
9046 int ArgumentPackSubstitutionIndex;
9047
9048 /// RAII object used to change the argument pack substitution index
9049 /// within a \c Sema object.
9050 ///
9051 /// See \c ArgumentPackSubstitutionIndex for more information.
9052 class ArgumentPackSubstitutionIndexRAII {
9053 Sema &Self;
9054 int OldSubstitutionIndex;
9055
9056 public:
9057 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
9058 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
9059 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
9060 }
9061
9062 ~ArgumentPackSubstitutionIndexRAII() {
9063 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
9064 }
9065 };
9066
9067 friend class ArgumentPackSubstitutionRAII;
9068
9069 /// For each declaration that involved template argument deduction, the
9070 /// set of diagnostics that were suppressed during that template argument
9071 /// deduction.
9072 ///
9073 /// FIXME: Serialize this structure to the AST file.
9074 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
9075 SuppressedDiagnosticsMap;
9076 SuppressedDiagnosticsMap SuppressedDiagnostics;
9077
9078 /// A stack object to be created when performing template
9079 /// instantiation.
9080 ///
9081 /// Construction of an object of type \c InstantiatingTemplate
9082 /// pushes the current instantiation onto the stack of active
9083 /// instantiations. If the size of this stack exceeds the maximum
9084 /// number of recursive template instantiations, construction
9085 /// produces an error and evaluates true.
9086 ///
9087 /// Destruction of this object will pop the named instantiation off
9088 /// the stack.
9089 struct InstantiatingTemplate {
9090 /// Note that we are instantiating a class template,
9091 /// function template, variable template, alias template,
9092 /// or a member thereof.
9093 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9094 Decl *Entity,
9095 SourceRange InstantiationRange = SourceRange());
9096
9097 struct ExceptionSpecification {};
9098 /// Note that we are instantiating an exception specification
9099 /// of a function template.
9100 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9101 FunctionDecl *Entity, ExceptionSpecification,
9102 SourceRange InstantiationRange = SourceRange());
9103
9104 /// Note that we are instantiating a default argument in a
9105 /// template-id.
9106 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9107 TemplateParameter Param, TemplateDecl *Template,
9108 ArrayRef<TemplateArgument> TemplateArgs,
9109 SourceRange InstantiationRange = SourceRange());
9110
9111 /// Note that we are substituting either explicitly-specified or
9112 /// deduced template arguments during function template argument deduction.
9113 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9114 FunctionTemplateDecl *FunctionTemplate,
9115 ArrayRef<TemplateArgument> TemplateArgs,
9116 CodeSynthesisContext::SynthesisKind Kind,
9117 sema::TemplateDeductionInfo &DeductionInfo,
9118 SourceRange InstantiationRange = SourceRange());
9119
9120 /// Note that we are instantiating as part of template
9121 /// argument deduction for a class template declaration.
9122 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9123 TemplateDecl *Template,
9124 ArrayRef<TemplateArgument> TemplateArgs,
9125 sema::TemplateDeductionInfo &DeductionInfo,
9126 SourceRange InstantiationRange = SourceRange());
9127
9128 /// Note that we are instantiating as part of template
9129 /// argument deduction for a class template partial
9130 /// specialization.
9131 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9132 ClassTemplatePartialSpecializationDecl *PartialSpec,
9133 ArrayRef<TemplateArgument> TemplateArgs,
9134 sema::TemplateDeductionInfo &DeductionInfo,
9135 SourceRange InstantiationRange = SourceRange());
9136
9137 /// Note that we are instantiating as part of template
9138 /// argument deduction for a variable template partial
9139 /// specialization.
9140 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9141 VarTemplatePartialSpecializationDecl *PartialSpec,
9142 ArrayRef<TemplateArgument> TemplateArgs,
9143 sema::TemplateDeductionInfo &DeductionInfo,
9144 SourceRange InstantiationRange = SourceRange());
9145
9146 /// Note that we are instantiating a default argument for a function
9147 /// parameter.
9148 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9149 ParmVarDecl *Param,
9150 ArrayRef<TemplateArgument> TemplateArgs,
9151 SourceRange InstantiationRange = SourceRange());
9152
9153 /// Note that we are substituting prior template arguments into a
9154 /// non-type parameter.
9155 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9156 NamedDecl *Template,
9157 NonTypeTemplateParmDecl *Param,
9158 ArrayRef<TemplateArgument> TemplateArgs,
9159 SourceRange InstantiationRange);
9160
9161 /// Note that we are substituting prior template arguments into a
9162 /// template template parameter.
9163 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9164 NamedDecl *Template,
9165 TemplateTemplateParmDecl *Param,
9166 ArrayRef<TemplateArgument> TemplateArgs,
9167 SourceRange InstantiationRange);
9168
9169 /// Note that we are checking the default template argument
9170 /// against the template parameter for a given template-id.
9171 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9172 TemplateDecl *Template,
9173 NamedDecl *Param,
9174 ArrayRef<TemplateArgument> TemplateArgs,
9175 SourceRange InstantiationRange);
9176
9177 struct ConstraintsCheck {};
9178 /// \brief Note that we are checking the constraints associated with some
9179 /// constrained entity (a concept declaration or a template with associated
9180 /// constraints).
9181 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9182 ConstraintsCheck, NamedDecl *Template,
9183 ArrayRef<TemplateArgument> TemplateArgs,
9184 SourceRange InstantiationRange);
9185
9186 struct ConstraintSubstitution {};
9187 /// \brief Note that we are checking a constraint expression associated
9188 /// with a template declaration or as part of the satisfaction check of a
9189 /// concept.
9190 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9191 ConstraintSubstitution, NamedDecl *Template,
9192 sema::TemplateDeductionInfo &DeductionInfo,
9193 SourceRange InstantiationRange);
9194
9195 struct ConstraintNormalization {};
9196 /// \brief Note that we are normalizing a constraint expression.
9197 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9198 ConstraintNormalization, NamedDecl *Template,
9199 SourceRange InstantiationRange);
9200
9201 struct ParameterMappingSubstitution {};
9202 /// \brief Note that we are subtituting into the parameter mapping of an
9203 /// atomic constraint during constraint normalization.
9204 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9205 ParameterMappingSubstitution, NamedDecl *Template,
9206 SourceRange InstantiationRange);
9207
9208 /// \brief Note that we are substituting template arguments into a part of
9209 /// a requirement of a requires expression.
9210 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9211 concepts::Requirement *Req,
9212 sema::TemplateDeductionInfo &DeductionInfo,
9213 SourceRange InstantiationRange = SourceRange());
9214
9215 /// \brief Note that we are checking the satisfaction of the constraint
9216 /// expression inside of a nested requirement.
9217 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9218 concepts::NestedRequirement *Req, ConstraintsCheck,
9219 SourceRange InstantiationRange = SourceRange());
9220
9221 /// Note that we have finished instantiating this template.
9222 void Clear();
9223
9224 ~InstantiatingTemplate() { Clear(); }
9225
9226 /// Determines whether we have exceeded the maximum
9227 /// recursive template instantiations.
9228 bool isInvalid() const { return Invalid; }
9229
9230 /// Determine whether we are already instantiating this
9231 /// specialization in some surrounding active instantiation.
9232 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
9233
9234 private:
9235 Sema &SemaRef;
9236 bool Invalid;
9237 bool AlreadyInstantiating;
9238 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
9239 SourceRange InstantiationRange);
9240
9241 InstantiatingTemplate(
9242 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
9243 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
9244 Decl *Entity, NamedDecl *Template = nullptr,
9245 ArrayRef<TemplateArgument> TemplateArgs = None,
9246 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
9247
9248 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
9249
9250 InstantiatingTemplate&
9251 operator=(const InstantiatingTemplate&) = delete;
9252 };
9253
9254 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
9255 void popCodeSynthesisContext();
9256
9257 /// Determine whether we are currently performing template instantiation.
9258 bool inTemplateInstantiation() const {
9259 return CodeSynthesisContexts.size() > NonInstantiationEntries;
9260 }
9261
9262 void PrintContextStack() {
9263 if (!CodeSynthesisContexts.empty() &&
9264 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
9265 PrintInstantiationStack();
9266 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
9267 }
9268 if (PragmaAttributeCurrentTargetDecl)
9269 PrintPragmaAttributeInstantiationPoint();
9270 }
9271 void PrintInstantiationStack();
9272
9273 void PrintPragmaAttributeInstantiationPoint();
9274
9275 /// Determines whether we are currently in a context where
9276 /// template argument substitution failures are not considered
9277 /// errors.
9278 ///
9279 /// \returns An empty \c Optional if we're not in a SFINAE context.
9280 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
9281 /// template-deduction context object, which can be used to capture
9282 /// diagnostics that will be suppressed.
9283 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
9284
9285 /// Determines whether we are currently in a context that
9286 /// is not evaluated as per C++ [expr] p5.
9287 bool isUnevaluatedContext() const {
9288 assert(!ExprEvalContexts.empty() &&(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9289, __extension__ __PRETTY_FUNCTION__
))
9289 "Must be in an expression evaluation context")(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9289, __extension__ __PRETTY_FUNCTION__
))
;
9290 return ExprEvalContexts.back().isUnevaluated();
9291 }
9292
9293 bool isImmediateFunctionContext() const {
9294 assert(!ExprEvalContexts.empty() &&(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9295, __extension__ __PRETTY_FUNCTION__
))
9295 "Must be in an expression evaluation context")(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9295, __extension__ __PRETTY_FUNCTION__
))
;
9296 return ExprEvalContexts.back().isImmediateFunctionContext();
9297 }
9298
9299 /// RAII class used to determine whether SFINAE has
9300 /// trapped any errors that occur during template argument
9301 /// deduction.
9302 class SFINAETrap {
9303 Sema &SemaRef;
9304 unsigned PrevSFINAEErrors;
9305 bool PrevInNonInstantiationSFINAEContext;
9306 bool PrevAccessCheckingSFINAE;
9307 bool PrevLastDiagnosticIgnored;
9308
9309 public:
9310 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
9311 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
9312 PrevInNonInstantiationSFINAEContext(
9313 SemaRef.InNonInstantiationSFINAEContext),
9314 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
9315 PrevLastDiagnosticIgnored(
9316 SemaRef.getDiagnostics().isLastDiagnosticIgnored())
9317 {
9318 if (!SemaRef.isSFINAEContext())
9319 SemaRef.InNonInstantiationSFINAEContext = true;
9320 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
9321 }
9322
9323 ~SFINAETrap() {
9324 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
9325 SemaRef.InNonInstantiationSFINAEContext
9326 = PrevInNonInstantiationSFINAEContext;
9327 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
9328 SemaRef.getDiagnostics().setLastDiagnosticIgnored(
9329 PrevLastDiagnosticIgnored);
9330 }
9331
9332 /// Determine whether any SFINAE errors have been trapped.
9333 bool hasErrorOccurred() const {
9334 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
9335 }
9336 };
9337
9338 /// RAII class used to indicate that we are performing provisional
9339 /// semantic analysis to determine the validity of a construct, so
9340 /// typo-correction and diagnostics in the immediate context (not within
9341 /// implicitly-instantiated templates) should be suppressed.
9342 class TentativeAnalysisScope {
9343 Sema &SemaRef;
9344 // FIXME: Using a SFINAETrap for this is a hack.
9345 SFINAETrap Trap;
9346 bool PrevDisableTypoCorrection;
9347 public:
9348 explicit TentativeAnalysisScope(Sema &SemaRef)
9349 : SemaRef(SemaRef), Trap(SemaRef, true),
9350 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
9351 SemaRef.DisableTypoCorrection = true;
9352 }
9353 ~TentativeAnalysisScope() {
9354 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
9355 }
9356 };
9357
9358 /// The current instantiation scope used to store local
9359 /// variables.
9360 LocalInstantiationScope *CurrentInstantiationScope;
9361
9362 /// Tracks whether we are in a context where typo correction is
9363 /// disabled.
9364 bool DisableTypoCorrection;
9365
9366 /// The number of typos corrected by CorrectTypo.
9367 unsigned TyposCorrected;
9368
9369 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9370 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9371
9372 /// A cache containing identifiers for which typo correction failed and
9373 /// their locations, so that repeated attempts to correct an identifier in a
9374 /// given location are ignored if typo correction already failed for it.
9375 IdentifierSourceLocations TypoCorrectionFailures;
9376
9377 /// Worker object for performing CFG-based warnings.
9378 sema::AnalysisBasedWarnings AnalysisWarnings;
9379 threadSafety::BeforeSet *ThreadSafetyDeclCache;
9380
9381 /// An entity for which implicit template instantiation is required.
9382 ///
9383 /// The source location associated with the declaration is the first place in
9384 /// the source code where the declaration was "used". It is not necessarily
9385 /// the point of instantiation (which will be either before or after the
9386 /// namespace-scope declaration that triggered this implicit instantiation),
9387 /// However, it is the location that diagnostics should generally refer to,
9388 /// because users will need to know what code triggered the instantiation.
9389 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
9390
9391 /// The queue of implicit template instantiations that are required
9392 /// but have not yet been performed.
9393 std::deque<PendingImplicitInstantiation> PendingInstantiations;
9394
9395 /// Queue of implicit template instantiations that cannot be performed
9396 /// eagerly.
9397 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
9398
9399 class GlobalEagerInstantiationScope {
9400 public:
9401 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
9402 : S(S), Enabled(Enabled) {
9403 if (!Enabled) return;
9404
9405 SavedPendingInstantiations.swap(S.PendingInstantiations);
9406 SavedVTableUses.swap(S.VTableUses);
9407 }
9408
9409 void perform() {
9410 if (Enabled) {
33
Assuming field 'Enabled' is true
34
Taking true branch
9411 S.DefineUsedVTables();
9412 S.PerformPendingInstantiations();
35
Calling 'Sema::PerformPendingInstantiations'
9413 }
9414 }
9415
9416 ~GlobalEagerInstantiationScope() {
9417 if (!Enabled) return;
9418
9419 // Restore the set of pending vtables.
9420 assert(S.VTableUses.empty() &&(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "clang/include/clang/Sema/Sema.h", 9421, __extension__ __PRETTY_FUNCTION__
))
9421 "VTableUses should be empty before it is discarded.")(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "clang/include/clang/Sema/Sema.h", 9421, __extension__ __PRETTY_FUNCTION__
))
;
9422 S.VTableUses.swap(SavedVTableUses);
9423
9424 // Restore the set of pending implicit instantiations.
9425 if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) {
9426 assert(S.PendingInstantiations.empty() &&(static_cast <bool> (S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "clang/include/clang/Sema/Sema.h", 9427, __extension__ __PRETTY_FUNCTION__
))
9427 "PendingInstantiations should be empty before it is discarded.")(static_cast <bool> (S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "clang/include/clang/Sema/Sema.h", 9427, __extension__ __PRETTY_FUNCTION__
))
;
9428 S.PendingInstantiations.swap(SavedPendingInstantiations);
9429 } else {
9430 // Template instantiations in the PCH may be delayed until the TU.
9431 S.PendingInstantiations.swap(SavedPendingInstantiations);
9432 S.PendingInstantiations.insert(S.PendingInstantiations.end(),
9433 SavedPendingInstantiations.begin(),
9434 SavedPendingInstantiations.end());
9435 }
9436 }
9437
9438 private:
9439 Sema &S;
9440 SmallVector<VTableUse, 16> SavedVTableUses;
9441 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
9442 bool Enabled;
9443 };
9444
9445 /// The queue of implicit template instantiations that are required
9446 /// and must be performed within the current local scope.
9447 ///
9448 /// This queue is only used for member functions of local classes in
9449 /// templates, which must be instantiated in the same scope as their
9450 /// enclosing function, so that they can reference function-local
9451 /// types, static variables, enumerators, etc.
9452 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
9453
9454 class LocalEagerInstantiationScope {
9455 public:
9456 LocalEagerInstantiationScope(Sema &S) : S(S) {
9457 SavedPendingLocalImplicitInstantiations.swap(
9458 S.PendingLocalImplicitInstantiations);
9459 }
9460
9461 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
9462
9463 ~LocalEagerInstantiationScope() {
9464 assert(S.PendingLocalImplicitInstantiations.empty() &&(static_cast <bool> (S.PendingLocalImplicitInstantiations
.empty() && "there shouldn't be any pending local implicit instantiations"
) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "clang/include/clang/Sema/Sema.h", 9465, __extension__ __PRETTY_FUNCTION__
))
9465 "there shouldn't be any pending local implicit instantiations")(static_cast <bool> (S.PendingLocalImplicitInstantiations
.empty() && "there shouldn't be any pending local implicit instantiations"
) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "clang/include/clang/Sema/Sema.h", 9465, __extension__ __PRETTY_FUNCTION__
))
;
9466 SavedPendingLocalImplicitInstantiations.swap(
9467 S.PendingLocalImplicitInstantiations);
9468 }
9469
9470 private:
9471 Sema &S;
9472 std::deque<PendingImplicitInstantiation>
9473 SavedPendingLocalImplicitInstantiations;
9474 };
9475
9476 /// A helper class for building up ExtParameterInfos.
9477 class ExtParameterInfoBuilder {
9478 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
9479 bool HasInteresting = false;
9480
9481 public:
9482 /// Set the ExtParameterInfo for the parameter at the given index,
9483 ///
9484 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
9485 assert(Infos.size() <= index)(static_cast <bool> (Infos.size() <= index) ? void (
0) : __assert_fail ("Infos.size() <= index", "clang/include/clang/Sema/Sema.h"
, 9485, __extension__ __PRETTY_FUNCTION__))
;
9486 Infos.resize(index);
9487 Infos.push_back(info);
9488
9489 if (!HasInteresting)
9490 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
9491 }
9492
9493 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
9494 /// ExtParameterInfo array we've built up.
9495 const FunctionProtoType::ExtParameterInfo *
9496 getPointerOrNull(unsigned numParams) {
9497 if (!HasInteresting) return nullptr;
9498 Infos.resize(numParams);
9499 return Infos.data();
9500 }
9501 };
9502
9503 void PerformPendingInstantiations(bool LocalOnly = false);
9504
9505 TypeSourceInfo *SubstType(TypeSourceInfo *T,
9506 const MultiLevelTemplateArgumentList &TemplateArgs,
9507 SourceLocation Loc, DeclarationName Entity,
9508 bool AllowDeducedTST = false);
9509
9510 QualType SubstType(QualType T,
9511 const MultiLevelTemplateArgumentList &TemplateArgs,
9512 SourceLocation Loc, DeclarationName Entity);
9513
9514 TypeSourceInfo *SubstType(TypeLoc TL,
9515 const MultiLevelTemplateArgumentList &TemplateArgs,
9516 SourceLocation Loc, DeclarationName Entity);
9517
9518 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
9519 const MultiLevelTemplateArgumentList &TemplateArgs,
9520 SourceLocation Loc,
9521 DeclarationName Entity,
9522 CXXRecordDecl *ThisContext,
9523 Qualifiers ThisTypeQuals);
9524 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
9525 const MultiLevelTemplateArgumentList &Args);
9526 bool SubstExceptionSpec(SourceLocation Loc,
9527 FunctionProtoType::ExceptionSpecInfo &ESI,
9528 SmallVectorImpl<QualType> &ExceptionStorage,
9529 const MultiLevelTemplateArgumentList &Args);
9530 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
9531 const MultiLevelTemplateArgumentList &TemplateArgs,
9532 int indexAdjustment,
9533 Optional<unsigned> NumExpansions,
9534 bool ExpectParameterPack);
9535 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
9536 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
9537 const MultiLevelTemplateArgumentList &TemplateArgs,
9538 SmallVectorImpl<QualType> &ParamTypes,
9539 SmallVectorImpl<ParmVarDecl *> *OutParams,
9540 ExtParameterInfoBuilder &ParamInfos);
9541 ExprResult SubstExpr(Expr *E,
9542 const MultiLevelTemplateArgumentList &TemplateArgs);
9543
9544 /// Substitute the given template arguments into a list of
9545 /// expressions, expanding pack expansions if required.
9546 ///
9547 /// \param Exprs The list of expressions to substitute into.
9548 ///
9549 /// \param IsCall Whether this is some form of call, in which case
9550 /// default arguments will be dropped.
9551 ///
9552 /// \param TemplateArgs The set of template arguments to substitute.
9553 ///
9554 /// \param Outputs Will receive all of the substituted arguments.
9555 ///
9556 /// \returns true if an error occurred, false otherwise.
9557 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
9558 const MultiLevelTemplateArgumentList &TemplateArgs,
9559 SmallVectorImpl<Expr *> &Outputs);
9560
9561 StmtResult SubstStmt(Stmt *S,
9562 const MultiLevelTemplateArgumentList &TemplateArgs);
9563
9564 TemplateParameterList *
9565 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
9566 const MultiLevelTemplateArgumentList &TemplateArgs);
9567
9568 bool
9569 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
9570 const MultiLevelTemplateArgumentList &TemplateArgs,
9571 TemplateArgumentListInfo &Outputs);
9572
9573
9574 Decl *SubstDecl(Decl *D, DeclContext *Owner,
9575 const MultiLevelTemplateArgumentList &TemplateArgs);
9576
9577 /// Substitute the name and return type of a defaulted 'operator<=>' to form
9578 /// an implicit 'operator=='.
9579 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
9580 FunctionDecl *Spaceship);
9581
9582 ExprResult SubstInitializer(Expr *E,
9583 const MultiLevelTemplateArgumentList &TemplateArgs,
9584 bool CXXDirectInit);
9585
9586 bool
9587 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
9588 CXXRecordDecl *Pattern,
9589 const MultiLevelTemplateArgumentList &TemplateArgs);
9590
9591 bool
9592 InstantiateClass(SourceLocation PointOfInstantiation,
9593 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
9594 const MultiLevelTemplateArgumentList &TemplateArgs,
9595 TemplateSpecializationKind TSK,
9596 bool Complain = true);
9597
9598 bool InstantiateEnum(SourceLocation PointOfInstantiation,
9599 EnumDecl *Instantiation, EnumDecl *Pattern,
9600 const MultiLevelTemplateArgumentList &TemplateArgs,
9601 TemplateSpecializationKind TSK);
9602
9603 bool InstantiateInClassInitializer(
9604 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
9605 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
9606
9607 struct LateInstantiatedAttribute {
9608 const Attr *TmplAttr;
9609 LocalInstantiationScope *Scope;
9610 Decl *NewDecl;
9611
9612 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
9613 Decl *D)
9614 : TmplAttr(A), Scope(S), NewDecl(D)
9615 { }
9616 };
9617 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
9618
9619 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
9620 const Decl *Pattern, Decl *Inst,
9621 LateInstantiatedAttrVec *LateAttrs = nullptr,
9622 LocalInstantiationScope *OuterMostScope = nullptr);
9623
9624 void
9625 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
9626 const Decl *Pattern, Decl *Inst,
9627 LateInstantiatedAttrVec *LateAttrs = nullptr,
9628 LocalInstantiationScope *OuterMostScope = nullptr);
9629
9630 void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
9631
9632 bool usesPartialOrExplicitSpecialization(
9633 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
9634
9635 bool
9636 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
9637 ClassTemplateSpecializationDecl *ClassTemplateSpec,
9638 TemplateSpecializationKind TSK,
9639 bool Complain = true);
9640
9641 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
9642 CXXRecordDecl *Instantiation,
9643 const MultiLevelTemplateArgumentList &TemplateArgs,
9644 TemplateSpecializationKind TSK);
9645
9646 void InstantiateClassTemplateSpecializationMembers(
9647 SourceLocation PointOfInstantiation,
9648 ClassTemplateSpecializationDecl *ClassTemplateSpec,
9649 TemplateSpecializationKind TSK);
9650
9651 NestedNameSpecifierLoc
9652 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
9653 const MultiLevelTemplateArgumentList &TemplateArgs);
9654
9655 DeclarationNameInfo
9656 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
9657 const MultiLevelTemplateArgumentList &TemplateArgs);
9658 TemplateName
9659 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
9660 SourceLocation Loc,
9661 const MultiLevelTemplateArgumentList &TemplateArgs);
9662
9663 bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
9664 const MultiLevelTemplateArgumentList &TemplateArgs);
9665
9666 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
9667 ParmVarDecl *Param);
9668 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
9669 FunctionDecl *Function);
9670 bool CheckInstantiatedFunctionTemplateConstraints(
9671 SourceLocation PointOfInstantiation, FunctionDecl *Decl,
9672 ArrayRef<TemplateArgument> TemplateArgs,
9673 ConstraintSatisfaction &Satisfaction);
9674 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
9675 const TemplateArgumentList *Args,
9676 SourceLocation Loc);
9677 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
9678 FunctionDecl *Function,
9679 bool Recursive = false,
9680 bool DefinitionRequired = false,
9681 bool AtEndOfTU = false);
9682 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
9683 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
9684 const TemplateArgumentList &TemplateArgList,
9685 const TemplateArgumentListInfo &TemplateArgsInfo,
9686 SmallVectorImpl<TemplateArgument> &Converted,
9687 SourceLocation PointOfInstantiation,
9688 LateInstantiatedAttrVec *LateAttrs = nullptr,
9689 LocalInstantiationScope *StartingScope = nullptr);
9690 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
9691 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
9692 const MultiLevelTemplateArgumentList &TemplateArgs);
9693 void
9694 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
9695 const MultiLevelTemplateArgumentList &TemplateArgs,
9696 LateInstantiatedAttrVec *LateAttrs,
9697 DeclContext *Owner,
9698 LocalInstantiationScope *StartingScope,
9699 bool InstantiatingVarTemplate = false,
9700 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
9701
9702 void InstantiateVariableInitializer(
9703 VarDecl *Var, VarDecl *OldVar,
9704 const MultiLevelTemplateArgumentList &TemplateArgs);
9705 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
9706 VarDecl *Var, bool Recursive = false,
9707 bool DefinitionRequired = false,
9708 bool AtEndOfTU = false);
9709
9710 void InstantiateMemInitializers(CXXConstructorDecl *New,
9711 const CXXConstructorDecl *Tmpl,
9712 const MultiLevelTemplateArgumentList &TemplateArgs);
9713
9714 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
9715 const MultiLevelTemplateArgumentList &TemplateArgs,
9716 bool FindingInstantiatedContext = false);
9717 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
9718 const MultiLevelTemplateArgumentList &TemplateArgs);
9719
9720 // Objective-C declarations.
9721 enum ObjCContainerKind {
9722 OCK_None = -1,
9723 OCK_Interface = 0,
9724 OCK_Protocol,
9725 OCK_Category,
9726 OCK_ClassExtension,
9727 OCK_Implementation,
9728 OCK_CategoryImplementation
9729 };
9730 ObjCContainerKind getObjCContainerKind() const;
9731
9732 DeclResult actOnObjCTypeParam(Scope *S,
9733 ObjCTypeParamVariance variance,
9734 SourceLocation varianceLoc,
9735 unsigned index,
9736 IdentifierInfo *paramName,
9737 SourceLocation paramLoc,
9738 SourceLocation colonLoc,
9739 ParsedType typeBound);
9740
9741 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
9742 ArrayRef<Decl *> typeParams,
9743 SourceLocation rAngleLoc);
9744 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
9745
9746 Decl *ActOnStartClassInterface(
9747 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9748 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9749 IdentifierInfo *SuperName, SourceLocation SuperLoc,
9750 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
9751 Decl *const *ProtoRefs, unsigned NumProtoRefs,
9752 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9753 const ParsedAttributesView &AttrList);
9754
9755 void ActOnSuperClassOfClassInterface(Scope *S,
9756 SourceLocation AtInterfaceLoc,
9757 ObjCInterfaceDecl *IDecl,
9758 IdentifierInfo *ClassName,
9759 SourceLocation ClassLoc,
9760 IdentifierInfo *SuperName,
9761 SourceLocation SuperLoc,
9762 ArrayRef<ParsedType> SuperTypeArgs,
9763 SourceRange SuperTypeArgsRange);
9764
9765 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
9766 SmallVectorImpl<SourceLocation> &ProtocolLocs,
9767 IdentifierInfo *SuperName,
9768 SourceLocation SuperLoc);
9769
9770 Decl *ActOnCompatibilityAlias(
9771 SourceLocation AtCompatibilityAliasLoc,
9772 IdentifierInfo *AliasName, SourceLocation AliasLocation,
9773 IdentifierInfo *ClassName, SourceLocation ClassLocation);
9774
9775 bool CheckForwardProtocolDeclarationForCircularDependency(
9776 IdentifierInfo *PName,
9777 SourceLocation &PLoc, SourceLocation PrevLoc,
9778 const ObjCList<ObjCProtocolDecl> &PList);
9779
9780 Decl *ActOnStartProtocolInterface(
9781 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
9782 SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
9783 unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
9784 SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
9785
9786 Decl *ActOnStartCategoryInterface(
9787 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9788 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9789 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
9790 Decl *const *ProtoRefs, unsigned NumProtoRefs,
9791 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9792 const ParsedAttributesView &AttrList);
9793
9794 Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
9795 IdentifierInfo *ClassName,
9796 SourceLocation ClassLoc,
9797 IdentifierInfo *SuperClassname,
9798 SourceLocation SuperClassLoc,
9799 const ParsedAttributesView &AttrList);
9800
9801 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
9802 IdentifierInfo *ClassName,
9803 SourceLocation ClassLoc,
9804 IdentifierInfo *CatName,
9805 SourceLocation CatLoc,
9806 const ParsedAttributesView &AttrList);
9807
9808 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
9809 ArrayRef<Decl *> Decls);
9810
9811 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
9812 IdentifierInfo **IdentList,
9813 SourceLocation *IdentLocs,
9814 ArrayRef<ObjCTypeParamList *> TypeParamLists,
9815 unsigned NumElts);
9816
9817 DeclGroupPtrTy
9818 ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
9819 ArrayRef<IdentifierLocPair> IdentList,
9820 const ParsedAttributesView &attrList);
9821
9822 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
9823 ArrayRef<IdentifierLocPair> ProtocolId,
9824 SmallVectorImpl<Decl *> &Protocols);
9825
9826 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
9827 SourceLocation ProtocolLoc,
9828 IdentifierInfo *TypeArgId,
9829 SourceLocation TypeArgLoc,
9830 bool SelectProtocolFirst = false);
9831
9832 /// Given a list of identifiers (and their locations), resolve the
9833 /// names to either Objective-C protocol qualifiers or type
9834 /// arguments, as appropriate.
9835 void actOnObjCTypeArgsOrProtocolQualifiers(
9836 Scope *S,
9837 ParsedType baseType,
9838 SourceLocation lAngleLoc,
9839 ArrayRef<IdentifierInfo *> identifiers,
9840 ArrayRef<SourceLocation> identifierLocs,
9841 SourceLocation rAngleLoc,
9842 SourceLocation &typeArgsLAngleLoc,
9843 SmallVectorImpl<ParsedType> &typeArgs,
9844 SourceLocation &typeArgsRAngleLoc,
9845 SourceLocation &protocolLAngleLoc,
9846 SmallVectorImpl<Decl *> &protocols,
9847 SourceLocation &protocolRAngleLoc,
9848 bool warnOnIncompleteProtocols);
9849
9850 /// Build a an Objective-C protocol-qualified 'id' type where no
9851 /// base type was specified.
9852 TypeResult actOnObjCProtocolQualifierType(
9853 SourceLocation lAngleLoc,
9854 ArrayRef<Decl *> protocols,
9855 ArrayRef<SourceLocation> protocolLocs,
9856 SourceLocation rAngleLoc);
9857
9858 /// Build a specialized and/or protocol-qualified Objective-C type.
9859 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
9860 Scope *S,
9861 SourceLocation Loc,
9862 ParsedType BaseType,
9863 SourceLocation TypeArgsLAngleLoc,
9864 ArrayRef<ParsedType> TypeArgs,
9865 SourceLocation TypeArgsRAngleLoc,
9866 SourceLocation ProtocolLAngleLoc,
9867 ArrayRef<Decl *> Protocols,
9868 ArrayRef<SourceLocation> ProtocolLocs,
9869 SourceLocation ProtocolRAngleLoc);
9870
9871 /// Build an Objective-C type parameter type.
9872 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
9873 SourceLocation ProtocolLAngleLoc,
9874 ArrayRef<ObjCProtocolDecl *> Protocols,
9875 ArrayRef<SourceLocation> ProtocolLocs,
9876 SourceLocation ProtocolRAngleLoc,
9877 bool FailOnError = false);
9878
9879 /// Build an Objective-C object pointer type.
9880 QualType BuildObjCObjectType(QualType BaseType,
9881 SourceLocation Loc,
9882 SourceLocation TypeArgsLAngleLoc,
9883 ArrayRef<TypeSourceInfo *> TypeArgs,
9884 SourceLocation TypeArgsRAngleLoc,
9885 SourceLocation ProtocolLAngleLoc,
9886 ArrayRef<ObjCProtocolDecl *> Protocols,
9887 ArrayRef<SourceLocation> ProtocolLocs,
9888 SourceLocation ProtocolRAngleLoc,
9889 bool FailOnError = false);
9890
9891 /// Ensure attributes are consistent with type.
9892 /// \param [in, out] Attributes The attributes to check; they will
9893 /// be modified to be consistent with \p PropertyTy.
9894 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
9895 SourceLocation Loc,
9896 unsigned &Attributes,
9897 bool propertyInPrimaryClass);
9898
9899 /// Process the specified property declaration and create decls for the
9900 /// setters and getters as needed.
9901 /// \param property The property declaration being processed
9902 void ProcessPropertyDecl(ObjCPropertyDecl *property);
9903
9904
9905 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
9906 ObjCPropertyDecl *SuperProperty,
9907 const IdentifierInfo *Name,
9908 bool OverridingProtocolProperty);
9909
9910 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
9911 ObjCInterfaceDecl *ID);
9912
9913 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
9914 ArrayRef<Decl *> allMethods = None,
9915 ArrayRef<DeclGroupPtrTy> allTUVars = None);
9916
9917 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
9918 SourceLocation LParenLoc,
9919 FieldDeclarator &FD, ObjCDeclSpec &ODS,
9920 Selector GetterSel, Selector SetterSel,
9921 tok::ObjCKeywordKind MethodImplKind,
9922 DeclContext *lexicalDC = nullptr);
9923
9924 Decl *ActOnPropertyImplDecl(Scope *S,
9925 SourceLocation AtLoc,
9926 SourceLocation PropertyLoc,
9927 bool ImplKind,
9928 IdentifierInfo *PropertyId,
9929 IdentifierInfo *PropertyIvar,
9930 SourceLocation PropertyIvarLoc,
9931 ObjCPropertyQueryKind QueryKind);
9932
9933 enum ObjCSpecialMethodKind {
9934 OSMK_None,
9935 OSMK_Alloc,
9936 OSMK_New,
9937 OSMK_Copy,
9938 OSMK_RetainingInit,
9939 OSMK_NonRetainingInit
9940 };
9941
9942 struct ObjCArgInfo {
9943 IdentifierInfo *Name;
9944 SourceLocation NameLoc;
9945 // The Type is null if no type was specified, and the DeclSpec is invalid
9946 // in this case.
9947 ParsedType Type;
9948 ObjCDeclSpec DeclSpec;
9949
9950 /// ArgAttrs - Attribute list for this argument.
9951 ParsedAttributesView ArgAttrs;
9952 };
9953
9954 Decl *ActOnMethodDeclaration(
9955 Scope *S,
9956 SourceLocation BeginLoc, // location of the + or -.
9957 SourceLocation EndLoc, // location of the ; or {.
9958 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
9959 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
9960 // optional arguments. The number of types/arguments is obtained
9961 // from the Sel.getNumArgs().
9962 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
9963 unsigned CNumArgs, // c-style args
9964 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
9965 bool isVariadic, bool MethodDefinition);
9966
9967 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
9968 const ObjCObjectPointerType *OPT,
9969 bool IsInstance);
9970 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
9971 bool IsInstance);
9972
9973 bool CheckARCMethodDecl(ObjCMethodDecl *method);
9974 bool inferObjCARCLifetime(ValueDecl *decl);
9975
9976 void deduceOpenCLAddressSpace(ValueDecl *decl);
9977
9978 ExprResult
9979 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
9980 Expr *BaseExpr,
9981 SourceLocation OpLoc,
9982 DeclarationName MemberName,
9983 SourceLocation MemberLoc,
9984 SourceLocation SuperLoc, QualType SuperType,
9985 bool Super);
9986
9987 ExprResult
9988 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
9989 IdentifierInfo &propertyName,
9990 SourceLocation receiverNameLoc,
9991 SourceLocation propertyNameLoc);
9992
9993 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
9994
9995 /// Describes the kind of message expression indicated by a message
9996 /// send that starts with an identifier.
9997 enum ObjCMessageKind {
9998 /// The message is sent to 'super'.
9999 ObjCSuperMessage,
10000 /// The message is an instance message.
10001 ObjCInstanceMessage,
10002 /// The message is a class message, and the identifier is a type
10003 /// name.
10004 ObjCClassMessage
10005 };
10006
10007 ObjCMessageKind getObjCMessageKind(Scope *S,
10008 IdentifierInfo *Name,
10009 SourceLocation NameLoc,
10010 bool IsSuper,
10011 bool HasTrailingDot,
10012 ParsedType &ReceiverType);
10013
10014 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
10015 Selector Sel,
10016 SourceLocation LBracLoc,
10017 ArrayRef<SourceLocation> SelectorLocs,
10018 SourceLocation RBracLoc,
10019 MultiExprArg Args);
10020
10021 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
10022 QualType ReceiverType,
10023 SourceLocation SuperLoc,
10024 Selector Sel,
10025 ObjCMethodDecl *Method,
10026 SourceLocation LBracLoc,
10027 ArrayRef<SourceLocation> SelectorLocs,
10028 SourceLocation RBracLoc,
10029 MultiExprArg Args,
10030 bool isImplicit = false);
10031
10032 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
10033 bool isSuperReceiver,
10034 SourceLocation Loc,
10035 Selector Sel,
10036 ObjCMethodDecl *Method,
10037 MultiExprArg Args);
10038
10039 ExprResult ActOnClassMessage(Scope *S,
10040 ParsedType Receiver,
10041 Selector Sel,
10042 SourceLocation LBracLoc,
10043 ArrayRef<SourceLocation> SelectorLocs,
10044 SourceLocation RBracLoc,
10045 MultiExprArg Args);
10046
10047 ExprResult BuildInstanceMessage(Expr *Receiver,
10048 QualType ReceiverType,
10049 SourceLocation SuperLoc,
10050 Selector Sel,
10051 ObjCMethodDecl *Method,
10052 SourceLocation LBracLoc,
10053 ArrayRef<SourceLocation> SelectorLocs,
10054 SourceLocation RBracLoc,
10055 MultiExprArg Args,
10056 bool isImplicit = false);
10057
10058 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
10059 QualType ReceiverType,
10060 SourceLocation Loc,
10061 Selector Sel,
10062 ObjCMethodDecl *Method,
10063 MultiExprArg Args);
10064
10065 ExprResult ActOnInstanceMessage(Scope *S,
10066 Expr *Receiver,
10067 Selector Sel,
10068 SourceLocation LBracLoc,
10069 ArrayRef<SourceLocation> SelectorLocs,
10070 SourceLocation RBracLoc,
10071 MultiExprArg Args);
10072
10073 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
10074 ObjCBridgeCastKind Kind,
10075 SourceLocation BridgeKeywordLoc,
10076 TypeSourceInfo *TSInfo,
10077 Expr *SubExpr);
10078
10079 ExprResult ActOnObjCBridgedCast(Scope *S,
10080 SourceLocation LParenLoc,
10081 ObjCBridgeCastKind Kind,
10082 SourceLocation BridgeKeywordLoc,
10083 ParsedType Type,
10084 SourceLocation RParenLoc,
10085 Expr *SubExpr);
10086
10087 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
10088
10089 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
10090
10091 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
10092 CastKind &Kind);
10093
10094 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
10095 QualType DestType, QualType SrcType,
10096 ObjCInterfaceDecl *&RelatedClass,
10097 ObjCMethodDecl *&ClassMethod,
10098 ObjCMethodDecl *&InstanceMethod,
10099 TypedefNameDecl *&TDNDecl,
10100 bool CfToNs, bool Diagnose = true);
10101
10102 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
10103 QualType DestType, QualType SrcType,
10104 Expr *&SrcExpr, bool Diagnose = true);
10105
10106 bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr,
10107 bool Diagnose = true);
10108
10109 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
10110
10111 /// Check whether the given new method is a valid override of the
10112 /// given overridden method, and set any properties that should be inherited.
10113 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
10114 const ObjCMethodDecl *Overridden);
10115
10116 /// Describes the compatibility of a result type with its method.
10117 enum ResultTypeCompatibilityKind {
10118 RTC_Compatible,
10119 RTC_Incompatible,
10120 RTC_Unknown
10121 };
10122
10123 void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
10124 ObjCMethodDecl *overridden);
10125
10126 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
10127 ObjCInterfaceDecl *CurrentClass,
10128 ResultTypeCompatibilityKind RTC);
10129
10130 enum PragmaOptionsAlignKind {
10131 POAK_Native, // #pragma options align=native
10132 POAK_Natural, // #pragma options align=natural
10133 POAK_Packed, // #pragma options align=packed
10134 POAK_Power, // #pragma options align=power
10135 POAK_Mac68k, // #pragma options align=mac68k
10136 POAK_Reset // #pragma options align=reset
10137 };
10138
10139 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
10140 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
10141 PragmaClangSectionAction Action,
10142 PragmaClangSectionKind SecKind, StringRef SecName);
10143
10144 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
10145 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
10146 SourceLocation PragmaLoc);
10147
10148 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
10149 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
10150 StringRef SlotLabel, Expr *Alignment);
10151
10152 enum class PragmaAlignPackDiagnoseKind {
10153 NonDefaultStateAtInclude,
10154 ChangedStateAtExit
10155 };
10156
10157 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
10158 SourceLocation IncludeLoc);
10159 void DiagnoseUnterminatedPragmaAlignPack();
10160
10161 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
10162 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
10163
10164 /// ActOnPragmaMSComment - Called on well formed
10165 /// \#pragma comment(kind, "arg").
10166 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
10167 StringRef Arg);
10168
10169 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
10170 /// pointers_to_members(representation method[, general purpose
10171 /// representation]).
10172 void ActOnPragmaMSPointersToMembers(
10173 LangOptions::PragmaMSPointersToMembersKind Kind,
10174 SourceLocation PragmaLoc);
10175
10176 /// Called on well formed \#pragma vtordisp().
10177 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
10178 SourceLocation PragmaLoc,
10179 MSVtorDispMode Value);
10180
10181 enum PragmaSectionKind {
10182 PSK_DataSeg,
10183 PSK_BSSSeg,
10184 PSK_ConstSeg,
10185 PSK_CodeSeg,
10186 };
10187
10188 bool UnifySection(StringRef SectionName, int SectionFlags,
10189 NamedDecl *TheDecl);
10190 bool UnifySection(StringRef SectionName,
10191 int SectionFlags,
10192 SourceLocation PragmaSectionLocation);
10193
10194 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
10195 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
10196 PragmaMsStackAction Action,
10197 llvm::StringRef StackSlotLabel,
10198 StringLiteral *SegmentName,
10199 llvm::StringRef PragmaName);
10200
10201 /// Called on well formed \#pragma section().
10202 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
10203 int SectionFlags, StringLiteral *SegmentName);
10204
10205 /// Called on well-formed \#pragma init_seg().
10206 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
10207 StringLiteral *SegmentName);
10208
10209 /// Called on #pragma clang __debug dump II
10210 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
10211
10212 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
10213 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
10214 StringRef Value);
10215
10216 /// Are precise floating point semantics currently enabled?
10217 bool isPreciseFPEnabled() {
10218 return !CurFPFeatures.getAllowFPReassociate() &&
10219 !CurFPFeatures.getNoSignedZero() &&
10220 !CurFPFeatures.getAllowReciprocal() &&
10221 !CurFPFeatures.getAllowApproxFunc();
10222 }
10223
10224 void ActOnPragmaFPEvalMethod(SourceLocation Loc,
10225 LangOptions::FPEvalMethodKind Value);
10226
10227 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
10228 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
10229 PragmaFloatControlKind Value);
10230
10231 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
10232 void ActOnPragmaUnused(const Token &Identifier,
10233 Scope *curScope,
10234 SourceLocation PragmaLoc);
10235
10236 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
10237 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
10238 SourceLocation PragmaLoc);
10239
10240 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
10241 SourceLocation Loc);
10242 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
10243
10244 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
10245 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
10246 SourceLocation PragmaLoc,
10247 SourceLocation WeakNameLoc);
10248
10249 /// ActOnPragmaRedefineExtname - Called on well formed
10250 /// \#pragma redefine_extname oldname newname.
10251 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
10252 IdentifierInfo* AliasName,
10253 SourceLocation PragmaLoc,
10254 SourceLocation WeakNameLoc,
10255 SourceLocation AliasNameLoc);
10256
10257 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
10258 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
10259 IdentifierInfo* AliasName,
10260 SourceLocation PragmaLoc,
10261 SourceLocation WeakNameLoc,
10262 SourceLocation AliasNameLoc);
10263
10264 /// ActOnPragmaFPContract - Called on well formed
10265 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
10266 /// \#pragma clang fp contract
10267 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
10268
10269 /// Called on well formed
10270 /// \#pragma clang fp reassociate
10271 void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled);
10272
10273 /// ActOnPragmaFenvAccess - Called on well formed
10274 /// \#pragma STDC FENV_ACCESS
10275 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
10276
10277 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
10278 void ActOnPragmaFPExceptions(SourceLocation Loc,
10279 LangOptions::FPExceptionModeKind);
10280
10281 /// Called to set constant rounding mode for floating point operations.
10282 void setRoundingMode(SourceLocation Loc, llvm::RoundingMode);
10283
10284 /// Called to set exception behavior for floating point operations.
10285 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
10286
10287 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
10288 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
10289 void AddAlignmentAttributesForRecord(RecordDecl *RD);
10290
10291 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
10292 void AddMsStructLayoutForRecord(RecordDecl *RD);
10293
10294 /// PushNamespaceVisibilityAttr - Note that we've entered a
10295 /// namespace with a visibility attribute.
10296 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
10297 SourceLocation Loc);
10298
10299 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
10300 /// add an appropriate visibility attribute.
10301 void AddPushedVisibilityAttribute(Decl *RD);
10302
10303 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
10304 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
10305 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
10306
10307 /// FreeVisContext - Deallocate and null out VisContext.
10308 void FreeVisContext();
10309
10310 /// AddCFAuditedAttribute - Check whether we're currently within
10311 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
10312 /// the appropriate attribute.
10313 void AddCFAuditedAttribute(Decl *D);
10314
10315 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
10316 SourceLocation PragmaLoc,
10317 attr::ParsedSubjectMatchRuleSet Rules);
10318 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
10319 const IdentifierInfo *Namespace);
10320
10321 /// Called on well-formed '\#pragma clang attribute pop'.
10322 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
10323 const IdentifierInfo *Namespace);
10324
10325 /// Adds the attributes that have been specified using the
10326 /// '\#pragma clang attribute push' directives to the given declaration.
10327 void AddPragmaAttributes(Scope *S, Decl *D);
10328
10329 void DiagnoseUnterminatedPragmaAttribute();
10330
10331 /// Called on well formed \#pragma clang optimize.
10332 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
10333
10334 /// Get the location for the currently active "\#pragma clang optimize
10335 /// off". If this location is invalid, then the state of the pragma is "on".
10336 SourceLocation getOptimizeOffPragmaLocation() const {
10337 return OptimizeOffPragmaLocation;
10338 }
10339
10340 /// Only called on function definitions; if there is a pragma in scope
10341 /// with the effect of a range-based optnone, consider marking the function
10342 /// with attribute optnone.
10343 void AddRangeBasedOptnone(FunctionDecl *FD);
10344
10345 /// Adds the 'optnone' attribute to the function declaration if there
10346 /// are no conflicts; Loc represents the location causing the 'optnone'
10347 /// attribute to be added (usually because of a pragma).
10348 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
10349
10350 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
10351 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10352 bool IsPackExpansion);
10353 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
10354 bool IsPackExpansion);
10355
10356 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
10357 /// declaration.
10358 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10359 Expr *OE);
10360
10361 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
10362 /// declaration.
10363 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
10364 Expr *ParamExpr);
10365
10366 /// AddAlignValueAttr - Adds an align_value attribute to a particular
10367 /// declaration.
10368 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
10369
10370 /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
10371 void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
10372 StringRef Annot, MutableArrayRef<Expr *> Args);
10373
10374 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
10375 /// declaration.
10376 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
10377 Expr *MaxThreads, Expr *MinBlocks);
10378
10379 /// AddModeAttr - Adds a mode attribute to a particular declaration.
10380 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
10381 bool InInstantiation = false);
10382
10383 void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
10384 ParameterABI ABI);
10385
10386 enum class RetainOwnershipKind {NS, CF, OS};
10387 void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
10388 RetainOwnershipKind K, bool IsTemplateInstantiation);
10389
10390 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
10391 /// attribute to a particular declaration.
10392 void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
10393 Expr *Min, Expr *Max);
10394
10395 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
10396 /// particular declaration.
10397 void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
10398 Expr *Min, Expr *Max);
10399
10400 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
10401
10402 //===--------------------------------------------------------------------===//
10403 // C++ Coroutines TS
10404 //
10405 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
10406 StringRef Keyword);
10407 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10408 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10409 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
10410
10411 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
10412 bool IsImplicit = false);
10413 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
10414 UnresolvedLookupExpr* Lookup);
10415 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
10416 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
10417 bool IsImplicit = false);
10418 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
10419 bool buildCoroutineParameterMoves(SourceLocation Loc);
10420 VarDecl *buildCoroutinePromise(SourceLocation Loc);
10421 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
10422 /// Lookup 'coroutine_traits' in std namespace and std::experimental
10423 /// namespace. The namespace found is recorded in Namespace.
10424 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
10425 SourceLocation FuncLoc,
10426 NamespaceDecl *&Namespace);
10427 /// Check that the expression co_await promise.final_suspend() shall not be
10428 /// potentially-throwing.
10429 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
10430
10431 //===--------------------------------------------------------------------===//
10432 // OpenMP directives and clauses.
10433 //
10434private:
10435 void *VarDataSharingAttributesStack;
10436
10437 struct DeclareTargetContextInfo {
10438 struct MapInfo {
10439 OMPDeclareTargetDeclAttr::MapTypeTy MT;
10440 SourceLocation Loc;
10441 };
10442 /// Explicitly listed variables and functions in a 'to' or 'link' clause.
10443 llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped;
10444
10445 /// The 'device_type' as parsed from the clause.
10446 OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any;
10447
10448 /// The directive kind, `begin declare target` or `declare target`.
10449 OpenMPDirectiveKind Kind;
10450
10451 /// The directive with indirect clause.
10452 Optional<Expr *> Indirect;
10453
10454 /// The directive location.
10455 SourceLocation Loc;
10456
10457 DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc)
10458 : Kind(Kind), Loc(Loc) {}
10459 };
10460
10461 /// Number of nested '#pragma omp declare target' directives.
10462 SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting;
10463
10464 /// Initialization of data-sharing attributes stack.
10465 void InitDataSharingAttributesStack();
10466 void DestroyDataSharingAttributesStack();
10467 ExprResult
10468 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
10469 bool StrictlyPositive = true,
10470 bool SuppressExprDiags = false);
10471 /// Returns OpenMP nesting level for current directive.
10472 unsigned getOpenMPNestingLevel() const;
10473
10474 /// Adjusts the function scopes index for the target-based regions.
10475 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
10476 unsigned Level) const;
10477
10478 /// Returns the number of scopes associated with the construct on the given
10479 /// OpenMP level.
10480 int getNumberOfConstructScopes(unsigned Level) const;
10481
10482 /// Push new OpenMP function region for non-capturing function.
10483 void pushOpenMPFunctionRegion();
10484
10485 /// Pop OpenMP function region for non-capturing function.
10486 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
10487
10488 /// Analyzes and checks a loop nest for use by a loop transformation.
10489 ///
10490 /// \param Kind The loop transformation directive kind.
10491 /// \param NumLoops How many nested loops the directive is expecting.
10492 /// \param AStmt Associated statement of the transformation directive.
10493 /// \param LoopHelpers [out] The loop analysis result.
10494 /// \param Body [out] The body code nested in \p NumLoops loop.
10495 /// \param OriginalInits [out] Collection of statements and declarations that
10496 /// must have been executed/declared before entering the
10497 /// loop.
10498 ///
10499 /// \return Whether there was any error.
10500 bool checkTransformableLoopNest(
10501 OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
10502 SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
10503 Stmt *&Body,
10504 SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
10505 &OriginalInits);
10506
10507 /// Helper to keep information about the current `omp begin/end declare
10508 /// variant` nesting.
10509 struct OMPDeclareVariantScope {
10510 /// The associated OpenMP context selector.
10511 OMPTraitInfo *TI;
10512
10513 /// The associated OpenMP context selector mangling.
10514 std::string NameSuffix;
10515
10516 OMPDeclareVariantScope(OMPTraitInfo &TI);
10517 };
10518
10519 /// Return the OMPTraitInfo for the surrounding scope, if any.
10520 OMPTraitInfo *getOMPTraitInfoForSurroundingScope() {
10521 return OMPDeclareVariantScopes.empty() ? nullptr
10522 : OMPDeclareVariantScopes.back().TI;
10523 }
10524
10525 /// The current `omp begin/end declare variant` scopes.
10526 SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
10527
10528 /// The current `omp begin/end assumes` scopes.
10529 SmallVector<AssumptionAttr *, 4> OMPAssumeScoped;
10530
10531 /// All `omp assumes` we encountered so far.
10532 SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal;
10533
10534public:
10535 /// The declarator \p D defines a function in the scope \p S which is nested
10536 /// in an `omp begin/end declare variant` scope. In this method we create a
10537 /// declaration for \p D and rename \p D according to the OpenMP context
10538 /// selector of the surrounding scope. Return all base functions in \p Bases.
10539 void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
10540 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists,
10541 SmallVectorImpl<FunctionDecl *> &Bases);
10542
10543 /// Register \p D as specialization of all base functions in \p Bases in the
10544 /// current `omp begin/end declare variant` scope.
10545 void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
10546 Decl *D, SmallVectorImpl<FunctionDecl *> &Bases);
10547
10548 /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`.
10549 void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D);
10550
10551 /// Can we exit an OpenMP declare variant scope at the moment.
10552 bool isInOpenMPDeclareVariantScope() const {
10553 return !OMPDeclareVariantScopes.empty();
10554 }
10555
10556 /// Given the potential call expression \p Call, determine if there is a
10557 /// specialization via the OpenMP declare variant mechanism available. If
10558 /// there is, return the specialized call expression, otherwise return the
10559 /// original \p Call.
10560 ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope,
10561 SourceLocation LParenLoc, MultiExprArg ArgExprs,
10562 SourceLocation RParenLoc, Expr *ExecConfig);
10563
10564 /// Handle a `omp begin declare variant`.
10565 void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI);
10566
10567 /// Handle a `omp end declare variant`.
10568 void ActOnOpenMPEndDeclareVariant();
10569
10570 /// Checks if the variant/multiversion functions are compatible.
10571 bool areMultiversionVariantFunctionsCompatible(
10572 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10573 const PartialDiagnostic &NoProtoDiagID,
10574 const PartialDiagnosticAt &NoteCausedDiagIDAt,
10575 const PartialDiagnosticAt &NoSupportDiagIDAt,
10576 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10577 bool ConstexprSupported, bool CLinkageMayDiffer);
10578
10579 /// Function tries to capture lambda's captured variables in the OpenMP region
10580 /// before the original lambda is captured.
10581 void tryCaptureOpenMPLambdas(ValueDecl *V);
10582
10583 /// Return true if the provided declaration \a VD should be captured by
10584 /// reference.
10585 /// \param Level Relative level of nested OpenMP construct for that the check
10586 /// is performed.
10587 /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
10588 bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
10589 unsigned OpenMPCaptureLevel) const;
10590
10591 /// Check if the specified variable is used in one of the private
10592 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
10593 /// constructs.
10594 VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
10595 unsigned StopAt = 0);
10596 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
10597 ExprObjectKind OK, SourceLocation Loc);
10598
10599 /// If the current region is a loop-based region, mark the start of the loop
10600 /// construct.
10601 void startOpenMPLoop();
10602
10603 /// If the current region is a range loop-based region, mark the start of the
10604 /// loop construct.
10605 void startOpenMPCXXRangeFor();
10606
10607 /// Check if the specified variable is used in 'private' clause.
10608 /// \param Level Relative level of nested OpenMP construct for that the check
10609 /// is performed.
10610 OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
10611 unsigned CapLevel) const;
10612
10613 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
10614 /// for \p FD based on DSA for the provided corresponding captured declaration
10615 /// \p D.
10616 void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
10617
10618 /// Check if the specified variable is captured by 'target' directive.
10619 /// \param Level Relative level of nested OpenMP construct for that the check
10620 /// is performed.
10621 bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
10622 unsigned CaptureLevel) const;
10623
10624 /// Check if the specified global variable must be captured by outer capture
10625 /// regions.
10626 /// \param Level Relative level of nested OpenMP construct for that
10627 /// the check is performed.
10628 bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
10629 unsigned CaptureLevel) const;
10630
10631 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
10632 Expr *Op);
10633 /// Called on start of new data sharing attribute block.
10634 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
10635 const DeclarationNameInfo &DirName, Scope *CurScope,
10636 SourceLocation Loc);
10637 /// Start analysis of clauses.
10638 void StartOpenMPClause(OpenMPClauseKind K);
10639 /// End analysis of clauses.
10640 void EndOpenMPClause();
10641 /// Called on end of data sharing attribute block.
10642 void EndOpenMPDSABlock(Stmt *CurDirective);
10643
10644 /// Check if the current region is an OpenMP loop region and if it is,
10645 /// mark loop control variable, used in \p Init for loop initialization, as
10646 /// private by default.
10647 /// \param Init First part of the for loop.
10648 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
10649
10650 /// Called on well-formed '\#pragma omp metadirective' after parsing
10651 /// of the associated statement.
10652 StmtResult ActOnOpenMPMetaDirective(ArrayRef<OMPClause *> Clauses,
10653 Stmt *AStmt, SourceLocation StartLoc,
10654 SourceLocation EndLoc);
10655
10656 // OpenMP directives and clauses.
10657 /// Called on correct id-expression from the '#pragma omp
10658 /// threadprivate'.
10659 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
10660 const DeclarationNameInfo &Id,
10661 OpenMPDirectiveKind Kind);
10662 /// Called on well-formed '#pragma omp threadprivate'.
10663 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
10664 SourceLocation Loc,
10665 ArrayRef<Expr *> VarList);
10666 /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
10667 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
10668 ArrayRef<Expr *> VarList);
10669 /// Called on well-formed '#pragma omp allocate'.
10670 DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
10671 ArrayRef<Expr *> VarList,
10672 ArrayRef<OMPClause *> Clauses,
10673 DeclContext *Owner = nullptr);
10674
10675 /// Called on well-formed '#pragma omp [begin] assume[s]'.
10676 void ActOnOpenMPAssumesDirective(SourceLocation Loc,
10677 OpenMPDirectiveKind DKind,
10678 ArrayRef<std::string> Assumptions,
10679 bool SkippedClauses);
10680
10681 /// Check if there is an active global `omp begin assumes` directive.
10682 bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); }
10683
10684 /// Check if there is an active global `omp assumes` directive.
10685 bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); }
10686
10687 /// Called on well-formed '#pragma omp end assumes'.
10688 void ActOnOpenMPEndAssumesDirective();
10689
10690 /// Called on well-formed '#pragma omp requires'.
10691 DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
10692 ArrayRef<OMPClause *> ClauseList);
10693 /// Check restrictions on Requires directive
10694 OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
10695 ArrayRef<OMPClause *> Clauses);
10696 /// Check if the specified type is allowed to be used in 'omp declare
10697 /// reduction' construct.
10698 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10699 TypeResult ParsedType);
10700 /// Called on start of '#pragma omp declare reduction'.
10701 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
10702 Scope *S, DeclContext *DC, DeclarationName Name,
10703 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10704 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
10705 /// Initialize declare reduction construct initializer.
10706 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
10707 /// Finish current declare reduction construct initializer.
10708 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
10709 /// Initialize declare reduction construct initializer.
10710 /// \return omp_priv variable.
10711 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
10712 /// Finish current declare reduction construct initializer.
10713 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
10714 VarDecl *OmpPrivParm);
10715 /// Called at the end of '#pragma omp declare reduction'.
10716 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
10717 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
10718
10719 /// Check variable declaration in 'omp declare mapper' construct.
10720 TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
10721 /// Check if the specified type is allowed to be used in 'omp declare
10722 /// mapper' construct.
10723 QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
10724 TypeResult ParsedType);
10725 /// Called on start of '#pragma omp declare mapper'.
10726 DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(
10727 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
10728 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
10729 Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses,
10730 Decl *PrevDeclInScope = nullptr);
10731 /// Build the mapper variable of '#pragma omp declare mapper'.
10732 ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S,
10733 QualType MapperType,
10734 SourceLocation StartLoc,
10735 DeclarationName VN);
10736 bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const;
10737 const ValueDecl *getOpenMPDeclareMapperVarName() const;
10738
10739 /// Called on the start of target region i.e. '#pragma omp declare target'.
10740 bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
10741
10742 /// Called at the end of target region i.e. '#pragma omp end declare target'.
10743 const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective();
10744
10745 /// Called once a target context is completed, that can be when a
10746 /// '#pragma omp end declare target' was encountered or when a
10747 /// '#pragma omp declare target' without declaration-definition-seq was
10748 /// encountered.
10749 void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
10750
10751 /// Searches for the provided declaration name for OpenMP declare target
10752 /// directive.
10753 NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope,
10754 CXXScopeSpec &ScopeSpec,
10755 const DeclarationNameInfo &Id);
10756
10757 /// Called on correct id-expression from the '#pragma omp declare target'.
10758 void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
10759 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10760 DeclareTargetContextInfo &DTCI);
10761
10762 /// Check declaration inside target region.
10763 void
10764 checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
10765 SourceLocation IdLoc = SourceLocation());
10766 /// Finishes analysis of the deferred functions calls that may be declared as
10767 /// host/nohost during device/host compilation.
10768 void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
10769 const FunctionDecl *Callee,
10770 SourceLocation Loc);
10771
10772 /// Return true if currently in OpenMP task with untied clause context.
10773 bool isInOpenMPTaskUntiedContext() const;
10774
10775 /// Return true inside OpenMP declare target region.
10776 bool isInOpenMPDeclareTargetContext() const {
10777 return !DeclareTargetNesting.empty();
10778 }
10779 /// Return true inside OpenMP target region.
10780 bool isInOpenMPTargetExecutionDirective() const;
10781
10782 /// Return the number of captured regions created for an OpenMP directive.
10783 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
10784
10785 /// Initialization of captured region for OpenMP region.
10786 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
10787
10788 /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to
10789 /// an OpenMP loop directive.
10790 StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt);
10791
10792 /// Process a canonical OpenMP loop nest that can either be a canonical
10793 /// literal loop (ForStmt or CXXForRangeStmt), or the generated loop of an
10794 /// OpenMP loop transformation construct.
10795 StmtResult ActOnOpenMPLoopnest(Stmt *AStmt);
10796
10797 /// End of OpenMP region.
10798 ///
10799 /// \param S Statement associated with the current OpenMP region.
10800 /// \param Clauses List of clauses for the current OpenMP region.
10801 ///
10802 /// \returns Statement for finished OpenMP region.
10803 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
10804 StmtResult ActOnOpenMPExecutableDirective(
10805 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
10806 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
10807 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
10808 /// Called on well-formed '\#pragma omp parallel' after parsing
10809 /// of the associated statement.
10810 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
10811 Stmt *AStmt,
10812 SourceLocation StartLoc,
10813 SourceLocation EndLoc);
10814 using VarsWithInheritedDSAType =
10815 llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
10816 /// Called on well-formed '\#pragma omp simd' after parsing
10817 /// of the associated statement.
10818 StmtResult
10819 ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10820 SourceLocation StartLoc, SourceLocation EndLoc,
10821 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10822 /// Called on well-formed '#pragma omp tile' after parsing of its clauses and
10823 /// the associated statement.
10824 StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
10825 Stmt *AStmt, SourceLocation StartLoc,
10826 SourceLocation EndLoc);
10827 /// Called on well-formed '#pragma omp unroll' after parsing of its clauses
10828 /// and the associated statement.
10829 StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
10830 Stmt *AStmt, SourceLocation StartLoc,
10831 SourceLocation EndLoc);
10832 /// Called on well-formed '\#pragma omp for' after parsing
10833 /// of the associated statement.
10834 StmtResult
10835 ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10836 SourceLocation StartLoc, SourceLocation EndLoc,
10837 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10838 /// Called on well-formed '\#pragma omp for simd' after parsing
10839 /// of the associated statement.
10840 StmtResult
10841 ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10842 SourceLocation StartLoc, SourceLocation EndLoc,
10843 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10844 /// Called on well-formed '\#pragma omp sections' after parsing
10845 /// of the associated statement.
10846 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
10847 Stmt *AStmt, SourceLocation StartLoc,
10848 SourceLocation EndLoc);
10849 /// Called on well-formed '\#pragma omp section' after parsing of the
10850 /// associated statement.
10851 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
10852 SourceLocation EndLoc);
10853 /// Called on well-formed '\#pragma omp single' after parsing of the
10854 /// associated statement.
10855 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
10856 Stmt *AStmt, SourceLocation StartLoc,
10857 SourceLocation EndLoc);
10858 /// Called on well-formed '\#pragma omp master' after parsing of the
10859 /// associated statement.
10860 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
10861 SourceLocation EndLoc);
10862 /// Called on well-formed '\#pragma omp critical' after parsing of the
10863 /// associated statement.
10864 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
10865 ArrayRef<OMPClause *> Clauses,
10866 Stmt *AStmt, SourceLocation StartLoc,
10867 SourceLocation EndLoc);
10868 /// Called on well-formed '\#pragma omp parallel for' after parsing
10869 /// of the associated statement.
10870 StmtResult ActOnOpenMPParallelForDirective(
10871 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10872 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10873 /// Called on well-formed '\#pragma omp parallel for simd' after
10874 /// parsing of the associated statement.
10875 StmtResult ActOnOpenMPParallelForSimdDirective(
10876 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10877 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10878 /// Called on well-formed '\#pragma omp parallel master' after
10879 /// parsing of the associated statement.
10880 StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10881 Stmt *AStmt,
10882 SourceLocation StartLoc,
10883 SourceLocation EndLoc);
10884 /// Called on well-formed '\#pragma omp parallel sections' after
10885 /// parsing of the associated statement.
10886 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10887 Stmt *AStmt,
10888 SourceLocation StartLoc,
10889 SourceLocation EndLoc);
10890 /// Called on well-formed '\#pragma omp task' after parsing of the
10891 /// associated statement.
10892 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10893 Stmt *AStmt, SourceLocation StartLoc,
10894 SourceLocation EndLoc);
10895 /// Called on well-formed '\#pragma omp taskyield'.
10896 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10897 SourceLocation EndLoc);
10898 /// Called on well-formed '\#pragma omp barrier'.
10899 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10900 SourceLocation EndLoc);
10901 /// Called on well-formed '\#pragma omp taskwait'.
10902 StmtResult ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses,
10903 SourceLocation StartLoc,
10904 SourceLocation EndLoc);
10905 /// Called on well-formed '\#pragma omp taskgroup'.
10906 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10907 Stmt *AStmt, SourceLocation StartLoc,
10908 SourceLocation EndLoc);
10909 /// Called on well-formed '\#pragma omp flush'.
10910 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10911 SourceLocation StartLoc,
10912 SourceLocation EndLoc);
10913 /// Called on well-formed '\#pragma omp depobj'.
10914 StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10915 SourceLocation StartLoc,
10916 SourceLocation EndLoc);
10917 /// Called on well-formed '\#pragma omp scan'.
10918 StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10919 SourceLocation StartLoc,
10920 SourceLocation EndLoc);
10921 /// Called on well-formed '\#pragma omp ordered' after parsing of the
10922 /// associated statement.
10923 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10924 Stmt *AStmt, SourceLocation StartLoc,
10925 SourceLocation EndLoc);
10926 /// Called on well-formed '\#pragma omp atomic' after parsing of the
10927 /// associated statement.
10928 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10929 Stmt *AStmt, SourceLocation StartLoc,
10930 SourceLocation EndLoc);
10931 /// Called on well-formed '\#pragma omp target' after parsing of the
10932 /// associated statement.
10933 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
10934 Stmt *AStmt, SourceLocation StartLoc,
10935 SourceLocation EndLoc);
10936 /// Called on well-formed '\#pragma omp target data' after parsing of
10937 /// the associated statement.
10938 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
10939 Stmt *AStmt, SourceLocation StartLoc,
10940 SourceLocation EndLoc);
10941 /// Called on well-formed '\#pragma omp target enter data' after
10942 /// parsing of the associated statement.
10943 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
10944 SourceLocation StartLoc,
10945 SourceLocation EndLoc,
10946 Stmt *AStmt);
10947 /// Called on well-formed '\#pragma omp target exit data' after
10948 /// parsing of the associated statement.
10949 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
10950 SourceLocation StartLoc,
10951 SourceLocation EndLoc,
10952 Stmt *AStmt);
10953 /// Called on well-formed '\#pragma omp target parallel' after
10954 /// parsing of the associated statement.
10955 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
10956 Stmt *AStmt,
10957 SourceLocation StartLoc,
10958 SourceLocation EndLoc);
10959 /// Called on well-formed '\#pragma omp target parallel for' after
10960 /// parsing of the associated statement.
10961 StmtResult ActOnOpenMPTargetParallelForDirective(
10962 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10963 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10964 /// Called on well-formed '\#pragma omp teams' after parsing of the
10965 /// associated statement.
10966 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
10967 Stmt *AStmt, SourceLocation StartLoc,
10968 SourceLocation EndLoc);
10969 /// Called on well-formed '\#pragma omp teams loop' after parsing of the
10970 /// associated statement.
10971 StmtResult ActOnOpenMPTeamsGenericLoopDirective(
10972 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10973 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10974 /// Called on well-formed '\#pragma omp target teams loop' after parsing of
10975 /// the associated statement.
10976 StmtResult ActOnOpenMPTargetTeamsGenericLoopDirective(
10977 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10978 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10979 /// Called on well-formed '\#pragma omp parallel loop' after parsing of the
10980 /// associated statement.
10981 StmtResult ActOnOpenMPParallelGenericLoopDirective(
10982 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10983 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10984 /// Called on well-formed '\#pragma omp target parallel loop' after parsing
10985 /// of the associated statement.
10986 StmtResult ActOnOpenMPTargetParallelGenericLoopDirective(
10987 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10988 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10989 /// Called on well-formed '\#pragma omp cancellation point'.
10990 StmtResult
10991 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
10992 SourceLocation EndLoc,
10993 OpenMPDirectiveKind CancelRegion);
10994 /// Called on well-formed '\#pragma omp cancel'.
10995 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
10996 SourceLocation StartLoc,
10997 SourceLocation EndLoc,
10998 OpenMPDirectiveKind CancelRegion);
10999 /// Called on well-formed '\#pragma omp taskloop' after parsing of the
11000 /// associated statement.
11001 StmtResult
11002 ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11003 SourceLocation StartLoc, SourceLocation EndLoc,
11004 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11005 /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
11006 /// the associated statement.
11007 StmtResult ActOnOpenMPTaskLoopSimdDirective(
11008 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11009 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11010 /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
11011 /// associated statement.
11012 StmtResult ActOnOpenMPMasterTaskLoopDirective(
11013 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11014 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11015 /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
11016 /// the associated statement.
11017 StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
11018 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11019 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11020 /// Called on well-formed '\#pragma omp parallel master taskloop' after
11021 /// parsing of the associated statement.
11022 StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
11023 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11024 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11025 /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
11026 /// parsing of the associated statement.
11027 StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
11028 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11029 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11030 /// Called on well-formed '\#pragma omp distribute' after parsing
11031 /// of the associated statement.
11032 StmtResult
11033 ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11034 SourceLocation StartLoc, SourceLocation EndLoc,
11035 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11036 /// Called on well-formed '\#pragma omp target update'.
11037 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
11038 SourceLocation StartLoc,
11039 SourceLocation EndLoc,
11040 Stmt *AStmt);
11041 /// Called on well-formed '\#pragma omp distribute parallel for' after
11042 /// parsing of the associated statement.
11043 StmtResult ActOnOpenMPDistributeParallelForDirective(
11044 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11045 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11046 /// Called on well-formed '\#pragma omp distribute parallel for simd'
11047 /// after parsing of the associated statement.
11048 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
11049 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11050 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11051 /// Called on well-formed '\#pragma omp distribute simd' after
11052 /// parsing of the associated statement.
11053 StmtResult ActOnOpenMPDistributeSimdDirective(
11054 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11055 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11056 /// Called on well-formed '\#pragma omp target parallel for simd' after
11057 /// parsing of the associated statement.
11058 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
11059 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11060 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11061 /// Called on well-formed '\#pragma omp target simd' after parsing of
11062 /// the associated statement.
11063 StmtResult
11064 ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11065 SourceLocation StartLoc, SourceLocation EndLoc,
11066 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11067 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
11068 /// the associated statement.
11069 StmtResult ActOnOpenMPTeamsDistributeDirective(
11070 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11071 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11072 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
11073 /// of the associated statement.
11074 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
11075 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11076 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11077 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
11078 /// after parsing of the associated statement.
11079 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
11080 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11081 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11082 /// Called on well-formed '\#pragma omp teams distribute parallel for'
11083 /// after parsing of the associated statement.
11084 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
11085 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11086 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11087 /// Called on well-formed '\#pragma omp target teams' after parsing of the
11088 /// associated statement.
11089 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
11090 Stmt *AStmt,
11091 SourceLocation StartLoc,
11092 SourceLocation EndLoc);
11093 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
11094 /// of the associated statement.
11095 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
11096 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11097 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11098 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
11099 /// after parsing of the associated statement.
11100 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
11101 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11102 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11103 /// Called on well-formed '\#pragma omp target teams distribute parallel for
11104 /// simd' after parsing of the associated statement.
11105 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
11106 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11107 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11108 /// Called on well-formed '\#pragma omp target teams distribute simd' after
11109 /// parsing of the associated statement.
11110 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
11111 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11112 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11113 /// Called on well-formed '\#pragma omp interop'.
11114 StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
11115 SourceLocation StartLoc,
11116 SourceLocation EndLoc);
11117 /// Called on well-formed '\#pragma omp dispatch' after parsing of the
11118 // /associated statement.
11119 StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
11120 Stmt *AStmt, SourceLocation StartLoc,
11121 SourceLocation EndLoc);
11122 /// Called on well-formed '\#pragma omp masked' after parsing of the
11123 // /associated statement.
11124 StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
11125 Stmt *AStmt, SourceLocation StartLoc,
11126 SourceLocation EndLoc);
11127
11128 /// Called on well-formed '\#pragma omp loop' after parsing of the
11129 /// associated statement.
11130 StmtResult ActOnOpenMPGenericLoopDirective(
11131 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11132 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11133
11134 /// Checks correctness of linear modifiers.
11135 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11136 SourceLocation LinLoc);
11137 /// Checks that the specified declaration matches requirements for the linear
11138 /// decls.
11139 bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
11140 OpenMPLinearClauseKind LinKind, QualType Type,
11141 bool IsDeclareSimd = false);
11142
11143 /// Called on well-formed '\#pragma omp declare simd' after parsing of
11144 /// the associated method/function.
11145 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
11146 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
11147 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
11148 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
11149 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
11150
11151 /// Checks '\#pragma omp declare variant' variant function and original
11152 /// functions after parsing of the associated method/function.
11153 /// \param DG Function declaration to which declare variant directive is
11154 /// applied to.
11155 /// \param VariantRef Expression that references the variant function, which
11156 /// must be used instead of the original one, specified in \p DG.
11157 /// \param TI The trait info object representing the match clause.
11158 /// \param NumAppendArgs The number of omp_interop_t arguments to account for
11159 /// in checking.
11160 /// \returns None, if the function/variant function are not compatible with
11161 /// the pragma, pair of original function/variant ref expression otherwise.
11162 Optional<std::pair<FunctionDecl *, Expr *>>
11163 checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef,
11164 OMPTraitInfo &TI, unsigned NumAppendArgs,
11165 SourceRange SR);
11166
11167 /// Called on well-formed '\#pragma omp declare variant' after parsing of
11168 /// the associated method/function.
11169 /// \param FD Function declaration to which declare variant directive is
11170 /// applied to.
11171 /// \param VariantRef Expression that references the variant function, which
11172 /// must be used instead of the original one, specified in \p DG.
11173 /// \param TI The context traits associated with the function variant.
11174 /// \param AdjustArgsNothing The list of 'nothing' arguments.
11175 /// \param AdjustArgsNeedDevicePtr The list of 'need_device_ptr' arguments.
11176 /// \param AppendArgs The list of 'append_args' arguments.
11177 /// \param AdjustArgsLoc The Location of an 'adjust_args' clause.
11178 /// \param AppendArgsLoc The Location of an 'append_args' clause.
11179 /// \param SR The SourceRange of the 'declare variant' directive.
11180 void ActOnOpenMPDeclareVariantDirective(
11181 FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
11182 ArrayRef<Expr *> AdjustArgsNothing,
11183 ArrayRef<Expr *> AdjustArgsNeedDevicePtr,
11184 ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs,
11185 SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc,
11186 SourceRange SR);
11187
11188 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
11189 Expr *Expr,
11190 SourceLocation StartLoc,
11191 SourceLocation LParenLoc,
11192 SourceLocation EndLoc);
11193 /// Called on well-formed 'allocator' clause.
11194 OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
11195 SourceLocation StartLoc,
11196 SourceLocation LParenLoc,
11197 SourceLocation EndLoc);
11198 /// Called on well-formed 'if' clause.
11199 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11200 Expr *Condition, SourceLocation StartLoc,
11201 SourceLocation LParenLoc,
11202 SourceLocation NameModifierLoc,
11203 SourceLocation ColonLoc,
11204 SourceLocation EndLoc);
11205 /// Called on well-formed 'final' clause.
11206 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
11207 SourceLocation LParenLoc,
11208 SourceLocation EndLoc);
11209 /// Called on well-formed 'num_threads' clause.
11210 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11211 SourceLocation StartLoc,
11212 SourceLocation LParenLoc,
11213 SourceLocation EndLoc);
11214 /// Called on well-formed 'align' clause.
11215 OMPClause *ActOnOpenMPAlignClause(Expr *Alignment, SourceLocation StartLoc,
11216 SourceLocation LParenLoc,
11217 SourceLocation EndLoc);
11218 /// Called on well-formed 'safelen' clause.
11219 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
11220 SourceLocation StartLoc,
11221 SourceLocation LParenLoc,
11222 SourceLocation EndLoc);
11223 /// Called on well-formed 'simdlen' clause.
11224 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
11225 SourceLocation LParenLoc,
11226 SourceLocation EndLoc);
11227 /// Called on well-form 'sizes' clause.
11228 OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
11229 SourceLocation StartLoc,
11230 SourceLocation LParenLoc,
11231 SourceLocation EndLoc);
11232 /// Called on well-form 'full' clauses.
11233 OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc,
11234 SourceLocation EndLoc);
11235 /// Called on well-form 'partial' clauses.
11236 OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, SourceLocation StartLoc,
11237 SourceLocation LParenLoc,
11238 SourceLocation EndLoc);
11239 /// Called on well-formed 'collapse' clause.
11240 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
11241 SourceLocation StartLoc,
11242 SourceLocation LParenLoc,
11243 SourceLocation EndLoc);
11244 /// Called on well-formed 'ordered' clause.
11245 OMPClause *
11246 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
11247 SourceLocation LParenLoc = SourceLocation(),
11248 Expr *NumForLoops = nullptr);
11249 /// Called on well-formed 'grainsize' clause.
11250 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
11251 SourceLocation LParenLoc,
11252 SourceLocation EndLoc);
11253 /// Called on well-formed 'num_tasks' clause.
11254 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
11255 SourceLocation LParenLoc,
11256 SourceLocation EndLoc);
11257 /// Called on well-formed 'hint' clause.
11258 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11259 SourceLocation LParenLoc,
11260 SourceLocation EndLoc);
11261 /// Called on well-formed 'detach' clause.
11262 OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
11263 SourceLocation LParenLoc,
11264 SourceLocation EndLoc);
11265
11266 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
11267 unsigned Argument,
11268 SourceLocation ArgumentLoc,
11269 SourceLocation StartLoc,
11270 SourceLocation LParenLoc,
11271 SourceLocation EndLoc);
11272 /// Called on well-formed 'when' clause.
11273 OMPClause *ActOnOpenMPWhenClause(OMPTraitInfo &TI, SourceLocation StartLoc,
11274 SourceLocation LParenLoc,
11275 SourceLocation EndLoc);
11276 /// Called on well-formed 'default' clause.
11277 OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind,
11278 SourceLocation KindLoc,
11279 SourceLocation StartLoc,
11280 SourceLocation LParenLoc,
11281 SourceLocation EndLoc);
11282 /// Called on well-formed 'proc_bind' clause.
11283 OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
11284 SourceLocation KindLoc,
11285 SourceLocation StartLoc,
11286 SourceLocation LParenLoc,
11287 SourceLocation EndLoc);
11288 /// Called on well-formed 'order' clause.
11289 OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
11290 SourceLocation KindLoc,
11291 SourceLocation StartLoc,
11292 SourceLocation LParenLoc,
11293 SourceLocation EndLoc);
11294 /// Called on well-formed 'update' clause.
11295 OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
11296 SourceLocation KindLoc,
11297 SourceLocation StartLoc,
11298 SourceLocation LParenLoc,
11299 SourceLocation EndLoc);
11300
11301 OMPClause *ActOnOpenMPSingleExprWithArgClause(
11302 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
11303 SourceLocation StartLoc, SourceLocation LParenLoc,
11304 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
11305 SourceLocation EndLoc);
11306 /// Called on well-formed 'schedule' clause.
11307 OMPClause *ActOnOpenMPScheduleClause(
11308 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
11309 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11310 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11311 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
11312
11313 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
11314 SourceLocation EndLoc);
11315 /// Called on well-formed 'nowait' clause.
11316 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
11317 SourceLocation EndLoc);
11318 /// Called on well-formed 'untied' clause.
11319 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
11320 SourceLocation EndLoc);
11321 /// Called on well-formed 'mergeable' clause.
11322 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
11323 SourceLocation EndLoc);
11324 /// Called on well-formed 'read' clause.
11325 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
11326 SourceLocation EndLoc);
11327 /// Called on well-formed 'write' clause.
11328 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
11329 SourceLocation EndLoc);
11330 /// Called on well-formed 'update' clause.
11331 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
11332 SourceLocation EndLoc);
11333 /// Called on well-formed 'capture' clause.
11334 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
11335 SourceLocation EndLoc);
11336 /// Called on well-formed 'compare' clause.
11337 OMPClause *ActOnOpenMPCompareClause(SourceLocation StartLoc,
11338 SourceLocation EndLoc);
11339 /// Called on well-formed 'seq_cst' clause.
11340 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
11341 SourceLocation EndLoc);
11342 /// Called on well-formed 'acq_rel' clause.
11343 OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
11344 SourceLocation EndLoc);
11345 /// Called on well-formed 'acquire' clause.
11346 OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc,
11347 SourceLocation EndLoc);
11348 /// Called on well-formed 'release' clause.
11349 OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc,
11350 SourceLocation EndLoc);
11351 /// Called on well-formed 'relaxed' clause.
11352 OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
11353 SourceLocation EndLoc);
11354
11355 /// Called on well-formed 'init' clause.
11356 OMPClause *ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
11357 bool IsTarget, bool IsTargetSync,
11358 SourceLocation StartLoc,
11359 SourceLocation LParenLoc,
11360 SourceLocation VarLoc,
11361 SourceLocation EndLoc);
11362
11363 /// Called on well-formed 'use' clause.
11364 OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
11365 SourceLocation LParenLoc,
11366 SourceLocation VarLoc, SourceLocation EndLoc);
11367
11368 /// Called on well-formed 'destroy' clause.
11369 OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
11370 SourceLocation LParenLoc,
11371 SourceLocation VarLoc,
11372 SourceLocation EndLoc);
11373 /// Called on well-formed 'novariants' clause.
11374 OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition,
11375 SourceLocation StartLoc,
11376 SourceLocation LParenLoc,
11377 SourceLocation EndLoc);
11378 /// Called on well-formed 'nocontext' clause.
11379 OMPClause *ActOnOpenMPNocontextClause(Expr *Condition,
11380 SourceLocation StartLoc,
11381 SourceLocation LParenLoc,
11382 SourceLocation EndLoc);
11383 /// Called on well-formed 'filter' clause.
11384 OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
11385 SourceLocation LParenLoc,
11386 SourceLocation EndLoc);
11387 /// Called on well-formed 'threads' clause.
11388 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
11389 SourceLocation EndLoc);
11390 /// Called on well-formed 'simd' clause.
11391 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
11392 SourceLocation EndLoc);
11393 /// Called on well-formed 'nogroup' clause.
11394 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
11395 SourceLocation EndLoc);
11396 /// Called on well-formed 'unified_address' clause.
11397 OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
11398 SourceLocation EndLoc);
11399
11400 /// Called on well-formed 'unified_address' clause.
11401 OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
11402 SourceLocation EndLoc);
11403
11404 /// Called on well-formed 'reverse_offload' clause.
11405 OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
11406 SourceLocation EndLoc);
11407
11408 /// Called on well-formed 'dynamic_allocators' clause.
11409 OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
11410 SourceLocation EndLoc);
11411
11412 /// Called on well-formed 'atomic_default_mem_order' clause.
11413 OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
11414 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
11415 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
11416
11417 OMPClause *ActOnOpenMPVarListClause(
11418 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr,
11419 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
11420 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
11421 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
11422 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
11423 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
11424 SourceLocation ExtraModifierLoc,
11425 ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11426 ArrayRef<SourceLocation> MotionModifiersLoc);
11427 /// Called on well-formed 'inclusive' clause.
11428 OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
11429 SourceLocation StartLoc,
11430 SourceLocation LParenLoc,
11431 SourceLocation EndLoc);
11432 /// Called on well-formed 'exclusive' clause.
11433 OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
11434 SourceLocation StartLoc,
11435 SourceLocation LParenLoc,
11436 SourceLocation EndLoc);
11437 /// Called on well-formed 'allocate' clause.
11438 OMPClause *
11439 ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
11440 SourceLocation StartLoc, SourceLocation ColonLoc,
11441 SourceLocation LParenLoc, SourceLocation EndLoc);
11442 /// Called on well-formed 'private' clause.
11443 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
11444 SourceLocation StartLoc,
11445 SourceLocation LParenLoc,
11446 SourceLocation EndLoc);
11447 /// Called on well-formed 'firstprivate' clause.
11448 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
11449 SourceLocation StartLoc,
11450 SourceLocation LParenLoc,
11451 SourceLocation EndLoc);
11452 /// Called on well-formed 'lastprivate' clause.
11453 OMPClause *ActOnOpenMPLastprivateClause(
11454 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
11455 SourceLocation LPKindLoc, SourceLocation ColonLoc,
11456 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
11457 /// Called on well-formed 'shared' clause.
11458 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
11459 SourceLocation StartLoc,
11460 SourceLocation LParenLoc,
11461 SourceLocation EndLoc);
11462 /// Called on well-formed 'reduction' clause.
11463 OMPClause *ActOnOpenMPReductionClause(
11464 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
11465 SourceLocation StartLoc, SourceLocation LParenLoc,
11466 SourceLocation ModifierLoc, SourceLocation ColonLoc,
11467 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
11468 const DeclarationNameInfo &ReductionId,
11469 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11470 /// Called on well-formed 'task_reduction' clause.
11471 OMPClause *ActOnOpenMPTaskReductionClause(
11472 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11473 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
11474 CXXScopeSpec &ReductionIdScopeSpec,
11475 const DeclarationNameInfo &ReductionId,
11476 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11477 /// Called on well-formed 'in_reduction' clause.
11478 OMPClause *ActOnOpenMPInReductionClause(
11479 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11480 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
11481 CXXScopeSpec &ReductionIdScopeSpec,
11482 const DeclarationNameInfo &ReductionId,
11483 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11484 /// Called on well-formed 'linear' clause.
11485 OMPClause *
11486 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
11487 SourceLocation StartLoc, SourceLocation LParenLoc,
11488 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
11489 SourceLocation ColonLoc, SourceLocation EndLoc);
11490 /// Called on well-formed 'aligned' clause.
11491 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
11492 Expr *Alignment,
11493 SourceLocation StartLoc,
11494 SourceLocation LParenLoc,
11495 SourceLocation ColonLoc,
11496 SourceLocation EndLoc);
11497 /// Called on well-formed 'copyin' clause.
11498 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11499 SourceLocation StartLoc,
11500 SourceLocation LParenLoc,
11501 SourceLocation EndLoc);
11502 /// Called on well-formed 'copyprivate' clause.
11503 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11504 SourceLocation StartLoc,
11505 SourceLocation LParenLoc,
11506 SourceLocation EndLoc);
11507 /// Called on well-formed 'flush' pseudo clause.
11508 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11509 SourceLocation StartLoc,
11510 SourceLocation LParenLoc,
11511 SourceLocation EndLoc);
11512 /// Called on well-formed 'depobj' pseudo clause.
11513 OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
11514 SourceLocation LParenLoc,
11515 SourceLocation EndLoc);
11516 /// Called on well-formed 'depend' clause.
11517 OMPClause *
11518 ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
11519 SourceLocation DepLoc, SourceLocation ColonLoc,
11520 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11521 SourceLocation LParenLoc, SourceLocation EndLoc);
11522 /// Called on well-formed 'device' clause.
11523 OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
11524 Expr *Device, SourceLocation StartLoc,
11525 SourceLocation LParenLoc,
11526 SourceLocation ModifierLoc,
11527 SourceLocation EndLoc);
11528 /// Called on well-formed 'map' clause.
11529 OMPClause *ActOnOpenMPMapClause(
11530 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
11531 ArrayRef<SourceLocation> MapTypeModifiersLoc,
11532 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
11533 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11534 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
11535 const OMPVarListLocTy &Locs, bool NoDiagnose = false,
11536 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11537 /// Called on well-formed 'num_teams' clause.
11538 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
11539 SourceLocation LParenLoc,
11540 SourceLocation EndLoc);
11541 /// Called on well-formed 'thread_limit' clause.
11542 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11543 SourceLocation StartLoc,
11544 SourceLocation LParenLoc,
11545 SourceLocation EndLoc);
11546 /// Called on well-formed 'priority' clause.
11547 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
11548 SourceLocation LParenLoc,
11549 SourceLocation EndLoc);
11550 /// Called on well-formed 'dist_schedule' clause.
11551 OMPClause *ActOnOpenMPDistScheduleClause(
11552 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
11553 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
11554 SourceLocation CommaLoc, SourceLocation EndLoc);
11555 /// Called on well-formed 'defaultmap' clause.
11556 OMPClause *ActOnOpenMPDefaultmapClause(
11557 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11558 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11559 SourceLocation KindLoc, SourceLocation EndLoc);
11560 /// Called on well-formed 'to' clause.
11561 OMPClause *
11562 ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11563 ArrayRef<SourceLocation> MotionModifiersLoc,
11564 CXXScopeSpec &MapperIdScopeSpec,
11565 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11566 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11567 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11568 /// Called on well-formed 'from' clause.
11569 OMPClause *
11570 ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11571 ArrayRef<SourceLocation> MotionModifiersLoc,
11572 CXXScopeSpec &MapperIdScopeSpec,
11573 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11574 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11575 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11576 /// Called on well-formed 'use_device_ptr' clause.
11577 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11578 const OMPVarListLocTy &Locs);
11579 /// Called on well-formed 'use_device_addr' clause.
11580 OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
11581 const OMPVarListLocTy &Locs);
11582 /// Called on well-formed 'is_device_ptr' clause.
11583 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11584 const OMPVarListLocTy &Locs);
11585 /// Called on well-formed 'has_device_addr' clause.
11586 OMPClause *ActOnOpenMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
11587 const OMPVarListLocTy &Locs);
11588 /// Called on well-formed 'nontemporal' clause.
11589 OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
11590 SourceLocation StartLoc,
11591 SourceLocation LParenLoc,
11592 SourceLocation EndLoc);
11593
11594 /// Data for list of allocators.
11595 struct UsesAllocatorsData {
11596 /// Allocator.
11597 Expr *Allocator = nullptr;
11598 /// Allocator traits.
11599 Expr *AllocatorTraits = nullptr;
11600 /// Locations of '(' and ')' symbols.
11601 SourceLocation LParenLoc, RParenLoc;
11602 };
11603 /// Called on well-formed 'uses_allocators' clause.
11604 OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc,
11605 SourceLocation LParenLoc,
11606 SourceLocation EndLoc,
11607 ArrayRef<UsesAllocatorsData> Data);
11608 /// Called on well-formed 'affinity' clause.
11609 OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc,
11610 SourceLocation LParenLoc,
11611 SourceLocation ColonLoc,
11612 SourceLocation EndLoc, Expr *Modifier,
11613 ArrayRef<Expr *> Locators);
11614 /// Called on a well-formed 'bind' clause.
11615 OMPClause *ActOnOpenMPBindClause(OpenMPBindClauseKind Kind,
11616 SourceLocation KindLoc,
11617 SourceLocation StartLoc,
11618 SourceLocation LParenLoc,
11619 SourceLocation EndLoc);
11620
11621 /// The kind of conversion being performed.
11622 enum CheckedConversionKind {
11623 /// An implicit conversion.
11624 CCK_ImplicitConversion,
11625 /// A C-style cast.
11626 CCK_CStyleCast,
11627 /// A functional-style cast.
11628 CCK_FunctionalCast,
11629 /// A cast other than a C-style cast.
11630 CCK_OtherCast,
11631 /// A conversion for an operand of a builtin overloaded operator.
11632 CCK_ForBuiltinOverloadedOp
11633 };
11634
11635 static bool isCast(CheckedConversionKind CCK) {
11636 return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
11637 CCK == CCK_OtherCast;
11638 }
11639
11640 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
11641 /// cast. If there is already an implicit cast, merge into the existing one.
11642 /// If isLvalue, the result of the cast is an lvalue.
11643 ExprResult
11644 ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
11645 ExprValueKind VK = VK_PRValue,
11646 const CXXCastPath *BasePath = nullptr,
11647 CheckedConversionKind CCK = CCK_ImplicitConversion);
11648
11649 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
11650 /// to the conversion from scalar type ScalarTy to the Boolean type.
11651 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
11652
11653 /// IgnoredValueConversions - Given that an expression's result is
11654 /// syntactically ignored, perform any conversions that are
11655 /// required.
11656 ExprResult IgnoredValueConversions(Expr *E);
11657
11658 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
11659 // functions and arrays to their respective pointers (C99 6.3.2.1).
11660 ExprResult UsualUnaryConversions(Expr *E);
11661
11662 /// CallExprUnaryConversions - a special case of an unary conversion
11663 /// performed on a function designator of a call expression.
11664 ExprResult CallExprUnaryConversions(Expr *E);
11665
11666 // DefaultFunctionArrayConversion - converts functions and arrays
11667 // to their respective pointers (C99 6.3.2.1).
11668 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
11669
11670 // DefaultFunctionArrayLvalueConversion - converts functions and
11671 // arrays to their respective pointers and performs the
11672 // lvalue-to-rvalue conversion.
11673 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
11674 bool Diagnose = true);
11675
11676 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
11677 // the operand. This function is a no-op if the operand has a function type
11678 // or an array type.
11679 ExprResult DefaultLvalueConversion(Expr *E);
11680
11681 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
11682 // do not have a prototype. Integer promotions are performed on each
11683 // argument, and arguments that have type float are promoted to double.
11684 ExprResult DefaultArgumentPromotion(Expr *E);
11685
11686 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
11687 /// it as an xvalue. In C++98, the result will still be a prvalue, because
11688 /// we don't have xvalues there.
11689 ExprResult TemporaryMaterializationConversion(Expr *E);
11690
11691 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
11692 enum VariadicCallType {
11693 VariadicFunction,
11694 VariadicBlock,
11695 VariadicMethod,
11696 VariadicConstructor,
11697 VariadicDoesNotApply
11698 };
11699
11700 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
11701 const FunctionProtoType *Proto,
11702 Expr *Fn);
11703
11704 // Used for determining in which context a type is allowed to be passed to a
11705 // vararg function.
11706 enum VarArgKind {
11707 VAK_Valid,
11708 VAK_ValidInCXX11,
11709 VAK_Undefined,
11710 VAK_MSVCUndefined,
11711 VAK_Invalid
11712 };
11713
11714 // Determines which VarArgKind fits an expression.
11715 VarArgKind isValidVarArgType(const QualType &Ty);
11716
11717 /// Check to see if the given expression is a valid argument to a variadic
11718 /// function, issuing a diagnostic if not.
11719 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
11720
11721 /// Check whether the given statement can have musttail applied to it,
11722 /// issuing a diagnostic and returning false if not. In the success case,
11723 /// the statement is rewritten to remove implicit nodes from the return
11724 /// value.
11725 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11726
11727private:
11728 /// Check whether the given statement can have musttail applied to it,
11729 /// issuing a diagnostic and returning false if not.
11730 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11731
11732public:
11733 /// Check to see if a given expression could have '.c_str()' called on it.
11734 bool hasCStrMethod(const Expr *E);
11735
11736 /// GatherArgumentsForCall - Collector argument expressions for various
11737 /// form of call prototypes.
11738 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
11739 const FunctionProtoType *Proto,
11740 unsigned FirstParam, ArrayRef<Expr *> Args,
11741 SmallVectorImpl<Expr *> &AllArgs,
11742 VariadicCallType CallType = VariadicDoesNotApply,
11743 bool AllowExplicit = false,
11744 bool IsListInitialization = false);
11745
11746 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
11747 // will create a runtime trap if the resulting type is not a POD type.
11748 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
11749 FunctionDecl *FDecl);
11750
11751 /// Context in which we're performing a usual arithmetic conversion.
11752 enum ArithConvKind {
11753 /// An arithmetic operation.
11754 ACK_Arithmetic,
11755 /// A bitwise operation.
11756 ACK_BitwiseOp,
11757 /// A comparison.
11758 ACK_Comparison,
11759 /// A conditional (?:) operator.
11760 ACK_Conditional,
11761 /// A compound assignment expression.
11762 ACK_CompAssign,
11763 };
11764
11765 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
11766 // operands and then handles various conversions that are common to binary
11767 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
11768 // routine returns the first non-arithmetic type found. The client is
11769 // responsible for emitting appropriate error diagnostics.
11770 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
11771 SourceLocation Loc, ArithConvKind ACK);
11772
11773 /// AssignConvertType - All of the 'assignment' semantic checks return this
11774 /// enum to indicate whether the assignment was allowed. These checks are
11775 /// done for simple assignments, as well as initialization, return from
11776 /// function, argument passing, etc. The query is phrased in terms of a
11777 /// source and destination type.
11778 enum AssignConvertType {
11779 /// Compatible - the types are compatible according to the standard.
11780 Compatible,
11781
11782 /// PointerToInt - The assignment converts a pointer to an int, which we
11783 /// accept as an extension.
11784 PointerToInt,
11785
11786 /// IntToPointer - The assignment converts an int to a pointer, which we
11787 /// accept as an extension.
11788 IntToPointer,
11789
11790 /// FunctionVoidPointer - The assignment is between a function pointer and
11791 /// void*, which the standard doesn't allow, but we accept as an extension.
11792 FunctionVoidPointer,
11793
11794 /// IncompatiblePointer - The assignment is between two pointers types that
11795 /// are not compatible, but we accept them as an extension.
11796 IncompatiblePointer,
11797
11798 /// IncompatibleFunctionPointer - The assignment is between two function
11799 /// pointers types that are not compatible, but we accept them as an
11800 /// extension.
11801 IncompatibleFunctionPointer,
11802
11803 /// IncompatiblePointerSign - The assignment is between two pointers types
11804 /// which point to integers which have a different sign, but are otherwise
11805 /// identical. This is a subset of the above, but broken out because it's by
11806 /// far the most common case of incompatible pointers.
11807 IncompatiblePointerSign,
11808
11809 /// CompatiblePointerDiscardsQualifiers - The assignment discards
11810 /// c/v/r qualifiers, which we accept as an extension.
11811 CompatiblePointerDiscardsQualifiers,
11812
11813 /// IncompatiblePointerDiscardsQualifiers - The assignment
11814 /// discards qualifiers that we don't permit to be discarded,
11815 /// like address spaces.
11816 IncompatiblePointerDiscardsQualifiers,
11817
11818 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
11819 /// changes address spaces in nested pointer types which is not allowed.
11820 /// For instance, converting __private int ** to __generic int ** is
11821 /// illegal even though __private could be converted to __generic.
11822 IncompatibleNestedPointerAddressSpaceMismatch,
11823
11824 /// IncompatibleNestedPointerQualifiers - The assignment is between two
11825 /// nested pointer types, and the qualifiers other than the first two
11826 /// levels differ e.g. char ** -> const char **, but we accept them as an
11827 /// extension.
11828 IncompatibleNestedPointerQualifiers,
11829
11830 /// IncompatibleVectors - The assignment is between two vector types that
11831 /// have the same size, which we accept as an extension.
11832 IncompatibleVectors,
11833
11834 /// IntToBlockPointer - The assignment converts an int to a block
11835 /// pointer. We disallow this.
11836 IntToBlockPointer,
11837
11838 /// IncompatibleBlockPointer - The assignment is between two block
11839 /// pointers types that are not compatible.
11840 IncompatibleBlockPointer,
11841
11842 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
11843 /// id type and something else (that is incompatible with it). For example,
11844 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
11845 IncompatibleObjCQualifiedId,
11846
11847 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
11848 /// object with __weak qualifier.
11849 IncompatibleObjCWeakRef,
11850
11851 /// Incompatible - We reject this conversion outright, it is invalid to
11852 /// represent it in the AST.
11853 Incompatible
11854 };
11855
11856 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
11857 /// assignment conversion type specified by ConvTy. This returns true if the
11858 /// conversion was invalid or false if the conversion was accepted.
11859 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
11860 SourceLocation Loc,
11861 QualType DstType, QualType SrcType,
11862 Expr *SrcExpr, AssignmentAction Action,
11863 bool *Complained = nullptr);
11864
11865 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
11866 /// enum. If AllowMask is true, then we also allow the complement of a valid
11867 /// value, to be used as a mask.
11868 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
11869 bool AllowMask) const;
11870
11871 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11872 /// integer not in the range of enum values.
11873 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11874 Expr *SrcExpr);
11875
11876 /// CheckAssignmentConstraints - Perform type checking for assignment,
11877 /// argument passing, variable initialization, and function return values.
11878 /// C99 6.5.16.
11879 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
11880 QualType LHSType,
11881 QualType RHSType);
11882
11883 /// Check assignment constraints and optionally prepare for a conversion of
11884 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
11885 /// is true.
11886 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
11887 ExprResult &RHS,
11888 CastKind &Kind,
11889 bool ConvertRHS = true);
11890
11891 /// Check assignment constraints for an assignment of RHS to LHSType.
11892 ///
11893 /// \param LHSType The destination type for the assignment.
11894 /// \param RHS The source expression for the assignment.
11895 /// \param Diagnose If \c true, diagnostics may be produced when checking
11896 /// for assignability. If a diagnostic is produced, \p RHS will be
11897 /// set to ExprError(). Note that this function may still return
11898 /// without producing a diagnostic, even for an invalid assignment.
11899 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
11900 /// in an audited Core Foundation API and does not need to be checked
11901 /// for ARC retain issues.
11902 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
11903 /// conversions necessary to perform the assignment. If \c false,
11904 /// \p Diagnose must also be \c false.
11905 AssignConvertType CheckSingleAssignmentConstraints(
11906 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
11907 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
11908
11909 // If the lhs type is a transparent union, check whether we
11910 // can initialize the transparent union with the given expression.
11911 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
11912 ExprResult &RHS);
11913
11914 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
11915
11916 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
11917
11918 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11919 AssignmentAction Action,
11920 bool AllowExplicit = false);
11921 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11922 const ImplicitConversionSequence& ICS,
11923 AssignmentAction Action,
11924 CheckedConversionKind CCK
11925 = CCK_ImplicitConversion);
11926 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11927 const StandardConversionSequence& SCS,
11928 AssignmentAction Action,
11929 CheckedConversionKind CCK);
11930
11931 ExprResult PerformQualificationConversion(
11932 Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
11933 CheckedConversionKind CCK = CCK_ImplicitConversion);
11934
11935 /// the following "Check" methods will return a valid/converted QualType
11936 /// or a null QualType (indicating an error diagnostic was issued).
11937
11938 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
11939 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
11940 ExprResult &RHS);
11941 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
11942 ExprResult &RHS);
11943 QualType CheckPointerToMemberOperands( // C++ 5.5
11944 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
11945 SourceLocation OpLoc, bool isIndirect);
11946 QualType CheckMultiplyDivideOperands( // C99 6.5.5
11947 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
11948 bool IsDivide);
11949 QualType CheckRemainderOperands( // C99 6.5.5
11950 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11951 bool IsCompAssign = false);
11952 QualType CheckAdditionOperands( // C99 6.5.6
11953 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11954 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
11955 QualType CheckSubtractionOperands( // C99 6.5.6
11956 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11957 QualType* CompLHSTy = nullptr);
11958 QualType CheckShiftOperands( // C99 6.5.7
11959 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11960 BinaryOperatorKind Opc, bool IsCompAssign = false);
11961 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
11962 QualType CheckCompareOperands( // C99 6.5.8/9
11963 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11964 BinaryOperatorKind Opc);
11965 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
11966 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11967 BinaryOperatorKind Opc);
11968 QualType CheckLogicalOperands( // C99 6.5.[13,14]
11969 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11970 BinaryOperatorKind Opc);
11971 // CheckAssignmentOperands is used for both simple and compound assignment.
11972 // For simple assignment, pass both expressions and a null converted type.
11973 // For compound assignment, pass both expressions and the converted type.
11974 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
11975 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
11976
11977 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
11978 UnaryOperatorKind Opcode, Expr *Op);
11979 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
11980 BinaryOperatorKind Opcode,
11981 Expr *LHS, Expr *RHS);
11982 ExprResult checkPseudoObjectRValue(Expr *E);
11983 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
11984
11985 QualType CheckConditionalOperands( // C99 6.5.15
11986 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
11987 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
11988 QualType CXXCheckConditionalOperands( // C++ 5.16
11989 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
11990 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
11991 QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
11992 ExprResult &RHS,
11993 SourceLocation QuestionLoc);
11994 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
11995 bool ConvertArgs = true);
11996 QualType FindCompositePointerType(SourceLocation Loc,
11997 ExprResult &E1, ExprResult &E2,
11998 bool ConvertArgs = true) {
11999 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
12000 QualType Composite =
12001 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
12002 E1 = E1Tmp;
12003 E2 = E2Tmp;
12004 return Composite;
12005 }
12006
12007 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
12008 SourceLocation QuestionLoc);
12009
12010 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
12011 SourceLocation QuestionLoc);
12012
12013 void DiagnoseAlwaysNonNullPointer(Expr *E,
12014 Expr::NullPointerConstantKind NullType,
12015 bool IsEqual, SourceRange Range);
12016
12017 /// type checking for vector binary operators.
12018 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
12019 SourceLocation Loc, bool IsCompAssign,
12020 bool AllowBothBool, bool AllowBoolConversion,
12021 bool AllowBoolOperation, bool ReportInvalid);
12022 QualType GetSignedVectorType(QualType V);
12023 QualType GetSignedSizelessVectorType(QualType V);
12024 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12025 SourceLocation Loc,
12026 BinaryOperatorKind Opc);
12027 QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12028 SourceLocation Loc,
12029 BinaryOperatorKind Opc);
12030 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12031 SourceLocation Loc);
12032
12033 // type checking for sizeless vector binary operators.
12034 QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
12035 SourceLocation Loc, bool IsCompAssign,
12036 ArithConvKind OperationKind);
12037
12038 /// Type checking for matrix binary operators.
12039 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12040 SourceLocation Loc,
12041 bool IsCompAssign);
12042 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12043 SourceLocation Loc, bool IsCompAssign);
12044
12045 bool isValidSveBitcast(QualType srcType, QualType destType);
12046
12047 bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
12048
12049 bool areVectorTypesSameSize(QualType srcType, QualType destType);
12050 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
12051 bool isLaxVectorConversion(QualType srcType, QualType destType);
12052
12053 /// type checking declaration initializers (C99 6.7.8)
12054 bool CheckForConstantInitializer(Expr *e, QualType t);
12055
12056 // type checking C++ declaration initializers (C++ [dcl.init]).
12057
12058 /// ReferenceCompareResult - Expresses the result of comparing two
12059 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
12060 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
12061 enum ReferenceCompareResult {
12062 /// Ref_Incompatible - The two types are incompatible, so direct
12063 /// reference binding is not possible.
12064 Ref_Incompatible = 0,
12065 /// Ref_Related - The two types are reference-related, which means
12066 /// that their unqualified forms (T1 and T2) are either the same
12067 /// or T1 is a base class of T2.
12068 Ref_Related,
12069 /// Ref_Compatible - The two types are reference-compatible.
12070 Ref_Compatible
12071 };
12072
12073 // Fake up a scoped enumeration that still contextually converts to bool.
12074 struct ReferenceConversionsScope {
12075 /// The conversions that would be performed on an lvalue of type T2 when
12076 /// binding a reference of type T1 to it, as determined when evaluating
12077 /// whether T1 is reference-compatible with T2.
12078 enum ReferenceConversions {
12079 Qualification = 0x1,
12080 NestedQualification = 0x2,
12081 Function = 0x4,
12082 DerivedToBase = 0x8,
12083 ObjC = 0x10,
12084 ObjCLifetime = 0x20,
12085
12086 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)LLVM_BITMASK_LARGEST_ENUMERATOR = ObjCLifetime
12087 };
12088 };
12089 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
12090
12091 ReferenceCompareResult
12092 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
12093 ReferenceConversions *Conv = nullptr);
12094
12095 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12096 Expr *CastExpr, CastKind &CastKind,
12097 ExprValueKind &VK, CXXCastPath &Path);
12098
12099 /// Force an expression with unknown-type to an expression of the
12100 /// given type.
12101 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
12102
12103 /// Type-check an expression that's being passed to an
12104 /// __unknown_anytype parameter.
12105 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
12106 Expr *result, QualType &paramType);
12107
12108 // CheckMatrixCast - Check type constraints for matrix casts.
12109 // We allow casting between matrixes of the same dimensions i.e. when they
12110 // have the same number of rows and column. Returns true if the cast is
12111 // invalid.
12112 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
12113 CastKind &Kind);
12114
12115 // CheckVectorCast - check type constraints for vectors.
12116 // Since vectors are an extension, there are no C standard reference for this.
12117 // We allow casting between vectors and integer datatypes of the same size.
12118 // returns true if the cast is invalid
12119 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
12120 CastKind &Kind);
12121
12122 /// Prepare `SplattedExpr` for a vector splat operation, adding
12123 /// implicit casts if necessary.
12124 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
12125
12126 // CheckExtVectorCast - check type constraints for extended vectors.
12127 // Since vectors are an extension, there are no C standard reference for this.
12128 // We allow casting between vectors and integer datatypes of the same size,
12129 // or vectors and the element type of that vector.
12130 // returns the cast expr
12131 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
12132 CastKind &Kind);
12133
12134 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
12135 SourceLocation LParenLoc,
12136 Expr *CastExpr,
12137 SourceLocation RParenLoc);
12138
12139 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
12140
12141 /// Checks for invalid conversions and casts between
12142 /// retainable pointers and other pointer kinds for ARC and Weak.
12143 ARCConversionResult CheckObjCConversion(SourceRange castRange,
12144 QualType castType, Expr *&op,
12145 CheckedConversionKind CCK,
12146 bool Diagnose = true,
12147 bool DiagnoseCFAudited = false,
12148 BinaryOperatorKind Opc = BO_PtrMemD
12149 );
12150
12151 Expr *stripARCUnbridgedCast(Expr *e);
12152 void diagnoseARCUnbridgedCast(Expr *e);
12153
12154 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
12155 QualType ExprType);
12156
12157 /// checkRetainCycles - Check whether an Objective-C message send
12158 /// might create an obvious retain cycle.
12159 void checkRetainCycles(ObjCMessageExpr *msg);
12160 void checkRetainCycles(Expr *receiver, Expr *argument);
12161 void checkRetainCycles(VarDecl *Var, Expr *Init);
12162
12163 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
12164 /// to weak/__unsafe_unretained type.
12165 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
12166
12167 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
12168 /// to weak/__unsafe_unretained expression.
12169 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
12170
12171 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
12172 /// \param Method - May be null.
12173 /// \param [out] ReturnType - The return type of the send.
12174 /// \return true iff there were any incompatible types.
12175 bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
12176 MultiExprArg Args, Selector Sel,
12177 ArrayRef<SourceLocation> SelectorLocs,
12178 ObjCMethodDecl *Method, bool isClassMessage,
12179 bool isSuperMessage, SourceLocation lbrac,
12180 SourceLocation rbrac, SourceRange RecRange,
12181 QualType &ReturnType, ExprValueKind &VK);
12182
12183 /// Determine the result of a message send expression based on
12184 /// the type of the receiver, the method expected to receive the message,
12185 /// and the form of the message send.
12186 QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
12187 ObjCMethodDecl *Method, bool isClassMessage,
12188 bool isSuperMessage);
12189
12190 /// If the given expression involves a message send to a method
12191 /// with a related result type, emit a note describing what happened.
12192 void EmitRelatedResultTypeNote(const Expr *E);
12193
12194 /// Given that we had incompatible pointer types in a return
12195 /// statement, check whether we're in a method with a related result
12196 /// type, and if so, emit a note describing what happened.
12197 void EmitRelatedResultTypeNoteForReturn(QualType destType);
12198
12199 class ConditionResult {
12200 Decl *ConditionVar;
12201 FullExprArg Condition;
12202 bool Invalid;
12203 bool HasKnownValue;
12204 bool KnownValue;
12205
12206 friend class Sema;
12207 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
12208 bool IsConstexpr)
12209 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
12210 HasKnownValue(IsConstexpr && Condition.get() &&
12211 !Condition.get()->isValueDependent()),
12212 KnownValue(HasKnownValue &&
12213 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
12214 explicit ConditionResult(bool Invalid)
12215 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
12216 HasKnownValue(false), KnownValue(false) {}
12217
12218 public:
12219 ConditionResult() : ConditionResult(false) {}
12220 bool isInvalid() const { return Invalid; }
12221 std::pair<VarDecl *, Expr *> get() const {
12222 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
12223 Condition.get());
12224 }
12225 llvm::Optional<bool> getKnownValue() const {
12226 if (!HasKnownValue)
12227 return None;
12228 return KnownValue;
12229 }
12230 };
12231 static ConditionResult ConditionError() { return ConditionResult(true); }
12232
12233 enum class ConditionKind {
12234 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
12235 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
12236 Switch ///< An integral condition for a 'switch' statement.
12237 };
12238 QualType PreferredConditionType(ConditionKind K) const {
12239 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
12240 }
12241
12242 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
12243 ConditionKind CK, bool MissingOK = false);
12244
12245 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
12246 SourceLocation StmtLoc,
12247 ConditionKind CK);
12248
12249 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
12250
12251 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
12252 SourceLocation StmtLoc,
12253 ConditionKind CK);
12254 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
12255
12256 /// CheckBooleanCondition - Diagnose problems involving the use of
12257 /// the given expression as a boolean condition (e.g. in an if
12258 /// statement). Also performs the standard function and array
12259 /// decays, possibly changing the input variable.
12260 ///
12261 /// \param Loc - A location associated with the condition, e.g. the
12262 /// 'if' keyword.
12263 /// \return true iff there were any errors
12264 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
12265 bool IsConstexpr = false);
12266
12267 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
12268 /// found in an explicit(bool) specifier.
12269 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
12270
12271 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
12272 /// Returns true if the explicit specifier is now resolved.
12273 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
12274
12275 /// DiagnoseAssignmentAsCondition - Given that an expression is
12276 /// being used as a boolean condition, warn if it's an assignment.
12277 void DiagnoseAssignmentAsCondition(Expr *E);
12278
12279 /// Redundant parentheses over an equality comparison can indicate
12280 /// that the user intended an assignment used as condition.
12281 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
12282
12283 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
12284 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
12285
12286 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
12287 /// the specified width and sign. If an overflow occurs, detect it and emit
12288 /// the specified diagnostic.
12289 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
12290 unsigned NewWidth, bool NewSign,
12291 SourceLocation Loc, unsigned DiagID);
12292
12293 /// Checks that the Objective-C declaration is declared in the global scope.
12294 /// Emits an error and marks the declaration as invalid if it's not declared
12295 /// in the global scope.
12296 bool CheckObjCDeclScope(Decl *D);
12297
12298 /// Abstract base class used for diagnosing integer constant
12299 /// expression violations.
12300 class VerifyICEDiagnoser {
12301 public:
12302 bool Suppress;
12303
12304 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
12305
12306 virtual SemaDiagnosticBuilder
12307 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
12308 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
12309 SourceLocation Loc) = 0;
12310 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
12311 virtual ~VerifyICEDiagnoser() {}
12312 };
12313
12314 enum AllowFoldKind {
12315 NoFold,
12316 AllowFold,
12317 };
12318
12319 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
12320 /// and reports the appropriate diagnostics. Returns false on success.
12321 /// Can optionally return the value of the expression.
12322 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12323 VerifyICEDiagnoser &Diagnoser,
12324 AllowFoldKind CanFold = NoFold);
12325 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12326 unsigned DiagID,
12327 AllowFoldKind CanFold = NoFold);
12328 ExprResult VerifyIntegerConstantExpression(Expr *E,
12329 llvm::APSInt *Result = nullptr,
12330 AllowFoldKind CanFold = NoFold);
12331 ExprResult VerifyIntegerConstantExpression(Expr *E,
12332 AllowFoldKind CanFold = NoFold) {
12333 return VerifyIntegerConstantExpression(E, nullptr, CanFold);
12334 }
12335
12336 /// VerifyBitField - verifies that a bit field expression is an ICE and has
12337 /// the correct width, and that the field type is valid.
12338 /// Returns false on success.
12339 /// Can optionally return whether the bit-field is of width 0
12340 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
12341 QualType FieldTy, bool IsMsStruct,
12342 Expr *BitWidth, bool *ZeroWidth = nullptr);
12343
12344private:
12345 unsigned ForceCUDAHostDeviceDepth = 0;
12346
12347public:
12348 /// Increments our count of the number of times we've seen a pragma forcing
12349 /// functions to be __host__ __device__. So long as this count is greater
12350 /// than zero, all functions encountered will be __host__ __device__.
12351 void PushForceCUDAHostDevice();
12352
12353 /// Decrements our count of the number of times we've seen a pragma forcing
12354 /// functions to be __host__ __device__. Returns false if the count is 0
12355 /// before incrementing, so you can emit an error.
12356 bool PopForceCUDAHostDevice();
12357
12358 /// Diagnostics that are emitted only if we discover that the given function
12359 /// must be codegen'ed. Because handling these correctly adds overhead to
12360 /// compilation, this is currently only enabled for CUDA compilations.
12361 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
12362 std::vector<PartialDiagnosticAt>>
12363 DeviceDeferredDiags;
12364
12365 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
12366 /// key in a hashtable, both the FD and location are hashed.
12367 struct FunctionDeclAndLoc {
12368 CanonicalDeclPtr<FunctionDecl> FD;
12369 SourceLocation Loc;
12370 };
12371
12372 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
12373 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
12374 /// same deferred diag twice.
12375 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
12376
12377 /// An inverse call graph, mapping known-emitted functions to one of their
12378 /// known-emitted callers (plus the location of the call).
12379 ///
12380 /// Functions that we can tell a priori must be emitted aren't added to this
12381 /// map.
12382 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
12383 /* Caller = */ FunctionDeclAndLoc>
12384 DeviceKnownEmittedFns;
12385
12386 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12387 /// context is "used as device code".
12388 ///
12389 /// - If CurContext is a __host__ function, does not emit any diagnostics
12390 /// unless \p EmitOnBothSides is true.
12391 /// - If CurContext is a __device__ or __global__ function, emits the
12392 /// diagnostics immediately.
12393 /// - If CurContext is a __host__ __device__ function and we are compiling for
12394 /// the device, creates a diagnostic which is emitted if and when we realize
12395 /// that the function will be codegen'ed.
12396 ///
12397 /// Example usage:
12398 ///
12399 /// // Variable-length arrays are not allowed in CUDA device code.
12400 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
12401 /// return ExprError();
12402 /// // Otherwise, continue parsing as normal.
12403 SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc,
12404 unsigned DiagID);
12405
12406 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12407 /// context is "used as host code".
12408 ///
12409 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
12410 SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
12411
12412 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12413 /// context is "used as device code".
12414 ///
12415 /// - If CurContext is a `declare target` function or it is known that the
12416 /// function is emitted for the device, emits the diagnostics immediately.
12417 /// - If CurContext is a non-`declare target` function and we are compiling
12418 /// for the device, creates a diagnostic which is emitted if and when we
12419 /// realize that the function will be codegen'ed.
12420 ///
12421 /// Example usage:
12422 ///
12423 /// // Variable-length arrays are not allowed in NVPTX device code.
12424 /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
12425 /// return ExprError();
12426 /// // Otherwise, continue parsing as normal.
12427 SemaDiagnosticBuilder
12428 diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD);
12429
12430 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12431 /// context is "used as host code".
12432 ///
12433 /// - If CurContext is a `declare target` function or it is known that the
12434 /// function is emitted for the host, emits the diagnostics immediately.
12435 /// - If CurContext is a non-host function, just ignore it.
12436 ///
12437 /// Example usage:
12438 ///
12439 /// // Variable-length arrays are not allowed in NVPTX device code.
12440 /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
12441 /// return ExprError();
12442 /// // Otherwise, continue parsing as normal.
12443 SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc,
12444 unsigned DiagID, FunctionDecl *FD);
12445
12446 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
12447 FunctionDecl *FD = nullptr);
12448 SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
12449 const PartialDiagnostic &PD,
12450 FunctionDecl *FD = nullptr) {
12451 return targetDiag(Loc, PD.getDiagID(), FD) << PD;
12452 }
12453
12454 /// Check if the type is allowed to be used for the current target.
12455 void checkTypeSupport(QualType Ty, SourceLocation Loc,
12456 ValueDecl *D = nullptr);
12457
12458 enum CUDAFunctionTarget {
12459 CFT_Device,
12460 CFT_Global,
12461 CFT_Host,
12462 CFT_HostDevice,
12463 CFT_InvalidTarget
12464 };
12465
12466 /// Determines whether the given function is a CUDA device/host/kernel/etc.
12467 /// function.
12468 ///
12469 /// Use this rather than examining the function's attributes yourself -- you
12470 /// will get it wrong. Returns CFT_Host if D is null.
12471 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
12472 bool IgnoreImplicitHDAttr = false);
12473 CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
12474
12475 enum CUDAVariableTarget {
12476 CVT_Device, /// Emitted on device side with a shadow variable on host side
12477 CVT_Host, /// Emitted on host side only
12478 CVT_Both, /// Emitted on both sides with different addresses
12479 CVT_Unified, /// Emitted as a unified address, e.g. managed variables
12480 };
12481 /// Determines whether the given variable is emitted on host or device side.
12482 CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D);
12483
12484 /// Gets the CUDA target for the current context.
12485 CUDAFunctionTarget CurrentCUDATarget() {
12486 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
12487 }
12488
12489 static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D);
12490
12491 // CUDA function call preference. Must be ordered numerically from
12492 // worst to best.
12493 enum CUDAFunctionPreference {
12494 CFP_Never, // Invalid caller/callee combination.
12495 CFP_WrongSide, // Calls from host-device to host or device
12496 // function that do not match current compilation
12497 // mode.
12498 CFP_HostDevice, // Any calls to host/device functions.
12499 CFP_SameSide, // Calls from host-device to host or device
12500 // function matching current compilation mode.
12501 CFP_Native, // host-to-host or device-to-device calls.
12502 };
12503
12504 /// Identifies relative preference of a given Caller/Callee
12505 /// combination, based on their host/device attributes.
12506 /// \param Caller function which needs address of \p Callee.
12507 /// nullptr in case of global context.
12508 /// \param Callee target function
12509 ///
12510 /// \returns preference value for particular Caller/Callee combination.
12511 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
12512 const FunctionDecl *Callee);
12513
12514 /// Determines whether Caller may invoke Callee, based on their CUDA
12515 /// host/device attributes. Returns false if the call is not allowed.
12516 ///
12517 /// Note: Will return true for CFP_WrongSide calls. These may appear in
12518 /// semantically correct CUDA programs, but only if they're never codegen'ed.
12519 bool IsAllowedCUDACall(const FunctionDecl *Caller,
12520 const FunctionDecl *Callee) {
12521 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
12522 }
12523
12524 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
12525 /// depending on FD and the current compilation settings.
12526 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
12527 const LookupResult &Previous);
12528
12529 /// May add implicit CUDAConstantAttr attribute to VD, depending on VD
12530 /// and current compilation settings.
12531 void MaybeAddCUDAConstantAttr(VarDecl *VD);
12532
12533public:
12534 /// Check whether we're allowed to call Callee from the current context.
12535 ///
12536 /// - If the call is never allowed in a semantically-correct program
12537 /// (CFP_Never), emits an error and returns false.
12538 ///
12539 /// - If the call is allowed in semantically-correct programs, but only if
12540 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
12541 /// be emitted if and when the caller is codegen'ed, and returns true.
12542 ///
12543 /// Will only create deferred diagnostics for a given SourceLocation once,
12544 /// so you can safely call this multiple times without generating duplicate
12545 /// deferred errors.
12546 ///
12547 /// - Otherwise, returns true without emitting any diagnostics.
12548 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
12549
12550 void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture);
12551
12552 /// Set __device__ or __host__ __device__ attributes on the given lambda
12553 /// operator() method.
12554 ///
12555 /// CUDA lambdas by default is host device function unless it has explicit
12556 /// host or device attribute.
12557 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
12558
12559 /// Finds a function in \p Matches with highest calling priority
12560 /// from \p Caller context and erases all functions with lower
12561 /// calling priority.
12562 void EraseUnwantedCUDAMatches(
12563 const FunctionDecl *Caller,
12564 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
12565
12566 /// Given a implicit special member, infer its CUDA target from the
12567 /// calls it needs to make to underlying base/field special members.
12568 /// \param ClassDecl the class for which the member is being created.
12569 /// \param CSM the kind of special member.
12570 /// \param MemberDecl the special member itself.
12571 /// \param ConstRHS true if this is a copy operation with a const object on
12572 /// its RHS.
12573 /// \param Diagnose true if this call should emit diagnostics.
12574 /// \return true if there was an error inferring.
12575 /// The result of this call is implicit CUDA target attribute(s) attached to
12576 /// the member declaration.
12577 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
12578 CXXSpecialMember CSM,
12579 CXXMethodDecl *MemberDecl,
12580 bool ConstRHS,
12581 bool Diagnose);
12582
12583 /// \return true if \p CD can be considered empty according to CUDA
12584 /// (E.2.3.1 in CUDA 7.5 Programming guide).
12585 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
12586 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
12587
12588 // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
12589 // case of error emits appropriate diagnostic and invalidates \p Var.
12590 //
12591 // \details CUDA allows only empty constructors as initializers for global
12592 // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
12593 // __shared__ variables whether they are local or not (they all are implicitly
12594 // static in CUDA). One exception is that CUDA allows constant initializers
12595 // for __constant__ and __device__ variables.
12596 void checkAllowedCUDAInitializer(VarDecl *VD);
12597
12598 /// Check whether NewFD is a valid overload for CUDA. Emits
12599 /// diagnostics and invalidates NewFD if not.
12600 void checkCUDATargetOverload(FunctionDecl *NewFD,
12601 const LookupResult &Previous);
12602 /// Copies target attributes from the template TD to the function FD.
12603 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
12604
12605 /// Returns the name of the launch configuration function. This is the name
12606 /// of the function that will be called to configure kernel call, with the
12607 /// parameters specified via <<<>>>.
12608 std::string getCudaConfigureFuncName() const;
12609
12610 /// \name Code completion
12611 //@{
12612 /// Describes the context in which code completion occurs.
12613 enum ParserCompletionContext {
12614 /// Code completion occurs at top-level or namespace context.
12615 PCC_Namespace,
12616 /// Code completion occurs within a class, struct, or union.
12617 PCC_Class,
12618 /// Code completion occurs within an Objective-C interface, protocol,
12619 /// or category.
12620 PCC_ObjCInterface,
12621 /// Code completion occurs within an Objective-C implementation or
12622 /// category implementation
12623 PCC_ObjCImplementation,
12624 /// Code completion occurs within the list of instance variables
12625 /// in an Objective-C interface, protocol, category, or implementation.
12626 PCC_ObjCInstanceVariableList,
12627 /// Code completion occurs following one or more template
12628 /// headers.
12629 PCC_Template,
12630 /// Code completion occurs following one or more template
12631 /// headers within a class.
12632 PCC_MemberTemplate,
12633 /// Code completion occurs within an expression.
12634 PCC_Expression,
12635 /// Code completion occurs within a statement, which may
12636 /// also be an expression or a declaration.
12637 PCC_Statement,
12638 /// Code completion occurs at the beginning of the
12639 /// initialization statement (or expression) in a for loop.
12640 PCC_ForInit,
12641 /// Code completion occurs within the condition of an if,
12642 /// while, switch, or for statement.
12643 PCC_Condition,
12644 /// Code completion occurs within the body of a function on a
12645 /// recovery path, where we do not have a specific handle on our position
12646 /// in the grammar.
12647 PCC_RecoveryInFunction,
12648 /// Code completion occurs where only a type is permitted.
12649 PCC_Type,
12650 /// Code completion occurs in a parenthesized expression, which
12651 /// might also be a type cast.
12652 PCC_ParenthesizedExpression,
12653 /// Code completion occurs within a sequence of declaration
12654 /// specifiers within a function, method, or block.
12655 PCC_LocalDeclarationSpecifiers
12656 };
12657
12658 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
12659 void CodeCompleteOrdinaryName(Scope *S,
12660 ParserCompletionContext CompletionContext);
12661 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
12662 bool AllowNonIdentifiers,
12663 bool AllowNestedNameSpecifiers);
12664
12665 struct CodeCompleteExpressionData;
12666 void CodeCompleteExpression(Scope *S,
12667 const CodeCompleteExpressionData &Data);
12668 void CodeCompleteExpression(Scope *S, QualType PreferredType,
12669 bool IsParenthesized = false);
12670 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
12671 SourceLocation OpLoc, bool IsArrow,
12672 bool IsBaseExprStatement,
12673 QualType PreferredType);
12674 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
12675 QualType PreferredType);
12676 void CodeCompleteTag(Scope *S, unsigned TagSpec);
12677 void CodeCompleteTypeQualifiers(DeclSpec &DS);
12678 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
12679 const VirtSpecifiers *VS = nullptr);
12680 void CodeCompleteBracketDeclarator(Scope *S);
12681 void CodeCompleteCase(Scope *S);
12682 enum class AttributeCompletion {
12683 Attribute,
12684 Scope,
12685 None,
12686 };
12687 void CodeCompleteAttribute(
12688 AttributeCommonInfo::Syntax Syntax,
12689 AttributeCompletion Completion = AttributeCompletion::Attribute,
12690 const IdentifierInfo *Scope = nullptr);
12691 /// Determines the preferred type of the current function argument, by
12692 /// examining the signatures of all possible overloads.
12693 /// Returns null if unknown or ambiguous, or if code completion is off.
12694 ///
12695 /// If the code completion point has been reached, also reports the function
12696 /// signatures that were considered.
12697 ///
12698 /// FIXME: rename to GuessCallArgumentType to reduce confusion.
12699 QualType ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args,
12700 SourceLocation OpenParLoc);
12701 QualType ProduceConstructorSignatureHelp(QualType Type, SourceLocation Loc,
12702 ArrayRef<Expr *> Args,
12703 SourceLocation OpenParLoc,
12704 bool Braced);
12705 QualType ProduceCtorInitMemberSignatureHelp(
12706 Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy,
12707 ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc,
12708 bool Braced);
12709 QualType ProduceTemplateArgumentSignatureHelp(
12710 TemplateTy, ArrayRef<ParsedTemplateArgument>, SourceLocation LAngleLoc);
12711 void CodeCompleteInitializer(Scope *S, Decl *D);
12712 /// Trigger code completion for a record of \p BaseType. \p InitExprs are
12713 /// expressions in the initializer list seen so far and \p D is the current
12714 /// Designation being parsed.
12715 void CodeCompleteDesignator(const QualType BaseType,
12716 llvm::ArrayRef<Expr *> InitExprs,
12717 const Designation &D);
12718 void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
12719
12720 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
12721 bool IsUsingDeclaration, QualType BaseType,
12722 QualType PreferredType);
12723 void CodeCompleteUsing(Scope *S);
12724 void CodeCompleteUsingDirective(Scope *S);
12725 void CodeCompleteNamespaceDecl(Scope *S);
12726 void CodeCompleteNamespaceAliasDecl(Scope *S);
12727 void CodeCompleteOperatorName(Scope *S);
12728 void CodeCompleteConstructorInitializer(
12729 Decl *Constructor,
12730 ArrayRef<CXXCtorInitializer *> Initializers);
12731
12732 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
12733 bool AfterAmpersand);
12734 void CodeCompleteAfterFunctionEquals(Declarator &D);
12735
12736 void CodeCompleteObjCAtDirective(Scope *S);
12737 void CodeCompleteObjCAtVisibility(Scope *S);
12738 void CodeCompleteObjCAtStatement(Scope *S);
12739 void CodeCompleteObjCAtExpression(Scope *S);
12740 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
12741 void CodeCompleteObjCPropertyGetter(Scope *S);
12742 void CodeCompleteObjCPropertySetter(Scope *S);
12743 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
12744 bool IsParameter);
12745 void CodeCompleteObjCMessageReceiver(Scope *S);
12746 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
12747 ArrayRef<IdentifierInfo *> SelIdents,
12748 bool AtArgumentExpression);
12749 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
12750 ArrayRef<IdentifierInfo *> SelIdents,
12751 bool AtArgumentExpression,
12752 bool IsSuper = false);
12753 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
12754 ArrayRef<IdentifierInfo *> SelIdents,
12755 bool AtArgumentExpression,
12756 ObjCInterfaceDecl *Super = nullptr);
12757 void CodeCompleteObjCForCollection(Scope *S,
12758 DeclGroupPtrTy IterationVar);
12759 void CodeCompleteObjCSelector(Scope *S,
12760 ArrayRef<IdentifierInfo *> SelIdents);
12761 void CodeCompleteObjCProtocolReferences(
12762 ArrayRef<IdentifierLocPair> Protocols);
12763 void CodeCompleteObjCProtocolDecl(Scope *S);
12764 void CodeCompleteObjCInterfaceDecl(Scope *S);
12765 void CodeCompleteObjCSuperclass(Scope *S,
12766 IdentifierInfo *ClassName,
12767 SourceLocation ClassNameLoc);
12768 void CodeCompleteObjCImplementationDecl(Scope *S);
12769 void CodeCompleteObjCInterfaceCategory(Scope *S,
12770 IdentifierInfo *ClassName,
12771 SourceLocation ClassNameLoc);
12772 void CodeCompleteObjCImplementationCategory(Scope *S,
12773 IdentifierInfo *ClassName,
12774 SourceLocation ClassNameLoc);
12775 void CodeCompleteObjCPropertyDefinition(Scope *S);
12776 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
12777 IdentifierInfo *PropertyName);
12778 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
12779 ParsedType ReturnType);
12780 void CodeCompleteObjCMethodDeclSelector(Scope *S,
12781 bool IsInstanceMethod,
12782 bool AtParameterName,
12783 ParsedType ReturnType,
12784 ArrayRef<IdentifierInfo *> SelIdents);
12785 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
12786 SourceLocation ClassNameLoc,
12787 bool IsBaseExprStatement);
12788 void CodeCompletePreprocessorDirective(bool InConditional);
12789 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
12790 void CodeCompletePreprocessorMacroName(bool IsDefinition);
12791 void CodeCompletePreprocessorExpression();
12792 void CodeCompletePreprocessorMacroArgument(Scope *S,
12793 IdentifierInfo *Macro,
12794 MacroInfo *MacroInfo,
12795 unsigned Argument);
12796 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
12797 void CodeCompleteNaturalLanguage();
12798 void CodeCompleteAvailabilityPlatformName();
12799 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
12800 CodeCompletionTUInfo &CCTUInfo,
12801 SmallVectorImpl<CodeCompletionResult> &Results);
12802 //@}
12803
12804 //===--------------------------------------------------------------------===//
12805 // Extra semantic analysis beyond the C type system
12806
12807public:
12808 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
12809 unsigned ByteNo) const;
12810
12811private:
12812 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12813 const ArraySubscriptExpr *ASE=nullptr,
12814 bool AllowOnePastEnd=true, bool IndexNegated=false);
12815 void CheckArrayAccess(const Expr *E);
12816 // Used to grab the relevant information from a FormatAttr and a
12817 // FunctionDeclaration.
12818 struct FormatStringInfo {
12819 unsigned FormatIdx;
12820 unsigned FirstDataArg;
12821 bool HasVAListArg;
12822 };
12823
12824 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
12825 FormatStringInfo *FSI);
12826 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
12827 const FunctionProtoType *Proto);
12828 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
12829 ArrayRef<const Expr *> Args);
12830 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
12831 const FunctionProtoType *Proto);
12832 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
12833 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
12834 ArrayRef<const Expr *> Args,
12835 const FunctionProtoType *Proto, SourceLocation Loc);
12836
12837 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
12838 StringRef ParamName, QualType ArgTy, QualType ParamTy);
12839
12840 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
12841 const Expr *ThisArg, ArrayRef<const Expr *> Args,
12842 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
12843 VariadicCallType CallType);
12844
12845 bool CheckObjCString(Expr *Arg);
12846 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
12847
12848 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
12849 unsigned BuiltinID, CallExpr *TheCall);
12850
12851 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12852 CallExpr *TheCall);
12853
12854 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
12855
12856 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
12857 unsigned MaxWidth);
12858 bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12859 CallExpr *TheCall);
12860 bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12861 bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12862 bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12863 CallExpr *TheCall);
12864 bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg,
12865 bool WantCDE);
12866 bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12867 CallExpr *TheCall);
12868
12869 bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12870 CallExpr *TheCall);
12871 bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12872 bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12873 bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12874 bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12875 CallExpr *TheCall);
12876 bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
12877 CallExpr *TheCall);
12878 bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12879 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12880 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
12881 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
12882 bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall);
12883 bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
12884 ArrayRef<int> ArgNums);
12885 bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums);
12886 bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
12887 ArrayRef<int> ArgNums);
12888 bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12889 CallExpr *TheCall);
12890 bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12891 CallExpr *TheCall);
12892 bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12893 bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum);
12894 bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12895 CallExpr *TheCall);
12896
12897 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
12898 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
12899 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
12900 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
12901 bool SemaBuiltinComplex(CallExpr *TheCall);
12902 bool SemaBuiltinVSX(CallExpr *TheCall);
12903 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
12904 bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
12905
12906public:
12907 // Used by C++ template instantiation.
12908 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
12909 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
12910 SourceLocation BuiltinLoc,
12911 SourceLocation RParenLoc);
12912
12913private:
12914 bool SemaBuiltinPrefetch(CallExpr *TheCall);
12915 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
12916 bool SemaBuiltinArithmeticFence(CallExpr *TheCall);
12917 bool SemaBuiltinAssume(CallExpr *TheCall);
12918 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
12919 bool SemaBuiltinLongjmp(CallExpr *TheCall);
12920 bool SemaBuiltinSetjmp(CallExpr *TheCall);
12921 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
12922 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
12923 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
12924 AtomicExpr::AtomicOp Op);
12925 ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
12926 bool IsDelete);
12927 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
12928 llvm::APSInt &Result);
12929 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
12930 int High, bool RangeIsError = true);
12931 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
12932 unsigned Multiple);
12933 bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
12934 bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
12935 unsigned ArgBits);
12936 bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
12937 unsigned ArgBits);
12938 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
12939 int ArgNum, unsigned ExpectedFieldNum,
12940 bool AllowName);
12941 bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
12942 bool SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
12943 const char *TypeDesc);
12944
12945 bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc);
12946
12947 bool SemaBuiltinElementwiseMath(CallExpr *TheCall);
12948 bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall);
12949 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
12950
12951 // Matrix builtin handling.
12952 ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall,
12953 ExprResult CallResult);
12954 ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
12955 ExprResult CallResult);
12956 ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
12957 ExprResult CallResult);
12958
12959public:
12960 enum FormatStringType {
12961 FST_Scanf,
12962 FST_Printf,
12963 FST_NSString,
12964 FST_Strftime,
12965 FST_Strfmon,
12966 FST_Kprintf,
12967 FST_FreeBSDKPrintf,
12968 FST_OSTrace,
12969 FST_OSLog,
12970 FST_Unknown
12971 };
12972 static FormatStringType GetFormatStringType(const FormatAttr *Format);
12973
12974 bool FormatStringHasSArg(const StringLiteral *FExpr);
12975
12976 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
12977
12978private:
12979 bool CheckFormatArguments(const FormatAttr *Format,
12980 ArrayRef<const Expr *> Args,
12981 bool IsCXXMember,
12982 VariadicCallType CallType,
12983 SourceLocation Loc, SourceRange Range,
12984 llvm::SmallBitVector &CheckedVarArgs);
12985 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
12986 bool HasVAListArg, unsigned format_idx,
12987 unsigned firstDataArg, FormatStringType Type,
12988 VariadicCallType CallType,
12989 SourceLocation Loc, SourceRange range,
12990 llvm::SmallBitVector &CheckedVarArgs);
12991
12992 void CheckAbsoluteValueFunction(const CallExpr *Call,
12993 const FunctionDecl *FDecl);
12994
12995 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
12996
12997 void CheckMemaccessArguments(const CallExpr *Call,
12998 unsigned BId,
12999 IdentifierInfo *FnName);
13000
13001 void CheckStrlcpycatArguments(const CallExpr *Call,
13002 IdentifierInfo *FnName);
13003
13004 void CheckStrncatArguments(const CallExpr *Call,
13005 IdentifierInfo *FnName);
13006
13007 void CheckFreeArguments(const CallExpr *E);
13008
13009 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
13010 SourceLocation ReturnLoc,
13011 bool isObjCMethod = false,
13012 const AttrVec *Attrs = nullptr,
13013 const FunctionDecl *FD = nullptr);
13014
13015public:
13016 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,
13017 BinaryOperatorKind Opcode);
13018
13019private:
13020 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
13021 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
13022 void CheckForIntOverflow(Expr *E);
13023 void CheckUnsequencedOperations(const Expr *E);
13024
13025 /// Perform semantic checks on a completed expression. This will either
13026 /// be a full-expression or a default argument expression.
13027 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
13028 bool IsConstexpr = false);
13029
13030 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
13031 Expr *Init);
13032
13033 /// Check if there is a field shadowing.
13034 void CheckShadowInheritedFields(const SourceLocation &Loc,
13035 DeclarationName FieldName,
13036 const CXXRecordDecl *RD,
13037 bool DeclIsField = true);
13038
13039 /// Check if the given expression contains 'break' or 'continue'
13040 /// statement that produces control flow different from GCC.
13041 void CheckBreakContinueBinding(Expr *E);
13042
13043 /// Check whether receiver is mutable ObjC container which
13044 /// attempts to add itself into the container
13045 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
13046
13047 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
13048 const NamedDecl *Callee);
13049
13050 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
13051 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
13052 bool DeleteWasArrayForm);
13053public:
13054 /// Register a magic integral constant to be used as a type tag.
13055 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13056 uint64_t MagicValue, QualType Type,
13057 bool LayoutCompatible, bool MustBeNull);
13058
13059 struct TypeTagData {
13060 TypeTagData() {}
13061
13062 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
13063 Type(Type), LayoutCompatible(LayoutCompatible),
13064 MustBeNull(MustBeNull)
13065 {}
13066
13067 QualType Type;
13068
13069 /// If true, \c Type should be compared with other expression's types for
13070 /// layout-compatibility.
13071 unsigned LayoutCompatible : 1;
13072 unsigned MustBeNull : 1;
13073 };
13074
13075 /// A pair of ArgumentKind identifier and magic value. This uniquely
13076 /// identifies the magic value.
13077 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
13078
13079private:
13080 /// A map from magic value to type information.
13081 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
13082 TypeTagForDatatypeMagicValues;
13083
13084 /// Peform checks on a call of a function with argument_with_type_tag
13085 /// or pointer_with_type_tag attributes.
13086 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13087 const ArrayRef<const Expr *> ExprArgs,
13088 SourceLocation CallSiteLoc);
13089
13090 /// Check if we are taking the address of a packed field
13091 /// as this may be a problem if the pointer value is dereferenced.
13092 void CheckAddressOfPackedMember(Expr *rhs);
13093
13094 /// The parser's current scope.
13095 ///
13096 /// The parser maintains this state here.
13097 Scope *CurScope;
13098
13099 mutable IdentifierInfo *Ident_super;
13100 mutable IdentifierInfo *Ident___float128;
13101
13102 /// Nullability type specifiers.
13103 IdentifierInfo *Ident__Nonnull = nullptr;
13104 IdentifierInfo *Ident__Nullable = nullptr;
13105 IdentifierInfo *Ident__Nullable_result = nullptr;
13106 IdentifierInfo *Ident__Null_unspecified = nullptr;
13107
13108 IdentifierInfo *Ident_NSError = nullptr;
13109
13110 /// The handler for the FileChanged preprocessor events.
13111 ///
13112 /// Used for diagnostics that implement custom semantic analysis for #include
13113 /// directives, like -Wpragma-pack.
13114 sema::SemaPPCallbacks *SemaPPCallbackHandler;
13115
13116protected:
13117 friend class Parser;
13118 friend class InitializationSequence;
13119 friend class ASTReader;
13120 friend class ASTDeclReader;
13121 friend class ASTWriter;
13122
13123public:
13124 /// Retrieve the keyword associated
13125 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
13126
13127 /// The struct behind the CFErrorRef pointer.
13128 RecordDecl *CFError = nullptr;
13129 bool isCFError(RecordDecl *D);
13130
13131 /// Retrieve the identifier "NSError".
13132 IdentifierInfo *getNSErrorIdent();
13133
13134 /// Retrieve the parser's current scope.
13135 ///
13136 /// This routine must only be used when it is certain that semantic analysis
13137 /// and the parser are in precisely the same context, which is not the case
13138 /// when, e.g., we are performing any kind of template instantiation.
13139 /// Therefore, the only safe places to use this scope are in the parser
13140 /// itself and in routines directly invoked from the parser and *never* from
13141 /// template substitution or instantiation.
13142 Scope *getCurScope() const { return CurScope; }
13143
13144 void incrementMSManglingNumber() const {
13145 return CurScope->incrementMSManglingNumber();
13146 }
13147
13148 IdentifierInfo *getSuperIdentifier() const;
13149 IdentifierInfo *getFloat128Identifier() const;
13150
13151 Decl *getObjCDeclContext() const;
13152
13153 DeclContext *getCurLexicalContext() const {
13154 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
13155 }
13156
13157 const DeclContext *getCurObjCLexicalContext() const {
13158 const DeclContext *DC = getCurLexicalContext();
13159 // A category implicitly has the attribute of the interface.
13160 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
13161 DC = CatD->getClassInterface();
13162 return DC;
13163 }
13164
13165 /// Determine the number of levels of enclosing template parameters. This is
13166 /// only usable while parsing. Note that this does not include dependent
13167 /// contexts in which no template parameters have yet been declared, such as
13168 /// in a terse function template or generic lambda before the first 'auto' is
13169 /// encountered.
13170 unsigned getTemplateDepth(Scope *S) const;
13171
13172 /// To be used for checking whether the arguments being passed to
13173 /// function exceeds the number of parameters expected for it.
13174 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
13175 bool PartialOverloading = false) {
13176 // We check whether we're just after a comma in code-completion.
13177 if (NumArgs > 0 && PartialOverloading)
13178 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
13179 return NumArgs > NumParams;
13180 }
13181
13182 // Emitting members of dllexported classes is delayed until the class
13183 // (including field initializers) is fully parsed.
13184 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
13185 SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
13186
13187private:
13188 int ParsingClassDepth = 0;
13189
13190 class SavePendingParsedClassStateRAII {
13191 public:
13192 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
13193
13194 ~SavePendingParsedClassStateRAII() {
13195 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&(static_cast <bool> (S.DelayedOverridingExceptionSpecChecks
.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "clang/include/clang/Sema/Sema.h", 13196, __extension__ __PRETTY_FUNCTION__
))
13196 "there shouldn't be any pending delayed exception spec checks")(static_cast <bool> (S.DelayedOverridingExceptionSpecChecks
.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "clang/include/clang/Sema/Sema.h", 13196, __extension__ __PRETTY_FUNCTION__
))
;
13197 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&(static_cast <bool> (S.DelayedEquivalentExceptionSpecChecks
.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "clang/include/clang/Sema/Sema.h", 13198, __extension__ __PRETTY_FUNCTION__
))
13198 "there shouldn't be any pending delayed exception spec checks")(static_cast <bool> (S.DelayedEquivalentExceptionSpecChecks
.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "clang/include/clang/Sema/Sema.h", 13198, __extension__ __PRETTY_FUNCTION__
))
;
13199 swapSavedState();
13200 }
13201
13202 private:
13203 Sema &S;
13204 decltype(DelayedOverridingExceptionSpecChecks)
13205 SavedOverridingExceptionSpecChecks;
13206 decltype(DelayedEquivalentExceptionSpecChecks)
13207 SavedEquivalentExceptionSpecChecks;
13208
13209 void swapSavedState() {
13210 SavedOverridingExceptionSpecChecks.swap(
13211 S.DelayedOverridingExceptionSpecChecks);
13212 SavedEquivalentExceptionSpecChecks.swap(
13213 S.DelayedEquivalentExceptionSpecChecks);
13214 }
13215 };
13216
13217 /// Helper class that collects misaligned member designations and
13218 /// their location info for delayed diagnostics.
13219 struct MisalignedMember {
13220 Expr *E;
13221 RecordDecl *RD;
13222 ValueDecl *MD;
13223 CharUnits Alignment;
13224
13225 MisalignedMember() : E(), RD(), MD() {}
13226 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
13227 CharUnits Alignment)
13228 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
13229 explicit MisalignedMember(Expr *E)
13230 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
13231
13232 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
13233 };
13234 /// Small set of gathered accesses to potentially misaligned members
13235 /// due to the packed attribute.
13236 SmallVector<MisalignedMember, 4> MisalignedMembers;
13237
13238 /// Adds an expression to the set of gathered misaligned members.
13239 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13240 CharUnits Alignment);
13241
13242public:
13243 /// Diagnoses the current set of gathered accesses. This typically
13244 /// happens at full expression level. The set is cleared after emitting the
13245 /// diagnostics.
13246 void DiagnoseMisalignedMembers();
13247
13248 /// This function checks if the expression is in the sef of potentially
13249 /// misaligned members and it is converted to some pointer type T with lower
13250 /// or equal alignment requirements. If so it removes it. This is used when
13251 /// we do not want to diagnose such misaligned access (e.g. in conversions to
13252 /// void*).
13253 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
13254
13255 /// This function calls Action when it determines that E designates a
13256 /// misaligned member due to the packed attribute. This is used to emit
13257 /// local diagnostics like in reference binding.
13258 void RefersToMemberWithReducedAlignment(
13259 Expr *E,
13260 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13261 Action);
13262
13263 /// Describes the reason a calling convention specification was ignored, used
13264 /// for diagnostics.
13265 enum class CallingConventionIgnoredReason {
13266 ForThisTarget = 0,
13267 VariadicFunction,
13268 ConstructorDestructor,
13269 BuiltinFunction
13270 };
13271 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
13272 /// context is "used as device code".
13273 ///
13274 /// - If CurLexicalContext is a kernel function or it is known that the
13275 /// function will be emitted for the device, emits the diagnostics
13276 /// immediately.
13277 /// - If CurLexicalContext is a function and we are compiling
13278 /// for the device, but we don't know that this function will be codegen'ed
13279 /// for devive yet, creates a diagnostic which is emitted if and when we
13280 /// realize that the function will be codegen'ed.
13281 ///
13282 /// Example usage:
13283 ///
13284 /// Diagnose __float128 type usage only from SYCL device code if the current
13285 /// target doesn't support it
13286 /// if (!S.Context.getTargetInfo().hasFloat128Type() &&
13287 /// S.getLangOpts().SYCLIsDevice)
13288 /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
13289 SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc,
13290 unsigned DiagID);
13291
13292 /// Check whether we're allowed to call Callee from the current context.
13293 ///
13294 /// - If the call is never allowed in a semantically-correct program
13295 /// emits an error and returns false.
13296 ///
13297 /// - If the call is allowed in semantically-correct programs, but only if
13298 /// it's never codegen'ed, creates a deferred diagnostic to be emitted if
13299 /// and when the caller is codegen'ed, and returns true.
13300 ///
13301 /// - Otherwise, returns true without emitting any diagnostics.
13302 ///
13303 /// Adds Callee to DeviceCallGraph if we don't know if its caller will be
13304 /// codegen'ed yet.
13305 bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee);
13306 void deepTypeCheckForSYCLDevice(SourceLocation UsedAt,
13307 llvm::DenseSet<QualType> Visited,
13308 ValueDecl *DeclToCheck);
13309};
13310
13311/// RAII object that enters a new expression evaluation context.
13312class EnterExpressionEvaluationContext {
13313 Sema &Actions;
13314 bool Entered = true;
13315
13316public:
13317 EnterExpressionEvaluationContext(
13318 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
13319 Decl *LambdaContextDecl = nullptr,
13320 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
13321 Sema::ExpressionEvaluationContextRecord::EK_Other,
13322 bool ShouldEnter = true)
13323 : Actions(Actions), Entered(ShouldEnter) {
13324 if (Entered)
13325 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
13326 ExprContext);
13327 }
13328 EnterExpressionEvaluationContext(
13329 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
13330 Sema::ReuseLambdaContextDecl_t,
13331 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
13332 Sema::ExpressionEvaluationContextRecord::EK_Other)
13333 : Actions(Actions) {
13334 Actions.PushExpressionEvaluationContext(
13335 NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
13336 }
13337
13338 enum InitListTag { InitList };
13339 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
13340 bool ShouldEnter = true)
13341 : Actions(Actions), Entered(false) {
13342 // In C++11 onwards, narrowing checks are performed on the contents of
13343 // braced-init-lists, even when they occur within unevaluated operands.
13344 // Therefore we still need to instantiate constexpr functions used in such
13345 // a context.
13346 if (ShouldEnter && Actions.isUnevaluatedContext() &&
13347 Actions.getLangOpts().CPlusPlus11) {
13348 Actions.PushExpressionEvaluationContext(
13349 Sema::ExpressionEvaluationContext::UnevaluatedList);
13350 Entered = true;
13351 }
13352 }
13353
13354 ~EnterExpressionEvaluationContext() {
13355 if (Entered)
13356 Actions.PopExpressionEvaluationContext();
13357 }
13358};
13359
13360DeductionFailureInfo
13361MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
13362 sema::TemplateDeductionInfo &Info);
13363
13364/// Contains a late templated function.
13365/// Will be parsed at the end of the translation unit, used by Sema & Parser.
13366struct LateParsedTemplate {
13367 CachedTokens Toks;
13368 /// The template function declaration to be late parsed.
13369 Decl *D;
13370};
13371
13372template <>
13373void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
13374 PragmaMsStackAction Action,
13375 llvm::StringRef StackSlotLabel,
13376 AlignPackInfo Value);
13377
13378} // end namespace clang
13379
13380namespace llvm {
13381// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
13382// SourceLocation.
13383template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
13384 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
13385 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
13386
13387 static FunctionDeclAndLoc getEmptyKey() {
13388 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
13389 }
13390
13391 static FunctionDeclAndLoc getTombstoneKey() {
13392 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
13393 }
13394
13395 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
13396 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
13397 FDL.Loc.getHashValue());
13398 }
13399
13400 static bool isEqual(const FunctionDeclAndLoc &LHS,
13401 const FunctionDeclAndLoc &RHS) {
13402 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
13403 }
13404};
13405} // namespace llvm
13406
13407#endif