Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name 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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn359941/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-9~svn359941/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn359941/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn359941/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn359941/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn359941/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn359941=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-05-04-031955-17239-1 -x c++ /build/llvm-toolchain-snapshot-9~svn359941/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp -faddrsig

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

/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/Attr.h"
18#include "clang/AST/Availability.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/LocInfoType.h"
27#include "clang/AST/MangleNumberingContext.h"
28#include "clang/AST/NSAPI.h"
29#include "clang/AST/PrettyPrinter.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/TypeOrdering.h"
33#include "clang/Basic/ExpressionTraits.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/OpenMPKinds.h"
36#include "clang/Basic/PragmaKinds.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TemplateKinds.h"
39#include "clang/Basic/TypeTraits.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/CleanupInfo.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/ExternalSemaSource.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/ObjCMethodList.h"
46#include "clang/Sema/Ownership.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/TypoCorrection.h"
49#include "clang/Sema/Weak.h"
50#include "llvm/ADT/ArrayRef.h"
51#include "llvm/ADT/Optional.h"
52#include "llvm/ADT/SetVector.h"
53#include "llvm/ADT/SmallBitVector.h"
54#include "llvm/ADT/SmallPtrSet.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include <deque>
58#include <memory>
59#include <string>
60#include <vector>
61
62namespace llvm {
63 class APSInt;
64 template <typename ValueT> struct DenseMapInfo;
65 template <typename ValueT, typename ValueInfoT> class DenseSet;
66 class SmallBitVector;
67 struct InlineAsmIdentifierInfo;
68}
69
70namespace clang {
71 class ADLResult;
72 class ASTConsumer;
73 class ASTContext;
74 class ASTMutationListener;
75 class ASTReader;
76 class ASTWriter;
77 class ArrayType;
78 class ParsedAttr;
79 class BindingDecl;
80 class BlockDecl;
81 class CapturedDecl;
82 class CXXBasePath;
83 class CXXBasePaths;
84 class CXXBindTemporaryExpr;
85 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
86 class CXXConstructorDecl;
87 class CXXConversionDecl;
88 class CXXDeleteExpr;
89 class CXXDestructorDecl;
90 class CXXFieldCollector;
91 class CXXMemberCallExpr;
92 class CXXMethodDecl;
93 class CXXScopeSpec;
94 class CXXTemporary;
95 class CXXTryStmt;
96 class CallExpr;
97 class ClassTemplateDecl;
98 class ClassTemplatePartialSpecializationDecl;
99 class ClassTemplateSpecializationDecl;
100 class VarTemplatePartialSpecializationDecl;
101 class CodeCompleteConsumer;
102 class CodeCompletionAllocator;
103 class CodeCompletionTUInfo;
104 class CodeCompletionResult;
105 class CoroutineBodyStmt;
106 class Decl;
107 class DeclAccessPair;
108 class DeclContext;
109 class DeclRefExpr;
110 class DeclaratorDecl;
111 class DeducedTemplateArgument;
112 class DependentDiagnostic;
113 class DesignatedInitExpr;
114 class Designation;
115 class EnableIfAttr;
116 class EnumConstantDecl;
117 class Expr;
118 class ExtVectorType;
119 class FormatAttr;
120 class FriendDecl;
121 class FunctionDecl;
122 class FunctionProtoType;
123 class FunctionTemplateDecl;
124 class ImplicitConversionSequence;
125 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
126 class InitListExpr;
127 class InitializationKind;
128 class InitializationSequence;
129 class InitializedEntity;
130 class IntegerLiteral;
131 class LabelStmt;
132 class LambdaExpr;
133 class LangOptions;
134 class LocalInstantiationScope;
135 class LookupResult;
136 class MacroInfo;
137 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
138 class ModuleLoader;
139 class MultiLevelTemplateArgumentList;
140 class NamedDecl;
141 class ObjCCategoryDecl;
142 class ObjCCategoryImplDecl;
143 class ObjCCompatibleAliasDecl;
144 class ObjCContainerDecl;
145 class ObjCImplDecl;
146 class ObjCImplementationDecl;
147 class ObjCInterfaceDecl;
148 class ObjCIvarDecl;
149 template <class T> class ObjCList;
150 class ObjCMessageExpr;
151 class ObjCMethodDecl;
152 class ObjCPropertyDecl;
153 class ObjCProtocolDecl;
154 class OMPThreadPrivateDecl;
155 class OMPRequiresDecl;
156 class OMPDeclareReductionDecl;
157 class OMPDeclareSimdDecl;
158 class OMPClause;
159 struct OMPVarListLocTy;
160 struct OverloadCandidate;
161 class OverloadCandidateSet;
162 class OverloadExpr;
163 class ParenListExpr;
164 class ParmVarDecl;
165 class Preprocessor;
166 class PseudoDestructorTypeStorage;
167 class PseudoObjectExpr;
168 class QualType;
169 class StandardConversionSequence;
170 class Stmt;
171 class StringLiteral;
172 class SwitchStmt;
173 class TemplateArgument;
174 class TemplateArgumentList;
175 class TemplateArgumentLoc;
176 class TemplateDecl;
177 class TemplateInstantiationCallback;
178 class TemplateParameterList;
179 class TemplatePartialOrderingContext;
180 class TemplateTemplateParmDecl;
181 class Token;
182 class TypeAliasDecl;
183 class TypedefDecl;
184 class TypedefNameDecl;
185 class TypeLoc;
186 class TypoCorrectionConsumer;
187 class UnqualifiedId;
188 class UnresolvedLookupExpr;
189 class UnresolvedMemberExpr;
190 class UnresolvedSetImpl;
191 class UnresolvedSetIterator;
192 class UsingDecl;
193 class UsingShadowDecl;
194 class ValueDecl;
195 class VarDecl;
196 class VarTemplateSpecializationDecl;
197 class VisibilityAttr;
198 class VisibleDeclConsumer;
199 class IndirectFieldDecl;
200 struct DeductionFailureInfo;
201 class TemplateSpecCandidateSet;
202
203namespace sema {
204 class AccessedEntity;
205 class BlockScopeInfo;
206 class Capture;
207 class CapturedRegionScopeInfo;
208 class CapturingScopeInfo;
209 class CompoundScopeInfo;
210 class DelayedDiagnostic;
211 class DelayedDiagnosticPool;
212 class FunctionScopeInfo;
213 class LambdaScopeInfo;
214 class PossiblyUnreachableDiag;
215 class SemaPPCallbacks;
216 class TemplateDeductionInfo;
217}
218
219namespace threadSafety {
220 class BeforeSet;
221 void threadSafetyCleanup(BeforeSet* Cache);
222}
223
224// FIXME: No way to easily map from TemplateTypeParmTypes to
225// TemplateTypeParmDecls, so we have this horrible PointerUnion.
226typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
227 SourceLocation> UnexpandedParameterPack;
228
229/// Describes whether we've seen any nullability information for the given
230/// file.
231struct FileNullability {
232 /// The first pointer declarator (of any pointer kind) in the file that does
233 /// not have a corresponding nullability annotation.
234 SourceLocation PointerLoc;
235
236 /// The end location for the first pointer declarator in the file. Used for
237 /// placing fix-its.
238 SourceLocation PointerEndLoc;
239
240 /// Which kind of pointer declarator we saw.
241 uint8_t PointerKind;
242
243 /// Whether we saw any type nullability annotations in the given file.
244 bool SawTypeNullability = false;
245};
246
247/// A mapping from file IDs to a record of whether we've seen nullability
248/// information in that file.
249class FileNullabilityMap {
250 /// A mapping from file IDs to the nullability information for each file ID.
251 llvm::DenseMap<FileID, FileNullability> Map;
252
253 /// A single-element cache based on the file ID.
254 struct {
255 FileID File;
256 FileNullability Nullability;
257 } Cache;
258
259public:
260 FileNullability &operator[](FileID file) {
261 // Check the single-element cache.
262 if (file == Cache.File)
263 return Cache.Nullability;
264
265 // It's not in the single-element cache; flush the cache if we have one.
266 if (!Cache.File.isInvalid()) {
267 Map[Cache.File] = Cache.Nullability;
268 }
269
270 // Pull this entry into the cache.
271 Cache.File = file;
272 Cache.Nullability = Map[file];
273 return Cache.Nullability;
274 }
275};
276
277/// Keeps track of expected type during expression parsing. The type is tied to
278/// a particular token, all functions that update or consume the type take a
279/// start location of the token they are looking at as a parameter. This allows
280/// to avoid updating the type on hot paths in the parser.
281class PreferredTypeBuilder {
282public:
283 PreferredTypeBuilder() = default;
284 explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
285
286 void enterCondition(Sema &S, SourceLocation Tok);
287 void enterReturn(Sema &S, SourceLocation Tok);
288 void enterVariableInit(SourceLocation Tok, Decl *D);
289 /// Computing a type for the function argument may require running
290 /// overloading, so we postpone its computation until it is actually needed.
291 ///
292 /// Clients should be very careful when using this funciton, as it stores a
293 /// function_ref, clients should make sure all calls to get() with the same
294 /// location happen while function_ref is alive.
295 void enterFunctionArgument(SourceLocation Tok,
296 llvm::function_ref<QualType()> ComputeType);
297
298 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
299 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
300 SourceLocation OpLoc);
301 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
302 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
303 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
304 /// Handles all type casts, including C-style cast, C++ casts, etc.
305 void enterTypeCast(SourceLocation Tok, QualType CastType);
306
307 QualType get(SourceLocation Tok) const {
308 if (Tok != ExpectedLoc)
309 return QualType();
310 if (!Type.isNull())
311 return Type;
312 if (ComputeType)
313 return ComputeType();
314 return QualType();
315 }
316
317private:
318 /// Start position of a token for which we store expected type.
319 SourceLocation ExpectedLoc;
320 /// Expected type for a token starting at ExpectedLoc.
321 QualType Type;
322 /// A function to compute expected type at ExpectedLoc. It is only considered
323 /// if Type is null.
324 llvm::function_ref<QualType()> ComputeType;
325};
326
327/// Sema - This implements semantic analysis and AST building for C.
328class Sema {
329 Sema(const Sema &) = delete;
330 void operator=(const Sema &) = delete;
331
332 ///Source of additional semantic information.
333 ExternalSemaSource *ExternalSource;
334
335 ///Whether Sema has generated a multiplexer and has to delete it.
336 bool isMultiplexExternalSource;
337
338 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
339
340 bool isVisibleSlow(const NamedDecl *D);
341
342 /// Determine whether two declarations should be linked together, given that
343 /// the old declaration might not be visible and the new declaration might
344 /// not have external linkage.
345 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
346 const NamedDecl *New) {
347 if (isVisible(Old))
348 return true;
349 // See comment in below overload for why it's safe to compute the linkage
350 // of the new declaration here.
351 if (New->isExternallyDeclarable()) {
352 assert(Old->isExternallyDeclarable() &&((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 353, __PRETTY_FUNCTION__))
353 "should not have found a non-externally-declarable previous decl")((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 353, __PRETTY_FUNCTION__))
;
354 return true;
355 }
356 return false;
357 }
358 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
359
360 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
361 QualType ResultTy,
362 ArrayRef<QualType> Args);
363
364public:
365 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
366 typedef OpaquePtr<TemplateName> TemplateTy;
367 typedef OpaquePtr<QualType> TypeTy;
368
369 OpenCLOptions OpenCLFeatures;
370 FPOptions FPFeatures;
371
372 const LangOptions &LangOpts;
373 Preprocessor &PP;
374 ASTContext &Context;
375 ASTConsumer &Consumer;
376 DiagnosticsEngine &Diags;
377 SourceManager &SourceMgr;
378
379 /// Flag indicating whether or not to collect detailed statistics.
380 bool CollectStats;
381
382 /// Code-completion consumer.
383 CodeCompleteConsumer *CodeCompleter;
384
385 /// CurContext - This is the current declaration context of parsing.
386 DeclContext *CurContext;
387
388 /// Generally null except when we temporarily switch decl contexts,
389 /// like in \see ActOnObjCTemporaryExitContainerContext.
390 DeclContext *OriginalLexicalContext;
391
392 /// VAListTagName - The declaration name corresponding to __va_list_tag.
393 /// This is used as part of a hack to omit that class from ADL results.
394 DeclarationName VAListTagName;
395
396 bool MSStructPragmaOn; // True when \#pragma ms_struct on
397
398 /// Controls member pointer representation format under the MS ABI.
399 LangOptions::PragmaMSPointersToMembersKind
400 MSPointerToMemberRepresentationMethod;
401
402 /// Stack of active SEH __finally scopes. Can be empty.
403 SmallVector<Scope*, 2> CurrentSEHFinally;
404
405 /// Source location for newly created implicit MSInheritanceAttrs
406 SourceLocation ImplicitMSInheritanceAttrLoc;
407
408 /// pragma clang section kind
409 enum PragmaClangSectionKind {
410 PCSK_Invalid = 0,
411 PCSK_BSS = 1,
412 PCSK_Data = 2,
413 PCSK_Rodata = 3,
414 PCSK_Text = 4
415 };
416
417 enum PragmaClangSectionAction {
418 PCSA_Set = 0,
419 PCSA_Clear = 1
420 };
421
422 struct PragmaClangSection {
423 std::string SectionName;
424 bool Valid = false;
425 SourceLocation PragmaLocation;
426
427 void Act(SourceLocation PragmaLocation,
428 PragmaClangSectionAction Action,
429 StringLiteral* Name);
430 };
431
432 PragmaClangSection PragmaClangBSSSection;
433 PragmaClangSection PragmaClangDataSection;
434 PragmaClangSection PragmaClangRodataSection;
435 PragmaClangSection PragmaClangTextSection;
436
437 enum PragmaMsStackAction {
438 PSK_Reset = 0x0, // #pragma ()
439 PSK_Set = 0x1, // #pragma (value)
440 PSK_Push = 0x2, // #pragma (push[, id])
441 PSK_Pop = 0x4, // #pragma (pop[, id])
442 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
443 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
444 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
445 };
446
447 template<typename ValueType>
448 struct PragmaStack {
449 struct Slot {
450 llvm::StringRef StackSlotLabel;
451 ValueType Value;
452 SourceLocation PragmaLocation;
453 SourceLocation PragmaPushLocation;
454 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
455 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
456 : StackSlotLabel(StackSlotLabel), Value(Value),
457 PragmaLocation(PragmaLocation),
458 PragmaPushLocation(PragmaPushLocation) {}
459 };
460 void Act(SourceLocation PragmaLocation,
461 PragmaMsStackAction Action,
462 llvm::StringRef StackSlotLabel,
463 ValueType Value);
464
465 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
466 // method body to restore the stacks on exit, so it works like this:
467 //
468 // struct S {
469 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
470 // void Method {}
471 // #pragma <name>(pop, InternalPragmaSlot)
472 // };
473 //
474 // It works even with #pragma vtordisp, although MSVC doesn't support
475 // #pragma vtordisp(push [, id], n)
476 // syntax.
477 //
478 // Push / pop a named sentinel slot.
479 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
480 assert((Action == PSK_Push || Action == PSK_Pop) &&(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 481, __PRETTY_FUNCTION__))
481 "Can only push / pop #pragma stack sentinels!")(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 481, __PRETTY_FUNCTION__))
;
482 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
483 }
484
485 // Constructors.
486 explicit PragmaStack(const ValueType &Default)
487 : DefaultValue(Default), CurrentValue(Default) {}
488
489 bool hasValue() const { return CurrentValue != DefaultValue; }
490
491 SmallVector<Slot, 2> Stack;
492 ValueType DefaultValue; // Value used for PSK_Reset action.
493 ValueType CurrentValue;
494 SourceLocation CurrentPragmaLocation;
495 };
496 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
497 // we shouldn't do so if they're in a module).
498
499 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
500 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
501 ///
502 /// 0: Suppress all vtordisps
503 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
504 /// structors
505 /// 2: Always insert vtordisps to support RTTI on partially constructed
506 /// objects
507 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
508 // #pragma pack.
509 // Sentinel to represent when the stack is set to mac68k alignment.
510 static const unsigned kMac68kAlignmentSentinel = ~0U;
511 PragmaStack<unsigned> PackStack;
512 // The current #pragma pack values and locations at each #include.
513 struct PackIncludeState {
514 unsigned CurrentValue;
515 SourceLocation CurrentPragmaLocation;
516 bool HasNonDefaultValue, ShouldWarnOnInclude;
517 };
518 SmallVector<PackIncludeState, 8> PackIncludeStack;
519 // Segment #pragmas.
520 PragmaStack<StringLiteral *> DataSegStack;
521 PragmaStack<StringLiteral *> BSSSegStack;
522 PragmaStack<StringLiteral *> ConstSegStack;
523 PragmaStack<StringLiteral *> CodeSegStack;
524
525 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
526 // Actions should be performed only if we enter / exit a C++ method body.
527 class PragmaStackSentinelRAII {
528 public:
529 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
530 ~PragmaStackSentinelRAII();
531
532 private:
533 Sema &S;
534 StringRef SlotLabel;
535 bool ShouldAct;
536 };
537
538 /// A mapping that describes the nullability we've seen in each header file.
539 FileNullabilityMap NullabilityMap;
540
541 /// Last section used with #pragma init_seg.
542 StringLiteral *CurInitSeg;
543 SourceLocation CurInitSegLoc;
544
545 /// VisContext - Manages the stack for \#pragma GCC visibility.
546 void *VisContext; // Really a "PragmaVisStack*"
547
548 /// This an attribute introduced by \#pragma clang attribute.
549 struct PragmaAttributeEntry {
550 SourceLocation Loc;
551 ParsedAttr *Attribute;
552 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
553 bool IsUsed;
554 };
555
556 /// A push'd group of PragmaAttributeEntries.
557 struct PragmaAttributeGroup {
558 /// The location of the push attribute.
559 SourceLocation Loc;
560 /// The namespace of this push group.
561 const IdentifierInfo *Namespace;
562 SmallVector<PragmaAttributeEntry, 2> Entries;
563 };
564
565 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
566
567 /// The declaration that is currently receiving an attribute from the
568 /// #pragma attribute stack.
569 const Decl *PragmaAttributeCurrentTargetDecl;
570
571 /// This represents the last location of a "#pragma clang optimize off"
572 /// directive if such a directive has not been closed by an "on" yet. If
573 /// optimizations are currently "on", this is set to an invalid location.
574 SourceLocation OptimizeOffPragmaLocation;
575
576 /// Flag indicating if Sema is building a recovery call expression.
577 ///
578 /// This flag is used to avoid building recovery call expressions
579 /// if Sema is already doing so, which would cause infinite recursions.
580 bool IsBuildingRecoveryCallExpr;
581
582 /// Used to control the generation of ExprWithCleanups.
583 CleanupInfo Cleanup;
584
585 /// ExprCleanupObjects - This is the stack of objects requiring
586 /// cleanup that are created by the current full expression. The
587 /// element type here is ExprWithCleanups::Object.
588 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
589
590 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
591 /// to a variable (constant) that may or may not be odr-used in this Expr, and
592 /// we won't know until all lvalue-to-rvalue and discarded value conversions
593 /// have been applied to all subexpressions of the enclosing full expression.
594 /// This is cleared at the end of each full expression.
595 using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
596 MaybeODRUseExprSet MaybeODRUseExprs;
597
598 std::unique_ptr<sema::FunctionScopeInfo> PreallocatedFunctionScope;
599
600 /// Stack containing information about each of the nested
601 /// function, block, and method scopes that are currently active.
602 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
603
604 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
605 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
606 ExtVectorDeclsType;
607
608 /// ExtVectorDecls - This is a list all the extended vector types. This allows
609 /// us to associate a raw vector type with one of the ext_vector type names.
610 /// This is only necessary for issuing pretty diagnostics.
611 ExtVectorDeclsType ExtVectorDecls;
612
613 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
614 std::unique_ptr<CXXFieldCollector> FieldCollector;
615
616 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
617
618 /// Set containing all declared private fields that are not used.
619 NamedDeclSetType UnusedPrivateFields;
620
621 /// Set containing all typedefs that are likely unused.
622 llvm::SmallSetVector<const TypedefNameDecl *, 4>
623 UnusedLocalTypedefNameCandidates;
624
625 /// Delete-expressions to be analyzed at the end of translation unit
626 ///
627 /// This list contains class members, and locations of delete-expressions
628 /// that could not be proven as to whether they mismatch with new-expression
629 /// used in initializer of the field.
630 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
631 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
632 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
633
634 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
635
636 /// PureVirtualClassDiagSet - a set of class declarations which we have
637 /// emitted a list of pure virtual functions. Used to prevent emitting the
638 /// same list more than once.
639 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
640
641 /// ParsingInitForAutoVars - a set of declarations with auto types for which
642 /// we are currently parsing the initializer.
643 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
644
645 /// Look for a locally scoped extern "C" declaration by the given name.
646 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
647
648 typedef LazyVector<VarDecl *, ExternalSemaSource,
649 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
650 TentativeDefinitionsType;
651
652 /// All the tentative definitions encountered in the TU.
653 TentativeDefinitionsType TentativeDefinitions;
654
655 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
656 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
657 UnusedFileScopedDeclsType;
658
659 /// The set of file scoped decls seen so far that have not been used
660 /// and must warn if not used. Only contains the first declaration.
661 UnusedFileScopedDeclsType UnusedFileScopedDecls;
662
663 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
664 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
665 DelegatingCtorDeclsType;
666
667 /// All the delegating constructors seen so far in the file, used for
668 /// cycle detection at the end of the TU.
669 DelegatingCtorDeclsType DelegatingCtorDecls;
670
671 /// All the overriding functions seen during a class definition
672 /// that had their exception spec checks delayed, plus the overridden
673 /// function.
674 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
675 DelayedOverridingExceptionSpecChecks;
676
677 /// All the function redeclarations seen during a class definition that had
678 /// their exception spec checks delayed, plus the prior declaration they
679 /// should be checked against. Except during error recovery, the new decl
680 /// should always be a friend declaration, as that's the only valid way to
681 /// redeclare a special member before its class is complete.
682 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
683 DelayedEquivalentExceptionSpecChecks;
684
685 /// All the members seen during a class definition which were both
686 /// explicitly defaulted and had explicitly-specified exception
687 /// specifications, along with the function type containing their
688 /// user-specified exception specification. Those exception specifications
689 /// were overridden with the default specifications, but we still need to
690 /// check whether they are compatible with the default specification, and
691 /// we can't do that until the nesting set of class definitions is complete.
692 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
693 DelayedDefaultedMemberExceptionSpecs;
694
695 typedef llvm::MapVector<const FunctionDecl *,
696 std::unique_ptr<LateParsedTemplate>>
697 LateParsedTemplateMapT;
698 LateParsedTemplateMapT LateParsedTemplateMap;
699
700 /// Callback to the parser to parse templated functions when needed.
701 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
702 typedef void LateTemplateParserCleanupCB(void *P);
703 LateTemplateParserCB *LateTemplateParser;
704 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
705 void *OpaqueParser;
706
707 void SetLateTemplateParser(LateTemplateParserCB *LTP,
708 LateTemplateParserCleanupCB *LTPCleanup,
709 void *P) {
710 LateTemplateParser = LTP;
711 LateTemplateParserCleanup = LTPCleanup;
712 OpaqueParser = P;
713 }
714
715 class DelayedDiagnostics;
716
717 class DelayedDiagnosticsState {
718 sema::DelayedDiagnosticPool *SavedPool;
719 friend class Sema::DelayedDiagnostics;
720 };
721 typedef DelayedDiagnosticsState ParsingDeclState;
722 typedef DelayedDiagnosticsState ProcessingContextState;
723
724 /// A class which encapsulates the logic for delaying diagnostics
725 /// during parsing and other processing.
726 class DelayedDiagnostics {
727 /// The current pool of diagnostics into which delayed
728 /// diagnostics should go.
729 sema::DelayedDiagnosticPool *CurPool;
730
731 public:
732 DelayedDiagnostics() : CurPool(nullptr) {}
733
734 /// Adds a delayed diagnostic.
735 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
736
737 /// Determines whether diagnostics should be delayed.
738 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
739
740 /// Returns the current delayed-diagnostics pool.
741 sema::DelayedDiagnosticPool *getCurrentPool() const {
742 return CurPool;
743 }
744
745 /// Enter a new scope. Access and deprecation diagnostics will be
746 /// collected in this pool.
747 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
748 DelayedDiagnosticsState state;
749 state.SavedPool = CurPool;
750 CurPool = &pool;
751 return state;
752 }
753
754 /// Leave a delayed-diagnostic state that was previously pushed.
755 /// Do not emit any of the diagnostics. This is performed as part
756 /// of the bookkeeping of popping a pool "properly".
757 void popWithoutEmitting(DelayedDiagnosticsState state) {
758 CurPool = state.SavedPool;
759 }
760
761 /// Enter a new scope where access and deprecation diagnostics are
762 /// not delayed.
763 DelayedDiagnosticsState pushUndelayed() {
764 DelayedDiagnosticsState state;
765 state.SavedPool = CurPool;
766 CurPool = nullptr;
767 return state;
768 }
769
770 /// Undo a previous pushUndelayed().
771 void popUndelayed(DelayedDiagnosticsState state) {
772 assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 772, __PRETTY_FUNCTION__))
;
773 CurPool = state.SavedPool;
774 }
775 } DelayedDiagnostics;
776
777 /// A RAII object to temporarily push a declaration context.
778 class ContextRAII {
779 private:
780 Sema &S;
781 DeclContext *SavedContext;
782 ProcessingContextState SavedContextState;
783 QualType SavedCXXThisTypeOverride;
784
785 public:
786 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
787 : S(S), SavedContext(S.CurContext),
788 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
789 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
790 {
791 assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast
<void> (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 791, __PRETTY_FUNCTION__))
;
792 S.CurContext = ContextToPush;
793 if (NewThisContext)
794 S.CXXThisTypeOverride = QualType();
795 }
796
797 void pop() {
798 if (!SavedContext) return;
799 S.CurContext = SavedContext;
800 S.DelayedDiagnostics.popUndelayed(SavedContextState);
801 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
802 SavedContext = nullptr;
803 }
804
805 ~ContextRAII() {
806 pop();
807 }
808 };
809
810 /// RAII object to handle the state changes required to synthesize
811 /// a function body.
812 class SynthesizedFunctionScope {
813 Sema &S;
814 Sema::ContextRAII SavedContext;
815 bool PushedCodeSynthesisContext = false;
816
817 public:
818 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
819 : S(S), SavedContext(S, DC) {
820 S.PushFunctionScope();
821 S.PushExpressionEvaluationContext(
822 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
823 if (auto *FD = dyn_cast<FunctionDecl>(DC))
824 FD->setWillHaveBody(true);
825 else
826 assert(isa<ObjCMethodDecl>(DC))((isa<ObjCMethodDecl>(DC)) ? static_cast<void> (0
) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 826, __PRETTY_FUNCTION__))
;
827 }
828
829 void addContextNote(SourceLocation UseLoc) {
830 assert(!PushedCodeSynthesisContext)((!PushedCodeSynthesisContext) ? static_cast<void> (0) :
__assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 830, __PRETTY_FUNCTION__))
;
831
832 Sema::CodeSynthesisContext Ctx;
833 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
834 Ctx.PointOfInstantiation = UseLoc;
835 Ctx.Entity = cast<Decl>(S.CurContext);
836 S.pushCodeSynthesisContext(Ctx);
837
838 PushedCodeSynthesisContext = true;
839 }
840
841 ~SynthesizedFunctionScope() {
842 if (PushedCodeSynthesisContext)
843 S.popCodeSynthesisContext();
844 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
845 FD->setWillHaveBody(false);
846 S.PopExpressionEvaluationContext();
847 S.PopFunctionScopeInfo();
848 }
849 };
850
851 /// WeakUndeclaredIdentifiers - Identifiers contained in
852 /// \#pragma weak before declared. rare. may alias another
853 /// identifier, declared or undeclared
854 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
855
856 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
857 /// \#pragma redefine_extname before declared. Used in Solaris system headers
858 /// to define functions that occur in multiple standards to call the version
859 /// in the currently selected standard.
860 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
861
862
863 /// Load weak undeclared identifiers from the external source.
864 void LoadExternalWeakUndeclaredIdentifiers();
865
866 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
867 /// \#pragma weak during processing of other Decls.
868 /// I couldn't figure out a clean way to generate these in-line, so
869 /// we store them here and handle separately -- which is a hack.
870 /// It would be best to refactor this.
871 SmallVector<Decl*,2> WeakTopLevelDecl;
872
873 IdentifierResolver IdResolver;
874
875 /// Translation Unit Scope - useful to Objective-C actions that need
876 /// to lookup file scope declarations in the "ordinary" C decl namespace.
877 /// For example, user-defined classes, built-in "id" type, etc.
878 Scope *TUScope;
879
880 /// The C++ "std" namespace, where the standard library resides.
881 LazyDeclPtr StdNamespace;
882
883 /// The C++ "std::bad_alloc" class, which is defined by the C++
884 /// standard library.
885 LazyDeclPtr StdBadAlloc;
886
887 /// The C++ "std::align_val_t" enum class, which is defined by the C++
888 /// standard library.
889 LazyDeclPtr StdAlignValT;
890
891 /// The C++ "std::experimental" namespace, where the experimental parts
892 /// of the standard library resides.
893 NamespaceDecl *StdExperimentalNamespaceCache;
894
895 /// The C++ "std::initializer_list" template, which is defined in
896 /// \<initializer_list>.
897 ClassTemplateDecl *StdInitializerList;
898
899 /// The C++ "std::coroutine_traits" template, which is defined in
900 /// \<coroutine_traits>
901 ClassTemplateDecl *StdCoroutineTraitsCache;
902
903 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
904 RecordDecl *CXXTypeInfoDecl;
905
906 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
907 RecordDecl *MSVCGuidDecl;
908
909 /// Caches identifiers/selectors for NSFoundation APIs.
910 std::unique_ptr<NSAPI> NSAPIObj;
911
912 /// The declaration of the Objective-C NSNumber class.
913 ObjCInterfaceDecl *NSNumberDecl;
914
915 /// The declaration of the Objective-C NSValue class.
916 ObjCInterfaceDecl *NSValueDecl;
917
918 /// Pointer to NSNumber type (NSNumber *).
919 QualType NSNumberPointer;
920
921 /// Pointer to NSValue type (NSValue *).
922 QualType NSValuePointer;
923
924 /// The Objective-C NSNumber methods used to create NSNumber literals.
925 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
926
927 /// The declaration of the Objective-C NSString class.
928 ObjCInterfaceDecl *NSStringDecl;
929
930 /// Pointer to NSString type (NSString *).
931 QualType NSStringPointer;
932
933 /// The declaration of the stringWithUTF8String: method.
934 ObjCMethodDecl *StringWithUTF8StringMethod;
935
936 /// The declaration of the valueWithBytes:objCType: method.
937 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
938
939 /// The declaration of the Objective-C NSArray class.
940 ObjCInterfaceDecl *NSArrayDecl;
941
942 /// The declaration of the arrayWithObjects:count: method.
943 ObjCMethodDecl *ArrayWithObjectsMethod;
944
945 /// The declaration of the Objective-C NSDictionary class.
946 ObjCInterfaceDecl *NSDictionaryDecl;
947
948 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
949 ObjCMethodDecl *DictionaryWithObjectsMethod;
950
951 /// id<NSCopying> type.
952 QualType QIDNSCopying;
953
954 /// will hold 'respondsToSelector:'
955 Selector RespondsToSelectorSel;
956
957 /// A flag to remember whether the implicit forms of operator new and delete
958 /// have been declared.
959 bool GlobalNewDeleteDeclared;
960
961 /// A flag to indicate that we're in a context that permits abstract
962 /// references to fields. This is really a
963 bool AllowAbstractFieldReference;
964
965 /// Describes how the expressions currently being parsed are
966 /// evaluated at run-time, if at all.
967 enum class ExpressionEvaluationContext {
968 /// The current expression and its subexpressions occur within an
969 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
970 /// \c sizeof, where the type of the expression may be significant but
971 /// no code will be generated to evaluate the value of the expression at
972 /// run time.
973 Unevaluated,
974
975 /// The current expression occurs within a braced-init-list within
976 /// an unevaluated operand. This is mostly like a regular unevaluated
977 /// context, except that we still instantiate constexpr functions that are
978 /// referenced here so that we can perform narrowing checks correctly.
979 UnevaluatedList,
980
981 /// The current expression occurs within a discarded statement.
982 /// This behaves largely similarly to an unevaluated operand in preventing
983 /// definitions from being required, but not in other ways.
984 DiscardedStatement,
985
986 /// The current expression occurs within an unevaluated
987 /// operand that unconditionally permits abstract references to
988 /// fields, such as a SIZE operator in MS-style inline assembly.
989 UnevaluatedAbstract,
990
991 /// The current context is "potentially evaluated" in C++11 terms,
992 /// but the expression is evaluated at compile-time (like the values of
993 /// cases in a switch statement).
994 ConstantEvaluated,
995
996 /// The current expression is potentially evaluated at run time,
997 /// which means that code may be generated to evaluate the value of the
998 /// expression at run time.
999 PotentiallyEvaluated,
1000
1001 /// The current expression is potentially evaluated, but any
1002 /// declarations referenced inside that expression are only used if
1003 /// in fact the current expression is used.
1004 ///
1005 /// This value is used when parsing default function arguments, for which
1006 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1007 /// through varargs) but do not want to mark declarations as "referenced"
1008 /// until the default argument is used.
1009 PotentiallyEvaluatedIfUsed
1010 };
1011
1012 /// Data structure used to record current or nested
1013 /// expression evaluation contexts.
1014 struct ExpressionEvaluationContextRecord {
1015 /// The expression evaluation context.
1016 ExpressionEvaluationContext Context;
1017
1018 /// Whether the enclosing context needed a cleanup.
1019 CleanupInfo ParentCleanup;
1020
1021 /// Whether we are in a decltype expression.
1022 bool IsDecltype;
1023
1024 /// The number of active cleanup objects when we entered
1025 /// this expression evaluation context.
1026 unsigned NumCleanupObjects;
1027
1028 /// The number of typos encountered during this expression evaluation
1029 /// context (i.e. the number of TypoExprs created).
1030 unsigned NumTypos;
1031
1032 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1033
1034 /// The lambdas that are present within this context, if it
1035 /// is indeed an unevaluated context.
1036 SmallVector<LambdaExpr *, 2> Lambdas;
1037
1038 /// The declaration that provides context for lambda expressions
1039 /// and block literals if the normal declaration context does not
1040 /// suffice, e.g., in a default function argument.
1041 Decl *ManglingContextDecl;
1042
1043 /// The context information used to mangle lambda expressions
1044 /// and block literals within this context.
1045 ///
1046 /// This mangling information is allocated lazily, since most contexts
1047 /// do not have lambda expressions or block literals.
1048 std::unique_ptr<MangleNumberingContext> MangleNumbering;
1049
1050 /// If we are processing a decltype type, a set of call expressions
1051 /// for which we have deferred checking the completeness of the return type.
1052 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1053
1054 /// If we are processing a decltype type, a set of temporary binding
1055 /// expressions for which we have deferred checking the destructor.
1056 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1057
1058 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1059
1060 /// \brief Describes whether we are in an expression constext which we have
1061 /// to handle differently.
1062 enum ExpressionKind {
1063 EK_Decltype, EK_TemplateArgument, EK_Other
1064 } ExprContext;
1065
1066 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1067 unsigned NumCleanupObjects,
1068 CleanupInfo ParentCleanup,
1069 Decl *ManglingContextDecl,
1070 ExpressionKind ExprContext)
1071 : Context(Context), ParentCleanup(ParentCleanup),
1072 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1073 ManglingContextDecl(ManglingContextDecl), MangleNumbering(),
1074 ExprContext(ExprContext) {}
1075
1076 /// Retrieve the mangling numbering context, used to consistently
1077 /// number constructs like lambdas for mangling.
1078 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
1079
1080 bool isUnevaluated() const {
1081 return Context == ExpressionEvaluationContext::Unevaluated ||
1082 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1083 Context == ExpressionEvaluationContext::UnevaluatedList;
1084 }
1085 bool isConstantEvaluated() const {
1086 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1087 }
1088 };
1089
1090 /// A stack of expression evaluation contexts.
1091 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1092
1093 /// Emit a warning for all pending noderef expressions that we recorded.
1094 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1095
1096 /// Compute the mangling number context for a lambda expression or
1097 /// block literal.
1098 ///
1099 /// \param DC - The DeclContext containing the lambda expression or
1100 /// block literal.
1101 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
1102 /// associated with the context, if relevant.
1103 MangleNumberingContext *getCurrentMangleNumberContext(
1104 const DeclContext *DC,
1105 Decl *&ManglingContextDecl);
1106
1107
1108 /// SpecialMemberOverloadResult - The overloading result for a special member
1109 /// function.
1110 ///
1111 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1112 /// integer are used to determine whether overload resolution succeeded.
1113 class SpecialMemberOverloadResult {
1114 public:
1115 enum Kind {
1116 NoMemberOrDeleted,
1117 Ambiguous,
1118 Success
1119 };
1120
1121 private:
1122 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1123
1124 public:
1125 SpecialMemberOverloadResult() : Pair() {}
1126 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1127 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1128
1129 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1130 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1131
1132 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1133 void setKind(Kind K) { Pair.setInt(K); }
1134 };
1135
1136 class SpecialMemberOverloadResultEntry
1137 : public llvm::FastFoldingSetNode,
1138 public SpecialMemberOverloadResult {
1139 public:
1140 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1141 : FastFoldingSetNode(ID)
1142 {}
1143 };
1144
1145 /// A cache of special member function overload resolution results
1146 /// for C++ records.
1147 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1148
1149 /// A cache of the flags available in enumerations with the flag_bits
1150 /// attribute.
1151 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1152
1153 /// The kind of translation unit we are processing.
1154 ///
1155 /// When we're processing a complete translation unit, Sema will perform
1156 /// end-of-translation-unit semantic tasks (such as creating
1157 /// initializers for tentative definitions in C) once parsing has
1158 /// completed. Modules and precompiled headers perform different kinds of
1159 /// checks.
1160 TranslationUnitKind TUKind;
1161
1162 llvm::BumpPtrAllocator BumpAlloc;
1163
1164 /// The number of SFINAE diagnostics that have been trapped.
1165 unsigned NumSFINAEErrors;
1166
1167 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1168 UnparsedDefaultArgInstantiationsMap;
1169
1170 /// A mapping from parameters with unparsed default arguments to the
1171 /// set of instantiations of each parameter.
1172 ///
1173 /// This mapping is a temporary data structure used when parsing
1174 /// nested class templates or nested classes of class templates,
1175 /// where we might end up instantiating an inner class before the
1176 /// default arguments of its methods have been parsed.
1177 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1178
1179 // Contains the locations of the beginning of unparsed default
1180 // argument locations.
1181 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1182
1183 /// UndefinedInternals - all the used, undefined objects which require a
1184 /// definition in this translation unit.
1185 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1186
1187 /// Determine if VD, which must be a variable or function, is an external
1188 /// symbol that nonetheless can't be referenced from outside this translation
1189 /// unit because its type has no linkage and it's not extern "C".
1190 bool isExternalWithNoLinkageType(ValueDecl *VD);
1191
1192 /// Obtain a sorted list of functions that are undefined but ODR-used.
1193 void getUndefinedButUsed(
1194 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1195
1196 /// Retrieves list of suspicious delete-expressions that will be checked at
1197 /// the end of translation unit.
1198 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1199 getMismatchingDeleteExpressions() const;
1200
1201 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1202 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1203
1204 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1205 /// We need to maintain a list, since selectors can have differing signatures
1206 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1207 /// of selectors are "overloaded").
1208 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1209 /// methods inside categories with a particular selector.
1210 GlobalMethodPool MethodPool;
1211
1212 /// Method selectors used in a \@selector expression. Used for implementation
1213 /// of -Wselector.
1214 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1215
1216 /// List of SourceLocations where 'self' is implicitly retained inside a
1217 /// block.
1218 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1219 ImplicitlyRetainedSelfLocs;
1220
1221 /// Kinds of C++ special members.
1222 enum CXXSpecialMember {
1223 CXXDefaultConstructor,
1224 CXXCopyConstructor,
1225 CXXMoveConstructor,
1226 CXXCopyAssignment,
1227 CXXMoveAssignment,
1228 CXXDestructor,
1229 CXXInvalid
1230 };
1231
1232 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1233 SpecialMemberDecl;
1234
1235 /// The C++ special members which we are currently in the process of
1236 /// declaring. If this process recursively triggers the declaration of the
1237 /// same special member, we should act as if it is not yet declared.
1238 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1239
1240 /// The function definitions which were renamed as part of typo-correction
1241 /// to match their respective declarations. We want to keep track of them
1242 /// to ensure that we don't emit a "redefinition" error if we encounter a
1243 /// correctly named definition after the renamed definition.
1244 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1245
1246 /// Stack of types that correspond to the parameter entities that are
1247 /// currently being copy-initialized. Can be empty.
1248 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1249
1250 void ReadMethodPool(Selector Sel);
1251 void updateOutOfDateSelector(Selector Sel);
1252
1253 /// Private Helper predicate to check for 'self'.
1254 bool isSelfExpr(Expr *RExpr);
1255 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1256
1257 /// Cause the active diagnostic on the DiagosticsEngine to be
1258 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1259 /// should not be used elsewhere.
1260 void EmitCurrentDiagnostic(unsigned DiagID);
1261
1262 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1263 /// statements.
1264 class FPContractStateRAII {
1265 public:
1266 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1267 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1268
1269 private:
1270 Sema& S;
1271 FPOptions OldFPFeaturesState;
1272 };
1273
1274 void addImplicitTypedef(StringRef Name, QualType T);
1275
1276public:
1277 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1278 TranslationUnitKind TUKind = TU_Complete,
1279 CodeCompleteConsumer *CompletionConsumer = nullptr);
1280 ~Sema();
1281
1282 /// Perform initialization that occurs after the parser has been
1283 /// initialized but before it parses anything.
1284 void Initialize();
1285
1286 const LangOptions &getLangOpts() const { return LangOpts; }
1287 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1288 FPOptions &getFPOptions() { return FPFeatures; }
1289
1290 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1291 SourceManager &getSourceManager() const { return SourceMgr; }
1292 Preprocessor &getPreprocessor() const { return PP; }
1293 ASTContext &getASTContext() const { return Context; }
1294 ASTConsumer &getASTConsumer() const { return Consumer; }
1295 ASTMutationListener *getASTMutationListener() const;
1296 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1297
1298 ///Registers an external source. If an external source already exists,
1299 /// creates a multiplex external source and appends to it.
1300 ///
1301 ///\param[in] E - A non-null external sema source.
1302 ///
1303 void addExternalSource(ExternalSemaSource *E);
1304
1305 void PrintStats() const;
1306
1307 /// Helper class that creates diagnostics with optional
1308 /// template instantiation stacks.
1309 ///
1310 /// This class provides a wrapper around the basic DiagnosticBuilder
1311 /// class that emits diagnostics. SemaDiagnosticBuilder is
1312 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1313 /// does) and, if the diagnostic comes from inside a template
1314 /// instantiation, printing the template instantiation stack as
1315 /// well.
1316 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1317 Sema &SemaRef;
1318 unsigned DiagID;
1319
1320 public:
1321 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1322 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1323
1324 // This is a cunning lie. DiagnosticBuilder actually performs move
1325 // construction in its copy constructor (but due to varied uses, it's not
1326 // possible to conveniently express this as actual move construction). So
1327 // the default copy ctor here is fine, because the base class disables the
1328 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1329 // in that case anwyay.
1330 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1331
1332 ~SemaDiagnosticBuilder() {
1333 // If we aren't active, there is nothing to do.
1334 if (!isActive()) return;
1335
1336 // Otherwise, we need to emit the diagnostic. First flush the underlying
1337 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1338 // won't emit the diagnostic in its own destructor.
1339 //
1340 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1341 // do its own needless checks to see if the diagnostic needs to be
1342 // emitted. However, because we take care to ensure that the builder
1343 // objects never escape, a sufficiently smart compiler will be able to
1344 // eliminate that code.
1345 FlushCounts();
1346 Clear();
1347
1348 // Dispatch to Sema to emit the diagnostic.
1349 SemaRef.EmitCurrentDiagnostic(DiagID);
1350 }
1351
1352 /// Teach operator<< to produce an object of the correct type.
1353 template<typename T>
1354 friend const SemaDiagnosticBuilder &operator<<(
1355 const SemaDiagnosticBuilder &Diag, const T &Value) {
1356 const DiagnosticBuilder &BaseDiag = Diag;
1357 BaseDiag << Value;
1358 return Diag;
1359 }
1360 };
1361
1362 /// Emit a diagnostic.
1363 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1364 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1365 return SemaDiagnosticBuilder(DB, *this, DiagID);
1366 }
1367
1368 /// Emit a partial diagnostic.
1369 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1370
1371 /// Build a partial diagnostic.
1372 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1373
1374 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1375
1376 /// Get a string to suggest for zero-initialization of a type.
1377 std::string
1378 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1379 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1380
1381 /// Calls \c Lexer::getLocForEndOfToken()
1382 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1383
1384 /// Retrieve the module loader associated with the preprocessor.
1385 ModuleLoader &getModuleLoader() const;
1386
1387 void emitAndClearUnusedLocalTypedefWarnings();
1388
1389 enum TUFragmentKind {
1390 /// The global module fragment, between 'module;' and a module-declaration.
1391 Global,
1392 /// A normal translation unit fragment. For a non-module unit, this is the
1393 /// entire translation unit. Otherwise, it runs from the module-declaration
1394 /// to the private-module-fragment (if any) or the end of the TU (if not).
1395 Normal,
1396 /// The private module fragment, between 'module :private;' and the end of
1397 /// the translation unit.
1398 Private
1399 };
1400
1401 void ActOnStartOfTranslationUnit();
1402 void ActOnEndOfTranslationUnit();
1403 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1404
1405 void CheckDelegatingCtorCycles();
1406
1407 Scope *getScopeForContext(DeclContext *Ctx);
1408
1409 void PushFunctionScope();
1410 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1411 sema::LambdaScopeInfo *PushLambdaScope();
1412
1413 /// This is used to inform Sema what the current TemplateParameterDepth
1414 /// is during Parsing. Currently it is used to pass on the depth
1415 /// when parsing generic lambda 'auto' parameters.
1416 void RecordParsingTemplateParameterDepth(unsigned Depth);
1417
1418 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1419 RecordDecl *RD,
1420 CapturedRegionKind K);
1421 void
1422 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1423 const Decl *D = nullptr,
1424 const BlockExpr *blkExpr = nullptr);
1425
1426 sema::FunctionScopeInfo *getCurFunction() const {
1427 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1428 }
1429
1430 sema::FunctionScopeInfo *getEnclosingFunction() const;
1431
1432 void setFunctionHasBranchIntoScope();
1433 void setFunctionHasBranchProtectedScope();
1434 void setFunctionHasIndirectGoto();
1435
1436 void PushCompoundScope(bool IsStmtExpr);
1437 void PopCompoundScope();
1438
1439 sema::CompoundScopeInfo &getCurCompoundScope() const;
1440
1441 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1442
1443 /// Retrieve the current block, if any.
1444 sema::BlockScopeInfo *getCurBlock();
1445
1446 /// Retrieve the current lambda scope info, if any.
1447 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1448 /// lambda scope info ignoring all inner capturing scopes that are not
1449 /// lambda scopes.
1450 sema::LambdaScopeInfo *
1451 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1452
1453 /// Retrieve the current generic lambda info, if any.
1454 sema::LambdaScopeInfo *getCurGenericLambda();
1455
1456 /// Retrieve the current captured region, if any.
1457 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1458
1459 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1460 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1461
1462 void ActOnComment(SourceRange Comment);
1463
1464 //===--------------------------------------------------------------------===//
1465 // Type Analysis / Processing: SemaType.cpp.
1466 //
1467
1468 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1469 const DeclSpec *DS = nullptr);
1470 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1471 const DeclSpec *DS = nullptr);
1472 QualType BuildPointerType(QualType T,
1473 SourceLocation Loc, DeclarationName Entity);
1474 QualType BuildReferenceType(QualType T, bool LValueRef,
1475 SourceLocation Loc, DeclarationName Entity);
1476 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1477 Expr *ArraySize, unsigned Quals,
1478 SourceRange Brackets, DeclarationName Entity);
1479 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1480 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1481 SourceLocation AttrLoc);
1482 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1483 SourceLocation AttrLoc);
1484
1485 /// Same as above, but constructs the AddressSpace index if not provided.
1486 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1487 SourceLocation AttrLoc);
1488
1489 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1490
1491 /// Build a function type.
1492 ///
1493 /// This routine checks the function type according to C++ rules and
1494 /// under the assumption that the result type and parameter types have
1495 /// just been instantiated from a template. It therefore duplicates
1496 /// some of the behavior of GetTypeForDeclarator, but in a much
1497 /// simpler form that is only suitable for this narrow use case.
1498 ///
1499 /// \param T The return type of the function.
1500 ///
1501 /// \param ParamTypes The parameter types of the function. This array
1502 /// will be modified to account for adjustments to the types of the
1503 /// function parameters.
1504 ///
1505 /// \param Loc The location of the entity whose type involves this
1506 /// function type or, if there is no such entity, the location of the
1507 /// type that will have function type.
1508 ///
1509 /// \param Entity The name of the entity that involves the function
1510 /// type, if known.
1511 ///
1512 /// \param EPI Extra information about the function type. Usually this will
1513 /// be taken from an existing function with the same prototype.
1514 ///
1515 /// \returns A suitable function type, if there are no errors. The
1516 /// unqualified type will always be a FunctionProtoType.
1517 /// Otherwise, returns a NULL type.
1518 QualType BuildFunctionType(QualType T,
1519 MutableArrayRef<QualType> ParamTypes,
1520 SourceLocation Loc, DeclarationName Entity,
1521 const FunctionProtoType::ExtProtoInfo &EPI);
1522
1523 QualType BuildMemberPointerType(QualType T, QualType Class,
1524 SourceLocation Loc,
1525 DeclarationName Entity);
1526 QualType BuildBlockPointerType(QualType T,
1527 SourceLocation Loc, DeclarationName Entity);
1528 QualType BuildParenType(QualType T);
1529 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1530 QualType BuildReadPipeType(QualType T,
1531 SourceLocation Loc);
1532 QualType BuildWritePipeType(QualType T,
1533 SourceLocation Loc);
1534
1535 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1536 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1537
1538 /// Package the given type and TSI into a ParsedType.
1539 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1540 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1541 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1542 static QualType GetTypeFromParser(ParsedType Ty,
1543 TypeSourceInfo **TInfo = nullptr);
1544 CanThrowResult canThrow(const Expr *E);
1545 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1546 const FunctionProtoType *FPT);
1547 void UpdateExceptionSpec(FunctionDecl *FD,
1548 const FunctionProtoType::ExceptionSpecInfo &ESI);
1549 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1550 bool CheckDistantExceptionSpec(QualType T);
1551 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1552 bool CheckEquivalentExceptionSpec(
1553 const FunctionProtoType *Old, SourceLocation OldLoc,
1554 const FunctionProtoType *New, SourceLocation NewLoc);
1555 bool CheckEquivalentExceptionSpec(
1556 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1557 const FunctionProtoType *Old, SourceLocation OldLoc,
1558 const FunctionProtoType *New, SourceLocation NewLoc);
1559 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1560 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1561 const PartialDiagnostic &NestedDiagID,
1562 const PartialDiagnostic &NoteID,
1563 const FunctionProtoType *Superset,
1564 SourceLocation SuperLoc,
1565 const FunctionProtoType *Subset,
1566 SourceLocation SubLoc);
1567 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1568 const PartialDiagnostic &NoteID,
1569 const FunctionProtoType *Target,
1570 SourceLocation TargetLoc,
1571 const FunctionProtoType *Source,
1572 SourceLocation SourceLoc);
1573
1574 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1575
1576 /// The parser has parsed the context-sensitive type 'instancetype'
1577 /// in an Objective-C message declaration. Return the appropriate type.
1578 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1579
1580 /// Abstract class used to diagnose incomplete types.
1581 struct TypeDiagnoser {
1582 TypeDiagnoser() {}
1583
1584 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1585 virtual ~TypeDiagnoser() {}
1586 };
1587
1588 static int getPrintable(int I) { return I; }
1589 static unsigned getPrintable(unsigned I) { return I; }
1590 static bool getPrintable(bool B) { return B; }
1591 static const char * getPrintable(const char *S) { return S; }
1592 static StringRef getPrintable(StringRef S) { return S; }
1593 static const std::string &getPrintable(const std::string &S) { return S; }
1594 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1595 return II;
1596 }
1597 static DeclarationName getPrintable(DeclarationName N) { return N; }
1598 static QualType getPrintable(QualType T) { return T; }
1599 static SourceRange getPrintable(SourceRange R) { return R; }
1600 static SourceRange getPrintable(SourceLocation L) { return L; }
1601 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1602 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1603
1604 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1605 unsigned DiagID;
1606 std::tuple<const Ts &...> Args;
1607
1608 template <std::size_t... Is>
1609 void emit(const SemaDiagnosticBuilder &DB,
1610 llvm::index_sequence<Is...>) const {
1611 // Apply all tuple elements to the builder in order.
1612 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1613 (void)Dummy;
1614 }
1615
1616 public:
1617 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1618 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1619 assert(DiagID != 0 && "no diagnostic for type diagnoser")((DiagID != 0 && "no diagnostic for type diagnoser") ?
static_cast<void> (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 1619, __PRETTY_FUNCTION__))
;
1620 }
1621
1622 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1623 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1624 emit(DB, llvm::index_sequence_for<Ts...>());
1625 DB << T;
1626 }
1627 };
1628
1629private:
1630 /// Methods for marking which expressions involve dereferencing a pointer
1631 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1632 /// they are parsed, meaning that a noderef pointer may not be accessed. For
1633 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1634 /// `*p`, but need to check that `address of` is called on it. This requires
1635 /// keeping a container of all pending expressions and checking if the address
1636 /// of them are eventually taken.
1637 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1638 void CheckAddressOfNoDeref(const Expr *E);
1639 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1640
1641 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1642 TypeDiagnoser *Diagnoser);
1643
1644 struct ModuleScope {
1645 SourceLocation BeginLoc;
1646 clang::Module *Module = nullptr;
1647 bool ModuleInterface = false;
1648 bool ImplicitGlobalModuleFragment = false;
1649 VisibleModuleSet OuterVisibleModules;
1650 };
1651 /// The modules we're currently parsing.
1652 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1653
1654 /// Namespace definitions that we will export when they finish.
1655 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1656
1657 /// Get the module whose scope we are currently within.
1658 Module *getCurrentModule() const {
1659 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1660 }
1661
1662 VisibleModuleSet VisibleModules;
1663
1664public:
1665 /// Get the module owning an entity.
1666 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1667
1668 /// Make a merged definition of an existing hidden definition \p ND
1669 /// visible at the specified location.
1670 void makeMergedDefinitionVisible(NamedDecl *ND);
1671
1672 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1673
1674 /// Determine whether a declaration is visible to name lookup.
1675 bool isVisible(const NamedDecl *D) {
1676 return !D->isHidden() || isVisibleSlow(D);
1677 }
1678
1679 /// Determine whether any declaration of an entity is visible.
1680 bool
1681 hasVisibleDeclaration(const NamedDecl *D,
1682 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1683 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1684 }
1685 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1686 llvm::SmallVectorImpl<Module *> *Modules);
1687
1688 bool hasVisibleMergedDefinition(NamedDecl *Def);
1689 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1690
1691 /// Determine if \p D and \p Suggested have a structurally compatible
1692 /// layout as described in C11 6.2.7/1.
1693 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1694
1695 /// Determine if \p D has a visible definition. If not, suggest a declaration
1696 /// that should be made visible to expose the definition.
1697 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1698 bool OnlyNeedComplete = false);
1699 bool hasVisibleDefinition(const NamedDecl *D) {
1700 NamedDecl *Hidden;
1701 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1702 }
1703
1704 /// Determine if the template parameter \p D has a visible default argument.
1705 bool
1706 hasVisibleDefaultArgument(const NamedDecl *D,
1707 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1708
1709 /// Determine if there is a visible declaration of \p D that is an explicit
1710 /// specialization declaration for a specialization of a template. (For a
1711 /// member specialization, use hasVisibleMemberSpecialization.)
1712 bool hasVisibleExplicitSpecialization(
1713 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1714
1715 /// Determine if there is a visible declaration of \p D that is a member
1716 /// specialization declaration (as opposed to an instantiated declaration).
1717 bool hasVisibleMemberSpecialization(
1718 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1719
1720 /// Determine if \p A and \p B are equivalent internal linkage declarations
1721 /// from different modules, and thus an ambiguity error can be downgraded to
1722 /// an extension warning.
1723 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1724 const NamedDecl *B);
1725 void diagnoseEquivalentInternalLinkageDeclarations(
1726 SourceLocation Loc, const NamedDecl *D,
1727 ArrayRef<const NamedDecl *> Equiv);
1728
1729 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1730
1731 bool isCompleteType(SourceLocation Loc, QualType T) {
1732 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1733 }
1734 bool RequireCompleteType(SourceLocation Loc, QualType T,
1735 TypeDiagnoser &Diagnoser);
1736 bool RequireCompleteType(SourceLocation Loc, QualType T,
1737 unsigned DiagID);
1738
1739 template <typename... Ts>
1740 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1741 const Ts &...Args) {
1742 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1743 return RequireCompleteType(Loc, T, Diagnoser);
1744 }
1745
1746 void completeExprArrayBound(Expr *E);
1747 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1748 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1749
1750 template <typename... Ts>
1751 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1752 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1753 return RequireCompleteExprType(E, Diagnoser);
1754 }
1755
1756 bool RequireLiteralType(SourceLocation Loc, QualType T,
1757 TypeDiagnoser &Diagnoser);
1758 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1759
1760 template <typename... Ts>
1761 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1762 const Ts &...Args) {
1763 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1764 return RequireLiteralType(Loc, T, Diagnoser);
1765 }
1766
1767 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1768 const CXXScopeSpec &SS, QualType T,
1769 TagDecl *OwnedTagDecl = nullptr);
1770
1771 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1772 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1773 /// context, such as when building a type for decltype(auto).
1774 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1775 bool AsUnevaluated = true);
1776 QualType BuildUnaryTransformType(QualType BaseType,
1777 UnaryTransformType::UTTKind UKind,
1778 SourceLocation Loc);
1779
1780 //===--------------------------------------------------------------------===//
1781 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1782 //
1783
1784 struct SkipBodyInfo {
1785 SkipBodyInfo()
1786 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1787 New(nullptr) {}
1788 bool ShouldSkip;
1789 bool CheckSameAsPrevious;
1790 NamedDecl *Previous;
1791 NamedDecl *New;
1792 };
1793
1794 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1795
1796 void DiagnoseUseOfUnimplementedSelectors();
1797
1798 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1799
1800 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1801 Scope *S, CXXScopeSpec *SS = nullptr,
1802 bool isClassName = false, bool HasTrailingDot = false,
1803 ParsedType ObjectType = nullptr,
1804 bool IsCtorOrDtorName = false,
1805 bool WantNontrivialTypeSourceInfo = false,
1806 bool IsClassTemplateDeductionContext = true,
1807 IdentifierInfo **CorrectedII = nullptr);
1808 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1809 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1810 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1811 SourceLocation IILoc,
1812 Scope *S,
1813 CXXScopeSpec *SS,
1814 ParsedType &SuggestedType,
1815 bool IsTemplateName = false);
1816
1817 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1818 /// type name has failed in a dependent context. In these situations, we
1819 /// automatically form a DependentTypeName that will retry lookup in a related
1820 /// scope during instantiation.
1821 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1822 SourceLocation NameLoc,
1823 bool IsTemplateTypeArg);
1824
1825 /// Describes the result of the name lookup and resolution performed
1826 /// by \c ClassifyName().
1827 enum NameClassificationKind {
1828 NC_Unknown,
1829 NC_Error,
1830 NC_Keyword,
1831 NC_Type,
1832 NC_Expression,
1833 NC_NestedNameSpecifier,
1834 NC_TypeTemplate,
1835 NC_VarTemplate,
1836 NC_FunctionTemplate
1837 };
1838
1839 class NameClassification {
1840 NameClassificationKind Kind;
1841 ExprResult Expr;
1842 TemplateName Template;
1843 ParsedType Type;
1844
1845 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1846
1847 public:
1848 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1849
1850 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1851
1852 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1853
1854 static NameClassification Error() {
1855 return NameClassification(NC_Error);
1856 }
1857
1858 static NameClassification Unknown() {
1859 return NameClassification(NC_Unknown);
1860 }
1861
1862 static NameClassification NestedNameSpecifier() {
1863 return NameClassification(NC_NestedNameSpecifier);
1864 }
1865
1866 static NameClassification TypeTemplate(TemplateName Name) {
1867 NameClassification Result(NC_TypeTemplate);
1868 Result.Template = Name;
1869 return Result;
1870 }
1871
1872 static NameClassification VarTemplate(TemplateName Name) {
1873 NameClassification Result(NC_VarTemplate);
1874 Result.Template = Name;
1875 return Result;
1876 }
1877
1878 static NameClassification FunctionTemplate(TemplateName Name) {
1879 NameClassification Result(NC_FunctionTemplate);
1880 Result.Template = Name;
1881 return Result;
1882 }
1883
1884 NameClassificationKind getKind() const { return Kind; }
1885
1886 ParsedType getType() const {
1887 assert(Kind == NC_Type)((Kind == NC_Type) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 1887, __PRETTY_FUNCTION__))
;
1888 return Type;
1889 }
1890
1891 ExprResult getExpression() const {
1892 assert(Kind == NC_Expression)((Kind == NC_Expression) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Expression", "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 1892, __PRETTY_FUNCTION__))
;
1893 return Expr;
1894 }
1895
1896 TemplateName getTemplateName() const {
1897 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate) ? static_cast<void> (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 1898, __PRETTY_FUNCTION__))
1898 Kind == NC_VarTemplate)((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate) ? static_cast<void> (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 1898, __PRETTY_FUNCTION__))
;
1899 return Template;
1900 }
1901
1902 TemplateNameKind getTemplateNameKind() const {
1903 switch (Kind) {
1904 case NC_TypeTemplate:
1905 return TNK_Type_template;
1906 case NC_FunctionTemplate:
1907 return TNK_Function_template;
1908 case NC_VarTemplate:
1909 return TNK_Var_template;
1910 default:
1911 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 1911)
;
1912 }
1913 }
1914 };
1915
1916 /// Perform name lookup on the given name, classifying it based on
1917 /// the results of name lookup and the following token.
1918 ///
1919 /// This routine is used by the parser to resolve identifiers and help direct
1920 /// parsing. When the identifier cannot be found, this routine will attempt
1921 /// to correct the typo and classify based on the resulting name.
1922 ///
1923 /// \param S The scope in which we're performing name lookup.
1924 ///
1925 /// \param SS The nested-name-specifier that precedes the name.
1926 ///
1927 /// \param Name The identifier. If typo correction finds an alternative name,
1928 /// this pointer parameter will be updated accordingly.
1929 ///
1930 /// \param NameLoc The location of the identifier.
1931 ///
1932 /// \param NextToken The token following the identifier. Used to help
1933 /// disambiguate the name.
1934 ///
1935 /// \param IsAddressOfOperand True if this name is the operand of a unary
1936 /// address of ('&') expression, assuming it is classified as an
1937 /// expression.
1938 ///
1939 /// \param CCC The correction callback, if typo correction is desired.
1940 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
1941 IdentifierInfo *&Name, SourceLocation NameLoc,
1942 const Token &NextToken,
1943 bool IsAddressOfOperand,
1944 CorrectionCandidateCallback *CCC = nullptr);
1945
1946 /// Describes the detailed kind of a template name. Used in diagnostics.
1947 enum class TemplateNameKindForDiagnostics {
1948 ClassTemplate,
1949 FunctionTemplate,
1950 VarTemplate,
1951 AliasTemplate,
1952 TemplateTemplateParam,
1953 DependentTemplate
1954 };
1955 TemplateNameKindForDiagnostics
1956 getTemplateNameKindForDiagnostics(TemplateName Name);
1957
1958 /// Determine whether it's plausible that E was intended to be a
1959 /// template-name.
1960 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
1961 if (!getLangOpts().CPlusPlus || E.isInvalid())
1962 return false;
1963 Dependent = false;
1964 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
1965 return !DRE->hasExplicitTemplateArgs();
1966 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
1967 return !ME->hasExplicitTemplateArgs();
1968 Dependent = true;
1969 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
1970 return !DSDRE->hasExplicitTemplateArgs();
1971 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
1972 return !DSME->hasExplicitTemplateArgs();
1973 // Any additional cases recognized here should also be handled by
1974 // diagnoseExprIntendedAsTemplateName.
1975 return false;
1976 }
1977 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
1978 SourceLocation Less,
1979 SourceLocation Greater);
1980
1981 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1982
1983 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1984 MultiTemplateParamsArg TemplateParameterLists);
1985 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1986 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1987 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1988 DeclarationName Name, SourceLocation Loc,
1989 bool IsTemplateId);
1990 void
1991 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1992 SourceLocation FallbackLoc,
1993 SourceLocation ConstQualLoc = SourceLocation(),
1994 SourceLocation VolatileQualLoc = SourceLocation(),
1995 SourceLocation RestrictQualLoc = SourceLocation(),
1996 SourceLocation AtomicQualLoc = SourceLocation(),
1997 SourceLocation UnalignedQualLoc = SourceLocation());
1998
1999 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2000 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2001 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2002 const LookupResult &R);
2003 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2004 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2005 const LookupResult &R);
2006 void CheckShadow(Scope *S, VarDecl *D);
2007
2008 /// Warn if 'E', which is an expression that is about to be modified, refers
2009 /// to a shadowing declaration.
2010 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2011
2012 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2013
2014private:
2015 /// Map of current shadowing declarations to shadowed declarations. Warn if
2016 /// it looks like the user is trying to modify the shadowing declaration.
2017 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2018
2019public:
2020 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2021 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2022 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2023 TypedefNameDecl *NewTD);
2024 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2025 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2026 TypeSourceInfo *TInfo,
2027 LookupResult &Previous);
2028 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2029 LookupResult &Previous, bool &Redeclaration);
2030 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2031 TypeSourceInfo *TInfo,
2032 LookupResult &Previous,
2033 MultiTemplateParamsArg TemplateParamLists,
2034 bool &AddToScope,
2035 ArrayRef<BindingDecl *> Bindings = None);
2036 NamedDecl *
2037 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2038 MultiTemplateParamsArg TemplateParamLists);
2039 // Returns true if the variable declaration is a redeclaration
2040 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2041 void CheckVariableDeclarationType(VarDecl *NewVD);
2042 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2043 Expr *Init);
2044 void CheckCompleteVariableDeclaration(VarDecl *VD);
2045 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2046 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2047
2048 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2049 TypeSourceInfo *TInfo,
2050 LookupResult &Previous,
2051 MultiTemplateParamsArg TemplateParamLists,
2052 bool &AddToScope);
2053 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2054
2055 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
2056 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
2057
2058 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2059 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2060 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2061 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2062 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2063 // Returns true if the function declaration is a redeclaration
2064 bool CheckFunctionDeclaration(Scope *S,
2065 FunctionDecl *NewFD, LookupResult &Previous,
2066 bool IsMemberSpecialization);
2067 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2068 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2069 QualType NewT, QualType OldT);
2070 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2071 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2072 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition);
2073 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2074 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2075 SourceLocation Loc,
2076 QualType T);
2077 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2078 SourceLocation NameLoc, IdentifierInfo *Name,
2079 QualType T, TypeSourceInfo *TSInfo,
2080 StorageClass SC);
2081 void ActOnParamDefaultArgument(Decl *param,
2082 SourceLocation EqualLoc,
2083 Expr *defarg);
2084 void ActOnParamUnparsedDefaultArgument(Decl *param,
2085 SourceLocation EqualLoc,
2086 SourceLocation ArgLoc);
2087 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2088 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2089 SourceLocation EqualLoc);
2090
2091 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2092 void ActOnUninitializedDecl(Decl *dcl);
2093 void ActOnInitializerError(Decl *Dcl);
2094
2095 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2096 void ActOnCXXForRangeDecl(Decl *D);
2097 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2098 IdentifierInfo *Ident,
2099 ParsedAttributes &Attrs,
2100 SourceLocation AttrEnd);
2101 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2102 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2103 void CheckStaticLocalForDllExport(VarDecl *VD);
2104 void FinalizeDeclaration(Decl *D);
2105 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2106 ArrayRef<Decl *> Group);
2107 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2108
2109 /// Should be called on all declarations that might have attached
2110 /// documentation comments.
2111 void ActOnDocumentableDecl(Decl *D);
2112 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2113
2114 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2115 SourceLocation LocAfterDecls);
2116 void CheckForFunctionRedefinition(
2117 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2118 SkipBodyInfo *SkipBody = nullptr);
2119 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2120 MultiTemplateParamsArg TemplateParamLists,
2121 SkipBodyInfo *SkipBody = nullptr);
2122 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2123 SkipBodyInfo *SkipBody = nullptr);
2124 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2125 bool isObjCMethodDecl(Decl *D) {
2126 return D && isa<ObjCMethodDecl>(D);
2127 }
2128
2129 /// Determine whether we can delay parsing the body of a function or
2130 /// function template until it is used, assuming we don't care about emitting
2131 /// code for that function.
2132 ///
2133 /// This will be \c false if we may need the body of the function in the
2134 /// middle of parsing an expression (where it's impractical to switch to
2135 /// parsing a different function), for instance, if it's constexpr in C++11
2136 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2137 bool canDelayFunctionBody(const Declarator &D);
2138
2139 /// Determine whether we can skip parsing the body of a function
2140 /// definition, assuming we don't care about analyzing its body or emitting
2141 /// code for that function.
2142 ///
2143 /// This will be \c false only if we may need the body of the function in
2144 /// order to parse the rest of the program (for instance, if it is
2145 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2146 bool canSkipFunctionBody(Decl *D);
2147
2148 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2149 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2150 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2151 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2152 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2153
2154 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2155 /// attribute for which parsing is delayed.
2156 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2157
2158 /// Diagnose any unused parameters in the given sequence of
2159 /// ParmVarDecl pointers.
2160 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2161
2162 /// Diagnose whether the size of parameters or return value of a
2163 /// function or obj-c method definition is pass-by-value and larger than a
2164 /// specified threshold.
2165 void
2166 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2167 QualType ReturnTy, NamedDecl *D);
2168
2169 void DiagnoseInvalidJumps(Stmt *Body);
2170 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2171 SourceLocation AsmLoc,
2172 SourceLocation RParenLoc);
2173
2174 /// Handle a C++11 empty-declaration and attribute-declaration.
2175 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2176 SourceLocation SemiLoc);
2177
2178 enum class ModuleDeclKind {
2179 Interface, ///< 'export module X;'
2180 Implementation, ///< 'module X;'
2181 };
2182
2183 /// The parser has processed a module-declaration that begins the definition
2184 /// of a module interface or implementation.
2185 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2186 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2187 ModuleIdPath Path, bool IsFirstDecl);
2188
2189 /// The parser has processed a global-module-fragment declaration that begins
2190 /// the definition of the global module fragment of the current module unit.
2191 /// \param ModuleLoc The location of the 'module' keyword.
2192 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2193
2194 /// The parser has processed a private-module-fragment declaration that begins
2195 /// the definition of the private module fragment of the current module unit.
2196 /// \param ModuleLoc The location of the 'module' keyword.
2197 /// \param PrivateLoc The location of the 'private' keyword.
2198 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2199 SourceLocation PrivateLoc);
2200
2201 /// The parser has processed a module import declaration.
2202 ///
2203 /// \param StartLoc The location of the first token in the declaration. This
2204 /// could be the location of an '@', 'export', or 'import'.
2205 /// \param ExportLoc The location of the 'export' keyword, if any.
2206 /// \param ImportLoc The location of the 'import' keyword.
2207 /// \param Path The module access path.
2208 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2209 SourceLocation ExportLoc,
2210 SourceLocation ImportLoc, ModuleIdPath Path);
2211 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2212 SourceLocation ExportLoc,
2213 SourceLocation ImportLoc, Module *M,
2214 ModuleIdPath Path = {});
2215
2216 /// The parser has processed a module import translated from a
2217 /// #include or similar preprocessing directive.
2218 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2219 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2220
2221 /// The parsed has entered a submodule.
2222 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2223 /// The parser has left a submodule.
2224 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2225
2226 /// Create an implicit import of the given module at the given
2227 /// source location, for error recovery, if possible.
2228 ///
2229 /// This routine is typically used when an entity found by name lookup
2230 /// is actually hidden within a module that we know about but the user
2231 /// has forgotten to import.
2232 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2233 Module *Mod);
2234
2235 /// Kinds of missing import. Note, the values of these enumerators correspond
2236 /// to %select values in diagnostics.
2237 enum class MissingImportKind {
2238 Declaration,
2239 Definition,
2240 DefaultArgument,
2241 ExplicitSpecialization,
2242 PartialSpecialization
2243 };
2244
2245 /// Diagnose that the specified declaration needs to be visible but
2246 /// isn't, and suggest a module import that would resolve the problem.
2247 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2248 MissingImportKind MIK, bool Recover = true);
2249 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2250 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2251 MissingImportKind MIK, bool Recover);
2252
2253 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2254 SourceLocation LBraceLoc);
2255 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2256 SourceLocation RBraceLoc);
2257
2258 /// We've found a use of a templated declaration that would trigger an
2259 /// implicit instantiation. Check that any relevant explicit specializations
2260 /// and partial specializations are visible, and diagnose if not.
2261 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2262
2263 /// We've found a use of a template specialization that would select a
2264 /// partial specialization. Check that the partial specialization is visible,
2265 /// and diagnose if not.
2266 void checkPartialSpecializationVisibility(SourceLocation Loc,
2267 NamedDecl *Spec);
2268
2269 /// Retrieve a suitable printing policy for diagnostics.
2270 PrintingPolicy getPrintingPolicy() const {
2271 return getPrintingPolicy(Context, PP);
2272 }
2273
2274 /// Retrieve a suitable printing policy for diagnostics.
2275 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2276 const Preprocessor &PP);
2277
2278 /// Scope actions.
2279 void ActOnPopScope(SourceLocation Loc, Scope *S);
2280 void ActOnTranslationUnitScope(Scope *S);
2281
2282 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2283 RecordDecl *&AnonRecord);
2284 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2285 MultiTemplateParamsArg TemplateParams,
2286 bool IsExplicitInstantiation,
2287 RecordDecl *&AnonRecord);
2288
2289 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2290 AccessSpecifier AS,
2291 RecordDecl *Record,
2292 const PrintingPolicy &Policy);
2293
2294 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2295 RecordDecl *Record);
2296
2297 /// Common ways to introduce type names without a tag for use in diagnostics.
2298 /// Keep in sync with err_tag_reference_non_tag.
2299 enum NonTagKind {
2300 NTK_NonStruct,
2301 NTK_NonClass,
2302 NTK_NonUnion,
2303 NTK_NonEnum,
2304 NTK_Typedef,
2305 NTK_TypeAlias,
2306 NTK_Template,
2307 NTK_TypeAliasTemplate,
2308 NTK_TemplateTemplateArgument,
2309 };
2310
2311 /// Given a non-tag type declaration, returns an enum useful for indicating
2312 /// what kind of non-tag type this is.
2313 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2314
2315 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2316 TagTypeKind NewTag, bool isDefinition,
2317 SourceLocation NewTagLoc,
2318 const IdentifierInfo *Name);
2319
2320 enum TagUseKind {
2321 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2322 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2323 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2324 TUK_Friend // Friend declaration: 'friend struct foo;'
2325 };
2326
2327 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2328 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2329 SourceLocation NameLoc, const ParsedAttributesView &Attr,
2330 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2331 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2332 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2333 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2334 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2335 SkipBodyInfo *SkipBody = nullptr);
2336
2337 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2338 unsigned TagSpec, SourceLocation TagLoc,
2339 CXXScopeSpec &SS, IdentifierInfo *Name,
2340 SourceLocation NameLoc,
2341 const ParsedAttributesView &Attr,
2342 MultiTemplateParamsArg TempParamLists);
2343
2344 TypeResult ActOnDependentTag(Scope *S,
2345 unsigned TagSpec,
2346 TagUseKind TUK,
2347 const CXXScopeSpec &SS,
2348 IdentifierInfo *Name,
2349 SourceLocation TagLoc,
2350 SourceLocation NameLoc);
2351
2352 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2353 IdentifierInfo *ClassName,
2354 SmallVectorImpl<Decl *> &Decls);
2355 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2356 Declarator &D, Expr *BitfieldWidth);
2357
2358 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2359 Declarator &D, Expr *BitfieldWidth,
2360 InClassInitStyle InitStyle,
2361 AccessSpecifier AS);
2362 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2363 SourceLocation DeclStart, Declarator &D,
2364 Expr *BitfieldWidth,
2365 InClassInitStyle InitStyle,
2366 AccessSpecifier AS,
2367 const ParsedAttr &MSPropertyAttr);
2368
2369 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2370 TypeSourceInfo *TInfo,
2371 RecordDecl *Record, SourceLocation Loc,
2372 bool Mutable, Expr *BitfieldWidth,
2373 InClassInitStyle InitStyle,
2374 SourceLocation TSSL,
2375 AccessSpecifier AS, NamedDecl *PrevDecl,
2376 Declarator *D = nullptr);
2377
2378 bool CheckNontrivialField(FieldDecl *FD);
2379 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2380
2381 enum TrivialABIHandling {
2382 /// The triviality of a method unaffected by "trivial_abi".
2383 TAH_IgnoreTrivialABI,
2384
2385 /// The triviality of a method affected by "trivial_abi".
2386 TAH_ConsiderTrivialABI
2387 };
2388
2389 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2390 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2391 bool Diagnose = false);
2392 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2393 void ActOnLastBitfield(SourceLocation DeclStart,
2394 SmallVectorImpl<Decl *> &AllIvarDecls);
2395 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2396 Declarator &D, Expr *BitfieldWidth,
2397 tok::ObjCKeywordKind visibility);
2398
2399 // This is used for both record definitions and ObjC interface declarations.
2400 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2401 ArrayRef<Decl *> Fields, SourceLocation LBrac,
2402 SourceLocation RBrac, const ParsedAttributesView &AttrList);
2403
2404 /// ActOnTagStartDefinition - Invoked when we have entered the
2405 /// scope of a tag's definition (e.g., for an enumeration, class,
2406 /// struct, or union).
2407 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2408
2409 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2410 /// Differently from C++, actually parse the body and reject / error out
2411 /// in case of a structural mismatch.
2412 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2413 SkipBodyInfo &SkipBody);
2414
2415 typedef void *SkippedDefinitionContext;
2416
2417 /// Invoked when we enter a tag definition that we're skipping.
2418 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2419
2420 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2421
2422 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2423 /// C++ record definition's base-specifiers clause and are starting its
2424 /// member declarations.
2425 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2426 SourceLocation FinalLoc,
2427 bool IsFinalSpelledSealed,
2428 SourceLocation LBraceLoc);
2429
2430 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2431 /// the definition of a tag (enumeration, class, struct, or union).
2432 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2433 SourceRange BraceRange);
2434
2435 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2436
2437 void ActOnObjCContainerFinishDefinition();
2438
2439 /// Invoked when we must temporarily exit the objective-c container
2440 /// scope for parsing/looking-up C constructs.
2441 ///
2442 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2443 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2444 void ActOnObjCReenterContainerContext(DeclContext *DC);
2445
2446 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2447 /// error parsing the definition of a tag.
2448 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2449
2450 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2451 EnumConstantDecl *LastEnumConst,
2452 SourceLocation IdLoc,
2453 IdentifierInfo *Id,
2454 Expr *val);
2455 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2456 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2457 QualType EnumUnderlyingTy, bool IsFixed,
2458 const EnumDecl *Prev);
2459
2460 /// Determine whether the body of an anonymous enumeration should be skipped.
2461 /// \param II The name of the first enumerator.
2462 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2463 SourceLocation IILoc);
2464
2465 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2466 SourceLocation IdLoc, IdentifierInfo *Id,
2467 const ParsedAttributesView &Attrs,
2468 SourceLocation EqualLoc, Expr *Val);
2469 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2470 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
2471 const ParsedAttributesView &Attr);
2472
2473 DeclContext *getContainingDC(DeclContext *DC);
2474
2475 /// Set the current declaration context until it gets popped.
2476 void PushDeclContext(Scope *S, DeclContext *DC);
2477 void PopDeclContext();
2478
2479 /// EnterDeclaratorContext - Used when we must lookup names in the context
2480 /// of a declarator's nested name specifier.
2481 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2482 void ExitDeclaratorContext(Scope *S);
2483
2484 /// Push the parameters of D, which must be a function, into scope.
2485 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2486 void ActOnExitFunctionContext();
2487
2488 DeclContext *getFunctionLevelDeclContext();
2489
2490 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2491 /// to the function decl for the function being parsed. If we're currently
2492 /// in a 'block', this returns the containing context.
2493 FunctionDecl *getCurFunctionDecl();
2494
2495 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2496 /// the method decl for the method being parsed. If we're currently
2497 /// in a 'block', this returns the containing context.
2498 ObjCMethodDecl *getCurMethodDecl();
2499
2500 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2501 /// or C function we're in, otherwise return null. If we're currently
2502 /// in a 'block', this returns the containing context.
2503 NamedDecl *getCurFunctionOrMethodDecl();
2504
2505 /// Add this decl to the scope shadowed decl chains.
2506 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2507
2508 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2509 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2510 /// true if 'D' belongs to the given declaration context.
2511 ///
2512 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2513 /// enclosing namespace set of the context, rather than contained
2514 /// directly within it.
2515 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2516 bool AllowInlineNamespace = false);
2517
2518 /// Finds the scope corresponding to the given decl context, if it
2519 /// happens to be an enclosing scope. Otherwise return NULL.
2520 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2521
2522 /// Subroutines of ActOnDeclarator().
2523 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2524 TypeSourceInfo *TInfo);
2525 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2526
2527 /// Describes the kind of merge to perform for availability
2528 /// attributes (including "deprecated", "unavailable", and "availability").
2529 enum AvailabilityMergeKind {
2530 /// Don't merge availability attributes at all.
2531 AMK_None,
2532 /// Merge availability attributes for a redeclaration, which requires
2533 /// an exact match.
2534 AMK_Redeclaration,
2535 /// Merge availability attributes for an override, which requires
2536 /// an exact match or a weakening of constraints.
2537 AMK_Override,
2538 /// Merge availability attributes for an implementation of
2539 /// a protocol requirement.
2540 AMK_ProtocolImplementation,
2541 };
2542
2543 /// Describes the kind of priority given to an availability attribute.
2544 ///
2545 /// The sum of priorities deteremines the final priority of the attribute.
2546 /// The final priority determines how the attribute will be merged.
2547 /// An attribute with a lower priority will always remove higher priority
2548 /// attributes for the specified platform when it is being applied. An
2549 /// attribute with a higher priority will not be applied if the declaration
2550 /// already has an availability attribute with a lower priority for the
2551 /// specified platform. The final prirority values are not expected to match
2552 /// the values in this enumeration, but instead should be treated as a plain
2553 /// integer value. This enumeration just names the priority weights that are
2554 /// used to calculate that final vaue.
2555 enum AvailabilityPriority : int {
2556 /// The availability attribute was specified explicitly next to the
2557 /// declaration.
2558 AP_Explicit = 0,
2559
2560 /// The availability attribute was applied using '#pragma clang attribute'.
2561 AP_PragmaClangAttribute = 1,
2562
2563 /// The availability attribute for a specific platform was inferred from
2564 /// an availability attribute for another platform.
2565 AP_InferredFromOtherPlatform = 2
2566 };
2567
2568 /// Attribute merging methods. Return true if a new attribute was added.
2569 AvailabilityAttr *mergeAvailabilityAttr(
2570 NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, bool Implicit,
2571 VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted,
2572 bool IsUnavailable, StringRef Message, bool IsStrict,
2573 StringRef Replacement, AvailabilityMergeKind AMK, int Priority,
2574 unsigned AttrSpellingListIndex);
2575 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2576 TypeVisibilityAttr::VisibilityType Vis,
2577 unsigned AttrSpellingListIndex);
2578 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2579 VisibilityAttr::VisibilityType Vis,
2580 unsigned AttrSpellingListIndex);
2581 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2582 unsigned AttrSpellingListIndex, StringRef Uuid);
2583 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2584 unsigned AttrSpellingListIndex);
2585 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2586 unsigned AttrSpellingListIndex);
2587 MSInheritanceAttr *
2588 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2589 unsigned AttrSpellingListIndex,
2590 MSInheritanceAttr::Spelling SemanticSpelling);
2591 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2592 IdentifierInfo *Format, int FormatIdx,
2593 int FirstArg, unsigned AttrSpellingListIndex);
2594 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2595 unsigned AttrSpellingListIndex);
2596 CodeSegAttr *mergeCodeSegAttr(Decl *D, SourceRange Range, StringRef Name,
2597 unsigned AttrSpellingListIndex);
2598 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2599 IdentifierInfo *Ident,
2600 unsigned AttrSpellingListIndex);
2601 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2602 unsigned AttrSpellingListIndex);
2603 NoSpeculativeLoadHardeningAttr *
2604 mergeNoSpeculativeLoadHardeningAttr(Decl *D,
2605 const NoSpeculativeLoadHardeningAttr &AL);
2606 SpeculativeLoadHardeningAttr *
2607 mergeSpeculativeLoadHardeningAttr(Decl *D,
2608 const SpeculativeLoadHardeningAttr &AL);
2609 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2610 unsigned AttrSpellingListIndex);
2611 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
2612 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
2613 const InternalLinkageAttr &AL);
2614 CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
2615 CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
2616
2617 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2618 AvailabilityMergeKind AMK = AMK_Redeclaration);
2619 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2620 LookupResult &OldDecls);
2621 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2622 bool MergeTypeWithOld);
2623 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2624 Scope *S, bool MergeTypeWithOld);
2625 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2626 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2627 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2628 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2629 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2630 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2631 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2632
2633 // AssignmentAction - This is used by all the assignment diagnostic functions
2634 // to represent what is actually causing the operation
2635 enum AssignmentAction {
2636 AA_Assigning,
2637 AA_Passing,
2638 AA_Returning,
2639 AA_Converting,
2640 AA_Initializing,
2641 AA_Sending,
2642 AA_Casting,
2643 AA_Passing_CFAudited
2644 };
2645
2646 /// C++ Overloading.
2647 enum OverloadKind {
2648 /// This is a legitimate overload: the existing declarations are
2649 /// functions or function templates with different signatures.
2650 Ovl_Overload,
2651
2652 /// This is not an overload because the signature exactly matches
2653 /// an existing declaration.
2654 Ovl_Match,
2655
2656 /// This is not an overload because the lookup results contain a
2657 /// non-function.
2658 Ovl_NonFunction
2659 };
2660 OverloadKind CheckOverload(Scope *S,
2661 FunctionDecl *New,
2662 const LookupResult &OldDecls,
2663 NamedDecl *&OldDecl,
2664 bool IsForUsingDecl);
2665 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2666 bool ConsiderCudaAttrs = true);
2667
2668 ImplicitConversionSequence
2669 TryImplicitConversion(Expr *From, QualType ToType,
2670 bool SuppressUserConversions,
2671 bool AllowExplicit,
2672 bool InOverloadResolution,
2673 bool CStyle,
2674 bool AllowObjCWritebackConversion);
2675
2676 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2677 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2678 bool IsComplexPromotion(QualType FromType, QualType ToType);
2679 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2680 bool InOverloadResolution,
2681 QualType& ConvertedType, bool &IncompatibleObjC);
2682 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2683 QualType& ConvertedType, bool &IncompatibleObjC);
2684 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2685 QualType &ConvertedType);
2686 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2687 QualType& ConvertedType);
2688 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2689 const FunctionProtoType *NewType,
2690 unsigned *ArgPos = nullptr);
2691 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2692 QualType FromType, QualType ToType);
2693
2694 void maybeExtendBlockObject(ExprResult &E);
2695 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2696 bool CheckPointerConversion(Expr *From, QualType ToType,
2697 CastKind &Kind,
2698 CXXCastPath& BasePath,
2699 bool IgnoreBaseAccess,
2700 bool Diagnose = true);
2701 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2702 bool InOverloadResolution,
2703 QualType &ConvertedType);
2704 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2705 CastKind &Kind,
2706 CXXCastPath &BasePath,
2707 bool IgnoreBaseAccess);
2708 bool IsQualificationConversion(QualType FromType, QualType ToType,
2709 bool CStyle, bool &ObjCLifetimeConversion);
2710 bool IsFunctionConversion(QualType FromType, QualType ToType,
2711 QualType &ResultTy);
2712 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2713 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2714
2715 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2716 const VarDecl *NRVOCandidate,
2717 QualType ResultType,
2718 Expr *Value,
2719 bool AllowNRVO = true);
2720
2721 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2722 ExprResult Init);
2723 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2724 SourceLocation EqualLoc,
2725 ExprResult Init,
2726 bool TopLevelOfInitList = false,
2727 bool AllowExplicit = false);
2728 ExprResult PerformObjectArgumentInitialization(Expr *From,
2729 NestedNameSpecifier *Qualifier,
2730 NamedDecl *FoundDecl,
2731 CXXMethodDecl *Method);
2732
2733 /// Check that the lifetime of the initializer (and its subobjects) is
2734 /// sufficient for initializing the entity, and perform lifetime extension
2735 /// (when permitted) if not.
2736 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
2737
2738 ExprResult PerformContextuallyConvertToBool(Expr *From);
2739 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2740
2741 /// Contexts in which a converted constant expression is required.
2742 enum CCEKind {
2743 CCEK_CaseValue, ///< Expression in a case label.
2744 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2745 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2746 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2747 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2748 };
2749 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2750 llvm::APSInt &Value, CCEKind CCE);
2751 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2752 APValue &Value, CCEKind CCE);
2753
2754 /// Abstract base class used to perform a contextual implicit
2755 /// conversion from an expression to any type passing a filter.
2756 class ContextualImplicitConverter {
2757 public:
2758 bool Suppress;
2759 bool SuppressConversion;
2760
2761 ContextualImplicitConverter(bool Suppress = false,
2762 bool SuppressConversion = false)
2763 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2764
2765 /// Determine whether the specified type is a valid destination type
2766 /// for this conversion.
2767 virtual bool match(QualType T) = 0;
2768
2769 /// Emits a diagnostic complaining that the expression does not have
2770 /// integral or enumeration type.
2771 virtual SemaDiagnosticBuilder
2772 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2773
2774 /// Emits a diagnostic when the expression has incomplete class type.
2775 virtual SemaDiagnosticBuilder
2776 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2777
2778 /// Emits a diagnostic when the only matching conversion function
2779 /// is explicit.
2780 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2781 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2782
2783 /// Emits a note for the explicit conversion function.
2784 virtual SemaDiagnosticBuilder
2785 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2786
2787 /// Emits a diagnostic when there are multiple possible conversion
2788 /// functions.
2789 virtual SemaDiagnosticBuilder
2790 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2791
2792 /// Emits a note for one of the candidate conversions.
2793 virtual SemaDiagnosticBuilder
2794 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2795
2796 /// Emits a diagnostic when we picked a conversion function
2797 /// (for cases when we are not allowed to pick a conversion function).
2798 virtual SemaDiagnosticBuilder diagnoseConversion(
2799 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2800
2801 virtual ~ContextualImplicitConverter() {}
2802 };
2803
2804 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2805 bool AllowScopedEnumerations;
2806
2807 public:
2808 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2809 bool Suppress, bool SuppressConversion)
2810 : ContextualImplicitConverter(Suppress, SuppressConversion),
2811 AllowScopedEnumerations(AllowScopedEnumerations) {}
2812
2813 /// Match an integral or (possibly scoped) enumeration type.
2814 bool match(QualType T) override;
2815
2816 SemaDiagnosticBuilder
2817 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2818 return diagnoseNotInt(S, Loc, T);
2819 }
2820
2821 /// Emits a diagnostic complaining that the expression does not have
2822 /// integral or enumeration type.
2823 virtual SemaDiagnosticBuilder
2824 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2825 };
2826
2827 /// Perform a contextual implicit conversion.
2828 ExprResult PerformContextualImplicitConversion(
2829 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2830
2831
2832 enum ObjCSubscriptKind {
2833 OS_Array,
2834 OS_Dictionary,
2835 OS_Error
2836 };
2837 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2838
2839 // Note that LK_String is intentionally after the other literals, as
2840 // this is used for diagnostics logic.
2841 enum ObjCLiteralKind {
2842 LK_Array,
2843 LK_Dictionary,
2844 LK_Numeric,
2845 LK_Boxed,
2846 LK_String,
2847 LK_Block,
2848 LK_None
2849 };
2850 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2851
2852 ExprResult PerformObjectMemberConversion(Expr *From,
2853 NestedNameSpecifier *Qualifier,
2854 NamedDecl *FoundDecl,
2855 NamedDecl *Member);
2856
2857 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2858 // TODO: make this is a typesafe union.
2859 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2860 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2861
2862 using ADLCallKind = CallExpr::ADLCallKind;
2863
2864 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
2865 ArrayRef<Expr *> Args,
2866 OverloadCandidateSet &CandidateSet,
2867 bool SuppressUserConversions = false,
2868 bool PartialOverloading = false,
2869 bool AllowExplicit = false,
2870 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
2871 ConversionSequenceList EarlyConversions = None);
2872 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2873 ArrayRef<Expr *> Args,
2874 OverloadCandidateSet &CandidateSet,
2875 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2876 bool SuppressUserConversions = false,
2877 bool PartialOverloading = false,
2878 bool FirstArgumentIsBase = false);
2879 void AddMethodCandidate(DeclAccessPair FoundDecl,
2880 QualType ObjectType,
2881 Expr::Classification ObjectClassification,
2882 ArrayRef<Expr *> Args,
2883 OverloadCandidateSet& CandidateSet,
2884 bool SuppressUserConversion = false);
2885 void AddMethodCandidate(CXXMethodDecl *Method,
2886 DeclAccessPair FoundDecl,
2887 CXXRecordDecl *ActingContext, QualType ObjectType,
2888 Expr::Classification ObjectClassification,
2889 ArrayRef<Expr *> Args,
2890 OverloadCandidateSet& CandidateSet,
2891 bool SuppressUserConversions = false,
2892 bool PartialOverloading = false,
2893 ConversionSequenceList EarlyConversions = None);
2894 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2895 DeclAccessPair FoundDecl,
2896 CXXRecordDecl *ActingContext,
2897 TemplateArgumentListInfo *ExplicitTemplateArgs,
2898 QualType ObjectType,
2899 Expr::Classification ObjectClassification,
2900 ArrayRef<Expr *> Args,
2901 OverloadCandidateSet& CandidateSet,
2902 bool SuppressUserConversions = false,
2903 bool PartialOverloading = false);
2904 void AddTemplateOverloadCandidate(
2905 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
2906 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
2907 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
2908 bool PartialOverloading = false,
2909 ADLCallKind IsADLCandidate = ADLCallKind::NotADL);
2910 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2911 ArrayRef<QualType> ParamTypes,
2912 ArrayRef<Expr *> Args,
2913 OverloadCandidateSet &CandidateSet,
2914 ConversionSequenceList &Conversions,
2915 bool SuppressUserConversions,
2916 CXXRecordDecl *ActingContext = nullptr,
2917 QualType ObjectType = QualType(),
2918 Expr::Classification
2919 ObjectClassification = {});
2920 void AddConversionCandidate(CXXConversionDecl *Conversion,
2921 DeclAccessPair FoundDecl,
2922 CXXRecordDecl *ActingContext,
2923 Expr *From, QualType ToType,
2924 OverloadCandidateSet& CandidateSet,
2925 bool AllowObjCConversionOnExplicit,
2926 bool AllowResultConversion = true);
2927 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2928 DeclAccessPair FoundDecl,
2929 CXXRecordDecl *ActingContext,
2930 Expr *From, QualType ToType,
2931 OverloadCandidateSet &CandidateSet,
2932 bool AllowObjCConversionOnExplicit,
2933 bool AllowResultConversion = true);
2934 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2935 DeclAccessPair FoundDecl,
2936 CXXRecordDecl *ActingContext,
2937 const FunctionProtoType *Proto,
2938 Expr *Object, ArrayRef<Expr *> Args,
2939 OverloadCandidateSet& CandidateSet);
2940 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2941 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2942 OverloadCandidateSet& CandidateSet,
2943 SourceRange OpRange = SourceRange());
2944 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
2945 OverloadCandidateSet& CandidateSet,
2946 bool IsAssignmentOperator = false,
2947 unsigned NumContextualBoolArguments = 0);
2948 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2949 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2950 OverloadCandidateSet& CandidateSet);
2951 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2952 SourceLocation Loc,
2953 ArrayRef<Expr *> Args,
2954 TemplateArgumentListInfo *ExplicitTemplateArgs,
2955 OverloadCandidateSet& CandidateSet,
2956 bool PartialOverloading = false);
2957
2958 // Emit as a 'note' the specific overload candidate
2959 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2960 QualType DestType = QualType(),
2961 bool TakingAddress = false);
2962
2963 // Emit as a series of 'note's all template and non-templates identified by
2964 // the expression Expr
2965 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2966 bool TakingAddress = false);
2967
2968 /// Check the enable_if expressions on the given function. Returns the first
2969 /// failing attribute, or NULL if they were all successful.
2970 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2971 bool MissingImplicitThis = false);
2972
2973 /// Find the failed Boolean condition within a given Boolean
2974 /// constant expression, and describe it with a string.
2975 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
2976
2977 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2978 /// non-ArgDependent DiagnoseIfAttrs.
2979 ///
2980 /// Argument-dependent diagnose_if attributes should be checked each time a
2981 /// function is used as a direct callee of a function call.
2982 ///
2983 /// Returns true if any errors were emitted.
2984 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2985 const Expr *ThisArg,
2986 ArrayRef<const Expr *> Args,
2987 SourceLocation Loc);
2988
2989 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2990 /// ArgDependent DiagnoseIfAttrs.
2991 ///
2992 /// Argument-independent diagnose_if attributes should be checked on every use
2993 /// of a function.
2994 ///
2995 /// Returns true if any errors were emitted.
2996 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
2997 SourceLocation Loc);
2998
2999 /// Returns whether the given function's address can be taken or not,
3000 /// optionally emitting a diagnostic if the address can't be taken.
3001 ///
3002 /// Returns false if taking the address of the function is illegal.
3003 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3004 bool Complain = false,
3005 SourceLocation Loc = SourceLocation());
3006
3007 // [PossiblyAFunctionType] --> [Return]
3008 // NonFunctionType --> NonFunctionType
3009 // R (A) --> R(A)
3010 // R (*)(A) --> R (A)
3011 // R (&)(A) --> R (A)
3012 // R (S::*)(A) --> R (A)
3013 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3014
3015 FunctionDecl *
3016 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3017 QualType TargetType,
3018 bool Complain,
3019 DeclAccessPair &Found,
3020 bool *pHadMultipleCandidates = nullptr);
3021
3022 FunctionDecl *
3023 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
3024 DeclAccessPair &FoundResult);
3025
3026 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
3027 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3028
3029 FunctionDecl *
3030 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3031 bool Complain = false,
3032 DeclAccessPair *Found = nullptr);
3033
3034 bool ResolveAndFixSingleFunctionTemplateSpecialization(
3035 ExprResult &SrcExpr,
3036 bool DoFunctionPointerConverion = false,
3037 bool Complain = false,
3038 SourceRange OpRangeForComplaining = SourceRange(),
3039 QualType DestTypeForComplaining = QualType(),
3040 unsigned DiagIDForComplaining = 0);
3041
3042
3043 Expr *FixOverloadedFunctionReference(Expr *E,
3044 DeclAccessPair FoundDecl,
3045 FunctionDecl *Fn);
3046 ExprResult FixOverloadedFunctionReference(ExprResult,
3047 DeclAccessPair FoundDecl,
3048 FunctionDecl *Fn);
3049
3050 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3051 ArrayRef<Expr *> Args,
3052 OverloadCandidateSet &CandidateSet,
3053 bool PartialOverloading = false);
3054
3055 // An enum used to represent the different possible results of building a
3056 // range-based for loop.
3057 enum ForRangeStatus {
3058 FRS_Success,
3059 FRS_NoViableFunction,
3060 FRS_DiagnosticIssued
3061 };
3062
3063 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3064 SourceLocation RangeLoc,
3065 const DeclarationNameInfo &NameInfo,
3066 LookupResult &MemberLookup,
3067 OverloadCandidateSet *CandidateSet,
3068 Expr *Range, ExprResult *CallExpr);
3069
3070 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3071 UnresolvedLookupExpr *ULE,
3072 SourceLocation LParenLoc,
3073 MultiExprArg Args,
3074 SourceLocation RParenLoc,
3075 Expr *ExecConfig,
3076 bool AllowTypoCorrection=true,
3077 bool CalleesAddressIsTaken=false);
3078
3079 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3080 MultiExprArg Args, SourceLocation RParenLoc,
3081 OverloadCandidateSet *CandidateSet,
3082 ExprResult *Result);
3083
3084 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3085 UnaryOperatorKind Opc,
3086 const UnresolvedSetImpl &Fns,
3087 Expr *input, bool RequiresADL = true);
3088
3089 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3090 BinaryOperatorKind Opc,
3091 const UnresolvedSetImpl &Fns,
3092 Expr *LHS, Expr *RHS,
3093 bool RequiresADL = true);
3094
3095 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3096 SourceLocation RLoc,
3097 Expr *Base,Expr *Idx);
3098
3099 ExprResult
3100 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3101 SourceLocation LParenLoc,
3102 MultiExprArg Args,
3103 SourceLocation RParenLoc);
3104 ExprResult
3105 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3106 MultiExprArg Args,
3107 SourceLocation RParenLoc);
3108
3109 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3110 SourceLocation OpLoc,
3111 bool *NoArrowOperatorFound = nullptr);
3112
3113 /// CheckCallReturnType - Checks that a call expression's return type is
3114 /// complete. Returns true on failure. The location passed in is the location
3115 /// that best represents the call.
3116 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3117 CallExpr *CE, FunctionDecl *FD);
3118
3119 /// Helpers for dealing with blocks and functions.
3120 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3121 bool CheckParameterNames);
3122 void CheckCXXDefaultArguments(FunctionDecl *FD);
3123 void CheckExtraCXXDefaultArguments(Declarator &D);
3124 Scope *getNonFieldDeclScope(Scope *S);
3125
3126 /// \name Name lookup
3127 ///
3128 /// These routines provide name lookup that is used during semantic
3129 /// analysis to resolve the various kinds of names (identifiers,
3130 /// overloaded operator names, constructor names, etc.) into zero or
3131 /// more declarations within a particular scope. The major entry
3132 /// points are LookupName, which performs unqualified name lookup,
3133 /// and LookupQualifiedName, which performs qualified name lookup.
3134 ///
3135 /// All name lookup is performed based on some specific criteria,
3136 /// which specify what names will be visible to name lookup and how
3137 /// far name lookup should work. These criteria are important both
3138 /// for capturing language semantics (certain lookups will ignore
3139 /// certain names, for example) and for performance, since name
3140 /// lookup is often a bottleneck in the compilation of C++. Name
3141 /// lookup criteria is specified via the LookupCriteria enumeration.
3142 ///
3143 /// The results of name lookup can vary based on the kind of name
3144 /// lookup performed, the current language, and the translation
3145 /// unit. In C, for example, name lookup will either return nothing
3146 /// (no entity found) or a single declaration. In C++, name lookup
3147 /// can additionally refer to a set of overloaded functions or
3148 /// result in an ambiguity. All of the possible results of name
3149 /// lookup are captured by the LookupResult class, which provides
3150 /// the ability to distinguish among them.
3151 //@{
3152
3153 /// Describes the kind of name lookup to perform.
3154 enum LookupNameKind {
3155 /// Ordinary name lookup, which finds ordinary names (functions,
3156 /// variables, typedefs, etc.) in C and most kinds of names
3157 /// (functions, variables, members, types, etc.) in C++.
3158 LookupOrdinaryName = 0,
3159 /// Tag name lookup, which finds the names of enums, classes,
3160 /// structs, and unions.
3161 LookupTagName,
3162 /// Label name lookup.
3163 LookupLabel,
3164 /// Member name lookup, which finds the names of
3165 /// class/struct/union members.
3166 LookupMemberName,
3167 /// Look up of an operator name (e.g., operator+) for use with
3168 /// operator overloading. This lookup is similar to ordinary name
3169 /// lookup, but will ignore any declarations that are class members.
3170 LookupOperatorName,
3171 /// Look up of a name that precedes the '::' scope resolution
3172 /// operator in C++. This lookup completely ignores operator, object,
3173 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3174 LookupNestedNameSpecifierName,
3175 /// Look up a namespace name within a C++ using directive or
3176 /// namespace alias definition, ignoring non-namespace names (C++
3177 /// [basic.lookup.udir]p1).
3178 LookupNamespaceName,
3179 /// Look up all declarations in a scope with the given name,
3180 /// including resolved using declarations. This is appropriate
3181 /// for checking redeclarations for a using declaration.
3182 LookupUsingDeclName,
3183 /// Look up an ordinary name that is going to be redeclared as a
3184 /// name with linkage. This lookup ignores any declarations that
3185 /// are outside of the current scope unless they have linkage. See
3186 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3187 LookupRedeclarationWithLinkage,
3188 /// Look up a friend of a local class. This lookup does not look
3189 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3190 LookupLocalFriendName,
3191 /// Look up the name of an Objective-C protocol.
3192 LookupObjCProtocolName,
3193 /// Look up implicit 'self' parameter of an objective-c method.
3194 LookupObjCImplicitSelfParam,
3195 /// Look up the name of an OpenMP user-defined reduction operation.
3196 LookupOMPReductionName,
3197 /// Look up the name of an OpenMP user-defined mapper.
3198 LookupOMPMapperName,
3199 /// Look up any declaration with any name.
3200 LookupAnyName
3201 };
3202
3203 /// Specifies whether (or how) name lookup is being performed for a
3204 /// redeclaration (vs. a reference).
3205 enum RedeclarationKind {
3206 /// The lookup is a reference to this name that is not for the
3207 /// purpose of redeclaring the name.
3208 NotForRedeclaration = 0,
3209 /// The lookup results will be used for redeclaration of a name,
3210 /// if an entity by that name already exists and is visible.
3211 ForVisibleRedeclaration,
3212 /// The lookup results will be used for redeclaration of a name
3213 /// with external linkage; non-visible lookup results with external linkage
3214 /// may also be found.
3215 ForExternalRedeclaration
3216 };
3217
3218 RedeclarationKind forRedeclarationInCurContext() {
3219 // A declaration with an owning module for linkage can never link against
3220 // anything that is not visible. We don't need to check linkage here; if
3221 // the context has internal linkage, redeclaration lookup won't find things
3222 // from other TUs, and we can't safely compute linkage yet in general.
3223 if (cast<Decl>(CurContext)
3224 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3225 return ForVisibleRedeclaration;
3226 return ForExternalRedeclaration;
3227 }
3228
3229 /// The possible outcomes of name lookup for a literal operator.
3230 enum LiteralOperatorLookupResult {
3231 /// The lookup resulted in an error.
3232 LOLR_Error,
3233 /// The lookup found no match but no diagnostic was issued.
3234 LOLR_ErrorNoDiagnostic,
3235 /// The lookup found a single 'cooked' literal operator, which
3236 /// expects a normal literal to be built and passed to it.
3237 LOLR_Cooked,
3238 /// The lookup found a single 'raw' literal operator, which expects
3239 /// a string literal containing the spelling of the literal token.
3240 LOLR_Raw,
3241 /// The lookup found an overload set of literal operator templates,
3242 /// which expect the characters of the spelling of the literal token to be
3243 /// passed as a non-type template argument pack.
3244 LOLR_Template,
3245 /// The lookup found an overload set of literal operator templates,
3246 /// which expect the character type and characters of the spelling of the
3247 /// string literal token to be passed as template arguments.
3248 LOLR_StringTemplate
3249 };
3250
3251 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3252 CXXSpecialMember SM,
3253 bool ConstArg,
3254 bool VolatileArg,
3255 bool RValueThis,
3256 bool ConstThis,
3257 bool VolatileThis);
3258
3259 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3260 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3261 TypoRecoveryCallback;
3262
3263private:
3264 bool CppLookupName(LookupResult &R, Scope *S);
3265
3266 struct TypoExprState {
3267 std::unique_ptr<TypoCorrectionConsumer> Consumer;
3268 TypoDiagnosticGenerator DiagHandler;
3269 TypoRecoveryCallback RecoveryHandler;
3270 TypoExprState();
3271 TypoExprState(TypoExprState &&other) noexcept;
3272 TypoExprState &operator=(TypoExprState &&other) noexcept;
3273 };
3274
3275 /// The set of unhandled TypoExprs and their associated state.
3276 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3277
3278 /// Creates a new TypoExpr AST node.
3279 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3280 TypoDiagnosticGenerator TDG,
3281 TypoRecoveryCallback TRC);
3282
3283 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
3284 //
3285 // The boolean value will be true to indicate that the namespace was loaded
3286 // from an AST/PCH file, or false otherwise.
3287 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3288
3289 /// Whether we have already loaded known namespaces from an extenal
3290 /// source.
3291 bool LoadedExternalKnownNamespaces;
3292
3293 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
3294 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3295 /// should be skipped entirely.
3296 std::unique_ptr<TypoCorrectionConsumer>
3297 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3298 Sema::LookupNameKind LookupKind, Scope *S,
3299 CXXScopeSpec *SS,
3300 CorrectionCandidateCallback &CCC,
3301 DeclContext *MemberContext, bool EnteringContext,
3302 const ObjCObjectPointerType *OPT,
3303 bool ErrorRecovery);
3304
3305public:
3306 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3307
3308 /// Clears the state of the given TypoExpr.
3309 void clearDelayedTypo(TypoExpr *TE);
3310
3311 /// Look up a name, looking for a single declaration. Return
3312 /// null if the results were absent, ambiguous, or overloaded.
3313 ///
3314 /// It is preferable to use the elaborated form and explicitly handle
3315 /// ambiguity and overloaded.
3316 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3317 SourceLocation Loc,
3318 LookupNameKind NameKind,
3319 RedeclarationKind Redecl
3320 = NotForRedeclaration);
3321 bool LookupName(LookupResult &R, Scope *S,
3322 bool AllowBuiltinCreation = false);
3323 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3324 bool InUnqualifiedLookup = false);
3325 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3326 CXXScopeSpec &SS);
3327 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3328 bool AllowBuiltinCreation = false,
3329 bool EnteringContext = false);
3330 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3331 RedeclarationKind Redecl
3332 = NotForRedeclaration);
3333 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3334
3335 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3336 QualType T1, QualType T2,
3337 UnresolvedSetImpl &Functions);
3338
3339 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3340 SourceLocation GnuLabelLoc = SourceLocation());
3341
3342 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3343 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3344 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3345 unsigned Quals);
3346 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3347 bool RValueThis, unsigned ThisQuals);
3348 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3349 unsigned Quals);
3350 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3351 bool RValueThis, unsigned ThisQuals);
3352 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3353
3354 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3355 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3356 ArrayRef<QualType> ArgTys,
3357 bool AllowRaw,
3358 bool AllowTemplate,
3359 bool AllowStringTemplate,
3360 bool DiagnoseMissing);
3361 bool isKnownName(StringRef name);
3362
3363 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3364 ArrayRef<Expr *> Args, ADLResult &Functions);
3365
3366 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3367 VisibleDeclConsumer &Consumer,
3368 bool IncludeGlobalScope = true,
3369 bool LoadExternal = true);
3370 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3371 VisibleDeclConsumer &Consumer,
3372 bool IncludeGlobalScope = true,
3373 bool IncludeDependentBases = false,
3374 bool LoadExternal = true);
3375
3376 enum CorrectTypoKind {
3377 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3378 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3379 };
3380
3381 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3382 Sema::LookupNameKind LookupKind,
3383 Scope *S, CXXScopeSpec *SS,
3384 CorrectionCandidateCallback &CCC,
3385 CorrectTypoKind Mode,
3386 DeclContext *MemberContext = nullptr,
3387 bool EnteringContext = false,
3388 const ObjCObjectPointerType *OPT = nullptr,
3389 bool RecordFailure = true);
3390
3391 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3392 Sema::LookupNameKind LookupKind, Scope *S,
3393 CXXScopeSpec *SS,
3394 CorrectionCandidateCallback &CCC,
3395 TypoDiagnosticGenerator TDG,
3396 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3397 DeclContext *MemberContext = nullptr,
3398 bool EnteringContext = false,
3399 const ObjCObjectPointerType *OPT = nullptr);
3400
3401 /// Process any TypoExprs in the given Expr and its children,
3402 /// generating diagnostics as appropriate and returning a new Expr if there
3403 /// were typos that were all successfully corrected and ExprError if one or
3404 /// more typos could not be corrected.
3405 ///
3406 /// \param E The Expr to check for TypoExprs.
3407 ///
3408 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3409 /// initializer.
3410 ///
3411 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3412 /// it is an acceptable/usable result from a single combination of typo
3413 /// corrections. As long as the filter returns ExprError, different
3414 /// combinations of corrections will be tried until all are exhausted.
3415 ExprResult
3416 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3417 llvm::function_ref<ExprResult(Expr *)> Filter =
3418 [](Expr *E) -> ExprResult { return E; });
3419
3420 ExprResult
3421 CorrectDelayedTyposInExpr(Expr *E,
3422 llvm::function_ref<ExprResult(Expr *)> Filter) {
3423 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3424 }
3425
3426 ExprResult
3427 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3428 llvm::function_ref<ExprResult(Expr *)> Filter =
3429 [](Expr *E) -> ExprResult { return E; }) {
3430 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3431 }
3432
3433 ExprResult
3434 CorrectDelayedTyposInExpr(ExprResult ER,
3435 llvm::function_ref<ExprResult(Expr *)> Filter) {
3436 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3437 }
3438
3439 void diagnoseTypo(const TypoCorrection &Correction,
3440 const PartialDiagnostic &TypoDiag,
3441 bool ErrorRecovery = true);
3442
3443 void diagnoseTypo(const TypoCorrection &Correction,
3444 const PartialDiagnostic &TypoDiag,
3445 const PartialDiagnostic &PrevNote,
3446 bool ErrorRecovery = true);
3447
3448 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3449
3450 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3451 ArrayRef<Expr *> Args,
3452 AssociatedNamespaceSet &AssociatedNamespaces,
3453 AssociatedClassSet &AssociatedClasses);
3454
3455 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3456 bool ConsiderLinkage, bool AllowInlineNamespace);
3457
3458 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3459
3460 void DiagnoseAmbiguousLookup(LookupResult &Result);
3461 //@}
3462
3463 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3464 SourceLocation IdLoc,
3465 bool TypoCorrection = false);
3466 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3467 Scope *S, bool ForRedeclaration,
3468 SourceLocation Loc);
3469 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3470 Scope *S);
3471 void AddKnownFunctionAttributes(FunctionDecl *FD);
3472
3473 // More parsing and symbol table subroutines.
3474
3475 void ProcessPragmaWeak(Scope *S, Decl *D);
3476 // Decl attributes - this routine is the top level dispatcher.
3477 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3478 // Helper for delayed processing of attributes.
3479 void ProcessDeclAttributeDelayed(Decl *D,
3480 const ParsedAttributesView &AttrList);
3481 void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
3482 bool IncludeCXX11Attributes = true);
3483 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3484 const ParsedAttributesView &AttrList);
3485
3486 void checkUnusedDeclAttributes(Declarator &D);
3487
3488 /// Determine if type T is a valid subject for a nonnull and similar
3489 /// attributes. By default, we look through references (the behavior used by
3490 /// nonnull), but if the second parameter is true, then we treat a reference
3491 /// type as valid.
3492 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3493
3494 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
3495 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
3496 const FunctionDecl *FD = nullptr);
3497 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
3498 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
3499 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
3500 StringRef &Str,
3501 SourceLocation *ArgLocation = nullptr);
3502 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3503 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3504 bool checkMSInheritanceAttrOnDefinition(
3505 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3506 MSInheritanceAttr::Spelling SemanticSpelling);
3507
3508 void CheckAlignasUnderalignment(Decl *D);
3509
3510 /// Adjust the calling convention of a method to be the ABI default if it
3511 /// wasn't specified explicitly. This handles method types formed from
3512 /// function type typedefs and typename template arguments.
3513 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3514 SourceLocation Loc);
3515
3516 // Check if there is an explicit attribute, but only look through parens.
3517 // The intent is to look for an attribute on the current declarator, but not
3518 // one that came from a typedef.
3519 bool hasExplicitCallingConv(QualType &T);
3520
3521 /// Get the outermost AttributedType node that sets a calling convention.
3522 /// Valid types should not have multiple attributes with different CCs.
3523 const AttributedType *getCallingConvAttributedType(QualType T) const;
3524
3525 /// Stmt attributes - this routine is the top level dispatcher.
3526 StmtResult ProcessStmtAttributes(Stmt *Stmt,
3527 const ParsedAttributesView &Attrs,
3528 SourceRange Range);
3529
3530 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3531 ObjCMethodDecl *MethodDecl,
3532 bool IsProtocolMethodDecl);
3533
3534 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3535 ObjCMethodDecl *Overridden,
3536 bool IsProtocolMethodDecl);
3537
3538 /// WarnExactTypedMethods - This routine issues a warning if method
3539 /// implementation declaration matches exactly that of its declaration.
3540 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3541 ObjCMethodDecl *MethodDecl,
3542 bool IsProtocolMethodDecl);
3543
3544 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3545
3546 /// CheckImplementationIvars - This routine checks if the instance variables
3547 /// listed in the implelementation match those listed in the interface.
3548 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3549 ObjCIvarDecl **Fields, unsigned nIvars,
3550 SourceLocation Loc);
3551
3552 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3553 /// remains unimplemented in the class or category \@implementation.
3554 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3555 ObjCContainerDecl* IDecl,
3556 bool IncompleteImpl = false);
3557
3558 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3559 /// which must be implemented by this implementation.
3560 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3561 ObjCContainerDecl *CDecl,
3562 bool SynthesizeProperties);
3563
3564 /// Diagnose any null-resettable synthesized setters.
3565 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3566
3567 /// DefaultSynthesizeProperties - This routine default synthesizes all
3568 /// properties which must be synthesized in the class's \@implementation.
3569 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3570 ObjCInterfaceDecl *IDecl,
3571 SourceLocation AtEnd);
3572 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3573
3574 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3575 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3576 /// declared in class 'IFace'.
3577 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3578 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3579
3580 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3581 /// backs the property is not used in the property's accessor.
3582 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3583 const ObjCImplementationDecl *ImplD);
3584
3585 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3586 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3587 /// It also returns ivar's property on success.
3588 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3589 const ObjCPropertyDecl *&PDecl) const;
3590
3591 /// Called by ActOnProperty to handle \@property declarations in
3592 /// class extensions.
3593 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3594 SourceLocation AtLoc,
3595 SourceLocation LParenLoc,
3596 FieldDeclarator &FD,
3597 Selector GetterSel,
3598 SourceLocation GetterNameLoc,
3599 Selector SetterSel,
3600 SourceLocation SetterNameLoc,
3601 const bool isReadWrite,
3602 unsigned &Attributes,
3603 const unsigned AttributesAsWritten,
3604 QualType T,
3605 TypeSourceInfo *TSI,
3606 tok::ObjCKeywordKind MethodImplKind);
3607
3608 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3609 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3610 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3611 ObjCContainerDecl *CDecl,
3612 SourceLocation AtLoc,
3613 SourceLocation LParenLoc,
3614 FieldDeclarator &FD,
3615 Selector GetterSel,
3616 SourceLocation GetterNameLoc,
3617 Selector SetterSel,
3618 SourceLocation SetterNameLoc,
3619 const bool isReadWrite,
3620 const unsigned Attributes,
3621 const unsigned AttributesAsWritten,
3622 QualType T,
3623 TypeSourceInfo *TSI,
3624 tok::ObjCKeywordKind MethodImplKind,
3625 DeclContext *lexicalDC = nullptr);
3626
3627 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3628 /// warning) when atomic property has one but not the other user-declared
3629 /// setter or getter.
3630 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3631 ObjCInterfaceDecl* IDecl);
3632
3633 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3634
3635 void DiagnoseMissingDesignatedInitOverrides(
3636 const ObjCImplementationDecl *ImplD,
3637 const ObjCInterfaceDecl *IFD);
3638
3639 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3640
3641 enum MethodMatchStrategy {
3642 MMS_loose,
3643 MMS_strict
3644 };
3645
3646 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3647 /// true, or false, accordingly.
3648 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3649 const ObjCMethodDecl *PrevMethod,
3650 MethodMatchStrategy strategy = MMS_strict);
3651
3652 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3653 /// or protocol against those declared in their implementations.
3654 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3655 const SelectorSet &ClsMap,
3656 SelectorSet &InsMapSeen,
3657 SelectorSet &ClsMapSeen,
3658 ObjCImplDecl* IMPDecl,
3659 ObjCContainerDecl* IDecl,
3660 bool &IncompleteImpl,
3661 bool ImmediateClass,
3662 bool WarnCategoryMethodImpl=false);
3663
3664 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3665 /// category matches with those implemented in its primary class and
3666 /// warns each time an exact match is found.
3667 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3668
3669 /// Add the given method to the list of globally-known methods.
3670 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3671
3672private:
3673 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3674 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3675 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3676
3677 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3678 /// optionally warns if there are multiple signatures.
3679 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3680 bool receiverIdOrClass,
3681 bool instance);
3682
3683public:
3684 /// - Returns instance or factory methods in global method pool for
3685 /// given selector. It checks the desired kind first, if none is found, and
3686 /// parameter checkTheOther is set, it then checks the other kind. If no such
3687 /// method or only one method is found, function returns false; otherwise, it
3688 /// returns true.
3689 bool
3690 CollectMultipleMethodsInGlobalPool(Selector Sel,
3691 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3692 bool InstanceFirst, bool CheckTheOther,
3693 const ObjCObjectType *TypeBound = nullptr);
3694
3695 bool
3696 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3697 SourceRange R, bool receiverIdOrClass,
3698 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3699
3700 void
3701 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3702 Selector Sel, SourceRange R,
3703 bool receiverIdOrClass);
3704
3705private:
3706 /// - Returns a selector which best matches given argument list or
3707 /// nullptr if none could be found
3708 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3709 bool IsInstance,
3710 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3711
3712
3713 /// Record the typo correction failure and return an empty correction.
3714 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3715 bool RecordFailure = true) {
3716 if (RecordFailure)
3717 TypoCorrectionFailures[Typo].insert(TypoLoc);
3718 return TypoCorrection();
3719 }
3720
3721public:
3722 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3723 /// unit are added to a global pool. This allows us to efficiently associate
3724 /// a selector with a method declaraation for purposes of typechecking
3725 /// messages sent to "id" (where the class of the object is unknown).
3726 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3727 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3728 }
3729
3730 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3731 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3732 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3733 }
3734
3735 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3736 /// pool.
3737 void AddAnyMethodToGlobalPool(Decl *D);
3738
3739 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3740 /// there are multiple signatures.
3741 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3742 bool receiverIdOrClass=false) {
3743 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3744 /*instance*/true);
3745 }
3746
3747 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3748 /// there are multiple signatures.
3749 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3750 bool receiverIdOrClass=false) {
3751 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3752 /*instance*/false);
3753 }
3754
3755 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3756 QualType ObjectType=QualType());
3757 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3758 /// implementation.
3759 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3760
3761 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3762 /// initialization.
3763 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3764 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3765
3766 //===--------------------------------------------------------------------===//
3767 // Statement Parsing Callbacks: SemaStmt.cpp.
3768public:
3769 class FullExprArg {
3770 public:
3771 FullExprArg() : E(nullptr) { }
3772 FullExprArg(Sema &actions) : E(nullptr) { }
3773
3774 ExprResult release() {
3775 return E;
3776 }
3777
3778 Expr *get() const { return E; }
3779
3780 Expr *operator->() {
3781 return E;
3782 }
3783
3784 private:
3785 // FIXME: No need to make the entire Sema class a friend when it's just
3786 // Sema::MakeFullExpr that needs access to the constructor below.
3787 friend class Sema;
3788
3789 explicit FullExprArg(Expr *expr) : E(expr) {}
3790
3791 Expr *E;
3792 };
3793
3794 FullExprArg MakeFullExpr(Expr *Arg) {
3795 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3796 }
3797 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3798 return FullExprArg(
3799 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
3800 }
3801 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3802 ExprResult FE =
3803 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3804 /*DiscardedValue*/ true);
3805 return FullExprArg(FE.get());
3806 }
3807
3808 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
3809 StmtResult ActOnExprStmtError();
3810
3811 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3812 bool HasLeadingEmptyMacro = false);
3813
3814 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
3815 void ActOnFinishOfCompoundStmt();
3816 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3817 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3818
3819 /// A RAII object to enter scope of a compound statement.
3820 class CompoundScopeRAII {
3821 public:
3822 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
3823 S.ActOnStartOfCompoundStmt(IsStmtExpr);
3824 }
3825
3826 ~CompoundScopeRAII() {
3827 S.ActOnFinishOfCompoundStmt();
3828 }
3829
3830 private:
3831 Sema &S;
3832 };
3833
3834 /// An RAII helper that pops function a function scope on exit.
3835 struct FunctionScopeRAII {
3836 Sema &S;
3837 bool Active;
3838 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3839 ~FunctionScopeRAII() {
3840 if (Active)
3841 S.PopFunctionScopeInfo();
3842 }
3843 void disable() { Active = false; }
3844 };
3845
3846 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3847 SourceLocation StartLoc,
3848 SourceLocation EndLoc);
3849 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3850 StmtResult ActOnForEachLValueExpr(Expr *E);
3851 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
3852 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
3853 SourceLocation DotDotDotLoc, ExprResult RHS,
3854 SourceLocation ColonLoc);
3855 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3856
3857 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3858 SourceLocation ColonLoc,
3859 Stmt *SubStmt, Scope *CurScope);
3860 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3861 SourceLocation ColonLoc, Stmt *SubStmt);
3862
3863 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3864 ArrayRef<const Attr*> Attrs,
3865 Stmt *SubStmt);
3866
3867 class ConditionResult;
3868 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3869 Stmt *InitStmt,
3870 ConditionResult Cond, Stmt *ThenVal,
3871 SourceLocation ElseLoc, Stmt *ElseVal);
3872 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3873 Stmt *InitStmt,
3874 ConditionResult Cond, Stmt *ThenVal,
3875 SourceLocation ElseLoc, Stmt *ElseVal);
3876 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3877 Stmt *InitStmt,
3878 ConditionResult Cond);
3879 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3880 Stmt *Switch, Stmt *Body);
3881 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3882 Stmt *Body);
3883 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3884 SourceLocation WhileLoc, SourceLocation CondLParen,
3885 Expr *Cond, SourceLocation CondRParen);
3886
3887 StmtResult ActOnForStmt(SourceLocation ForLoc,
3888 SourceLocation LParenLoc,
3889 Stmt *First,
3890 ConditionResult Second,
3891 FullExprArg Third,
3892 SourceLocation RParenLoc,
3893 Stmt *Body);
3894 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3895 Expr *collection);
3896 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3897 Stmt *First, Expr *collection,
3898 SourceLocation RParenLoc);
3899 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3900
3901 enum BuildForRangeKind {
3902 /// Initial building of a for-range statement.
3903 BFRK_Build,
3904 /// Instantiation or recovery rebuild of a for-range statement. Don't
3905 /// attempt any typo-correction.
3906 BFRK_Rebuild,
3907 /// Determining whether a for-range statement could be built. Avoid any
3908 /// unnecessary or irreversible actions.
3909 BFRK_Check
3910 };
3911
3912 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3913 SourceLocation CoawaitLoc,
3914 Stmt *InitStmt,
3915 Stmt *LoopVar,
3916 SourceLocation ColonLoc, Expr *Collection,
3917 SourceLocation RParenLoc,
3918 BuildForRangeKind Kind);
3919 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3920 SourceLocation CoawaitLoc,
3921 Stmt *InitStmt,
3922 SourceLocation ColonLoc,
3923 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3924 Expr *Cond, Expr *Inc,
3925 Stmt *LoopVarDecl,
3926 SourceLocation RParenLoc,
3927 BuildForRangeKind Kind);
3928 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3929
3930 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3931 SourceLocation LabelLoc,
3932 LabelDecl *TheDecl);
3933 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3934 SourceLocation StarLoc,
3935 Expr *DestExp);
3936 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3937 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3938
3939 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3940 CapturedRegionKind Kind, unsigned NumParams);
3941 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3942 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3943 CapturedRegionKind Kind,
3944 ArrayRef<CapturedParamNameType> Params);
3945 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3946 void ActOnCapturedRegionError();
3947 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3948 SourceLocation Loc,
3949 unsigned NumParams);
3950
3951 enum CopyElisionSemanticsKind {
3952 CES_Strict = 0,
3953 CES_AllowParameters = 1,
3954 CES_AllowDifferentTypes = 2,
3955 CES_AllowExceptionVariables = 4,
3956 CES_FormerDefault = (CES_AllowParameters),
3957 CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
3958 CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
3959 CES_AllowExceptionVariables),
3960 };
3961
3962 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3963 CopyElisionSemanticsKind CESK);
3964 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3965 CopyElisionSemanticsKind CESK);
3966
3967 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3968 Scope *CurScope);
3969 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3970 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3971
3972 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3973 bool IsVolatile, unsigned NumOutputs,
3974 unsigned NumInputs, IdentifierInfo **Names,
3975 MultiExprArg Constraints, MultiExprArg Exprs,
3976 Expr *AsmString, MultiExprArg Clobbers,
3977 SourceLocation RParenLoc);
3978
3979 void FillInlineAsmIdentifierInfo(Expr *Res,
3980 llvm::InlineAsmIdentifierInfo &Info);
3981 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3982 SourceLocation TemplateKWLoc,
3983 UnqualifiedId &Id,
3984 bool IsUnevaluatedContext);
3985 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3986 unsigned &Offset, SourceLocation AsmLoc);
3987 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3988 SourceLocation AsmLoc);
3989 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3990 ArrayRef<Token> AsmToks,
3991 StringRef AsmString,
3992 unsigned NumOutputs, unsigned NumInputs,
3993 ArrayRef<StringRef> Constraints,
3994 ArrayRef<StringRef> Clobbers,
3995 ArrayRef<Expr*> Exprs,
3996 SourceLocation EndLoc);
3997 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3998 SourceLocation Location,
3999 bool AlwaysCreate);
4000
4001 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4002 SourceLocation StartLoc,
4003 SourceLocation IdLoc, IdentifierInfo *Id,
4004 bool Invalid = false);
4005
4006 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4007
4008 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4009 Decl *Parm, Stmt *Body);
4010
4011 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4012
4013 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4014 MultiStmtArg Catch, Stmt *Finally);
4015
4016 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4017 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4018 Scope *CurScope);
4019 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4020 Expr *operand);
4021 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4022 Expr *SynchExpr,
4023 Stmt *SynchBody);
4024
4025 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4026
4027 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4028 SourceLocation StartLoc,
4029 SourceLocation IdLoc,
4030 IdentifierInfo *Id);
4031
4032 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4033
4034 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4035 Decl *ExDecl, Stmt *HandlerBlock);
4036 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4037 ArrayRef<Stmt *> Handlers);
4038
4039 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4040 SourceLocation TryLoc, Stmt *TryBlock,
4041 Stmt *Handler);
4042 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4043 Expr *FilterExpr,
4044 Stmt *Block);
4045 void ActOnStartSEHFinallyBlock();
4046 void ActOnAbortSEHFinallyBlock();
4047 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4048 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4049
4050 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4051
4052 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4053
4054 /// If it's a file scoped decl that must warn if not used, keep track
4055 /// of it.
4056 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4057
4058 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4059 /// whose result is unused, warn.
4060 void DiagnoseUnusedExprResult(const Stmt *S);
4061 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4062 void DiagnoseUnusedDecl(const NamedDecl *ND);
4063
4064 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4065 /// statement as a \p Body, and it is located on the same line.
4066 ///
4067 /// This helps prevent bugs due to typos, such as:
4068 /// if (condition);
4069 /// do_stuff();
4070 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4071 const Stmt *Body,
4072 unsigned DiagID);
4073
4074 /// Warn if a for/while loop statement \p S, which is followed by
4075 /// \p PossibleBody, has a suspicious null statement as a body.
4076 void DiagnoseEmptyLoopBody(const Stmt *S,
4077 const Stmt *PossibleBody);
4078
4079 /// Warn if a value is moved to itself.
4080 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4081 SourceLocation OpLoc);
4082
4083 /// Warn if we're implicitly casting from a _Nullable pointer type to a
4084 /// _Nonnull one.
4085 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4086 SourceLocation Loc);
4087
4088 /// Warn when implicitly casting 0 to nullptr.
4089 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4090
4091 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
4092 return DelayedDiagnostics.push(pool);
4093 }
4094 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4095
4096 typedef ProcessingContextState ParsingClassState;
4097 ParsingClassState PushParsingClass() {
4098 return DelayedDiagnostics.pushUndelayed();
4099 }
4100 void PopParsingClass(ParsingClassState state) {
4101 DelayedDiagnostics.popUndelayed(state);
4102 }
4103
4104 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4105
4106 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4107 const ObjCInterfaceDecl *UnknownObjCClass,
4108 bool ObjCPropertyAccess,
4109 bool AvoidPartialAvailabilityChecks = false,
4110 ObjCInterfaceDecl *ClassReceiver = nullptr);
4111
4112 bool makeUnavailableInSystemHeader(SourceLocation loc,
4113 UnavailableAttr::ImplicitReason reason);
4114
4115 /// Issue any -Wunguarded-availability warnings in \c FD
4116 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4117
4118 //===--------------------------------------------------------------------===//
4119 // Expression Parsing Callbacks: SemaExpr.cpp.
4120
4121 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4122 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4123 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4124 bool ObjCPropertyAccess = false,
4125 bool AvoidPartialAvailabilityChecks = false,
4126 ObjCInterfaceDecl *ClassReciever = nullptr);
4127 void NoteDeletedFunction(FunctionDecl *FD);
4128 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4129 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4130 ObjCMethodDecl *Getter,
4131 SourceLocation Loc);
4132 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4133 ArrayRef<Expr *> Args);
4134
4135 void PushExpressionEvaluationContext(
4136 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4137 ExpressionEvaluationContextRecord::ExpressionKind Type =
4138 ExpressionEvaluationContextRecord::EK_Other);
4139 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4140 void PushExpressionEvaluationContext(
4141 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
4142 ExpressionEvaluationContextRecord::ExpressionKind Type =
4143 ExpressionEvaluationContextRecord::EK_Other);
4144 void PopExpressionEvaluationContext();
4145
4146 void DiscardCleanupsInEvaluationContext();
4147
4148 ExprResult TransformToPotentiallyEvaluated(Expr *E);
4149 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4150
4151 ExprResult ActOnConstantExpression(ExprResult Res);
4152
4153 // Functions for marking a declaration referenced. These functions also
4154 // contain the relevant logic for marking if a reference to a function or
4155 // variable is an odr-use (in the C++11 sense). There are separate variants
4156 // for expressions referring to a decl; these exist because odr-use marking
4157 // needs to be delayed for some constant variables when we build one of the
4158 // named expressions.
4159 //
4160 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4161 // should usually be true. This only needs to be set to false if the lack of
4162 // odr-use cannot be determined from the current context (for instance,
4163 // because the name denotes a virtual function and was written without an
4164 // explicit nested-name-specifier).
4165 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4166 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4167 bool MightBeOdrUse = true);
4168 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4169 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4170 void MarkMemberReferenced(MemberExpr *E);
4171
4172 void UpdateMarkingForLValueToRValue(Expr *E);
4173 void CleanupVarDeclMarking();
4174
4175 enum TryCaptureKind {
4176 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4177 };
4178
4179 /// Try to capture the given variable.
4180 ///
4181 /// \param Var The variable to capture.
4182 ///
4183 /// \param Loc The location at which the capture occurs.
4184 ///
4185 /// \param Kind The kind of capture, which may be implicit (for either a
4186 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4187 ///
4188 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4189 /// an explicit lambda capture.
4190 ///
4191 /// \param BuildAndDiagnose Whether we are actually supposed to add the
4192 /// captures or diagnose errors. If false, this routine merely check whether
4193 /// the capture can occur without performing the capture itself or complaining
4194 /// if the variable cannot be captured.
4195 ///
4196 /// \param CaptureType Will be set to the type of the field used to capture
4197 /// this variable in the innermost block or lambda. Only valid when the
4198 /// variable can be captured.
4199 ///
4200 /// \param DeclRefType Will be set to the type of a reference to the capture
4201 /// from within the current scope. Only valid when the variable can be
4202 /// captured.
4203 ///
4204 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4205 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4206 /// This is useful when enclosing lambdas must speculatively capture
4207 /// variables that may or may not be used in certain specializations of
4208 /// a nested generic lambda.
4209 ///
4210 /// \returns true if an error occurred (i.e., the variable cannot be
4211 /// captured) and false if the capture succeeded.
4212 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4213 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4214 QualType &CaptureType,
4215 QualType &DeclRefType,
4216 const unsigned *const FunctionScopeIndexToStopAt);
4217
4218 /// Try to capture the given variable.
4219 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4220 TryCaptureKind Kind = TryCapture_Implicit,
4221 SourceLocation EllipsisLoc = SourceLocation());
4222
4223 /// Checks if the variable must be captured.
4224 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4225
4226 /// Given a variable, determine the type that a reference to that
4227 /// variable will have in the given scope.
4228 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4229
4230 /// Mark all of the declarations referenced within a particular AST node as
4231 /// referenced. Used when template instantiation instantiates a non-dependent
4232 /// type -- entities referenced by the type are now referenced.
4233 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4234 void MarkDeclarationsReferencedInExpr(Expr *E,
4235 bool SkipLocalVariables = false);
4236
4237 /// Try to recover by turning the given expression into a
4238 /// call. Returns true if recovery was attempted or an error was
4239 /// emitted; this may also leave the ExprResult invalid.
4240 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4241 bool ForceComplain = false,
4242 bool (*IsPlausibleResult)(QualType) = nullptr);
4243
4244 /// Figure out if an expression could be turned into a call.
4245 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4246 UnresolvedSetImpl &NonTemplateOverloads);
4247
4248 /// Conditionally issue a diagnostic based on the current
4249 /// evaluation context.
4250 ///
4251 /// \param Statement If Statement is non-null, delay reporting the
4252 /// diagnostic until the function body is parsed, and then do a basic
4253 /// reachability analysis to determine if the statement is reachable.
4254 /// If it is unreachable, the diagnostic will not be emitted.
4255 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4256 const PartialDiagnostic &PD);
4257
4258 // Primary Expressions.
4259 SourceRange getExprRange(Expr *E) const;
4260
4261 ExprResult ActOnIdExpression(
4262 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4263 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4264 CorrectionCandidateCallback *CCC = nullptr,
4265 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4266
4267 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4268 TemplateArgumentListInfo &Buffer,
4269 DeclarationNameInfo &NameInfo,
4270 const TemplateArgumentListInfo *&TemplateArgs);
4271
4272 bool
4273 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4274 CorrectionCandidateCallback &CCC,
4275 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4276 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4277
4278 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4279 IdentifierInfo *II,
4280 bool AllowBuiltinCreation=false);
4281
4282 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4283 SourceLocation TemplateKWLoc,
4284 const DeclarationNameInfo &NameInfo,
4285 bool isAddressOfOperand,
4286 const TemplateArgumentListInfo *TemplateArgs);
4287
4288 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
4289 ExprValueKind VK,
4290 SourceLocation Loc,
4291 const CXXScopeSpec *SS = nullptr);
4292 ExprResult
4293 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4294 const DeclarationNameInfo &NameInfo,
4295 const CXXScopeSpec *SS = nullptr,
4296 NamedDecl *FoundD = nullptr,
4297 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4298 ExprResult
4299 BuildAnonymousStructUnionMemberReference(
4300 const CXXScopeSpec &SS,
4301 SourceLocation nameLoc,
4302 IndirectFieldDecl *indirectField,
4303 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4304 Expr *baseObjectExpr = nullptr,
4305 SourceLocation opLoc = SourceLocation());
4306
4307 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4308 SourceLocation TemplateKWLoc,
4309 LookupResult &R,
4310 const TemplateArgumentListInfo *TemplateArgs,
4311 const Scope *S);
4312 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4313 SourceLocation TemplateKWLoc,
4314 LookupResult &R,
4315 const TemplateArgumentListInfo *TemplateArgs,
4316 bool IsDefiniteInstance,
4317 const Scope *S);
4318 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4319 const LookupResult &R,
4320 bool HasTrailingLParen);
4321
4322 ExprResult
4323 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4324 const DeclarationNameInfo &NameInfo,
4325 bool IsAddressOfOperand, const Scope *S,
4326 TypeSourceInfo **RecoveryTSI = nullptr);
4327
4328 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4329 SourceLocation TemplateKWLoc,
4330 const DeclarationNameInfo &NameInfo,
4331 const TemplateArgumentListInfo *TemplateArgs);
4332
4333 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4334 LookupResult &R,
4335 bool NeedsADL,
4336 bool AcceptInvalidDecl = false);
4337 ExprResult BuildDeclarationNameExpr(
4338 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4339 NamedDecl *FoundD = nullptr,
4340 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4341 bool AcceptInvalidDecl = false);
4342
4343 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4344 DeclarationNameInfo &SuffixInfo,
4345 ArrayRef<Expr *> Args,
4346 SourceLocation LitEndLoc,
4347 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4348
4349 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4350 PredefinedExpr::IdentKind IK);
4351 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4352 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4353
4354 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4355
4356 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4357 ExprResult ActOnCharacterConstant(const Token &Tok,
4358 Scope *UDLScope = nullptr);
4359 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4360 ExprResult ActOnParenListExpr(SourceLocation L,
4361 SourceLocation R,
4362 MultiExprArg Val);
4363
4364 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4365 /// fragments (e.g. "foo" "bar" L"baz").
4366 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4367 Scope *UDLScope = nullptr);
4368
4369 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4370 SourceLocation DefaultLoc,
4371 SourceLocation RParenLoc,
4372 Expr *ControllingExpr,
4373 ArrayRef<ParsedType> ArgTypes,
4374 ArrayRef<Expr *> ArgExprs);
4375 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4376 SourceLocation DefaultLoc,
4377 SourceLocation RParenLoc,
4378 Expr *ControllingExpr,
4379 ArrayRef<TypeSourceInfo *> Types,
4380 ArrayRef<Expr *> Exprs);
4381
4382 // Binary/Unary Operators. 'Tok' is the token for the operator.
4383 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4384 Expr *InputExpr);
4385 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4386 UnaryOperatorKind Opc, Expr *Input);
4387 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4388 tok::TokenKind Op, Expr *Input);
4389
4390 bool isQualifiedMemberAccess(Expr *E);
4391 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4392
4393 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4394 SourceLocation OpLoc,
4395 UnaryExprOrTypeTrait ExprKind,
4396 SourceRange R);
4397 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4398 UnaryExprOrTypeTrait ExprKind);
4399 ExprResult
4400 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4401 UnaryExprOrTypeTrait ExprKind,
4402 bool IsType, void *TyOrEx,
4403 SourceRange ArgRange);
4404
4405 ExprResult CheckPlaceholderExpr(Expr *E);
4406 bool CheckVecStepExpr(Expr *E);
4407
4408 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4409 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4410 SourceRange ExprRange,
4411 UnaryExprOrTypeTrait ExprKind);
4412 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4413 SourceLocation OpLoc,
4414 IdentifierInfo &Name,
4415 SourceLocation NameLoc,
4416 SourceLocation RParenLoc);
4417 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4418 tok::TokenKind Kind, Expr *Input);
4419
4420 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4421 Expr *Idx, SourceLocation RLoc);
4422 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4423 Expr *Idx, SourceLocation RLoc);
4424 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4425 Expr *LowerBound, SourceLocation ColonLoc,
4426 Expr *Length, SourceLocation RBLoc);
4427
4428 // This struct is for use by ActOnMemberAccess to allow
4429 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4430 // changing the access operator from a '.' to a '->' (to see if that is the
4431 // change needed to fix an error about an unknown member, e.g. when the class
4432 // defines a custom operator->).
4433 struct ActOnMemberAccessExtraArgs {
4434 Scope *S;
4435 UnqualifiedId &Id;
4436 Decl *ObjCImpDecl;
4437 };
4438
4439 ExprResult BuildMemberReferenceExpr(
4440 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4441 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4442 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4443 const TemplateArgumentListInfo *TemplateArgs,
4444 const Scope *S,
4445 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4446
4447 ExprResult
4448 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4449 bool IsArrow, const CXXScopeSpec &SS,
4450 SourceLocation TemplateKWLoc,
4451 NamedDecl *FirstQualifierInScope, LookupResult &R,
4452 const TemplateArgumentListInfo *TemplateArgs,
4453 const Scope *S,
4454 bool SuppressQualifierCheck = false,
4455 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4456
4457 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4458 SourceLocation OpLoc,
4459 const CXXScopeSpec &SS, FieldDecl *Field,
4460 DeclAccessPair FoundDecl,
4461 const DeclarationNameInfo &MemberNameInfo);
4462
4463 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4464
4465 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4466 const CXXScopeSpec &SS,
4467 const LookupResult &R);
4468
4469 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4470 bool IsArrow, SourceLocation OpLoc,
4471 const CXXScopeSpec &SS,
4472 SourceLocation TemplateKWLoc,
4473 NamedDecl *FirstQualifierInScope,
4474 const DeclarationNameInfo &NameInfo,
4475 const TemplateArgumentListInfo *TemplateArgs);
4476
4477 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4478 SourceLocation OpLoc,
4479 tok::TokenKind OpKind,
4480 CXXScopeSpec &SS,
4481 SourceLocation TemplateKWLoc,
4482 UnqualifiedId &Member,
4483 Decl *ObjCImpDecl);
4484
4485 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4486 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4487 FunctionDecl *FDecl,
4488 const FunctionProtoType *Proto,
4489 ArrayRef<Expr *> Args,
4490 SourceLocation RParenLoc,
4491 bool ExecConfig = false);
4492 void CheckStaticArrayArgument(SourceLocation CallLoc,
4493 ParmVarDecl *Param,
4494 const Expr *ArgExpr);
4495
4496 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4497 /// This provides the location of the left/right parens and a list of comma
4498 /// locations.
4499 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4500 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4501 Expr *ExecConfig = nullptr,
4502 bool IsExecConfig = false);
4503 ExprResult
4504 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
4505 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
4506 Expr *Config = nullptr, bool IsExecConfig = false,
4507 ADLCallKind UsesADL = ADLCallKind::NotADL);
4508
4509 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4510 MultiExprArg ExecConfig,
4511 SourceLocation GGGLoc);
4512
4513 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4514 Declarator &D, ParsedType &Ty,
4515 SourceLocation RParenLoc, Expr *CastExpr);
4516 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4517 TypeSourceInfo *Ty,
4518 SourceLocation RParenLoc,
4519 Expr *Op);
4520 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4521
4522 /// Build an altivec or OpenCL literal.
4523 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4524 SourceLocation RParenLoc, Expr *E,
4525 TypeSourceInfo *TInfo);
4526
4527 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4528
4529 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4530 ParsedType Ty,
4531 SourceLocation RParenLoc,
4532 Expr *InitExpr);
4533
4534 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4535 TypeSourceInfo *TInfo,
4536 SourceLocation RParenLoc,
4537 Expr *LiteralExpr);
4538
4539 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4540 MultiExprArg InitArgList,
4541 SourceLocation RBraceLoc);
4542
4543 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4544 SourceLocation Loc,
4545 bool GNUSyntax,
4546 ExprResult Init);
4547
4548private:
4549 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4550
4551public:
4552 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4553 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4554 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4555 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4556 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4557 Expr *LHSExpr, Expr *RHSExpr);
4558
4559 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4560
4561 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4562 /// in the case of a the GNU conditional expr extension.
4563 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4564 SourceLocation ColonLoc,
4565 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4566
4567 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4568 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4569 LabelDecl *TheDecl);
4570
4571 void ActOnStartStmtExpr();
4572 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4573 SourceLocation RPLoc); // "({..})"
4574 // Handle the final expression in a statement expression.
4575 ExprResult ActOnStmtExprResult(ExprResult E);
4576 void ActOnStmtExprError();
4577
4578 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4579 struct OffsetOfComponent {
4580 SourceLocation LocStart, LocEnd;
4581 bool isBrackets; // true if [expr], false if .ident
4582 union {
4583 IdentifierInfo *IdentInfo;
4584 Expr *E;
4585 } U;
4586 };
4587
4588 /// __builtin_offsetof(type, a.b[123][456].c)
4589 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4590 TypeSourceInfo *TInfo,
4591 ArrayRef<OffsetOfComponent> Components,
4592 SourceLocation RParenLoc);
4593 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4594 SourceLocation BuiltinLoc,
4595 SourceLocation TypeLoc,
4596 ParsedType ParsedArgTy,
4597 ArrayRef<OffsetOfComponent> Components,
4598 SourceLocation RParenLoc);
4599
4600 // __builtin_choose_expr(constExpr, expr1, expr2)
4601 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4602 Expr *CondExpr, Expr *LHSExpr,
4603 Expr *RHSExpr, SourceLocation RPLoc);
4604
4605 // __builtin_va_arg(expr, type)
4606 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4607 SourceLocation RPLoc);
4608 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4609 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4610
4611 // __null
4612 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4613
4614 bool CheckCaseExpression(Expr *E);
4615
4616 /// Describes the result of an "if-exists" condition check.
4617 enum IfExistsResult {
4618 /// The symbol exists.
4619 IER_Exists,
4620
4621 /// The symbol does not exist.
4622 IER_DoesNotExist,
4623
4624 /// The name is a dependent name, so the results will differ
4625 /// from one instantiation to the next.
4626 IER_Dependent,
4627
4628 /// An error occurred.
4629 IER_Error
4630 };
4631
4632 IfExistsResult
4633 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4634 const DeclarationNameInfo &TargetNameInfo);
4635
4636 IfExistsResult
4637 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4638 bool IsIfExists, CXXScopeSpec &SS,
4639 UnqualifiedId &Name);
4640
4641 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4642 bool IsIfExists,
4643 NestedNameSpecifierLoc QualifierLoc,
4644 DeclarationNameInfo NameInfo,
4645 Stmt *Nested);
4646 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4647 bool IsIfExists,
4648 CXXScopeSpec &SS, UnqualifiedId &Name,
4649 Stmt *Nested);
4650
4651 //===------------------------- "Block" Extension ------------------------===//
4652
4653 /// ActOnBlockStart - This callback is invoked when a block literal is
4654 /// started.
4655 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4656
4657 /// ActOnBlockArguments - This callback allows processing of block arguments.
4658 /// If there are no arguments, this is still invoked.
4659 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4660 Scope *CurScope);
4661
4662 /// ActOnBlockError - If there is an error parsing a block, this callback
4663 /// is invoked to pop the information about the block from the action impl.
4664 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4665
4666 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4667 /// literal was successfully completed. ^(int x){...}
4668 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4669 Scope *CurScope);
4670
4671 //===---------------------------- Clang Extensions ----------------------===//
4672
4673 /// __builtin_convertvector(...)
4674 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4675 SourceLocation BuiltinLoc,
4676 SourceLocation RParenLoc);
4677
4678 //===---------------------------- OpenCL Features -----------------------===//
4679
4680 /// __builtin_astype(...)
4681 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4682 SourceLocation BuiltinLoc,
4683 SourceLocation RParenLoc);
4684
4685 //===---------------------------- C++ Features --------------------------===//
4686
4687 // Act on C++ namespaces
4688 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4689 SourceLocation NamespaceLoc,
4690 SourceLocation IdentLoc, IdentifierInfo *Ident,
4691 SourceLocation LBrace,
4692 const ParsedAttributesView &AttrList,
4693 UsingDirectiveDecl *&UsingDecl);
4694 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4695
4696 NamespaceDecl *getStdNamespace() const;
4697 NamespaceDecl *getOrCreateStdNamespace();
4698
4699 NamespaceDecl *lookupStdExperimentalNamespace();
4700
4701 CXXRecordDecl *getStdBadAlloc() const;
4702 EnumDecl *getStdAlignValT() const;
4703
4704private:
4705 // A cache representing if we've fully checked the various comparison category
4706 // types stored in ASTContext. The bit-index corresponds to the integer value
4707 // of a ComparisonCategoryType enumerator.
4708 llvm::SmallBitVector FullyCheckedComparisonCategories;
4709
4710 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4711 CXXScopeSpec &SS,
4712 ParsedType TemplateTypeTy,
4713 IdentifierInfo *MemberOrBase);
4714
4715public:
4716 /// Lookup the specified comparison category types in the standard
4717 /// library, an check the VarDecls possibly returned by the operator<=>
4718 /// builtins for that type.
4719 ///
4720 /// \return The type of the comparison category type corresponding to the
4721 /// specified Kind, or a null type if an error occurs
4722 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
4723 SourceLocation Loc);
4724
4725 /// Tests whether Ty is an instance of std::initializer_list and, if
4726 /// it is and Element is not NULL, assigns the element type to Element.
4727 bool isStdInitializerList(QualType Ty, QualType *Element);
4728
4729 /// Looks for the std::initializer_list template and instantiates it
4730 /// with Element, or emits an error if it's not found.
4731 ///
4732 /// \returns The instantiated template, or null on error.
4733 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4734
4735 /// Determine whether Ctor is an initializer-list constructor, as
4736 /// defined in [dcl.init.list]p2.
4737 bool isInitListConstructor(const FunctionDecl *Ctor);
4738
4739 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
4740 SourceLocation NamespcLoc, CXXScopeSpec &SS,
4741 SourceLocation IdentLoc,
4742 IdentifierInfo *NamespcName,
4743 const ParsedAttributesView &AttrList);
4744
4745 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4746
4747 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4748 SourceLocation NamespaceLoc,
4749 SourceLocation AliasLoc,
4750 IdentifierInfo *Alias,
4751 CXXScopeSpec &SS,
4752 SourceLocation IdentLoc,
4753 IdentifierInfo *Ident);
4754
4755 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4756 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4757 const LookupResult &PreviousDecls,
4758 UsingShadowDecl *&PrevShadow);
4759 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4760 NamedDecl *Target,
4761 UsingShadowDecl *PrevDecl);
4762
4763 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4764 bool HasTypenameKeyword,
4765 const CXXScopeSpec &SS,
4766 SourceLocation NameLoc,
4767 const LookupResult &Previous);
4768 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4769 bool HasTypename,
4770 const CXXScopeSpec &SS,
4771 const DeclarationNameInfo &NameInfo,
4772 SourceLocation NameLoc);
4773
4774 NamedDecl *BuildUsingDeclaration(
4775 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
4776 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
4777 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
4778 const ParsedAttributesView &AttrList, bool IsInstantiation);
4779 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4780 ArrayRef<NamedDecl *> Expansions);
4781
4782 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4783
4784 /// Given a derived-class using shadow declaration for a constructor and the
4785 /// correspnding base class constructor, find or create the implicit
4786 /// synthesized derived class constructor to use for this initialization.
4787 CXXConstructorDecl *
4788 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4789 ConstructorUsingShadowDecl *DerivedShadow);
4790
4791 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
4792 SourceLocation UsingLoc,
4793 SourceLocation TypenameLoc, CXXScopeSpec &SS,
4794 UnqualifiedId &Name, SourceLocation EllipsisLoc,
4795 const ParsedAttributesView &AttrList);
4796 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
4797 MultiTemplateParamsArg TemplateParams,
4798 SourceLocation UsingLoc, UnqualifiedId &Name,
4799 const ParsedAttributesView &AttrList,
4800 TypeResult Type, Decl *DeclFromDeclSpec);
4801
4802 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4803 /// including handling of its default argument expressions.
4804 ///
4805 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4806 ExprResult
4807 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4808 NamedDecl *FoundDecl,
4809 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4810 bool HadMultipleCandidates, bool IsListInitialization,
4811 bool IsStdInitListInitialization,
4812 bool RequiresZeroInit, unsigned ConstructKind,
4813 SourceRange ParenRange);
4814
4815 /// Build a CXXConstructExpr whose constructor has already been resolved if
4816 /// it denotes an inherited constructor.
4817 ExprResult
4818 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4819 CXXConstructorDecl *Constructor, bool Elidable,
4820 MultiExprArg Exprs,
4821 bool HadMultipleCandidates, bool IsListInitialization,
4822 bool IsStdInitListInitialization,
4823 bool RequiresZeroInit, unsigned ConstructKind,
4824 SourceRange ParenRange);
4825
4826 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4827 // the constructor can be elidable?
4828 ExprResult
4829 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4830 NamedDecl *FoundDecl,
4831 CXXConstructorDecl *Constructor, bool Elidable,
4832 MultiExprArg Exprs, bool HadMultipleCandidates,
4833 bool IsListInitialization,
4834 bool IsStdInitListInitialization, bool RequiresZeroInit,
4835 unsigned ConstructKind, SourceRange ParenRange);
4836
4837 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4838
4839
4840 /// Instantiate or parse a C++ default argument expression as necessary.
4841 /// Return true on error.
4842 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4843 ParmVarDecl *Param);
4844
4845 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4846 /// the default expr if needed.
4847 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4848 FunctionDecl *FD,
4849 ParmVarDecl *Param);
4850
4851 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4852 /// constructed variable.
4853 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4854
4855 /// Helper class that collects exception specifications for
4856 /// implicitly-declared special member functions.
4857 class ImplicitExceptionSpecification {
4858 // Pointer to allow copying
4859 Sema *Self;
4860 // We order exception specifications thus:
4861 // noexcept is the most restrictive, but is only used in C++11.
4862 // throw() comes next.
4863 // Then a throw(collected exceptions)
4864 // Finally no specification, which is expressed as noexcept(false).
4865 // throw(...) is used instead if any called function uses it.
4866 ExceptionSpecificationType ComputedEST;
4867 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4868 SmallVector<QualType, 4> Exceptions;
4869
4870 void ClearExceptions() {
4871 ExceptionsSeen.clear();
4872 Exceptions.clear();
4873 }
4874
4875 public:
4876 explicit ImplicitExceptionSpecification(Sema &Self)
4877 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4878 if (!Self.getLangOpts().CPlusPlus11)
4879 ComputedEST = EST_DynamicNone;
4880 }
4881
4882 /// Get the computed exception specification type.
4883 ExceptionSpecificationType getExceptionSpecType() const {
4884 assert(!isComputedNoexcept(ComputedEST) &&((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 4885, __PRETTY_FUNCTION__))
4885 "noexcept(expr) should not be a possible result")((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 4885, __PRETTY_FUNCTION__))
;
4886 return ComputedEST;
4887 }
4888
4889 /// The number of exceptions in the exception specification.
4890 unsigned size() const { return Exceptions.size(); }
4891
4892 /// The set of exceptions in the exception specification.
4893 const QualType *data() const { return Exceptions.data(); }
4894
4895 /// Integrate another called method into the collected data.
4896 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4897
4898 /// Integrate an invoked expression into the collected data.
4899 void CalledExpr(Expr *E);
4900
4901 /// Overwrite an EPI's exception specification with this
4902 /// computed exception specification.
4903 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4904 FunctionProtoType::ExceptionSpecInfo ESI;
4905 ESI.Type = getExceptionSpecType();
4906 if (ESI.Type == EST_Dynamic) {
4907 ESI.Exceptions = Exceptions;
4908 } else if (ESI.Type == EST_None) {
4909 /// C++11 [except.spec]p14:
4910 /// The exception-specification is noexcept(false) if the set of
4911 /// potential exceptions of the special member function contains "any"
4912 ESI.Type = EST_NoexceptFalse;
4913 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4914 tok::kw_false).get();
4915 }
4916 return ESI;
4917 }
4918 };
4919
4920 /// Determine what sort of exception specification a defaulted
4921 /// copy constructor of a class will have.
4922 ImplicitExceptionSpecification
4923 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4924 CXXMethodDecl *MD);
4925
4926 /// Determine what sort of exception specification a defaulted
4927 /// default constructor of a class will have, and whether the parameter
4928 /// will be const.
4929 ImplicitExceptionSpecification
4930 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4931
4932 /// Determine what sort of exception specification a defaulted
4933 /// copy assignment operator of a class will have, and whether the
4934 /// parameter will be const.
4935 ImplicitExceptionSpecification
4936 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4937
4938 /// Determine what sort of exception specification a defaulted move
4939 /// constructor of a class will have.
4940 ImplicitExceptionSpecification
4941 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4942
4943 /// Determine what sort of exception specification a defaulted move
4944 /// assignment operator of a class will have.
4945 ImplicitExceptionSpecification
4946 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4947
4948 /// Determine what sort of exception specification a defaulted
4949 /// destructor of a class will have.
4950 ImplicitExceptionSpecification
4951 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4952
4953 /// Determine what sort of exception specification an inheriting
4954 /// constructor of a class will have.
4955 ImplicitExceptionSpecification
4956 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4957 CXXConstructorDecl *CD);
4958
4959 /// Evaluate the implicit exception specification for a defaulted
4960 /// special member function.
4961 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4962
4963 /// Check the given noexcept-specifier, convert its expression, and compute
4964 /// the appropriate ExceptionSpecificationType.
4965 ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
4966 ExceptionSpecificationType &EST);
4967
4968 /// Check the given exception-specification and update the
4969 /// exception specification information with the results.
4970 void checkExceptionSpecification(bool IsTopLevel,
4971 ExceptionSpecificationType EST,
4972 ArrayRef<ParsedType> DynamicExceptions,
4973 ArrayRef<SourceRange> DynamicExceptionRanges,
4974 Expr *NoexceptExpr,
4975 SmallVectorImpl<QualType> &Exceptions,
4976 FunctionProtoType::ExceptionSpecInfo &ESI);
4977
4978 /// Determine if we're in a case where we need to (incorrectly) eagerly
4979 /// parse an exception specification to work around a libstdc++ bug.
4980 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4981
4982 /// Add an exception-specification to the given member function
4983 /// (or member function template). The exception-specification was parsed
4984 /// after the method itself was declared.
4985 void actOnDelayedExceptionSpecification(Decl *Method,
4986 ExceptionSpecificationType EST,
4987 SourceRange SpecificationRange,
4988 ArrayRef<ParsedType> DynamicExceptions,
4989 ArrayRef<SourceRange> DynamicExceptionRanges,
4990 Expr *NoexceptExpr);
4991
4992 class InheritedConstructorInfo;
4993
4994 /// Determine if a special member function should have a deleted
4995 /// definition when it is defaulted.
4996 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4997 InheritedConstructorInfo *ICI = nullptr,
4998 bool Diagnose = false);
4999
5000 /// Declare the implicit default constructor for the given class.
5001 ///
5002 /// \param ClassDecl The class declaration into which the implicit
5003 /// default constructor will be added.
5004 ///
5005 /// \returns The implicitly-declared default constructor.
5006 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
5007 CXXRecordDecl *ClassDecl);
5008
5009 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5010 /// defining this constructor as the default constructor.
5011 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5012 CXXConstructorDecl *Constructor);
5013
5014 /// Declare the implicit destructor for the given class.
5015 ///
5016 /// \param ClassDecl The class declaration into which the implicit
5017 /// destructor will be added.
5018 ///
5019 /// \returns The implicitly-declared destructor.
5020 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5021
5022 /// DefineImplicitDestructor - Checks for feasibility of
5023 /// defining this destructor as the default destructor.
5024 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5025 CXXDestructorDecl *Destructor);
5026
5027 /// Build an exception spec for destructors that don't have one.
5028 ///
5029 /// C++11 says that user-defined destructors with no exception spec get one
5030 /// that looks as if the destructor was implicitly declared.
5031 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5032
5033 /// Define the specified inheriting constructor.
5034 void DefineInheritingConstructor(SourceLocation UseLoc,
5035 CXXConstructorDecl *Constructor);
5036
5037 /// Declare the implicit copy constructor for the given class.
5038 ///
5039 /// \param ClassDecl The class declaration into which the implicit
5040 /// copy constructor will be added.
5041 ///
5042 /// \returns The implicitly-declared copy constructor.
5043 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5044
5045 /// DefineImplicitCopyConstructor - Checks for feasibility of
5046 /// defining this constructor as the copy constructor.
5047 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5048 CXXConstructorDecl *Constructor);
5049
5050 /// Declare the implicit move constructor for the given class.
5051 ///
5052 /// \param ClassDecl The Class declaration into which the implicit
5053 /// move constructor will be added.
5054 ///
5055 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5056 /// declared.
5057 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5058
5059 /// DefineImplicitMoveConstructor - Checks for feasibility of
5060 /// defining this constructor as the move constructor.
5061 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5062 CXXConstructorDecl *Constructor);
5063
5064 /// Declare the implicit copy assignment operator for the given class.
5065 ///
5066 /// \param ClassDecl The class declaration into which the implicit
5067 /// copy assignment operator will be added.
5068 ///
5069 /// \returns The implicitly-declared copy assignment operator.
5070 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5071
5072 /// Defines an implicitly-declared copy assignment operator.
5073 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5074 CXXMethodDecl *MethodDecl);
5075
5076 /// Declare the implicit move assignment operator for the given class.
5077 ///
5078 /// \param ClassDecl The Class declaration into which the implicit
5079 /// move assignment operator will be added.
5080 ///
5081 /// \returns The implicitly-declared move assignment operator, or NULL if it
5082 /// wasn't declared.
5083 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5084
5085 /// Defines an implicitly-declared move assignment operator.
5086 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5087 CXXMethodDecl *MethodDecl);
5088
5089 /// Force the declaration of any implicitly-declared members of this
5090 /// class.
5091 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
5092
5093 /// Check a completed declaration of an implicit special member.
5094 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5095
5096 /// Determine whether the given function is an implicitly-deleted
5097 /// special member function.
5098 bool isImplicitlyDeleted(FunctionDecl *FD);
5099
5100 /// Check whether 'this' shows up in the type of a static member
5101 /// function after the (naturally empty) cv-qualifier-seq would be.
5102 ///
5103 /// \returns true if an error occurred.
5104 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5105
5106 /// Whether this' shows up in the exception specification of a static
5107 /// member function.
5108 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5109
5110 /// Check whether 'this' shows up in the attributes of the given
5111 /// static member function.
5112 ///
5113 /// \returns true if an error occurred.
5114 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5115
5116 /// MaybeBindToTemporary - If the passed in expression has a record type with
5117 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
5118 /// it simply returns the passed in expression.
5119 ExprResult MaybeBindToTemporary(Expr *E);
5120
5121 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5122 MultiExprArg ArgsPtr,
5123 SourceLocation Loc,
5124 SmallVectorImpl<Expr*> &ConvertedArgs,
5125 bool AllowExplicit = false,
5126 bool IsListInitialization = false);
5127
5128 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
5129 SourceLocation NameLoc,
5130 IdentifierInfo &Name);
5131
5132 ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
5133 Scope *S, CXXScopeSpec &SS,
5134 bool EnteringContext);
5135 ParsedType getDestructorName(SourceLocation TildeLoc,
5136 IdentifierInfo &II, SourceLocation NameLoc,
5137 Scope *S, CXXScopeSpec &SS,
5138 ParsedType ObjectType,
5139 bool EnteringContext);
5140
5141 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
5142 ParsedType ObjectType);
5143
5144 // Checks that reinterpret casts don't have undefined behavior.
5145 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
5146 bool IsDereference, SourceRange Range);
5147
5148 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
5149 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
5150 tok::TokenKind Kind,
5151 SourceLocation LAngleBracketLoc,
5152 Declarator &D,
5153 SourceLocation RAngleBracketLoc,
5154 SourceLocation LParenLoc,
5155 Expr *E,
5156 SourceLocation RParenLoc);
5157
5158 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
5159 tok::TokenKind Kind,
5160 TypeSourceInfo *Ty,
5161 Expr *E,
5162 SourceRange AngleBrackets,
5163 SourceRange Parens);
5164
5165 ExprResult BuildCXXTypeId(QualType TypeInfoType,
5166 SourceLocation TypeidLoc,
5167 TypeSourceInfo *Operand,
5168 SourceLocation RParenLoc);
5169 ExprResult BuildCXXTypeId(QualType TypeInfoType,
5170 SourceLocation TypeidLoc,
5171 Expr *Operand,
5172 SourceLocation RParenLoc);
5173
5174 /// ActOnCXXTypeid - Parse typeid( something ).
5175 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
5176 SourceLocation LParenLoc, bool isType,
5177 void *TyOrExpr,
5178 SourceLocation RParenLoc);
5179
5180 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5181 SourceLocation TypeidLoc,
5182 TypeSourceInfo *Operand,
5183 SourceLocation RParenLoc);
5184 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5185 SourceLocation TypeidLoc,
5186 Expr *Operand,
5187 SourceLocation RParenLoc);
5188
5189 /// ActOnCXXUuidof - Parse __uuidof( something ).
5190 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
5191 SourceLocation LParenLoc, bool isType,
5192 void *TyOrExpr,
5193 SourceLocation RParenLoc);
5194
5195 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
5196 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5197 tok::TokenKind Operator,
5198 SourceLocation EllipsisLoc, Expr *RHS,
5199 SourceLocation RParenLoc);
5200 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5201 BinaryOperatorKind Operator,
5202 SourceLocation EllipsisLoc, Expr *RHS,
5203 SourceLocation RParenLoc);
5204 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
5205 BinaryOperatorKind Operator);
5206
5207 //// ActOnCXXThis - Parse 'this' pointer.
5208 ExprResult ActOnCXXThis(SourceLocation loc);
5209
5210 /// Try to retrieve the type of the 'this' pointer.
5211 ///
5212 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
5213 QualType getCurrentThisType();
5214
5215 /// When non-NULL, the C++ 'this' expression is allowed despite the
5216 /// current context not being a non-static member function. In such cases,
5217 /// this provides the type used for 'this'.
5218 QualType CXXThisTypeOverride;
5219
5220 /// RAII object used to temporarily allow the C++ 'this' expression
5221 /// to be used, with the given qualifiers on the current class type.
5222 class CXXThisScopeRAII {
5223 Sema &S;
5224 QualType OldCXXThisTypeOverride;
5225 bool Enabled;
5226
5227 public:
5228 /// Introduce a new scope where 'this' may be allowed (when enabled),
5229 /// using the given declaration (which is either a class template or a
5230 /// class) along with the given qualifiers.
5231 /// along with the qualifiers placed on '*this'.
5232 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
5233 bool Enabled = true);
5234
5235 ~CXXThisScopeRAII();
5236 };
5237
5238 /// Make sure the value of 'this' is actually available in the current
5239 /// context, if it is a potentially evaluated context.
5240 ///
5241 /// \param Loc The location at which the capture of 'this' occurs.
5242 ///
5243 /// \param Explicit Whether 'this' is explicitly captured in a lambda
5244 /// capture list.
5245 ///
5246 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5247 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5248 /// This is useful when enclosing lambdas must speculatively capture
5249 /// 'this' that may or may not be used in certain specializations of
5250 /// a nested generic lambda (depending on whether the name resolves to
5251 /// a non-static member function or a static function).
5252 /// \return returns 'true' if failed, 'false' if success.
5253 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5254 bool BuildAndDiagnose = true,
5255 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5256 bool ByCopy = false);
5257
5258 /// Determine whether the given type is the type of *this that is used
5259 /// outside of the body of a member function for a type that is currently
5260 /// being defined.
5261 bool isThisOutsideMemberFunctionBody(QualType BaseType);
5262
5263 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5264 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5265
5266
5267 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5268 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5269
5270 ExprResult
5271 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5272 SourceLocation AtLoc, SourceLocation RParen);
5273
5274 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5275 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5276
5277 //// ActOnCXXThrow - Parse throw expressions.
5278 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5279 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5280 bool IsThrownVarInScope);
5281 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5282
5283 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5284 /// Can be interpreted either as function-style casting ("int(x)")
5285 /// or class type construction ("ClassType(x,y,z)")
5286 /// or creation of a value-initialized type ("int()").
5287 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5288 SourceLocation LParenOrBraceLoc,
5289 MultiExprArg Exprs,
5290 SourceLocation RParenOrBraceLoc,
5291 bool ListInitialization);
5292
5293 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5294 SourceLocation LParenLoc,
5295 MultiExprArg Exprs,
5296 SourceLocation RParenLoc,
5297 bool ListInitialization);
5298
5299 /// ActOnCXXNew - Parsed a C++ 'new' expression.
5300 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5301 SourceLocation PlacementLParen,
5302 MultiExprArg PlacementArgs,
5303 SourceLocation PlacementRParen,
5304 SourceRange TypeIdParens, Declarator &D,
5305 Expr *Initializer);
5306 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5307 SourceLocation PlacementLParen,
5308 MultiExprArg PlacementArgs,
5309 SourceLocation PlacementRParen,
5310 SourceRange TypeIdParens,
5311 QualType AllocType,
5312 TypeSourceInfo *AllocTypeInfo,
5313 Expr *ArraySize,
5314 SourceRange DirectInitRange,
5315 Expr *Initializer);
5316
5317 /// Determine whether \p FD is an aligned allocation or deallocation
5318 /// function that is unavailable.
5319 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
5320
5321 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
5322 /// function that is unavailable.
5323 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
5324 SourceLocation Loc);
5325
5326 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5327 SourceRange R);
5328
5329 /// The scope in which to find allocation functions.
5330 enum AllocationFunctionScope {
5331 /// Only look for allocation functions in the global scope.
5332 AFS_Global,
5333 /// Only look for allocation functions in the scope of the
5334 /// allocated class.
5335 AFS_Class,
5336 /// Look for allocation functions in both the global scope
5337 /// and in the scope of the allocated class.
5338 AFS_Both
5339 };
5340
5341 /// Finds the overloads of operator new and delete that are appropriate
5342 /// for the allocation.
5343 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5344 AllocationFunctionScope NewScope,
5345 AllocationFunctionScope DeleteScope,
5346 QualType AllocType, bool IsArray,
5347 bool &PassAlignment, MultiExprArg PlaceArgs,
5348 FunctionDecl *&OperatorNew,
5349 FunctionDecl *&OperatorDelete,
5350 bool Diagnose = true);
5351 void DeclareGlobalNewDelete();
5352 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5353 ArrayRef<QualType> Params);
5354
5355 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5356 DeclarationName Name, FunctionDecl* &Operator,
5357 bool Diagnose = true);
5358 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5359 bool CanProvideSize,
5360 bool Overaligned,
5361 DeclarationName Name);
5362 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5363 CXXRecordDecl *RD);
5364
5365 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5366 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5367 bool UseGlobal, bool ArrayForm,
5368 Expr *Operand);
5369 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5370 bool IsDelete, bool CallCanBeVirtual,
5371 bool WarnOnNonAbstractTypes,
5372 SourceLocation DtorLoc);
5373
5374 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5375 Expr *Operand, SourceLocation RParen);
5376 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5377 SourceLocation RParen);
5378
5379 /// Parsed one of the type trait support pseudo-functions.
5380 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5381 ArrayRef<ParsedType> Args,
5382 SourceLocation RParenLoc);
5383 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5384 ArrayRef<TypeSourceInfo *> Args,
5385 SourceLocation RParenLoc);
5386
5387 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5388 /// pseudo-functions.
5389 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5390 SourceLocation KWLoc,
5391 ParsedType LhsTy,
5392 Expr *DimExpr,
5393 SourceLocation RParen);
5394
5395 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5396 SourceLocation KWLoc,
5397 TypeSourceInfo *TSInfo,
5398 Expr *DimExpr,
5399 SourceLocation RParen);
5400
5401 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5402 /// pseudo-functions.
5403 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5404 SourceLocation KWLoc,
5405 Expr *Queried,
5406 SourceLocation RParen);
5407
5408 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5409 SourceLocation KWLoc,
5410 Expr *Queried,
5411 SourceLocation RParen);
5412
5413 ExprResult ActOnStartCXXMemberReference(Scope *S,
5414 Expr *Base,
5415 SourceLocation OpLoc,
5416 tok::TokenKind OpKind,
5417 ParsedType &ObjectType,
5418 bool &MayBePseudoDestructor);
5419
5420 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5421 SourceLocation OpLoc,
5422 tok::TokenKind OpKind,
5423 const CXXScopeSpec &SS,
5424 TypeSourceInfo *ScopeType,
5425 SourceLocation CCLoc,
5426 SourceLocation TildeLoc,
5427 PseudoDestructorTypeStorage DestroyedType);
5428
5429 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5430 SourceLocation OpLoc,
5431 tok::TokenKind OpKind,
5432 CXXScopeSpec &SS,
5433 UnqualifiedId &FirstTypeName,
5434 SourceLocation CCLoc,
5435 SourceLocation TildeLoc,
5436 UnqualifiedId &SecondTypeName);
5437
5438 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5439 SourceLocation OpLoc,
5440 tok::TokenKind OpKind,
5441 SourceLocation TildeLoc,
5442 const DeclSpec& DS);
5443
5444 /// MaybeCreateExprWithCleanups - If the current full-expression
5445 /// requires any cleanups, surround it with a ExprWithCleanups node.
5446 /// Otherwise, just returns the passed-in expression.
5447 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5448 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5449 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5450
5451 MaterializeTemporaryExpr *
5452 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5453 bool BoundToLvalueReference);
5454
5455 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
5456 return ActOnFinishFullExpr(
5457 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
5458 }
5459 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5460 bool DiscardedValue, bool IsConstexpr = false);
5461 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5462
5463 // Marks SS invalid if it represents an incomplete type.
5464 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5465
5466 DeclContext *computeDeclContext(QualType T);
5467 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5468 bool EnteringContext = false);
5469 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5470 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5471
5472 /// The parser has parsed a global nested-name-specifier '::'.
5473 ///
5474 /// \param CCLoc The location of the '::'.
5475 ///
5476 /// \param SS The nested-name-specifier, which will be updated in-place
5477 /// to reflect the parsed nested-name-specifier.
5478 ///
5479 /// \returns true if an error occurred, false otherwise.
5480 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5481
5482 /// The parser has parsed a '__super' nested-name-specifier.
5483 ///
5484 /// \param SuperLoc The location of the '__super' keyword.
5485 ///
5486 /// \param ColonColonLoc The location of the '::'.
5487 ///
5488 /// \param SS The nested-name-specifier, which will be updated in-place
5489 /// to reflect the parsed nested-name-specifier.
5490 ///
5491 /// \returns true if an error occurred, false otherwise.
5492 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5493 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5494
5495 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5496 bool *CanCorrect = nullptr);
5497 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5498
5499 /// Keeps information about an identifier in a nested-name-spec.
5500 ///
5501 struct NestedNameSpecInfo {
5502 /// The type of the object, if we're parsing nested-name-specifier in
5503 /// a member access expression.
5504 ParsedType ObjectType;
5505
5506 /// The identifier preceding the '::'.
5507 IdentifierInfo *Identifier;
5508
5509 /// The location of the identifier.
5510 SourceLocation IdentifierLoc;
5511
5512 /// The location of the '::'.
5513 SourceLocation CCLoc;
5514
5515 /// Creates info object for the most typical case.
5516 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5517 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5518 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5519 CCLoc(ColonColonLoc) {
5520 }
5521
5522 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5523 SourceLocation ColonColonLoc, QualType ObjectType)
5524 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5525 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5526 }
5527 };
5528
5529 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5530 NestedNameSpecInfo &IdInfo);
5531
5532 bool BuildCXXNestedNameSpecifier(Scope *S,
5533 NestedNameSpecInfo &IdInfo,
5534 bool EnteringContext,
5535 CXXScopeSpec &SS,
5536 NamedDecl *ScopeLookupResult,
5537 bool ErrorRecoveryLookup,
5538 bool *IsCorrectedToColon = nullptr,
5539 bool OnlyNamespace = false);
5540
5541 /// The parser has parsed a nested-name-specifier 'identifier::'.
5542 ///
5543 /// \param S The scope in which this nested-name-specifier occurs.
5544 ///
5545 /// \param IdInfo Parser information about an identifier in the
5546 /// nested-name-spec.
5547 ///
5548 /// \param EnteringContext Whether we're entering the context nominated by
5549 /// this nested-name-specifier.
5550 ///
5551 /// \param SS The nested-name-specifier, which is both an input
5552 /// parameter (the nested-name-specifier before this type) and an
5553 /// output parameter (containing the full nested-name-specifier,
5554 /// including this new type).
5555 ///
5556 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5557 /// error recovery. In this case do not emit error message.
5558 ///
5559 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5560 /// are allowed. The bool value pointed by this parameter is set to 'true'
5561 /// if the identifier is treated as if it was followed by ':', not '::'.
5562 ///
5563 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5564 ///
5565 /// \returns true if an error occurred, false otherwise.
5566 bool ActOnCXXNestedNameSpecifier(Scope *S,
5567 NestedNameSpecInfo &IdInfo,
5568 bool EnteringContext,
5569 CXXScopeSpec &SS,
5570 bool ErrorRecoveryLookup = false,
5571 bool *IsCorrectedToColon = nullptr,
5572 bool OnlyNamespace = false);
5573
5574 ExprResult ActOnDecltypeExpression(Expr *E);
5575
5576 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5577 const DeclSpec &DS,
5578 SourceLocation ColonColonLoc);
5579
5580 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5581 NestedNameSpecInfo &IdInfo,
5582 bool EnteringContext);
5583
5584 /// The parser has parsed a nested-name-specifier
5585 /// 'template[opt] template-name < template-args >::'.
5586 ///
5587 /// \param S The scope in which this nested-name-specifier occurs.
5588 ///
5589 /// \param SS The nested-name-specifier, which is both an input
5590 /// parameter (the nested-name-specifier before this type) and an
5591 /// output parameter (containing the full nested-name-specifier,
5592 /// including this new type).
5593 ///
5594 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5595 /// \param TemplateName the template name.
5596 /// \param TemplateNameLoc The location of the template name.
5597 /// \param LAngleLoc The location of the opening angle bracket ('<').
5598 /// \param TemplateArgs The template arguments.
5599 /// \param RAngleLoc The location of the closing angle bracket ('>').
5600 /// \param CCLoc The location of the '::'.
5601 ///
5602 /// \param EnteringContext Whether we're entering the context of the
5603 /// nested-name-specifier.
5604 ///
5605 ///
5606 /// \returns true if an error occurred, false otherwise.
5607 bool ActOnCXXNestedNameSpecifier(Scope *S,
5608 CXXScopeSpec &SS,
5609 SourceLocation TemplateKWLoc,
5610 TemplateTy TemplateName,
5611 SourceLocation TemplateNameLoc,
5612 SourceLocation LAngleLoc,
5613 ASTTemplateArgsPtr TemplateArgs,
5614 SourceLocation RAngleLoc,
5615 SourceLocation CCLoc,
5616 bool EnteringContext);
5617
5618 /// Given a C++ nested-name-specifier, produce an annotation value
5619 /// that the parser can use later to reconstruct the given
5620 /// nested-name-specifier.
5621 ///
5622 /// \param SS A nested-name-specifier.
5623 ///
5624 /// \returns A pointer containing all of the information in the
5625 /// nested-name-specifier \p SS.
5626 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5627
5628 /// Given an annotation pointer for a nested-name-specifier, restore
5629 /// the nested-name-specifier structure.
5630 ///
5631 /// \param Annotation The annotation pointer, produced by
5632 /// \c SaveNestedNameSpecifierAnnotation().
5633 ///
5634 /// \param AnnotationRange The source range corresponding to the annotation.
5635 ///
5636 /// \param SS The nested-name-specifier that will be updated with the contents
5637 /// of the annotation pointer.
5638 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5639 SourceRange AnnotationRange,
5640 CXXScopeSpec &SS);
5641
5642 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5643
5644 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5645 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5646 /// After this method is called, according to [C++ 3.4.3p3], names should be
5647 /// looked up in the declarator-id's scope, until the declarator is parsed and
5648 /// ActOnCXXExitDeclaratorScope is called.
5649 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5650 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5651
5652 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5653 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5654 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5655 /// Used to indicate that names should revert to being looked up in the
5656 /// defining scope.
5657 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5658
5659 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5660 /// initializer for the declaration 'Dcl'.
5661 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5662 /// static data member of class X, names should be looked up in the scope of
5663 /// class X.
5664 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5665
5666 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5667 /// initializer for the declaration 'Dcl'.
5668 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5669
5670 /// Create a new lambda closure type.
5671 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5672 TypeSourceInfo *Info,
5673 bool KnownDependent,
5674 LambdaCaptureDefault CaptureDefault);
5675
5676 /// Start the definition of a lambda expression.
5677 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5678 SourceRange IntroducerRange,
5679 TypeSourceInfo *MethodType,
5680 SourceLocation EndLoc,
5681 ArrayRef<ParmVarDecl *> Params,
5682 bool IsConstexprSpecified);
5683
5684 /// Endow the lambda scope info with the relevant properties.
5685 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5686 CXXMethodDecl *CallOperator,
5687 SourceRange IntroducerRange,
5688 LambdaCaptureDefault CaptureDefault,
5689 SourceLocation CaptureDefaultLoc,
5690 bool ExplicitParams,
5691 bool ExplicitResultType,
5692 bool Mutable);
5693
5694 /// Perform initialization analysis of the init-capture and perform
5695 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5696 /// not being used to initialize a reference.
5697 ParsedType actOnLambdaInitCaptureInitialization(
5698 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5699 LambdaCaptureInitKind InitKind, Expr *&Init) {
5700 return ParsedType::make(buildLambdaInitCaptureInitialization(
5701 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5702 }
5703 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5704 IdentifierInfo *Id,
5705 bool DirectInit, Expr *&Init);
5706
5707 /// Create a dummy variable within the declcontext of the lambda's
5708 /// call operator, for name lookup purposes for a lambda init capture.
5709 ///
5710 /// CodeGen handles emission of lambda captures, ignoring these dummy
5711 /// variables appropriately.
5712 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5713 QualType InitCaptureType,
5714 IdentifierInfo *Id,
5715 unsigned InitStyle, Expr *Init);
5716
5717 /// Build the implicit field for an init-capture.
5718 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5719
5720 /// Note that we have finished the explicit captures for the
5721 /// given lambda.
5722 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5723
5724 /// Introduce the lambda parameters into scope.
5725 void addLambdaParameters(
5726 ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
5727 CXXMethodDecl *CallOperator, Scope *CurScope);
5728
5729 /// Deduce a block or lambda's return type based on the return
5730 /// statements present in the body.
5731 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5732
5733 /// ActOnStartOfLambdaDefinition - This is called just before we start
5734 /// parsing the body of a lambda; it analyzes the explicit captures and
5735 /// arguments, and sets up various data-structures for the body of the
5736 /// lambda.
5737 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5738 Declarator &ParamInfo, Scope *CurScope);
5739
5740 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5741 /// is invoked to pop the information about the lambda.
5742 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5743 bool IsInstantiation = false);
5744
5745 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5746 /// was successfully completed.
5747 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5748 Scope *CurScope);
5749
5750 /// Does copying/destroying the captured variable have side effects?
5751 bool CaptureHasSideEffects(const sema::Capture &From);
5752
5753 /// Diagnose if an explicit lambda capture is unused. Returns true if a
5754 /// diagnostic is emitted.
5755 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
5756 const sema::Capture &From);
5757
5758 /// Complete a lambda-expression having processed and attached the
5759 /// lambda body.
5760 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5761 sema::LambdaScopeInfo *LSI);
5762
5763 /// Get the return type to use for a lambda's conversion function(s) to
5764 /// function pointer type, given the type of the call operator.
5765 QualType
5766 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
5767
5768 /// Define the "body" of the conversion from a lambda object to a
5769 /// function pointer.
5770 ///
5771 /// This routine doesn't actually define a sensible body; rather, it fills
5772 /// in the initialization expression needed to copy the lambda object into
5773 /// the block, and IR generation actually generates the real body of the
5774 /// block pointer conversion.
5775 void DefineImplicitLambdaToFunctionPointerConversion(
5776 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5777
5778 /// Define the "body" of the conversion from a lambda object to a
5779 /// block pointer.
5780 ///
5781 /// This routine doesn't actually define a sensible body; rather, it fills
5782 /// in the initialization expression needed to copy the lambda object into
5783 /// the block, and IR generation actually generates the real body of the
5784 /// block pointer conversion.
5785 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5786 CXXConversionDecl *Conv);
5787
5788 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5789 SourceLocation ConvLocation,
5790 CXXConversionDecl *Conv,
5791 Expr *Src);
5792
5793 // ParseObjCStringLiteral - Parse Objective-C string literals.
5794 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5795 ArrayRef<Expr *> Strings);
5796
5797 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5798
5799 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5800 /// numeric literal expression. Type of the expression will be "NSNumber *"
5801 /// or "id" if NSNumber is unavailable.
5802 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5803 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5804 bool Value);
5805 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5806
5807 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5808 /// '@' prefixed parenthesized expression. The type of the expression will
5809 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5810 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5811 /// "const char *" or C structure with attribute 'objc_boxable'.
5812 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5813
5814 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5815 Expr *IndexExpr,
5816 ObjCMethodDecl *getterMethod,
5817 ObjCMethodDecl *setterMethod);
5818
5819 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5820 MutableArrayRef<ObjCDictionaryElement> Elements);
5821
5822 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5823 TypeSourceInfo *EncodedTypeInfo,
5824 SourceLocation RParenLoc);
5825 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5826 CXXConversionDecl *Method,
5827 bool HadMultipleCandidates);
5828
5829 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5830 SourceLocation EncodeLoc,
5831 SourceLocation LParenLoc,
5832 ParsedType Ty,
5833 SourceLocation RParenLoc);
5834
5835 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5836 ExprResult ParseObjCSelectorExpression(Selector Sel,
5837 SourceLocation AtLoc,
5838 SourceLocation SelLoc,
5839 SourceLocation LParenLoc,
5840 SourceLocation RParenLoc,
5841 bool WarnMultipleSelectors);
5842
5843 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5844 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5845 SourceLocation AtLoc,
5846 SourceLocation ProtoLoc,
5847 SourceLocation LParenLoc,
5848 SourceLocation ProtoIdLoc,
5849 SourceLocation RParenLoc);
5850
5851 //===--------------------------------------------------------------------===//
5852 // C++ Declarations
5853 //
5854 Decl *ActOnStartLinkageSpecification(Scope *S,
5855 SourceLocation ExternLoc,
5856 Expr *LangStr,
5857 SourceLocation LBraceLoc);
5858 Decl *ActOnFinishLinkageSpecification(Scope *S,
5859 Decl *LinkageSpec,
5860 SourceLocation RBraceLoc);
5861
5862
5863 //===--------------------------------------------------------------------===//
5864 // C++ Classes
5865 //
5866 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
5867 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5868 const CXXScopeSpec *SS = nullptr);
5869 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5870
5871 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
5872 SourceLocation ColonLoc,
5873 const ParsedAttributesView &Attrs);
5874
5875 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5876 Declarator &D,
5877 MultiTemplateParamsArg TemplateParameterLists,
5878 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5879 InClassInitStyle InitStyle);
5880
5881 void ActOnStartCXXInClassMemberInitializer();
5882 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5883 SourceLocation EqualLoc,
5884 Expr *Init);
5885
5886 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5887 Scope *S,
5888 CXXScopeSpec &SS,
5889 IdentifierInfo *MemberOrBase,
5890 ParsedType TemplateTypeTy,
5891 const DeclSpec &DS,
5892 SourceLocation IdLoc,
5893 SourceLocation LParenLoc,
5894 ArrayRef<Expr *> Args,
5895 SourceLocation RParenLoc,
5896 SourceLocation EllipsisLoc);
5897
5898 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5899 Scope *S,
5900 CXXScopeSpec &SS,
5901 IdentifierInfo *MemberOrBase,
5902 ParsedType TemplateTypeTy,
5903 const DeclSpec &DS,
5904 SourceLocation IdLoc,
5905 Expr *InitList,
5906 SourceLocation EllipsisLoc);
5907
5908 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5909 Scope *S,
5910 CXXScopeSpec &SS,
5911 IdentifierInfo *MemberOrBase,
5912 ParsedType TemplateTypeTy,
5913 const DeclSpec &DS,
5914 SourceLocation IdLoc,
5915 Expr *Init,
5916 SourceLocation EllipsisLoc);
5917
5918 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5919 Expr *Init,
5920 SourceLocation IdLoc);
5921
5922 MemInitResult BuildBaseInitializer(QualType BaseType,
5923 TypeSourceInfo *BaseTInfo,
5924 Expr *Init,
5925 CXXRecordDecl *ClassDecl,
5926 SourceLocation EllipsisLoc);
5927
5928 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5929 Expr *Init,
5930 CXXRecordDecl *ClassDecl);
5931
5932 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5933 CXXCtorInitializer *Initializer);
5934
5935 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5936 ArrayRef<CXXCtorInitializer *> Initializers = None);
5937
5938 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5939
5940
5941 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5942 /// mark all the non-trivial destructors of its members and bases as
5943 /// referenced.
5944 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5945 CXXRecordDecl *Record);
5946
5947 /// The list of classes whose vtables have been used within
5948 /// this translation unit, and the source locations at which the
5949 /// first use occurred.
5950 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5951
5952 /// The list of vtables that are required but have not yet been
5953 /// materialized.
5954 SmallVector<VTableUse, 16> VTableUses;
5955
5956 /// The set of classes whose vtables have been used within
5957 /// this translation unit, and a bit that will be true if the vtable is
5958 /// required to be emitted (otherwise, it should be emitted only if needed
5959 /// by code generation).
5960 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5961
5962 /// Load any externally-stored vtable uses.
5963 void LoadExternalVTableUses();
5964
5965 /// Note that the vtable for the given class was used at the
5966 /// given location.
5967 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5968 bool DefinitionRequired = false);
5969
5970 /// Mark the exception specifications of all virtual member functions
5971 /// in the given class as needed.
5972 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5973 const CXXRecordDecl *RD);
5974
5975 /// MarkVirtualMembersReferenced - Will mark all members of the given
5976 /// CXXRecordDecl referenced.
5977 void MarkVirtualMembersReferenced(SourceLocation Loc,
5978 const CXXRecordDecl *RD);
5979
5980 /// Define all of the vtables that have been used in this
5981 /// translation unit and reference any virtual members used by those
5982 /// vtables.
5983 ///
5984 /// \returns true if any work was done, false otherwise.
5985 bool DefineUsedVTables();
5986
5987 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5988
5989 void ActOnMemInitializers(Decl *ConstructorDecl,
5990 SourceLocation ColonLoc,
5991 ArrayRef<CXXCtorInitializer*> MemInits,
5992 bool AnyErrors);
5993
5994 /// Check class-level dllimport/dllexport attribute. The caller must
5995 /// ensure that referenceDLLExportedClassMethods is called some point later
5996 /// when all outer classes of Class are complete.
5997 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5998 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
5999
6000 void referenceDLLExportedClassMethods();
6001
6002 void propagateDLLAttrToBaseClassTemplate(
6003 CXXRecordDecl *Class, Attr *ClassAttr,
6004 ClassTemplateSpecializationDecl *BaseTemplateSpec,
6005 SourceLocation BaseLoc);
6006
6007 void CheckCompletedCXXClass(CXXRecordDecl *Record);
6008
6009 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6010 /// conditions that are needed for the attribute to have an effect.
6011 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
6012
6013 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6014 Decl *TagDecl, SourceLocation LBrac,
6015 SourceLocation RBrac,
6016 const ParsedAttributesView &AttrList);
6017 void ActOnFinishCXXMemberDecls();
6018 void ActOnFinishCXXNonNestedClass(Decl *D);
6019
6020 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6021 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
6022 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6023 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6024 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6025 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6026 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6027 void ActOnFinishDelayedMemberInitializers(Decl *Record);
6028 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
6029 CachedTokens &Toks);
6030 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
6031 bool IsInsideALocalClassWithinATemplateFunction();
6032
6033 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6034 Expr *AssertExpr,
6035 Expr *AssertMessageExpr,
6036 SourceLocation RParenLoc);
6037 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6038 Expr *AssertExpr,
6039 StringLiteral *AssertMessageExpr,
6040 SourceLocation RParenLoc,
6041 bool Failed);
6042
6043 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
6044 SourceLocation FriendLoc,
6045 TypeSourceInfo *TSInfo);
6046 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6047 MultiTemplateParamsArg TemplateParams);
6048 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6049 MultiTemplateParamsArg TemplateParams);
6050
6051 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6052 StorageClass& SC);
6053 void CheckConstructor(CXXConstructorDecl *Constructor);
6054 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6055 StorageClass& SC);
6056 bool CheckDestructor(CXXDestructorDecl *Destructor);
6057 void CheckConversionDeclarator(Declarator &D, QualType &R,
6058 StorageClass& SC);
6059 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6060 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6061 StorageClass &SC);
6062 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
6063
6064 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
6065 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
6066 const FunctionProtoType *T);
6067 void CheckDelayedMemberExceptionSpecs();
6068
6069 //===--------------------------------------------------------------------===//
6070 // C++ Derived Classes
6071 //
6072
6073 /// ActOnBaseSpecifier - Parsed a base specifier
6074 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6075 SourceRange SpecifierRange,
6076 bool Virtual, AccessSpecifier Access,
6077 TypeSourceInfo *TInfo,
6078 SourceLocation EllipsisLoc);
6079
6080 BaseResult ActOnBaseSpecifier(Decl *classdecl,
6081 SourceRange SpecifierRange,
6082 ParsedAttributes &Attrs,
6083 bool Virtual, AccessSpecifier Access,
6084 ParsedType basetype,
6085 SourceLocation BaseLoc,
6086 SourceLocation EllipsisLoc);
6087
6088 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6089 MutableArrayRef<CXXBaseSpecifier *> Bases);
6090 void ActOnBaseSpecifiers(Decl *ClassDecl,
6091 MutableArrayRef<CXXBaseSpecifier *> Bases);
6092
6093 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6094 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6095 CXXBasePaths &Paths);
6096
6097 // FIXME: I don't like this name.
6098 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6099
6100 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6101 SourceLocation Loc, SourceRange Range,
6102 CXXCastPath *BasePath = nullptr,
6103 bool IgnoreAccess = false);
6104 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6105 unsigned InaccessibleBaseID,
6106 unsigned AmbigiousBaseConvID,
6107 SourceLocation Loc, SourceRange Range,
6108 DeclarationName Name,
6109 CXXCastPath *BasePath,
6110 bool IgnoreAccess = false);
6111
6112 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6113
6114 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6115 const CXXMethodDecl *Old);
6116
6117 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6118 /// covariant, according to C++ [class.virtual]p5.
6119 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6120 const CXXMethodDecl *Old);
6121
6122 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6123 /// spec is a subset of base spec.
6124 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6125 const CXXMethodDecl *Old);
6126
6127 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6128
6129 /// CheckOverrideControl - Check C++11 override control semantics.
6130 void CheckOverrideControl(NamedDecl *D);
6131
6132 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6133 /// not used in the declaration of an overriding method.
6134 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
6135
6136 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
6137 /// overrides a virtual member function marked 'final', according to
6138 /// C++11 [class.virtual]p4.
6139 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6140 const CXXMethodDecl *Old);
6141
6142
6143 //===--------------------------------------------------------------------===//
6144 // C++ Access Control
6145 //
6146
6147 enum AccessResult {
6148 AR_accessible,
6149 AR_inaccessible,
6150 AR_dependent,
6151 AR_delayed
6152 };
6153
6154 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
6155 NamedDecl *PrevMemberDecl,
6156 AccessSpecifier LexicalAS);
6157
6158 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
6159 DeclAccessPair FoundDecl);
6160 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
6161 DeclAccessPair FoundDecl);
6162 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
6163 SourceRange PlacementRange,
6164 CXXRecordDecl *NamingClass,
6165 DeclAccessPair FoundDecl,
6166 bool Diagnose = true);
6167 AccessResult CheckConstructorAccess(SourceLocation Loc,
6168 CXXConstructorDecl *D,
6169 DeclAccessPair FoundDecl,
6170 const InitializedEntity &Entity,
6171 bool IsCopyBindingRefToTemp = false);
6172 AccessResult CheckConstructorAccess(SourceLocation Loc,
6173 CXXConstructorDecl *D,
6174 DeclAccessPair FoundDecl,
6175 const InitializedEntity &Entity,
6176 const PartialDiagnostic &PDiag);
6177 AccessResult CheckDestructorAccess(SourceLocation Loc,
6178 CXXDestructorDecl *Dtor,
6179 const PartialDiagnostic &PDiag,
6180 QualType objectType = QualType());
6181 AccessResult CheckFriendAccess(NamedDecl *D);
6182 AccessResult CheckMemberAccess(SourceLocation UseLoc,
6183 CXXRecordDecl *NamingClass,
6184 DeclAccessPair Found);
6185 AccessResult
6186 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
6187 CXXRecordDecl *DecomposedClass,
6188 DeclAccessPair Field);
6189 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
6190 Expr *ObjectExpr,
6191 Expr *ArgExpr,
6192 DeclAccessPair FoundDecl);
6193 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
6194 DeclAccessPair FoundDecl);
6195 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
6196 QualType Base, QualType Derived,
6197 const CXXBasePath &Path,
6198 unsigned DiagID,
6199 bool ForceCheck = false,
6200 bool ForceUnprivileged = false);
6201 void CheckLookupAccess(const LookupResult &R);
6202 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
6203 QualType BaseType);
6204 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
6205 AccessSpecifier access,
6206 QualType objectType);
6207
6208 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
6209 const MultiLevelTemplateArgumentList &TemplateArgs);
6210 void PerformDependentDiagnostics(const DeclContext *Pattern,
6211 const MultiLevelTemplateArgumentList &TemplateArgs);
6212
6213 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
6214
6215 /// When true, access checking violations are treated as SFINAE
6216 /// failures rather than hard errors.
6217 bool AccessCheckingSFINAE;
6218
6219 enum AbstractDiagSelID {
6220 AbstractNone = -1,
6221 AbstractReturnType,
6222 AbstractParamType,
6223 AbstractVariableType,
6224 AbstractFieldType,
6225 AbstractIvarType,
6226 AbstractSynthesizedIvarType,
6227 AbstractArrayType
6228 };
6229
6230 bool isAbstractType(SourceLocation Loc, QualType T);
6231 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6232 TypeDiagnoser &Diagnoser);
6233 template <typename... Ts>
6234 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6235 const Ts &...Args) {
6236 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6237 return RequireNonAbstractType(Loc, T, Diagnoser);
6238 }
6239
6240 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6241
6242 //===--------------------------------------------------------------------===//
6243 // C++ Overloaded Operators [C++ 13.5]
6244 //
6245
6246 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6247
6248 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6249
6250 //===--------------------------------------------------------------------===//
6251 // C++ Templates [C++ 14]
6252 //
6253 void FilterAcceptableTemplateNames(LookupResult &R,
6254 bool AllowFunctionTemplates = true,
6255 bool AllowDependent = true);
6256 bool hasAnyAcceptableTemplateNames(LookupResult &R,
6257 bool AllowFunctionTemplates = true,
6258 bool AllowDependent = true);
6259 /// Try to interpret the lookup result D as a template-name.
6260 ///
6261 /// \param D A declaration found by name lookup.
6262 /// \param AllowFunctionTemplates Whether function templates should be
6263 /// considered valid results.
6264 /// \param AllowDependent Whether unresolved using declarations (that might
6265 /// name templates) should be considered valid results.
6266 NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
6267 bool AllowFunctionTemplates = true,
6268 bool AllowDependent = true);
6269
6270 bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
6271 QualType ObjectType, bool EnteringContext,
6272 bool &MemberOfUnknownSpecialization,
6273 SourceLocation TemplateKWLoc = SourceLocation());
6274
6275 TemplateNameKind isTemplateName(Scope *S,
6276 CXXScopeSpec &SS,
6277 bool hasTemplateKeyword,
6278 const UnqualifiedId &Name,
6279 ParsedType ObjectType,
6280 bool EnteringContext,
6281 TemplateTy &Template,
6282 bool &MemberOfUnknownSpecialization);
6283
6284 /// Determine whether a particular identifier might be the name in a C++1z
6285 /// deduction-guide declaration.
6286 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
6287 SourceLocation NameLoc,
6288 ParsedTemplateTy *Template = nullptr);
6289
6290 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
6291 SourceLocation IILoc,
6292 Scope *S,
6293 const CXXScopeSpec *SS,
6294 TemplateTy &SuggestedTemplate,
6295 TemplateNameKind &SuggestedKind);
6296
6297 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
6298 NamedDecl *Instantiation,
6299 bool InstantiatedFromMember,
6300 const NamedDecl *Pattern,
6301 const NamedDecl *PatternDef,
6302 TemplateSpecializationKind TSK,
6303 bool Complain = true);
6304
6305 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
6306 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
6307
6308 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
6309 SourceLocation EllipsisLoc,
6310 SourceLocation KeyLoc,
6311 IdentifierInfo *ParamName,
6312 SourceLocation ParamNameLoc,
6313 unsigned Depth, unsigned Position,
6314 SourceLocation EqualLoc,
6315 ParsedType DefaultArg);
6316
6317 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
6318 SourceLocation Loc);
6319 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
6320
6321 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
6322 unsigned Depth,
6323 unsigned Position,
6324 SourceLocation EqualLoc,
6325 Expr *DefaultArg);
6326 NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
6327 SourceLocation TmpLoc,
6328 TemplateParameterList *Params,
6329 SourceLocation EllipsisLoc,
6330 IdentifierInfo *ParamName,
6331 SourceLocation ParamNameLoc,
6332 unsigned Depth,
6333 unsigned Position,
6334 SourceLocation EqualLoc,
6335 ParsedTemplateArgument DefaultArg);
6336
6337 TemplateParameterList *
6338 ActOnTemplateParameterList(unsigned Depth,
6339 SourceLocation ExportLoc,
6340 SourceLocation TemplateLoc,
6341 SourceLocation LAngleLoc,
6342 ArrayRef<NamedDecl *> Params,
6343 SourceLocation RAngleLoc,
6344 Expr *RequiresClause);
6345
6346 /// The context in which we are checking a template parameter list.
6347 enum TemplateParamListContext {
6348 TPC_ClassTemplate,
6349 TPC_VarTemplate,
6350 TPC_FunctionTemplate,
6351 TPC_ClassTemplateMember,
6352 TPC_FriendClassTemplate,
6353 TPC_FriendFunctionTemplate,
6354 TPC_FriendFunctionTemplateDefinition,
6355 TPC_TypeAliasTemplate
6356 };
6357
6358 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
6359 TemplateParameterList *OldParams,
6360 TemplateParamListContext TPC,
6361 SkipBodyInfo *SkipBody = nullptr);
6362 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
6363 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
6364 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
6365 ArrayRef<TemplateParameterList *> ParamLists,
6366 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
6367
6368 DeclResult CheckClassTemplate(
6369 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
6370 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
6371 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
6372 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
6373 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
6374 TemplateParameterList **OuterTemplateParamLists,
6375 SkipBodyInfo *SkipBody = nullptr);
6376
6377 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6378 QualType NTTPType,
6379 SourceLocation Loc);
6380
6381 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6382 TemplateArgumentListInfo &Out);
6383
6384 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
6385
6386 void NoteAllFoundTemplates(TemplateName Name);
6387
6388 QualType CheckTemplateIdType(TemplateName Template,
6389 SourceLocation TemplateLoc,
6390 TemplateArgumentListInfo &TemplateArgs);
6391
6392 TypeResult
6393 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6394 TemplateTy Template, IdentifierInfo *TemplateII,
6395 SourceLocation TemplateIILoc,
6396 SourceLocation LAngleLoc,
6397 ASTTemplateArgsPtr TemplateArgs,
6398 SourceLocation RAngleLoc,
6399 bool IsCtorOrDtorName = false,
6400 bool IsClassName = false);
6401
6402 /// Parsed an elaborated-type-specifier that refers to a template-id,
6403 /// such as \c class T::template apply<U>.
6404 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6405 TypeSpecifierType TagSpec,
6406 SourceLocation TagLoc,
6407 CXXScopeSpec &SS,
6408 SourceLocation TemplateKWLoc,
6409 TemplateTy TemplateD,
6410 SourceLocation TemplateLoc,
6411 SourceLocation LAngleLoc,
6412 ASTTemplateArgsPtr TemplateArgsIn,
6413 SourceLocation RAngleLoc);
6414
6415 DeclResult ActOnVarTemplateSpecialization(
6416 Scope *S, Declarator &D, TypeSourceInfo *DI,
6417 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6418 StorageClass SC, bool IsPartialSpecialization);
6419
6420 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6421 SourceLocation TemplateLoc,
6422 SourceLocation TemplateNameLoc,
6423 const TemplateArgumentListInfo &TemplateArgs);
6424
6425 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6426 const DeclarationNameInfo &NameInfo,
6427 VarTemplateDecl *Template,
6428 SourceLocation TemplateLoc,
6429 const TemplateArgumentListInfo *TemplateArgs);
6430
6431 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
6432
6433 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6434 SourceLocation TemplateKWLoc,
6435 LookupResult &R,
6436 bool RequiresADL,
6437 const TemplateArgumentListInfo *TemplateArgs);
6438
6439 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6440 SourceLocation TemplateKWLoc,
6441 const DeclarationNameInfo &NameInfo,
6442 const TemplateArgumentListInfo *TemplateArgs);
6443
6444 TemplateNameKind ActOnDependentTemplateName(
6445 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6446 const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6447 TemplateTy &Template, bool AllowInjectedClassName = false);
6448
6449 DeclResult ActOnClassTemplateSpecialization(
6450 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
6451 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
6452 const ParsedAttributesView &Attr,
6453 MultiTemplateParamsArg TemplateParameterLists,
6454 SkipBodyInfo *SkipBody = nullptr);
6455
6456 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6457 TemplateDecl *PrimaryTemplate,
6458 unsigned NumExplicitArgs,
6459 ArrayRef<TemplateArgument> Args);
6460 void CheckTemplatePartialSpecialization(
6461 ClassTemplatePartialSpecializationDecl *Partial);
6462 void CheckTemplatePartialSpecialization(
6463 VarTemplatePartialSpecializationDecl *Partial);
6464
6465 Decl *ActOnTemplateDeclarator(Scope *S,
6466 MultiTemplateParamsArg TemplateParameterLists,
6467 Declarator &D);
6468
6469 bool
6470 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6471 TemplateSpecializationKind NewTSK,
6472 NamedDecl *PrevDecl,
6473 TemplateSpecializationKind PrevTSK,
6474 SourceLocation PrevPtOfInstantiation,
6475 bool &SuppressNew);
6476
6477 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6478 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6479 LookupResult &Previous);
6480
6481 bool CheckFunctionTemplateSpecialization(
6482 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6483 LookupResult &Previous, bool QualifiedFriend = false);
6484 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6485 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6486
6487 DeclResult ActOnExplicitInstantiation(
6488 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
6489 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
6490 TemplateTy Template, SourceLocation TemplateNameLoc,
6491 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
6492 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
6493
6494 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
6495 SourceLocation TemplateLoc,
6496 unsigned TagSpec, SourceLocation KWLoc,
6497 CXXScopeSpec &SS, IdentifierInfo *Name,
6498 SourceLocation NameLoc,
6499 const ParsedAttributesView &Attr);
6500
6501 DeclResult ActOnExplicitInstantiation(Scope *S,
6502 SourceLocation ExternLoc,
6503 SourceLocation TemplateLoc,
6504 Declarator &D);
6505
6506 TemplateArgumentLoc
6507 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6508 SourceLocation TemplateLoc,
6509 SourceLocation RAngleLoc,
6510 Decl *Param,
6511 SmallVectorImpl<TemplateArgument>
6512 &Converted,
6513 bool &HasDefaultArg);
6514
6515 /// Specifies the context in which a particular template
6516 /// argument is being checked.
6517 enum CheckTemplateArgumentKind {
6518 /// The template argument was specified in the code or was
6519 /// instantiated with some deduced template arguments.
6520 CTAK_Specified,
6521
6522 /// The template argument was deduced via template argument
6523 /// deduction.
6524 CTAK_Deduced,
6525
6526 /// The template argument was deduced from an array bound
6527 /// via template argument deduction.
6528 CTAK_DeducedFromArrayBound
6529 };
6530
6531 bool CheckTemplateArgument(NamedDecl *Param,
6532 TemplateArgumentLoc &Arg,
6533 NamedDecl *Template,
6534 SourceLocation TemplateLoc,
6535 SourceLocation RAngleLoc,
6536 unsigned ArgumentPackIndex,
6537 SmallVectorImpl<TemplateArgument> &Converted,
6538 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6539
6540 /// Check that the given template arguments can be be provided to
6541 /// the given template, converting the arguments along the way.
6542 ///
6543 /// \param Template The template to which the template arguments are being
6544 /// provided.
6545 ///
6546 /// \param TemplateLoc The location of the template name in the source.
6547 ///
6548 /// \param TemplateArgs The list of template arguments. If the template is
6549 /// a template template parameter, this function may extend the set of
6550 /// template arguments to also include substituted, defaulted template
6551 /// arguments.
6552 ///
6553 /// \param PartialTemplateArgs True if the list of template arguments is
6554 /// intentionally partial, e.g., because we're checking just the initial
6555 /// set of template arguments.
6556 ///
6557 /// \param Converted Will receive the converted, canonicalized template
6558 /// arguments.
6559 ///
6560 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6561 /// contain the converted forms of the template arguments as written.
6562 /// Otherwise, \p TemplateArgs will not be modified.
6563 ///
6564 /// \returns true if an error occurred, false otherwise.
6565 bool CheckTemplateArgumentList(TemplateDecl *Template,
6566 SourceLocation TemplateLoc,
6567 TemplateArgumentListInfo &TemplateArgs,
6568 bool PartialTemplateArgs,
6569 SmallVectorImpl<TemplateArgument> &Converted,
6570 bool UpdateArgsWithConversions = true);
6571
6572 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6573 TemplateArgumentLoc &Arg,
6574 SmallVectorImpl<TemplateArgument> &Converted);
6575
6576 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6577 TypeSourceInfo *Arg);
6578 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6579 QualType InstantiatedParamType, Expr *Arg,
6580 TemplateArgument &Converted,
6581 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6582 bool CheckTemplateTemplateArgument(TemplateParameterList *Params,
6583 TemplateArgumentLoc &Arg);
6584
6585 ExprResult
6586 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6587 QualType ParamType,
6588 SourceLocation Loc);
6589 ExprResult
6590 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6591 SourceLocation Loc);
6592
6593 /// Enumeration describing how template parameter lists are compared
6594 /// for equality.
6595 enum TemplateParameterListEqualKind {
6596 /// We are matching the template parameter lists of two templates
6597 /// that might be redeclarations.
6598 ///
6599 /// \code
6600 /// template<typename T> struct X;
6601 /// template<typename T> struct X;
6602 /// \endcode
6603 TPL_TemplateMatch,
6604
6605 /// We are matching the template parameter lists of two template
6606 /// template parameters as part of matching the template parameter lists
6607 /// of two templates that might be redeclarations.
6608 ///
6609 /// \code
6610 /// template<template<int I> class TT> struct X;
6611 /// template<template<int Value> class Other> struct X;
6612 /// \endcode
6613 TPL_TemplateTemplateParmMatch,
6614
6615 /// We are matching the template parameter lists of a template
6616 /// template argument against the template parameter lists of a template
6617 /// template parameter.
6618 ///
6619 /// \code
6620 /// template<template<int Value> class Metafun> struct X;
6621 /// template<int Value> struct integer_c;
6622 /// X<integer_c> xic;
6623 /// \endcode
6624 TPL_TemplateTemplateArgumentMatch
6625 };
6626
6627 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6628 TemplateParameterList *Old,
6629 bool Complain,
6630 TemplateParameterListEqualKind Kind,
6631 SourceLocation TemplateArgLoc
6632 = SourceLocation());
6633
6634 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6635
6636 /// Called when the parser has parsed a C++ typename
6637 /// specifier, e.g., "typename T::type".
6638 ///
6639 /// \param S The scope in which this typename type occurs.
6640 /// \param TypenameLoc the location of the 'typename' keyword
6641 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6642 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6643 /// \param IdLoc the location of the identifier.
6644 TypeResult
6645 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6646 const CXXScopeSpec &SS, const IdentifierInfo &II,
6647 SourceLocation IdLoc);
6648
6649 /// Called when the parser has parsed a C++ typename
6650 /// specifier that ends in a template-id, e.g.,
6651 /// "typename MetaFun::template apply<T1, T2>".
6652 ///
6653 /// \param S The scope in which this typename type occurs.
6654 /// \param TypenameLoc the location of the 'typename' keyword
6655 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6656 /// \param TemplateLoc the location of the 'template' keyword, if any.
6657 /// \param TemplateName The template name.
6658 /// \param TemplateII The identifier used to name the template.
6659 /// \param TemplateIILoc The location of the template name.
6660 /// \param LAngleLoc The location of the opening angle bracket ('<').
6661 /// \param TemplateArgs The template arguments.
6662 /// \param RAngleLoc The location of the closing angle bracket ('>').
6663 TypeResult
6664 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6665 const CXXScopeSpec &SS,
6666 SourceLocation TemplateLoc,
6667 TemplateTy TemplateName,
6668 IdentifierInfo *TemplateII,
6669 SourceLocation TemplateIILoc,
6670 SourceLocation LAngleLoc,
6671 ASTTemplateArgsPtr TemplateArgs,
6672 SourceLocation RAngleLoc);
6673
6674 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6675 SourceLocation KeywordLoc,
6676 NestedNameSpecifierLoc QualifierLoc,
6677 const IdentifierInfo &II,
6678 SourceLocation IILoc);
6679
6680 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6681 SourceLocation Loc,
6682 DeclarationName Name);
6683 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6684
6685 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6686 bool RebuildTemplateParamsInCurrentInstantiation(
6687 TemplateParameterList *Params);
6688
6689 std::string
6690 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6691 const TemplateArgumentList &Args);
6692
6693 std::string
6694 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6695 const TemplateArgument *Args,
6696 unsigned NumArgs);
6697
6698 //===--------------------------------------------------------------------===//
6699 // C++ Variadic Templates (C++0x [temp.variadic])
6700 //===--------------------------------------------------------------------===//
6701
6702 /// Determine whether an unexpanded parameter pack might be permitted in this
6703 /// location. Useful for error recovery.
6704 bool isUnexpandedParameterPackPermitted();
6705
6706 /// The context in which an unexpanded parameter pack is
6707 /// being diagnosed.
6708 ///
6709 /// Note that the values of this enumeration line up with the first
6710 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6711 enum UnexpandedParameterPackContext {
6712 /// An arbitrary expression.
6713 UPPC_Expression = 0,
6714
6715 /// The base type of a class type.
6716 UPPC_BaseType,
6717
6718 /// The type of an arbitrary declaration.
6719 UPPC_DeclarationType,
6720
6721 /// The type of a data member.
6722 UPPC_DataMemberType,
6723
6724 /// The size of a bit-field.
6725 UPPC_BitFieldWidth,
6726
6727 /// The expression in a static assertion.
6728 UPPC_StaticAssertExpression,
6729
6730 /// The fixed underlying type of an enumeration.
6731 UPPC_FixedUnderlyingType,
6732
6733 /// The enumerator value.
6734 UPPC_EnumeratorValue,
6735
6736 /// A using declaration.
6737 UPPC_UsingDeclaration,
6738
6739 /// A friend declaration.
6740 UPPC_FriendDeclaration,
6741
6742 /// A declaration qualifier.
6743 UPPC_DeclarationQualifier,
6744
6745 /// An initializer.
6746 UPPC_Initializer,
6747
6748 /// A default argument.
6749 UPPC_DefaultArgument,
6750
6751 /// The type of a non-type template parameter.
6752 UPPC_NonTypeTemplateParameterType,
6753
6754 /// The type of an exception.
6755 UPPC_ExceptionType,
6756
6757 /// Partial specialization.
6758 UPPC_PartialSpecialization,
6759
6760 /// Microsoft __if_exists.
6761 UPPC_IfExists,
6762
6763 /// Microsoft __if_not_exists.
6764 UPPC_IfNotExists,
6765
6766 /// Lambda expression.
6767 UPPC_Lambda,
6768
6769 /// Block expression,
6770 UPPC_Block
6771 };
6772
6773 /// Diagnose unexpanded parameter packs.
6774 ///
6775 /// \param Loc The location at which we should emit the diagnostic.
6776 ///
6777 /// \param UPPC The context in which we are diagnosing unexpanded
6778 /// parameter packs.
6779 ///
6780 /// \param Unexpanded the set of unexpanded parameter packs.
6781 ///
6782 /// \returns true if an error occurred, false otherwise.
6783 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6784 UnexpandedParameterPackContext UPPC,
6785 ArrayRef<UnexpandedParameterPack> Unexpanded);
6786
6787 /// If the given type contains an unexpanded parameter pack,
6788 /// diagnose the error.
6789 ///
6790 /// \param Loc The source location where a diagnostc should be emitted.
6791 ///
6792 /// \param T The type that is being checked for unexpanded parameter
6793 /// packs.
6794 ///
6795 /// \returns true if an error occurred, false otherwise.
6796 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6797 UnexpandedParameterPackContext UPPC);
6798
6799 /// If the given expression contains an unexpanded parameter
6800 /// pack, diagnose the error.
6801 ///
6802 /// \param E The expression that is being checked for unexpanded
6803 /// parameter packs.
6804 ///
6805 /// \returns true if an error occurred, false otherwise.
6806 bool DiagnoseUnexpandedParameterPack(Expr *E,
6807 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6808
6809 /// If the given nested-name-specifier contains an unexpanded
6810 /// parameter pack, diagnose the error.
6811 ///
6812 /// \param SS The nested-name-specifier that is being checked for
6813 /// unexpanded parameter packs.
6814 ///
6815 /// \returns true if an error occurred, false otherwise.
6816 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6817 UnexpandedParameterPackContext UPPC);
6818
6819 /// If the given name contains an unexpanded parameter pack,
6820 /// diagnose the error.
6821 ///
6822 /// \param NameInfo The name (with source location information) that
6823 /// is being checked for unexpanded parameter packs.
6824 ///
6825 /// \returns true if an error occurred, false otherwise.
6826 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6827 UnexpandedParameterPackContext UPPC);
6828
6829 /// If the given template name contains an unexpanded parameter pack,
6830 /// diagnose the error.
6831 ///
6832 /// \param Loc The location of the template name.
6833 ///
6834 /// \param Template The template name that is being checked for unexpanded
6835 /// parameter packs.
6836 ///
6837 /// \returns true if an error occurred, false otherwise.
6838 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6839 TemplateName Template,
6840 UnexpandedParameterPackContext UPPC);
6841
6842 /// If the given template argument contains an unexpanded parameter
6843 /// pack, diagnose the error.
6844 ///
6845 /// \param Arg The template argument that is being checked for unexpanded
6846 /// parameter packs.
6847 ///
6848 /// \returns true if an error occurred, false otherwise.
6849 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6850 UnexpandedParameterPackContext UPPC);
6851
6852 /// Collect the set of unexpanded parameter packs within the given
6853 /// template argument.
6854 ///
6855 /// \param Arg The template argument that will be traversed to find
6856 /// unexpanded parameter packs.
6857 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6858 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6859
6860 /// Collect the set of unexpanded parameter packs within the given
6861 /// template argument.
6862 ///
6863 /// \param Arg The template argument that will be traversed to find
6864 /// unexpanded parameter packs.
6865 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6866 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6867
6868 /// Collect the set of unexpanded parameter packs within the given
6869 /// type.
6870 ///
6871 /// \param T The type that will be traversed to find
6872 /// unexpanded parameter packs.
6873 void collectUnexpandedParameterPacks(QualType T,
6874 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6875
6876 /// Collect the set of unexpanded parameter packs within the given
6877 /// type.
6878 ///
6879 /// \param TL The type that will be traversed to find
6880 /// unexpanded parameter packs.
6881 void collectUnexpandedParameterPacks(TypeLoc TL,
6882 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6883
6884 /// Collect the set of unexpanded parameter packs within the given
6885 /// nested-name-specifier.
6886 ///
6887 /// \param NNS The nested-name-specifier that will be traversed to find
6888 /// unexpanded parameter packs.
6889 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6890 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6891
6892 /// Collect the set of unexpanded parameter packs within the given
6893 /// name.
6894 ///
6895 /// \param NameInfo The name that will be traversed to find
6896 /// unexpanded parameter packs.
6897 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6898 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6899
6900 /// Invoked when parsing a template argument followed by an
6901 /// ellipsis, which creates a pack expansion.
6902 ///
6903 /// \param Arg The template argument preceding the ellipsis, which
6904 /// may already be invalid.
6905 ///
6906 /// \param EllipsisLoc The location of the ellipsis.
6907 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6908 SourceLocation EllipsisLoc);
6909
6910 /// Invoked when parsing a type followed by an ellipsis, which
6911 /// creates a pack expansion.
6912 ///
6913 /// \param Type The type preceding the ellipsis, which will become
6914 /// the pattern of the pack expansion.
6915 ///
6916 /// \param EllipsisLoc The location of the ellipsis.
6917 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6918
6919 /// Construct a pack expansion type from the pattern of the pack
6920 /// expansion.
6921 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6922 SourceLocation EllipsisLoc,
6923 Optional<unsigned> NumExpansions);
6924
6925 /// Construct a pack expansion type from the pattern of the pack
6926 /// expansion.
6927 QualType CheckPackExpansion(QualType Pattern,
6928 SourceRange PatternRange,
6929 SourceLocation EllipsisLoc,
6930 Optional<unsigned> NumExpansions);
6931
6932 /// Invoked when parsing an expression followed by an ellipsis, which
6933 /// creates a pack expansion.
6934 ///
6935 /// \param Pattern The expression preceding the ellipsis, which will become
6936 /// the pattern of the pack expansion.
6937 ///
6938 /// \param EllipsisLoc The location of the ellipsis.
6939 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6940
6941 /// Invoked when parsing an expression followed by an ellipsis, which
6942 /// creates a pack expansion.
6943 ///
6944 /// \param Pattern The expression preceding the ellipsis, which will become
6945 /// the pattern of the pack expansion.
6946 ///
6947 /// \param EllipsisLoc The location of the ellipsis.
6948 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6949 Optional<unsigned> NumExpansions);
6950
6951 /// Determine whether we could expand a pack expansion with the
6952 /// given set of parameter packs into separate arguments by repeatedly
6953 /// transforming the pattern.
6954 ///
6955 /// \param EllipsisLoc The location of the ellipsis that identifies the
6956 /// pack expansion.
6957 ///
6958 /// \param PatternRange The source range that covers the entire pattern of
6959 /// the pack expansion.
6960 ///
6961 /// \param Unexpanded The set of unexpanded parameter packs within the
6962 /// pattern.
6963 ///
6964 /// \param ShouldExpand Will be set to \c true if the transformer should
6965 /// expand the corresponding pack expansions into separate arguments. When
6966 /// set, \c NumExpansions must also be set.
6967 ///
6968 /// \param RetainExpansion Whether the caller should add an unexpanded
6969 /// pack expansion after all of the expanded arguments. This is used
6970 /// when extending explicitly-specified template argument packs per
6971 /// C++0x [temp.arg.explicit]p9.
6972 ///
6973 /// \param NumExpansions The number of separate arguments that will be in
6974 /// the expanded form of the corresponding pack expansion. This is both an
6975 /// input and an output parameter, which can be set by the caller if the
6976 /// number of expansions is known a priori (e.g., due to a prior substitution)
6977 /// and will be set by the callee when the number of expansions is known.
6978 /// The callee must set this value when \c ShouldExpand is \c true; it may
6979 /// set this value in other cases.
6980 ///
6981 /// \returns true if an error occurred (e.g., because the parameter packs
6982 /// are to be instantiated with arguments of different lengths), false
6983 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6984 /// must be set.
6985 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6986 SourceRange PatternRange,
6987 ArrayRef<UnexpandedParameterPack> Unexpanded,
6988 const MultiLevelTemplateArgumentList &TemplateArgs,
6989 bool &ShouldExpand,
6990 bool &RetainExpansion,
6991 Optional<unsigned> &NumExpansions);
6992
6993 /// Determine the number of arguments in the given pack expansion
6994 /// type.
6995 ///
6996 /// This routine assumes that the number of arguments in the expansion is
6997 /// consistent across all of the unexpanded parameter packs in its pattern.
6998 ///
6999 /// Returns an empty Optional if the type can't be expanded.
7000 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
7001 const MultiLevelTemplateArgumentList &TemplateArgs);
7002
7003 /// Determine whether the given declarator contains any unexpanded
7004 /// parameter packs.
7005 ///
7006 /// This routine is used by the parser to disambiguate function declarators
7007 /// with an ellipsis prior to the ')', e.g.,
7008 ///
7009 /// \code
7010 /// void f(T...);
7011 /// \endcode
7012 ///
7013 /// To determine whether we have an (unnamed) function parameter pack or
7014 /// a variadic function.
7015 ///
7016 /// \returns true if the declarator contains any unexpanded parameter packs,
7017 /// false otherwise.
7018 bool containsUnexpandedParameterPacks(Declarator &D);
7019
7020 /// Returns the pattern of the pack expansion for a template argument.
7021 ///
7022 /// \param OrigLoc The template argument to expand.
7023 ///
7024 /// \param Ellipsis Will be set to the location of the ellipsis.
7025 ///
7026 /// \param NumExpansions Will be set to the number of expansions that will
7027 /// be generated from this pack expansion, if known a priori.
7028 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
7029 TemplateArgumentLoc OrigLoc,
7030 SourceLocation &Ellipsis,
7031 Optional<unsigned> &NumExpansions) const;
7032
7033 /// Given a template argument that contains an unexpanded parameter pack, but
7034 /// which has already been substituted, attempt to determine the number of
7035 /// elements that will be produced once this argument is fully-expanded.
7036 ///
7037 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
7038 /// avoid actually expanding the pack where possible.
7039 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
7040
7041 //===--------------------------------------------------------------------===//
7042 // C++ Template Argument Deduction (C++ [temp.deduct])
7043 //===--------------------------------------------------------------------===//
7044
7045 /// Adjust the type \p ArgFunctionType to match the calling convention,
7046 /// noreturn, and optionally the exception specification of \p FunctionType.
7047 /// Deduction often wants to ignore these properties when matching function
7048 /// types.
7049 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
7050 bool AdjustExceptionSpec = false);
7051
7052 /// Describes the result of template argument deduction.
7053 ///
7054 /// The TemplateDeductionResult enumeration describes the result of
7055 /// template argument deduction, as returned from
7056 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
7057 /// structure provides additional information about the results of
7058 /// template argument deduction, e.g., the deduced template argument
7059 /// list (if successful) or the specific template parameters or
7060 /// deduced arguments that were involved in the failure.
7061 enum TemplateDeductionResult {
7062 /// Template argument deduction was successful.
7063 TDK_Success = 0,
7064 /// The declaration was invalid; do nothing.
7065 TDK_Invalid,
7066 /// Template argument deduction exceeded the maximum template
7067 /// instantiation depth (which has already been diagnosed).
7068 TDK_InstantiationDepth,
7069 /// Template argument deduction did not deduce a value
7070 /// for every template parameter.
7071 TDK_Incomplete,
7072 /// Template argument deduction did not deduce a value for every
7073 /// expansion of an expanded template parameter pack.
7074 TDK_IncompletePack,
7075 /// Template argument deduction produced inconsistent
7076 /// deduced values for the given template parameter.
7077 TDK_Inconsistent,
7078 /// Template argument deduction failed due to inconsistent
7079 /// cv-qualifiers on a template parameter type that would
7080 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
7081 /// but were given a non-const "X".
7082 TDK_Underqualified,
7083 /// Substitution of the deduced template argument values
7084 /// resulted in an error.
7085 TDK_SubstitutionFailure,
7086 /// After substituting deduced template arguments, a dependent
7087 /// parameter type did not match the corresponding argument.
7088 TDK_DeducedMismatch,
7089 /// After substituting deduced template arguments, an element of
7090 /// a dependent parameter type did not match the corresponding element
7091 /// of the corresponding argument (when deducing from an initializer list).
7092 TDK_DeducedMismatchNested,
7093 /// A non-depnedent component of the parameter did not match the
7094 /// corresponding component of the argument.
7095 TDK_NonDeducedMismatch,
7096 /// When performing template argument deduction for a function
7097 /// template, there were too many call arguments.
7098 TDK_TooManyArguments,
7099 /// When performing template argument deduction for a function
7100 /// template, there were too few call arguments.
7101 TDK_TooFewArguments,
7102 /// The explicitly-specified template arguments were not valid
7103 /// template arguments for the given template.
7104 TDK_InvalidExplicitArguments,
7105 /// Checking non-dependent argument conversions failed.
7106 TDK_NonDependentConversionFailure,
7107 /// Deduction failed; that's all we know.
7108 TDK_MiscellaneousDeductionFailure,
7109 /// CUDA Target attributes do not match.
7110 TDK_CUDATargetMismatch
7111 };
7112
7113 TemplateDeductionResult
7114 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
7115 const TemplateArgumentList &TemplateArgs,
7116 sema::TemplateDeductionInfo &Info);
7117
7118 TemplateDeductionResult
7119 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
7120 const TemplateArgumentList &TemplateArgs,
7121 sema::TemplateDeductionInfo &Info);
7122
7123 TemplateDeductionResult SubstituteExplicitTemplateArguments(
7124 FunctionTemplateDecl *FunctionTemplate,
7125 TemplateArgumentListInfo &ExplicitTemplateArgs,
7126 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
7127 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
7128 sema::TemplateDeductionInfo &Info);
7129
7130 /// brief A function argument from which we performed template argument
7131 // deduction for a call.
7132 struct OriginalCallArg {
7133 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
7134 unsigned ArgIdx, QualType OriginalArgType)
7135 : OriginalParamType(OriginalParamType),
7136 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
7137 OriginalArgType(OriginalArgType) {}
7138
7139 QualType OriginalParamType;
7140 bool DecomposedParam;
7141 unsigned ArgIdx;
7142 QualType OriginalArgType;
7143 };
7144
7145 TemplateDeductionResult FinishTemplateArgumentDeduction(
7146 FunctionTemplateDecl *FunctionTemplate,
7147 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
7148 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
7149 sema::TemplateDeductionInfo &Info,
7150 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
7151 bool PartialOverloading = false,
7152 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
7153
7154 TemplateDeductionResult DeduceTemplateArguments(
7155 FunctionTemplateDecl *FunctionTemplate,
7156 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7157 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
7158 bool PartialOverloading,
7159 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
7160
7161 TemplateDeductionResult
7162 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7163 TemplateArgumentListInfo *ExplicitTemplateArgs,
7164 QualType ArgFunctionType,
7165 FunctionDecl *&Specialization,
7166 sema::TemplateDeductionInfo &Info,
7167 bool IsAddressOfFunction = false);
7168
7169 TemplateDeductionResult
7170 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7171 QualType ToType,
7172 CXXConversionDecl *&Specialization,
7173 sema::TemplateDeductionInfo &Info);
7174
7175 TemplateDeductionResult
7176 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7177 TemplateArgumentListInfo *ExplicitTemplateArgs,
7178 FunctionDecl *&Specialization,
7179 sema::TemplateDeductionInfo &Info,
7180 bool IsAddressOfFunction = false);
7181
7182 /// Substitute Replacement for \p auto in \p TypeWithAuto
7183 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
7184 /// Substitute Replacement for auto in TypeWithAuto
7185 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
7186 QualType Replacement);
7187 /// Completely replace the \c auto in \p TypeWithAuto by
7188 /// \p Replacement. This does not retain any \c auto type sugar.
7189 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
7190
7191 /// Result type of DeduceAutoType.
7192 enum DeduceAutoResult {
7193 DAR_Succeeded,
7194 DAR_Failed,
7195 DAR_FailedAlreadyDiagnosed
7196 };
7197
7198 DeduceAutoResult
7199 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
7200 Optional<unsigned> DependentDeductionDepth = None);
7201 DeduceAutoResult
7202 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
7203 Optional<unsigned> DependentDeductionDepth = None);
7204 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
7205 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
7206 bool Diagnose = true);
7207
7208 /// Declare implicit deduction guides for a class template if we've
7209 /// not already done so.
7210 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
7211 SourceLocation Loc);
7212
7213 QualType DeduceTemplateSpecializationFromInitializer(
7214 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
7215 const InitializationKind &Kind, MultiExprArg Init);
7216
7217 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
7218 QualType Type, TypeSourceInfo *TSI,
7219 SourceRange Range, bool DirectInit,
7220 Expr *Init);
7221
7222 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
7223
7224 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
7225 SourceLocation ReturnLoc,
7226 Expr *&RetExpr, AutoType *AT);
7227
7228 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
7229 FunctionTemplateDecl *FT2,
7230 SourceLocation Loc,
7231 TemplatePartialOrderingContext TPOC,
7232 unsigned NumCallArguments1,
7233 unsigned NumCallArguments2);
7234 UnresolvedSetIterator
7235 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
7236 TemplateSpecCandidateSet &FailedCandidates,
7237 SourceLocation Loc,
7238 const PartialDiagnostic &NoneDiag,
7239 const PartialDiagnostic &AmbigDiag,
7240 const PartialDiagnostic &CandidateDiag,
7241 bool Complain = true, QualType TargetType = QualType());
7242
7243 ClassTemplatePartialSpecializationDecl *
7244 getMoreSpecializedPartialSpecialization(
7245 ClassTemplatePartialSpecializationDecl *PS1,
7246 ClassTemplatePartialSpecializationDecl *PS2,
7247 SourceLocation Loc);
7248
7249 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
7250 sema::TemplateDeductionInfo &Info);
7251
7252 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
7253 VarTemplatePartialSpecializationDecl *PS1,
7254 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
7255
7256 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
7257 sema::TemplateDeductionInfo &Info);
7258
7259 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
7260 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
7261
7262 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
7263 bool OnlyDeduced,
7264 unsigned Depth,
7265 llvm::SmallBitVector &Used);
7266 void MarkDeducedTemplateParameters(
7267 const FunctionTemplateDecl *FunctionTemplate,
7268 llvm::SmallBitVector &Deduced) {
7269 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
7270 }
7271 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
7272 const FunctionTemplateDecl *FunctionTemplate,
7273 llvm::SmallBitVector &Deduced);
7274
7275 //===--------------------------------------------------------------------===//
7276 // C++ Template Instantiation
7277 //
7278
7279 MultiLevelTemplateArgumentList
7280 getTemplateInstantiationArgs(NamedDecl *D,
7281 const TemplateArgumentList *Innermost = nullptr,
7282 bool RelativeToPrimary = false,
7283 const FunctionDecl *Pattern = nullptr);
7284
7285 /// A context in which code is being synthesized (where a source location
7286 /// alone is not sufficient to identify the context). This covers template
7287 /// instantiation and various forms of implicitly-generated functions.
7288 struct CodeSynthesisContext {
7289 /// The kind of template instantiation we are performing
7290 enum SynthesisKind {
7291 /// We are instantiating a template declaration. The entity is
7292 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
7293 TemplateInstantiation,
7294
7295 /// We are instantiating a default argument for a template
7296 /// parameter. The Entity is the template parameter whose argument is
7297 /// being instantiated, the Template is the template, and the
7298 /// TemplateArgs/NumTemplateArguments provide the template arguments as
7299 /// specified.
7300 DefaultTemplateArgumentInstantiation,
7301
7302 /// We are instantiating a default argument for a function.
7303 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
7304 /// provides the template arguments as specified.
7305 DefaultFunctionArgumentInstantiation,
7306
7307 /// We are substituting explicit template arguments provided for
7308 /// a function template. The entity is a FunctionTemplateDecl.
7309 ExplicitTemplateArgumentSubstitution,
7310
7311 /// We are substituting template argument determined as part of
7312 /// template argument deduction for either a class template
7313 /// partial specialization or a function template. The
7314 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
7315 /// a TemplateDecl.
7316 DeducedTemplateArgumentSubstitution,
7317
7318 /// We are substituting prior template arguments into a new
7319 /// template parameter. The template parameter itself is either a
7320 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
7321 PriorTemplateArgumentSubstitution,
7322
7323 /// We are checking the validity of a default template argument that
7324 /// has been used when naming a template-id.
7325 DefaultTemplateArgumentChecking,
7326
7327 /// We are computing the exception specification for a defaulted special
7328 /// member function.
7329 ExceptionSpecEvaluation,
7330
7331 /// We are instantiating the exception specification for a function
7332 /// template which was deferred until it was needed.
7333 ExceptionSpecInstantiation,
7334
7335 /// We are declaring an implicit special member function.
7336 DeclaringSpecialMember,
7337
7338 /// We are defining a synthesized function (such as a defaulted special
7339 /// member).
7340 DefiningSynthesizedFunction,
7341
7342 /// Added for Template instantiation observation.
7343 /// Memoization means we are _not_ instantiating a template because
7344 /// it is already instantiated (but we entered a context where we
7345 /// would have had to if it was not already instantiated).
7346 Memoization
7347 } Kind;
7348
7349 /// Was the enclosing context a non-instantiation SFINAE context?
7350 bool SavedInNonInstantiationSFINAEContext;
7351
7352 /// The point of instantiation or synthesis within the source code.
7353 SourceLocation PointOfInstantiation;
7354
7355 /// The entity that is being synthesized.
7356 Decl *Entity;
7357
7358 /// The template (or partial specialization) in which we are
7359 /// performing the instantiation, for substitutions of prior template
7360 /// arguments.
7361 NamedDecl *Template;
7362
7363 /// The list of template arguments we are substituting, if they
7364 /// are not part of the entity.
7365 const TemplateArgument *TemplateArgs;
7366
7367 // FIXME: Wrap this union around more members, or perhaps store the
7368 // kind-specific members in the RAII object owning the context.
7369 union {
7370 /// The number of template arguments in TemplateArgs.
7371 unsigned NumTemplateArgs;
7372
7373 /// The special member being declared or defined.
7374 CXXSpecialMember SpecialMember;
7375 };
7376
7377 ArrayRef<TemplateArgument> template_arguments() const {
7378 assert(Kind != DeclaringSpecialMember)((Kind != DeclaringSpecialMember) ? static_cast<void> (
0) : __assert_fail ("Kind != DeclaringSpecialMember", "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 7378, __PRETTY_FUNCTION__))
;
7379 return {TemplateArgs, NumTemplateArgs};
7380 }
7381
7382 /// The template deduction info object associated with the
7383 /// substitution or checking of explicit or deduced template arguments.
7384 sema::TemplateDeductionInfo *DeductionInfo;
7385
7386 /// The source range that covers the construct that cause
7387 /// the instantiation, e.g., the template-id that causes a class
7388 /// template instantiation.
7389 SourceRange InstantiationRange;
7390
7391 CodeSynthesisContext()
7392 : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
7393 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
7394
7395 /// Determines whether this template is an actual instantiation
7396 /// that should be counted toward the maximum instantiation depth.
7397 bool isInstantiationRecord() const;
7398 };
7399
7400 /// List of active code synthesis contexts.
7401 ///
7402 /// This vector is treated as a stack. As synthesis of one entity requires
7403 /// synthesis of another, additional contexts are pushed onto the stack.
7404 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
7405
7406 /// Specializations whose definitions are currently being instantiated.
7407 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
7408
7409 /// Non-dependent types used in templates that have already been instantiated
7410 /// by some template instantiation.
7411 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
7412
7413 /// Extra modules inspected when performing a lookup during a template
7414 /// instantiation. Computed lazily.
7415 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7416
7417 /// Cache of additional modules that should be used for name lookup
7418 /// within the current template instantiation. Computed lazily; use
7419 /// getLookupModules() to get a complete set.
7420 llvm::DenseSet<Module*> LookupModulesCache;
7421
7422 /// Get the set of additional modules that should be checked during
7423 /// name lookup. A module and its imports become visible when instanting a
7424 /// template defined within it.
7425 llvm::DenseSet<Module*> &getLookupModules();
7426
7427 /// Map from the most recent declaration of a namespace to the most
7428 /// recent visible declaration of that namespace.
7429 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7430
7431 /// Whether we are in a SFINAE context that is not associated with
7432 /// template instantiation.
7433 ///
7434 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7435 /// of a template instantiation or template argument deduction.
7436 bool InNonInstantiationSFINAEContext;
7437
7438 /// The number of \p CodeSynthesisContexts that are not template
7439 /// instantiations and, therefore, should not be counted as part of the
7440 /// instantiation depth.
7441 ///
7442 /// When the instantiation depth reaches the user-configurable limit
7443 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7444 // FIXME: Should we have a similar limit for other forms of synthesis?
7445 unsigned NonInstantiationEntries;
7446
7447 /// The depth of the context stack at the point when the most recent
7448 /// error or warning was produced.
7449 ///
7450 /// This value is used to suppress printing of redundant context stacks
7451 /// when there are multiple errors or warnings in the same instantiation.
7452 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7453 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7454
7455 /// The template instantiation callbacks to trace or track
7456 /// instantiations (objects can be chained).
7457 ///
7458 /// This callbacks is used to print, trace or track template
7459 /// instantiations as they are being constructed.
7460 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
7461 TemplateInstCallbacks;
7462
7463 /// The current index into pack expansion arguments that will be
7464 /// used for substitution of parameter packs.
7465 ///
7466 /// The pack expansion index will be -1 to indicate that parameter packs
7467 /// should be instantiated as themselves. Otherwise, the index specifies
7468 /// which argument within the parameter pack will be used for substitution.
7469 int ArgumentPackSubstitutionIndex;
7470
7471 /// RAII object used to change the argument pack substitution index
7472 /// within a \c Sema object.
7473 ///
7474 /// See \c ArgumentPackSubstitutionIndex for more information.
7475 class ArgumentPackSubstitutionIndexRAII {
7476 Sema &Self;
7477 int OldSubstitutionIndex;
7478
7479 public:
7480 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7481 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7482 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7483 }
7484
7485 ~ArgumentPackSubstitutionIndexRAII() {
7486 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7487 }
7488 };
7489
7490 friend class ArgumentPackSubstitutionRAII;
7491
7492 /// For each declaration that involved template argument deduction, the
7493 /// set of diagnostics that were suppressed during that template argument
7494 /// deduction.
7495 ///
7496 /// FIXME: Serialize this structure to the AST file.
7497 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7498 SuppressedDiagnosticsMap;
7499 SuppressedDiagnosticsMap SuppressedDiagnostics;
7500
7501 /// A stack object to be created when performing template
7502 /// instantiation.
7503 ///
7504 /// Construction of an object of type \c InstantiatingTemplate
7505 /// pushes the current instantiation onto the stack of active
7506 /// instantiations. If the size of this stack exceeds the maximum
7507 /// number of recursive template instantiations, construction
7508 /// produces an error and evaluates true.
7509 ///
7510 /// Destruction of this object will pop the named instantiation off
7511 /// the stack.
7512 struct InstantiatingTemplate {
7513 /// Note that we are instantiating a class template,
7514 /// function template, variable template, alias template,
7515 /// or a member thereof.
7516 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7517 Decl *Entity,
7518 SourceRange InstantiationRange = SourceRange());
7519
7520 struct ExceptionSpecification {};
7521 /// Note that we are instantiating an exception specification
7522 /// of a function template.
7523 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7524 FunctionDecl *Entity, ExceptionSpecification,
7525 SourceRange InstantiationRange = SourceRange());
7526
7527 /// Note that we are instantiating a default argument in a
7528 /// template-id.
7529 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7530 TemplateParameter Param, TemplateDecl *Template,
7531 ArrayRef<TemplateArgument> TemplateArgs,
7532 SourceRange InstantiationRange = SourceRange());
7533
7534 /// Note that we are substituting either explicitly-specified or
7535 /// deduced template arguments during function template argument deduction.
7536 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7537 FunctionTemplateDecl *FunctionTemplate,
7538 ArrayRef<TemplateArgument> TemplateArgs,
7539 CodeSynthesisContext::SynthesisKind Kind,
7540 sema::TemplateDeductionInfo &DeductionInfo,
7541 SourceRange InstantiationRange = SourceRange());
7542
7543 /// Note that we are instantiating as part of template
7544 /// argument deduction for a class template declaration.
7545 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7546 TemplateDecl *Template,
7547 ArrayRef<TemplateArgument> TemplateArgs,
7548 sema::TemplateDeductionInfo &DeductionInfo,
7549 SourceRange InstantiationRange = SourceRange());
7550
7551 /// Note that we are instantiating as part of template
7552 /// argument deduction for a class template partial
7553 /// specialization.
7554 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7555 ClassTemplatePartialSpecializationDecl *PartialSpec,
7556 ArrayRef<TemplateArgument> TemplateArgs,
7557 sema::TemplateDeductionInfo &DeductionInfo,
7558 SourceRange InstantiationRange = SourceRange());
7559
7560 /// Note that we are instantiating as part of template
7561 /// argument deduction for a variable template partial
7562 /// specialization.
7563 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7564 VarTemplatePartialSpecializationDecl *PartialSpec,
7565 ArrayRef<TemplateArgument> TemplateArgs,
7566 sema::TemplateDeductionInfo &DeductionInfo,
7567 SourceRange InstantiationRange = SourceRange());
7568
7569 /// Note that we are instantiating a default argument for a function
7570 /// parameter.
7571 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7572 ParmVarDecl *Param,
7573 ArrayRef<TemplateArgument> TemplateArgs,
7574 SourceRange InstantiationRange = SourceRange());
7575
7576 /// Note that we are substituting prior template arguments into a
7577 /// non-type parameter.
7578 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7579 NamedDecl *Template,
7580 NonTypeTemplateParmDecl *Param,
7581 ArrayRef<TemplateArgument> TemplateArgs,
7582 SourceRange InstantiationRange);
7583
7584 /// Note that we are substituting prior template arguments into a
7585 /// template template parameter.
7586 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7587 NamedDecl *Template,
7588 TemplateTemplateParmDecl *Param,
7589 ArrayRef<TemplateArgument> TemplateArgs,
7590 SourceRange InstantiationRange);
7591
7592 /// Note that we are checking the default template argument
7593 /// against the template parameter for a given template-id.
7594 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7595 TemplateDecl *Template,
7596 NamedDecl *Param,
7597 ArrayRef<TemplateArgument> TemplateArgs,
7598 SourceRange InstantiationRange);
7599
7600
7601 /// Note that we have finished instantiating this template.
7602 void Clear();
7603
7604 ~InstantiatingTemplate() { Clear(); }
7605
7606 /// Determines whether we have exceeded the maximum
7607 /// recursive template instantiations.
7608 bool isInvalid() const { return Invalid; }
7609
7610 /// Determine whether we are already instantiating this
7611 /// specialization in some surrounding active instantiation.
7612 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7613
7614 private:
7615 Sema &SemaRef;
7616 bool Invalid;
7617 bool AlreadyInstantiating;
7618 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7619 SourceRange InstantiationRange);
7620
7621 InstantiatingTemplate(
7622 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7623 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7624 Decl *Entity, NamedDecl *Template = nullptr,
7625 ArrayRef<TemplateArgument> TemplateArgs = None,
7626 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7627
7628 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7629
7630 InstantiatingTemplate&
7631 operator=(const InstantiatingTemplate&) = delete;
7632 };
7633
7634 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7635 void popCodeSynthesisContext();
7636
7637 /// Determine whether we are currently performing template instantiation.
7638 bool inTemplateInstantiation() const {
7639 return CodeSynthesisContexts.size() > NonInstantiationEntries;
7640 }
7641
7642 void PrintContextStack() {
7643 if (!CodeSynthesisContexts.empty() &&
7644 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7645 PrintInstantiationStack();
7646 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7647 }
7648 if (PragmaAttributeCurrentTargetDecl)
7649 PrintPragmaAttributeInstantiationPoint();
7650 }
7651 void PrintInstantiationStack();
7652
7653 void PrintPragmaAttributeInstantiationPoint();
7654
7655 /// Determines whether we are currently in a context where
7656 /// template argument substitution failures are not considered
7657 /// errors.
7658 ///
7659 /// \returns An empty \c Optional if we're not in a SFINAE context.
7660 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7661 /// template-deduction context object, which can be used to capture
7662 /// diagnostics that will be suppressed.
7663 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7664
7665 /// Determines whether we are currently in a context that
7666 /// is not evaluated as per C++ [expr] p5.
7667 bool isUnevaluatedContext() const {
7668 assert(!ExprEvalContexts.empty() &&((!ExprEvalContexts.empty() && "Must be in an expression evaluation context"
) ? static_cast<void> (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 7669, __PRETTY_FUNCTION__))
7669 "Must be in an expression evaluation context")((!ExprEvalContexts.empty() && "Must be in an expression evaluation context"
) ? static_cast<void> (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 7669, __PRETTY_FUNCTION__))
;
7670 return ExprEvalContexts.back().isUnevaluated();
7671 }
7672
7673 /// RAII class used to determine whether SFINAE has
7674 /// trapped any errors that occur during template argument
7675 /// deduction.
7676 class SFINAETrap {
7677 Sema &SemaRef;
7678 unsigned PrevSFINAEErrors;
7679 bool PrevInNonInstantiationSFINAEContext;
7680 bool PrevAccessCheckingSFINAE;
7681 bool PrevLastDiagnosticIgnored;
7682
7683 public:
7684 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7685 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7686 PrevInNonInstantiationSFINAEContext(
7687 SemaRef.InNonInstantiationSFINAEContext),
7688 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
7689 PrevLastDiagnosticIgnored(
7690 SemaRef.getDiagnostics().isLastDiagnosticIgnored())
7691 {
7692 if (!SemaRef.isSFINAEContext())
7693 SemaRef.InNonInstantiationSFINAEContext = true;
7694 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7695 }
7696
7697 ~SFINAETrap() {
7698 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7699 SemaRef.InNonInstantiationSFINAEContext
7700 = PrevInNonInstantiationSFINAEContext;
7701 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7702 SemaRef.getDiagnostics().setLastDiagnosticIgnored(
7703 PrevLastDiagnosticIgnored);
7704 }
7705
7706 /// Determine whether any SFINAE errors have been trapped.
7707 bool hasErrorOccurred() const {
7708 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7709 }
7710 };
7711
7712 /// RAII class used to indicate that we are performing provisional
7713 /// semantic analysis to determine the validity of a construct, so
7714 /// typo-correction and diagnostics in the immediate context (not within
7715 /// implicitly-instantiated templates) should be suppressed.
7716 class TentativeAnalysisScope {
7717 Sema &SemaRef;
7718 // FIXME: Using a SFINAETrap for this is a hack.
7719 SFINAETrap Trap;
7720 bool PrevDisableTypoCorrection;
7721 public:
7722 explicit TentativeAnalysisScope(Sema &SemaRef)
7723 : SemaRef(SemaRef), Trap(SemaRef, true),
7724 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7725 SemaRef.DisableTypoCorrection = true;
7726 }
7727 ~TentativeAnalysisScope() {
7728 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7729 }
7730 };
7731
7732 /// The current instantiation scope used to store local
7733 /// variables.
7734 LocalInstantiationScope *CurrentInstantiationScope;
7735
7736 /// Tracks whether we are in a context where typo correction is
7737 /// disabled.
7738 bool DisableTypoCorrection;
7739
7740 /// The number of typos corrected by CorrectTypo.
7741 unsigned TyposCorrected;
7742
7743 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7744 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7745
7746 /// A cache containing identifiers for which typo correction failed and
7747 /// their locations, so that repeated attempts to correct an identifier in a
7748 /// given location are ignored if typo correction already failed for it.
7749 IdentifierSourceLocations TypoCorrectionFailures;
7750
7751 /// Worker object for performing CFG-based warnings.
7752 sema::AnalysisBasedWarnings AnalysisWarnings;
7753 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7754
7755 /// An entity for which implicit template instantiation is required.
7756 ///
7757 /// The source location associated with the declaration is the first place in
7758 /// the source code where the declaration was "used". It is not necessarily
7759 /// the point of instantiation (which will be either before or after the
7760 /// namespace-scope declaration that triggered this implicit instantiation),
7761 /// However, it is the location that diagnostics should generally refer to,
7762 /// because users will need to know what code triggered the instantiation.
7763 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7764
7765 /// The queue of implicit template instantiations that are required
7766 /// but have not yet been performed.
7767 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7768
7769 /// Queue of implicit template instantiations that cannot be performed
7770 /// eagerly.
7771 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
7772
7773 class GlobalEagerInstantiationScope {
7774 public:
7775 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
7776 : S(S), Enabled(Enabled) {
7777 if (!Enabled) return;
7778
7779 SavedPendingInstantiations.swap(S.PendingInstantiations);
7780 SavedVTableUses.swap(S.VTableUses);
7781 }
7782
7783 void perform() {
7784 if (Enabled) {
27
Assuming the condition is true
28
Taking true branch
7785 S.DefineUsedVTables();
7786 S.PerformPendingInstantiations();
29
Calling 'Sema::PerformPendingInstantiations'
7787 }
7788 }
7789
7790 ~GlobalEagerInstantiationScope() {
7791 if (!Enabled) return;
7792
7793 // Restore the set of pending vtables.
7794 assert(S.VTableUses.empty() &&((S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 7795, __PRETTY_FUNCTION__))
7795 "VTableUses should be empty before it is discarded.")((S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 7795, __PRETTY_FUNCTION__))
;
7796 S.VTableUses.swap(SavedVTableUses);
7797
7798 // Restore the set of pending implicit instantiations.
7799 assert(S.PendingInstantiations.empty() &&((S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 7800, __PRETTY_FUNCTION__))
7800 "PendingInstantiations should be empty before it is discarded.")((S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 7800, __PRETTY_FUNCTION__))
;
7801 S.PendingInstantiations.swap(SavedPendingInstantiations);
7802 }
7803
7804 private:
7805 Sema &S;
7806 SmallVector<VTableUse, 16> SavedVTableUses;
7807 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7808 bool Enabled;
7809 };
7810
7811 /// The queue of implicit template instantiations that are required
7812 /// and must be performed within the current local scope.
7813 ///
7814 /// This queue is only used for member functions of local classes in
7815 /// templates, which must be instantiated in the same scope as their
7816 /// enclosing function, so that they can reference function-local
7817 /// types, static variables, enumerators, etc.
7818 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7819
7820 class LocalEagerInstantiationScope {
7821 public:
7822 LocalEagerInstantiationScope(Sema &S) : S(S) {
7823 SavedPendingLocalImplicitInstantiations.swap(
7824 S.PendingLocalImplicitInstantiations);
7825 }
7826
7827 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
7828
7829 ~LocalEagerInstantiationScope() {
7830 assert(S.PendingLocalImplicitInstantiations.empty() &&((S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"
) ? static_cast<void> (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 7831, __PRETTY_FUNCTION__))
7831 "there shouldn't be any pending local implicit instantiations")((S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"
) ? static_cast<void> (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 7831, __PRETTY_FUNCTION__))
;
7832 SavedPendingLocalImplicitInstantiations.swap(
7833 S.PendingLocalImplicitInstantiations);
7834 }
7835
7836 private:
7837 Sema &S;
7838 std::deque<PendingImplicitInstantiation>
7839 SavedPendingLocalImplicitInstantiations;
7840 };
7841
7842 /// A helper class for building up ExtParameterInfos.
7843 class ExtParameterInfoBuilder {
7844 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7845 bool HasInteresting = false;
7846
7847 public:
7848 /// Set the ExtParameterInfo for the parameter at the given index,
7849 ///
7850 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7851 assert(Infos.size() <= index)((Infos.size() <= index) ? static_cast<void> (0) : __assert_fail
("Infos.size() <= index", "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 7851, __PRETTY_FUNCTION__))
;
7852 Infos.resize(index);
7853 Infos.push_back(info);
7854
7855 if (!HasInteresting)
7856 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7857 }
7858
7859 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7860 /// ExtParameterInfo array we've built up.
7861 const FunctionProtoType::ExtParameterInfo *
7862 getPointerOrNull(unsigned numParams) {
7863 if (!HasInteresting) return nullptr;
7864 Infos.resize(numParams);
7865 return Infos.data();
7866 }
7867 };
7868
7869 void PerformPendingInstantiations(bool LocalOnly = false);
7870
7871 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7872 const MultiLevelTemplateArgumentList &TemplateArgs,
7873 SourceLocation Loc, DeclarationName Entity,
7874 bool AllowDeducedTST = false);
7875
7876 QualType SubstType(QualType T,
7877 const MultiLevelTemplateArgumentList &TemplateArgs,
7878 SourceLocation Loc, DeclarationName Entity);
7879
7880 TypeSourceInfo *SubstType(TypeLoc TL,
7881 const MultiLevelTemplateArgumentList &TemplateArgs,
7882 SourceLocation Loc, DeclarationName Entity);
7883
7884 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7885 const MultiLevelTemplateArgumentList &TemplateArgs,
7886 SourceLocation Loc,
7887 DeclarationName Entity,
7888 CXXRecordDecl *ThisContext,
7889 Qualifiers ThisTypeQuals);
7890 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7891 const MultiLevelTemplateArgumentList &Args);
7892 bool SubstExceptionSpec(SourceLocation Loc,
7893 FunctionProtoType::ExceptionSpecInfo &ESI,
7894 SmallVectorImpl<QualType> &ExceptionStorage,
7895 const MultiLevelTemplateArgumentList &Args);
7896 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7897 const MultiLevelTemplateArgumentList &TemplateArgs,
7898 int indexAdjustment,
7899 Optional<unsigned> NumExpansions,
7900 bool ExpectParameterPack);
7901 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7902 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7903 const MultiLevelTemplateArgumentList &TemplateArgs,
7904 SmallVectorImpl<QualType> &ParamTypes,
7905 SmallVectorImpl<ParmVarDecl *> *OutParams,
7906 ExtParameterInfoBuilder &ParamInfos);
7907 ExprResult SubstExpr(Expr *E,
7908 const MultiLevelTemplateArgumentList &TemplateArgs);
7909
7910 /// Substitute the given template arguments into a list of
7911 /// expressions, expanding pack expansions if required.
7912 ///
7913 /// \param Exprs The list of expressions to substitute into.
7914 ///
7915 /// \param IsCall Whether this is some form of call, in which case
7916 /// default arguments will be dropped.
7917 ///
7918 /// \param TemplateArgs The set of template arguments to substitute.
7919 ///
7920 /// \param Outputs Will receive all of the substituted arguments.
7921 ///
7922 /// \returns true if an error occurred, false otherwise.
7923 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7924 const MultiLevelTemplateArgumentList &TemplateArgs,
7925 SmallVectorImpl<Expr *> &Outputs);
7926
7927 StmtResult SubstStmt(Stmt *S,
7928 const MultiLevelTemplateArgumentList &TemplateArgs);
7929
7930 TemplateParameterList *
7931 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
7932 const MultiLevelTemplateArgumentList &TemplateArgs);
7933
7934 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7935 const MultiLevelTemplateArgumentList &TemplateArgs);
7936
7937 ExprResult SubstInitializer(Expr *E,
7938 const MultiLevelTemplateArgumentList &TemplateArgs,
7939 bool CXXDirectInit);
7940
7941 bool
7942 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7943 CXXRecordDecl *Pattern,
7944 const MultiLevelTemplateArgumentList &TemplateArgs);
7945
7946 bool
7947 InstantiateClass(SourceLocation PointOfInstantiation,
7948 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7949 const MultiLevelTemplateArgumentList &TemplateArgs,
7950 TemplateSpecializationKind TSK,
7951 bool Complain = true);
7952
7953 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7954 EnumDecl *Instantiation, EnumDecl *Pattern,
7955 const MultiLevelTemplateArgumentList &TemplateArgs,
7956 TemplateSpecializationKind TSK);
7957
7958 bool InstantiateInClassInitializer(
7959 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7960 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7961
7962 struct LateInstantiatedAttribute {
7963 const Attr *TmplAttr;
7964 LocalInstantiationScope *Scope;
7965 Decl *NewDecl;
7966
7967 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7968 Decl *D)
7969 : TmplAttr(A), Scope(S), NewDecl(D)
7970 { }
7971 };
7972 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7973
7974 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7975 const Decl *Pattern, Decl *Inst,
7976 LateInstantiatedAttrVec *LateAttrs = nullptr,
7977 LocalInstantiationScope *OuterMostScope = nullptr);
7978
7979 void
7980 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7981 const Decl *Pattern, Decl *Inst,
7982 LateInstantiatedAttrVec *LateAttrs = nullptr,
7983 LocalInstantiationScope *OuterMostScope = nullptr);
7984
7985 bool usesPartialOrExplicitSpecialization(
7986 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
7987
7988 bool
7989 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7990 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7991 TemplateSpecializationKind TSK,
7992 bool Complain = true);
7993
7994 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7995 CXXRecordDecl *Instantiation,
7996 const MultiLevelTemplateArgumentList &TemplateArgs,
7997 TemplateSpecializationKind TSK);
7998
7999 void InstantiateClassTemplateSpecializationMembers(
8000 SourceLocation PointOfInstantiation,
8001 ClassTemplateSpecializationDecl *ClassTemplateSpec,
8002 TemplateSpecializationKind TSK);
8003
8004 NestedNameSpecifierLoc
8005 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
8006 const MultiLevelTemplateArgumentList &TemplateArgs);
8007
8008 DeclarationNameInfo
8009 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
8010 const MultiLevelTemplateArgumentList &TemplateArgs);
8011 TemplateName
8012 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
8013 SourceLocation Loc,
8014 const MultiLevelTemplateArgumentList &TemplateArgs);
8015 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
8016 TemplateArgumentListInfo &Result,
8017 const MultiLevelTemplateArgumentList &TemplateArgs);
8018
8019 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
8020 FunctionDecl *Function);
8021 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
8022 const TemplateArgumentList *Args,
8023 SourceLocation Loc);
8024 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
8025 FunctionDecl *Function,
8026 bool Recursive = false,
8027 bool DefinitionRequired = false,
8028 bool AtEndOfTU = false);
8029 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
8030 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
8031 const TemplateArgumentList &TemplateArgList,
8032 const TemplateArgumentListInfo &TemplateArgsInfo,
8033 SmallVectorImpl<TemplateArgument> &Converted,
8034 SourceLocation PointOfInstantiation, void *InsertPos,
8035 LateInstantiatedAttrVec *LateAttrs = nullptr,
8036 LocalInstantiationScope *StartingScope = nullptr);
8037 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
8038 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
8039 const MultiLevelTemplateArgumentList &TemplateArgs);
8040 void
8041 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
8042 const MultiLevelTemplateArgumentList &TemplateArgs,
8043 LateInstantiatedAttrVec *LateAttrs,
8044 DeclContext *Owner,
8045 LocalInstantiationScope *StartingScope,
8046 bool InstantiatingVarTemplate = false);
8047 void InstantiateVariableInitializer(
8048 VarDecl *Var, VarDecl *OldVar,
8049 const MultiLevelTemplateArgumentList &TemplateArgs);
8050 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
8051 VarDecl *Var, bool Recursive = false,
8052 bool DefinitionRequired = false,
8053 bool AtEndOfTU = false);
8054
8055 void InstantiateMemInitializers(CXXConstructorDecl *New,
8056 const CXXConstructorDecl *Tmpl,
8057 const MultiLevelTemplateArgumentList &TemplateArgs);
8058
8059 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
8060 const MultiLevelTemplateArgumentList &TemplateArgs,
8061 bool FindingInstantiatedContext = false);
8062 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
8063 const MultiLevelTemplateArgumentList &TemplateArgs);
8064
8065 // Objective-C declarations.
8066 enum ObjCContainerKind {
8067 OCK_None = -1,
8068 OCK_Interface = 0,
8069 OCK_Protocol,
8070 OCK_Category,
8071 OCK_ClassExtension,
8072 OCK_Implementation,
8073 OCK_CategoryImplementation
8074 };
8075 ObjCContainerKind getObjCContainerKind() const;
8076
8077 DeclResult actOnObjCTypeParam(Scope *S,
8078 ObjCTypeParamVariance variance,
8079 SourceLocation varianceLoc,
8080 unsigned index,
8081 IdentifierInfo *paramName,
8082 SourceLocation paramLoc,
8083 SourceLocation colonLoc,
8084 ParsedType typeBound);
8085
8086 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
8087 ArrayRef<Decl *> typeParams,
8088 SourceLocation rAngleLoc);
8089 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
8090
8091 Decl *ActOnStartClassInterface(
8092 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
8093 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
8094 IdentifierInfo *SuperName, SourceLocation SuperLoc,
8095 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
8096 Decl *const *ProtoRefs, unsigned NumProtoRefs,
8097 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
8098 const ParsedAttributesView &AttrList);
8099
8100 void ActOnSuperClassOfClassInterface(Scope *S,
8101 SourceLocation AtInterfaceLoc,
8102 ObjCInterfaceDecl *IDecl,
8103 IdentifierInfo *ClassName,
8104 SourceLocation ClassLoc,
8105 IdentifierInfo *SuperName,
8106 SourceLocation SuperLoc,
8107 ArrayRef<ParsedType> SuperTypeArgs,
8108 SourceRange SuperTypeArgsRange);
8109
8110 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
8111 SmallVectorImpl<SourceLocation> &ProtocolLocs,
8112 IdentifierInfo *SuperName,
8113 SourceLocation SuperLoc);
8114
8115 Decl *ActOnCompatibilityAlias(
8116 SourceLocation AtCompatibilityAliasLoc,
8117 IdentifierInfo *AliasName, SourceLocation AliasLocation,
8118 IdentifierInfo *ClassName, SourceLocation ClassLocation);
8119
8120 bool CheckForwardProtocolDeclarationForCircularDependency(
8121 IdentifierInfo *PName,
8122 SourceLocation &PLoc, SourceLocation PrevLoc,
8123 const ObjCList<ObjCProtocolDecl> &PList);
8124
8125 Decl *ActOnStartProtocolInterface(
8126 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
8127 SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
8128 unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
8129 SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
8130
8131 Decl *ActOnStartCategoryInterface(
8132 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
8133 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
8134 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
8135 Decl *const *ProtoRefs, unsigned NumProtoRefs,
8136 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
8137 const ParsedAttributesView &AttrList);
8138
8139 Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
8140 IdentifierInfo *ClassName,
8141 SourceLocation ClassLoc,
8142 IdentifierInfo *SuperClassname,
8143 SourceLocation SuperClassLoc,
8144 const ParsedAttributesView &AttrList);
8145
8146 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
8147 IdentifierInfo *ClassName,
8148 SourceLocation ClassLoc,
8149 IdentifierInfo *CatName,
8150 SourceLocation CatLoc,
8151 const ParsedAttributesView &AttrList);
8152
8153 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
8154 ArrayRef<Decl *> Decls);
8155
8156 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
8157 IdentifierInfo **IdentList,
8158 SourceLocation *IdentLocs,
8159 ArrayRef<ObjCTypeParamList *> TypeParamLists,
8160 unsigned NumElts);
8161
8162 DeclGroupPtrTy
8163 ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
8164 ArrayRef<IdentifierLocPair> IdentList,
8165 const ParsedAttributesView &attrList);
8166
8167 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
8168 ArrayRef<IdentifierLocPair> ProtocolId,
8169 SmallVectorImpl<Decl *> &Protocols);
8170
8171 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
8172 SourceLocation ProtocolLoc,
8173 IdentifierInfo *TypeArgId,
8174 SourceLocation TypeArgLoc,
8175 bool SelectProtocolFirst = false);
8176
8177 /// Given a list of identifiers (and their locations), resolve the
8178 /// names to either Objective-C protocol qualifiers or type
8179 /// arguments, as appropriate.
8180 void actOnObjCTypeArgsOrProtocolQualifiers(
8181 Scope *S,
8182 ParsedType baseType,
8183 SourceLocation lAngleLoc,
8184 ArrayRef<IdentifierInfo *> identifiers,
8185 ArrayRef<SourceLocation> identifierLocs,
8186 SourceLocation rAngleLoc,
8187 SourceLocation &typeArgsLAngleLoc,
8188 SmallVectorImpl<ParsedType> &typeArgs,
8189 SourceLocation &typeArgsRAngleLoc,
8190 SourceLocation &protocolLAngleLoc,
8191 SmallVectorImpl<Decl *> &protocols,
8192 SourceLocation &protocolRAngleLoc,
8193 bool warnOnIncompleteProtocols);
8194
8195 /// Build a an Objective-C protocol-qualified 'id' type where no
8196 /// base type was specified.
8197 TypeResult actOnObjCProtocolQualifierType(
8198 SourceLocation lAngleLoc,
8199 ArrayRef<Decl *> protocols,
8200 ArrayRef<SourceLocation> protocolLocs,
8201 SourceLocation rAngleLoc);
8202
8203 /// Build a specialized and/or protocol-qualified Objective-C type.
8204 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
8205 Scope *S,
8206 SourceLocation Loc,
8207 ParsedType BaseType,
8208 SourceLocation TypeArgsLAngleLoc,
8209 ArrayRef<ParsedType> TypeArgs,
8210 SourceLocation TypeArgsRAngleLoc,
8211 SourceLocation ProtocolLAngleLoc,
8212 ArrayRef<Decl *> Protocols,
8213 ArrayRef<SourceLocation> ProtocolLocs,
8214 SourceLocation ProtocolRAngleLoc);
8215
8216 /// Build an Objective-C type parameter type.
8217 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
8218 SourceLocation ProtocolLAngleLoc,
8219 ArrayRef<ObjCProtocolDecl *> Protocols,
8220 ArrayRef<SourceLocation> ProtocolLocs,
8221 SourceLocation ProtocolRAngleLoc,
8222 bool FailOnError = false);
8223
8224 /// Build an Objective-C object pointer type.
8225 QualType BuildObjCObjectType(QualType BaseType,
8226 SourceLocation Loc,
8227 SourceLocation TypeArgsLAngleLoc,
8228 ArrayRef<TypeSourceInfo *> TypeArgs,
8229 SourceLocation TypeArgsRAngleLoc,
8230 SourceLocation ProtocolLAngleLoc,
8231 ArrayRef<ObjCProtocolDecl *> Protocols,
8232 ArrayRef<SourceLocation> ProtocolLocs,
8233 SourceLocation ProtocolRAngleLoc,
8234 bool FailOnError = false);
8235
8236 /// Ensure attributes are consistent with type.
8237 /// \param [in, out] Attributes The attributes to check; they will
8238 /// be modified to be consistent with \p PropertyTy.
8239 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
8240 SourceLocation Loc,
8241 unsigned &Attributes,
8242 bool propertyInPrimaryClass);
8243
8244 /// Process the specified property declaration and create decls for the
8245 /// setters and getters as needed.
8246 /// \param property The property declaration being processed
8247 void ProcessPropertyDecl(ObjCPropertyDecl *property);
8248
8249
8250 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
8251 ObjCPropertyDecl *SuperProperty,
8252 const IdentifierInfo *Name,
8253 bool OverridingProtocolProperty);
8254
8255 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
8256 ObjCInterfaceDecl *ID);
8257
8258 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
8259 ArrayRef<Decl *> allMethods = None,
8260 ArrayRef<DeclGroupPtrTy> allTUVars = None);
8261
8262 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
8263 SourceLocation LParenLoc,
8264 FieldDeclarator &FD, ObjCDeclSpec &ODS,
8265 Selector GetterSel, Selector SetterSel,
8266 tok::ObjCKeywordKind MethodImplKind,
8267 DeclContext *lexicalDC = nullptr);
8268
8269 Decl *ActOnPropertyImplDecl(Scope *S,
8270 SourceLocation AtLoc,
8271 SourceLocation PropertyLoc,
8272 bool ImplKind,
8273 IdentifierInfo *PropertyId,
8274 IdentifierInfo *PropertyIvar,
8275 SourceLocation PropertyIvarLoc,
8276 ObjCPropertyQueryKind QueryKind);
8277
8278 enum ObjCSpecialMethodKind {
8279 OSMK_None,
8280 OSMK_Alloc,
8281 OSMK_New,
8282 OSMK_Copy,
8283 OSMK_RetainingInit,
8284 OSMK_NonRetainingInit
8285 };
8286
8287 struct ObjCArgInfo {
8288 IdentifierInfo *Name;
8289 SourceLocation NameLoc;
8290 // The Type is null if no type was specified, and the DeclSpec is invalid
8291 // in this case.
8292 ParsedType Type;
8293 ObjCDeclSpec DeclSpec;
8294
8295 /// ArgAttrs - Attribute list for this argument.
8296 ParsedAttributesView ArgAttrs;
8297 };
8298
8299 Decl *ActOnMethodDeclaration(
8300 Scope *S,
8301 SourceLocation BeginLoc, // location of the + or -.
8302 SourceLocation EndLoc, // location of the ; or {.
8303 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
8304 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
8305 // optional arguments. The number of types/arguments is obtained
8306 // from the Sel.getNumArgs().
8307 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
8308 unsigned CNumArgs, // c-style args
8309 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
8310 bool isVariadic, bool MethodDefinition);
8311
8312 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
8313 const ObjCObjectPointerType *OPT,
8314 bool IsInstance);
8315 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
8316 bool IsInstance);
8317
8318 bool CheckARCMethodDecl(ObjCMethodDecl *method);
8319 bool inferObjCARCLifetime(ValueDecl *decl);
8320
8321 ExprResult
8322 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
8323 Expr *BaseExpr,
8324 SourceLocation OpLoc,
8325 DeclarationName MemberName,
8326 SourceLocation MemberLoc,
8327 SourceLocation SuperLoc, QualType SuperType,
8328 bool Super);
8329
8330 ExprResult
8331 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
8332 IdentifierInfo &propertyName,
8333 SourceLocation receiverNameLoc,
8334 SourceLocation propertyNameLoc);
8335
8336 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
8337
8338 /// Describes the kind of message expression indicated by a message
8339 /// send that starts with an identifier.
8340 enum ObjCMessageKind {
8341 /// The message is sent to 'super'.
8342 ObjCSuperMessage,
8343 /// The message is an instance message.
8344 ObjCInstanceMessage,
8345 /// The message is a class message, and the identifier is a type
8346 /// name.
8347 ObjCClassMessage
8348 };
8349
8350 ObjCMessageKind getObjCMessageKind(Scope *S,
8351 IdentifierInfo *Name,
8352 SourceLocation NameLoc,
8353 bool IsSuper,
8354 bool HasTrailingDot,
8355 ParsedType &ReceiverType);
8356
8357 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
8358 Selector Sel,
8359 SourceLocation LBracLoc,
8360 ArrayRef<SourceLocation> SelectorLocs,
8361 SourceLocation RBracLoc,
8362 MultiExprArg Args);
8363
8364 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
8365 QualType ReceiverType,
8366 SourceLocation SuperLoc,
8367 Selector Sel,
8368 ObjCMethodDecl *Method,
8369 SourceLocation LBracLoc,
8370 ArrayRef<SourceLocation> SelectorLocs,
8371 SourceLocation RBracLoc,
8372 MultiExprArg Args,
8373 bool isImplicit = false);
8374
8375 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
8376 bool isSuperReceiver,
8377 SourceLocation Loc,
8378 Selector Sel,
8379 ObjCMethodDecl *Method,
8380 MultiExprArg Args);
8381
8382 ExprResult ActOnClassMessage(Scope *S,
8383 ParsedType Receiver,
8384 Selector Sel,
8385 SourceLocation LBracLoc,
8386 ArrayRef<SourceLocation> SelectorLocs,
8387 SourceLocation RBracLoc,
8388 MultiExprArg Args);
8389
8390 ExprResult BuildInstanceMessage(Expr *Receiver,
8391 QualType ReceiverType,
8392 SourceLocation SuperLoc,
8393 Selector Sel,
8394 ObjCMethodDecl *Method,
8395 SourceLocation LBracLoc,
8396 ArrayRef<SourceLocation> SelectorLocs,
8397 SourceLocation RBracLoc,
8398 MultiExprArg Args,
8399 bool isImplicit = false);
8400
8401 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
8402 QualType ReceiverType,
8403 SourceLocation Loc,
8404 Selector Sel,
8405 ObjCMethodDecl *Method,
8406 MultiExprArg Args);
8407
8408 ExprResult ActOnInstanceMessage(Scope *S,
8409 Expr *Receiver,
8410 Selector Sel,
8411 SourceLocation LBracLoc,
8412 ArrayRef<SourceLocation> SelectorLocs,
8413 SourceLocation RBracLoc,
8414 MultiExprArg Args);
8415
8416 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
8417 ObjCBridgeCastKind Kind,
8418 SourceLocation BridgeKeywordLoc,
8419 TypeSourceInfo *TSInfo,
8420 Expr *SubExpr);
8421
8422 ExprResult ActOnObjCBridgedCast(Scope *S,
8423 SourceLocation LParenLoc,
8424 ObjCBridgeCastKind Kind,
8425 SourceLocation BridgeKeywordLoc,
8426 ParsedType Type,
8427 SourceLocation RParenLoc,
8428 Expr *SubExpr);
8429
8430 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
8431
8432 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
8433
8434 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
8435 CastKind &Kind);
8436
8437 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8438 QualType DestType, QualType SrcType,
8439 ObjCInterfaceDecl *&RelatedClass,
8440 ObjCMethodDecl *&ClassMethod,
8441 ObjCMethodDecl *&InstanceMethod,
8442 TypedefNameDecl *&TDNDecl,
8443 bool CfToNs, bool Diagnose = true);
8444
8445 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8446 QualType DestType, QualType SrcType,
8447 Expr *&SrcExpr, bool Diagnose = true);
8448
8449 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8450 bool Diagnose = true);
8451
8452 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8453
8454 /// Check whether the given new method is a valid override of the
8455 /// given overridden method, and set any properties that should be inherited.
8456 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8457 const ObjCMethodDecl *Overridden);
8458
8459 /// Describes the compatibility of a result type with its method.
8460 enum ResultTypeCompatibilityKind {
8461 RTC_Compatible,
8462 RTC_Incompatible,
8463 RTC_Unknown
8464 };
8465
8466 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8467 ObjCInterfaceDecl *CurrentClass,
8468 ResultTypeCompatibilityKind RTC);
8469
8470 enum PragmaOptionsAlignKind {
8471 POAK_Native, // #pragma options align=native
8472 POAK_Natural, // #pragma options align=natural
8473 POAK_Packed, // #pragma options align=packed
8474 POAK_Power, // #pragma options align=power
8475 POAK_Mac68k, // #pragma options align=mac68k
8476 POAK_Reset // #pragma options align=reset
8477 };
8478
8479 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
8480 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
8481 PragmaClangSectionAction Action,
8482 PragmaClangSectionKind SecKind, StringRef SecName);
8483
8484 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8485 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8486 SourceLocation PragmaLoc);
8487
8488 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8489 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8490 StringRef SlotLabel, Expr *Alignment);
8491
8492 enum class PragmaPackDiagnoseKind {
8493 NonDefaultStateAtInclude,
8494 ChangedStateAtExit
8495 };
8496
8497 void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
8498 SourceLocation IncludeLoc);
8499 void DiagnoseUnterminatedPragmaPack();
8500
8501 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8502 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8503
8504 /// ActOnPragmaMSComment - Called on well formed
8505 /// \#pragma comment(kind, "arg").
8506 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8507 StringRef Arg);
8508
8509 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8510 /// pointers_to_members(representation method[, general purpose
8511 /// representation]).
8512 void ActOnPragmaMSPointersToMembers(
8513 LangOptions::PragmaMSPointersToMembersKind Kind,
8514 SourceLocation PragmaLoc);
8515
8516 /// Called on well formed \#pragma vtordisp().
8517 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8518 SourceLocation PragmaLoc,
8519 MSVtorDispAttr::Mode Value);
8520
8521 enum PragmaSectionKind {
8522 PSK_DataSeg,
8523 PSK_BSSSeg,
8524 PSK_ConstSeg,
8525 PSK_CodeSeg,
8526 };
8527
8528 bool UnifySection(StringRef SectionName,
8529 int SectionFlags,
8530 DeclaratorDecl *TheDecl);
8531 bool UnifySection(StringRef SectionName,
8532 int SectionFlags,
8533 SourceLocation PragmaSectionLocation);
8534
8535 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8536 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8537 PragmaMsStackAction Action,
8538 llvm::StringRef StackSlotLabel,
8539 StringLiteral *SegmentName,
8540 llvm::StringRef PragmaName);
8541
8542 /// Called on well formed \#pragma section().
8543 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8544 int SectionFlags, StringLiteral *SegmentName);
8545
8546 /// Called on well-formed \#pragma init_seg().
8547 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8548 StringLiteral *SegmentName);
8549
8550 /// Called on #pragma clang __debug dump II
8551 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8552
8553 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8554 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8555 StringRef Value);
8556
8557 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8558 void ActOnPragmaUnused(const Token &Identifier,
8559 Scope *curScope,
8560 SourceLocation PragmaLoc);
8561
8562 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8563 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8564 SourceLocation PragmaLoc);
8565
8566 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8567 SourceLocation Loc);
8568 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8569
8570 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8571 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8572 SourceLocation PragmaLoc,
8573 SourceLocation WeakNameLoc);
8574
8575 /// ActOnPragmaRedefineExtname - Called on well formed
8576 /// \#pragma redefine_extname oldname newname.
8577 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8578 IdentifierInfo* AliasName,
8579 SourceLocation PragmaLoc,
8580 SourceLocation WeakNameLoc,
8581 SourceLocation AliasNameLoc);
8582
8583 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8584 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8585 IdentifierInfo* AliasName,
8586 SourceLocation PragmaLoc,
8587 SourceLocation WeakNameLoc,
8588 SourceLocation AliasNameLoc);
8589
8590 /// ActOnPragmaFPContract - Called on well formed
8591 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8592 /// \#pragma clang fp contract
8593 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8594
8595 /// ActOnPragmaFenvAccess - Called on well formed
8596 /// \#pragma STDC FENV_ACCESS
8597 void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC);
8598
8599 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8600 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8601 void AddAlignmentAttributesForRecord(RecordDecl *RD);
8602
8603 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8604 void AddMsStructLayoutForRecord(RecordDecl *RD);
8605
8606 /// FreePackedContext - Deallocate and null out PackContext.
8607 void FreePackedContext();
8608
8609 /// PushNamespaceVisibilityAttr - Note that we've entered a
8610 /// namespace with a visibility attribute.
8611 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8612 SourceLocation Loc);
8613
8614 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8615 /// add an appropriate visibility attribute.
8616 void AddPushedVisibilityAttribute(Decl *RD);
8617
8618 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8619 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8620 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8621
8622 /// FreeVisContext - Deallocate and null out VisContext.
8623 void FreeVisContext();
8624
8625 /// AddCFAuditedAttribute - Check whether we're currently within
8626 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8627 /// the appropriate attribute.
8628 void AddCFAuditedAttribute(Decl *D);
8629
8630 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
8631 SourceLocation PragmaLoc,
8632 attr::ParsedSubjectMatchRuleSet Rules);
8633 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
8634 const IdentifierInfo *Namespace);
8635
8636 /// Called on well-formed '\#pragma clang attribute pop'.
8637 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
8638 const IdentifierInfo *Namespace);
8639
8640 /// Adds the attributes that have been specified using the
8641 /// '\#pragma clang attribute push' directives to the given declaration.
8642 void AddPragmaAttributes(Scope *S, Decl *D);
8643
8644 void DiagnoseUnterminatedPragmaAttribute();
8645
8646 /// Called on well formed \#pragma clang optimize.
8647 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8648
8649 /// Get the location for the currently active "\#pragma clang optimize
8650 /// off". If this location is invalid, then the state of the pragma is "on".
8651 SourceLocation getOptimizeOffPragmaLocation() const {
8652 return OptimizeOffPragmaLocation;
8653 }
8654
8655 /// Only called on function definitions; if there is a pragma in scope
8656 /// with the effect of a range-based optnone, consider marking the function
8657 /// with attribute optnone.
8658 void AddRangeBasedOptnone(FunctionDecl *FD);
8659
8660 /// Adds the 'optnone' attribute to the function declaration if there
8661 /// are no conflicts; Loc represents the location causing the 'optnone'
8662 /// attribute to be added (usually because of a pragma).
8663 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8664
8665 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8666 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8667 unsigned SpellingListIndex, bool IsPackExpansion);
8668 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8669 unsigned SpellingListIndex, bool IsPackExpansion);
8670
8671 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8672 /// declaration.
8673 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8674 unsigned SpellingListIndex);
8675
8676 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8677 /// declaration.
8678 void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8679 unsigned SpellingListIndex);
8680
8681 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8682 /// declaration.
8683 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8684 unsigned SpellingListIndex);
8685
8686 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8687 /// declaration.
8688 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8689 Expr *MinBlocks, unsigned SpellingListIndex);
8690
8691 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8692 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8693 unsigned SpellingListIndex, bool InInstantiation = false);
8694
8695 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8696 ParameterABI ABI, unsigned SpellingListIndex);
8697
8698 enum class RetainOwnershipKind {NS, CF, OS};
8699 void AddXConsumedAttr(Decl *D, SourceRange SR, unsigned SpellingIndex,
8700 RetainOwnershipKind K, bool IsTemplateInstantiation);
8701
8702 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
8703 /// attribute to a particular declaration.
8704 void addAMDGPUFlatWorkGroupSizeAttr(SourceRange AttrRange, Decl *D, Expr *Min,
8705 Expr *Max, unsigned SpellingListIndex);
8706
8707 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
8708 /// particular declaration.
8709 void addAMDGPUWavesPerEUAttr(SourceRange AttrRange, Decl *D, Expr *Min,
8710 Expr *Max, unsigned SpellingListIndex);
8711
8712 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
8713
8714 //===--------------------------------------------------------------------===//
8715 // C++ Coroutines TS
8716 //
8717 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
8718 StringRef Keyword);
8719 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8720 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8721 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8722
8723 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8724 bool IsImplicit = false);
8725 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8726 UnresolvedLookupExpr* Lookup);
8727 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8728 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8729 bool IsImplicit = false);
8730 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8731 bool buildCoroutineParameterMoves(SourceLocation Loc);
8732 VarDecl *buildCoroutinePromise(SourceLocation Loc);
8733 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8734 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
8735 SourceLocation FuncLoc);
8736
8737 //===--------------------------------------------------------------------===//
8738 // OpenCL extensions.
8739 //
8740private:
8741 std::string CurrOpenCLExtension;
8742 /// Extensions required by an OpenCL type.
8743 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8744 /// Extensions required by an OpenCL declaration.
8745 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8746public:
8747 llvm::StringRef getCurrentOpenCLExtension() const {
8748 return CurrOpenCLExtension;
8749 }
8750
8751 /// Check if a function declaration \p FD associates with any
8752 /// extensions present in OpenCLDeclExtMap and if so return the
8753 /// extension(s) name(s).
8754 std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD);
8755
8756 /// Check if a function type \p FT associates with any
8757 /// extensions present in OpenCLTypeExtMap and if so return the
8758 /// extension(s) name(s).
8759 std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT);
8760
8761 /// Find an extension in an appropriate extension map and return its name
8762 template<typename T, typename MapT>
8763 std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map);
8764
8765 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8766 CurrOpenCLExtension = Ext;
8767 }
8768
8769 /// Set OpenCL extensions for a type which can only be used when these
8770 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8771 /// \param Exts A space separated list of OpenCL extensions.
8772 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8773
8774 /// Set OpenCL extensions for a declaration which can only be
8775 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8776 /// nothing.
8777 /// \param Exts A space separated list of OpenCL extensions.
8778 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8779
8780 /// Set current OpenCL extensions for a type which can only be used
8781 /// when these OpenCL extensions are enabled. If current OpenCL extension is
8782 /// empty, do nothing.
8783 void setCurrentOpenCLExtensionForType(QualType T);
8784
8785 /// Set current OpenCL extensions for a declaration which
8786 /// can only be used when these OpenCL extensions are enabled. If current
8787 /// OpenCL extension is empty, do nothing.
8788 void setCurrentOpenCLExtensionForDecl(Decl *FD);
8789
8790 bool isOpenCLDisabledDecl(Decl *FD);
8791
8792 /// Check if type \p T corresponding to declaration specifier \p DS
8793 /// is disabled due to required OpenCL extensions being disabled. If so,
8794 /// emit diagnostics.
8795 /// \return true if type is disabled.
8796 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8797
8798 /// Check if declaration \p D used by expression \p E
8799 /// is disabled due to required OpenCL extensions being disabled. If so,
8800 /// emit diagnostics.
8801 /// \return true if type is disabled.
8802 bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
8803
8804 //===--------------------------------------------------------------------===//
8805 // OpenMP directives and clauses.
8806 //
8807private:
8808 void *VarDataSharingAttributesStack;
8809 /// Number of nested '#pragma omp declare target' directives.
8810 unsigned DeclareTargetNestingLevel = 0;
8811 /// Initialization of data-sharing attributes stack.
8812 void InitDataSharingAttributesStack();
8813 void DestroyDataSharingAttributesStack();
8814 ExprResult
8815 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8816 bool StrictlyPositive = true);
8817 /// Returns OpenMP nesting level for current directive.
8818 unsigned getOpenMPNestingLevel() const;
8819
8820 /// Adjusts the function scopes index for the target-based regions.
8821 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
8822 unsigned Level) const;
8823
8824 /// Push new OpenMP function region for non-capturing function.
8825 void pushOpenMPFunctionRegion();
8826
8827 /// Pop OpenMP function region for non-capturing function.
8828 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
8829
8830 /// Check whether we're allowed to call Callee from the current function.
8831 void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee);
8832
8833 /// Check if the expression is allowed to be used in expressions for the
8834 /// OpenMP devices.
8835 void checkOpenMPDeviceExpr(const Expr *E);
8836
8837 /// Checks if a type or a declaration is disabled due to the owning extension
8838 /// being disabled, and emits diagnostic messages if it is disabled.
8839 /// \param D type or declaration to be checked.
8840 /// \param DiagLoc source location for the diagnostic message.
8841 /// \param DiagInfo information to be emitted for the diagnostic message.
8842 /// \param SrcRange source range of the declaration.
8843 /// \param Map maps type or declaration to the extensions.
8844 /// \param Selector selects diagnostic message: 0 for type and 1 for
8845 /// declaration.
8846 /// \return true if the type or declaration is disabled.
8847 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8848 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8849 MapT &Map, unsigned Selector = 0,
8850 SourceRange SrcRange = SourceRange());
8851
8852public:
8853 /// Return true if the provided declaration \a VD should be captured by
8854 /// reference.
8855 /// \param Level Relative level of nested OpenMP construct for that the check
8856 /// is performed.
8857 bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const;
8858
8859 /// Check if the specified variable is used in one of the private
8860 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8861 /// constructs.
8862 VarDecl *isOpenMPCapturedDecl(ValueDecl *D);
8863 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8864 ExprObjectKind OK, SourceLocation Loc);
8865
8866 /// If the current region is a loop-based region, mark the start of the loop
8867 /// construct.
8868 void startOpenMPLoop();
8869
8870 /// Check if the specified variable is used in 'private' clause.
8871 /// \param Level Relative level of nested OpenMP construct for that the check
8872 /// is performed.
8873 bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const;
8874
8875 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
8876 /// for \p FD based on DSA for the provided corresponding captured declaration
8877 /// \p D.
8878 void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
8879
8880 /// Check if the specified variable is captured by 'target' directive.
8881 /// \param Level Relative level of nested OpenMP construct for that the check
8882 /// is performed.
8883 bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const;
8884
8885 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8886 Expr *Op);
8887 /// Called on start of new data sharing attribute block.
8888 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8889 const DeclarationNameInfo &DirName, Scope *CurScope,
8890 SourceLocation Loc);
8891 /// Start analysis of clauses.
8892 void StartOpenMPClause(OpenMPClauseKind K);
8893 /// End analysis of clauses.
8894 void EndOpenMPClause();
8895 /// Called on end of data sharing attribute block.
8896 void EndOpenMPDSABlock(Stmt *CurDirective);
8897
8898 /// Check if the current region is an OpenMP loop region and if it is,
8899 /// mark loop control variable, used in \p Init for loop initialization, as
8900 /// private by default.
8901 /// \param Init First part of the for loop.
8902 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8903
8904 // OpenMP directives and clauses.
8905 /// Called on correct id-expression from the '#pragma omp
8906 /// threadprivate'.
8907 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8908 const DeclarationNameInfo &Id,
8909 OpenMPDirectiveKind Kind);
8910 /// Called on well-formed '#pragma omp threadprivate'.
8911 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8912 SourceLocation Loc,
8913 ArrayRef<Expr *> VarList);
8914 /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8915 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
8916 ArrayRef<Expr *> VarList);
8917 /// Called on well-formed '#pragma omp allocate'.
8918 DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
8919 ArrayRef<Expr *> VarList,
8920 ArrayRef<OMPClause *> Clauses,
8921 DeclContext *Owner = nullptr);
8922 /// Called on well-formed '#pragma omp requires'.
8923 DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
8924 ArrayRef<OMPClause *> ClauseList);
8925 /// Check restrictions on Requires directive
8926 OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
8927 ArrayRef<OMPClause *> Clauses);
8928 /// Check if the specified type is allowed to be used in 'omp declare
8929 /// reduction' construct.
8930 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8931 TypeResult ParsedType);
8932 /// Called on start of '#pragma omp declare reduction'.
8933 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8934 Scope *S, DeclContext *DC, DeclarationName Name,
8935 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8936 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8937 /// Initialize declare reduction construct initializer.
8938 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8939 /// Finish current declare reduction construct initializer.
8940 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8941 /// Initialize declare reduction construct initializer.
8942 /// \return omp_priv variable.
8943 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8944 /// Finish current declare reduction construct initializer.
8945 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
8946 VarDecl *OmpPrivParm);
8947 /// Called at the end of '#pragma omp declare reduction'.
8948 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8949 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8950
8951 /// Check variable declaration in 'omp declare mapper' construct.
8952 TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
8953 /// Check if the specified type is allowed to be used in 'omp declare
8954 /// mapper' construct.
8955 QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
8956 TypeResult ParsedType);
8957 /// Called on start of '#pragma omp declare mapper'.
8958 OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart(
8959 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
8960 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
8961 Decl *PrevDeclInScope = nullptr);
8962 /// Build the mapper variable of '#pragma omp declare mapper'.
8963 void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
8964 Scope *S, QualType MapperType,
8965 SourceLocation StartLoc,
8966 DeclarationName VN);
8967 /// Called at the end of '#pragma omp declare mapper'.
8968 DeclGroupPtrTy
8969 ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
8970 ArrayRef<OMPClause *> ClauseList);
8971
8972 /// Called on the start of target region i.e. '#pragma omp declare target'.
8973 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8974 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8975 void ActOnFinishOpenMPDeclareTargetDirective();
8976 /// Called on correct id-expression from the '#pragma omp declare target'.
8977 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8978 const DeclarationNameInfo &Id,
8979 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8980 NamedDeclSetType &SameDirectiveDecls);
8981 /// Check declaration inside target region.
8982 void
8983 checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
8984 SourceLocation IdLoc = SourceLocation());
8985 /// Return true inside OpenMP declare target region.
8986 bool isInOpenMPDeclareTargetContext() const {
8987 return DeclareTargetNestingLevel > 0;
8988 }
8989 /// Return true inside OpenMP target region.
8990 bool isInOpenMPTargetExecutionDirective() const;
8991 /// Return true if (un)supported features for the current target should be
8992 /// diagnosed if OpenMP (offloading) is enabled.
8993 bool shouldDiagnoseTargetSupportFromOpenMP() const {
8994 return !getLangOpts().OpenMPIsDevice || isInOpenMPDeclareTargetContext() ||
8995 isInOpenMPTargetExecutionDirective();
8996 }
8997
8998 /// Return the number of captured regions created for an OpenMP directive.
8999 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
9000
9001 /// Initialization of captured region for OpenMP region.
9002 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
9003 /// End of OpenMP region.
9004 ///
9005 /// \param S Statement associated with the current OpenMP region.
9006 /// \param Clauses List of clauses for the current OpenMP region.
9007 ///
9008 /// \returns Statement for finished OpenMP region.
9009 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
9010 StmtResult ActOnOpenMPExecutableDirective(
9011 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
9012 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
9013 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
9014 /// Called on well-formed '\#pragma omp parallel' after parsing
9015 /// of the associated statement.
9016 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
9017 Stmt *AStmt,
9018 SourceLocation StartLoc,
9019 SourceLocation EndLoc);
9020 using VarsWithInheritedDSAType =
9021 llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
9022 /// Called on well-formed '\#pragma omp simd' after parsing
9023 /// of the associated statement.
9024 StmtResult
9025 ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9026 SourceLocation StartLoc, SourceLocation EndLoc,
9027 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9028 /// Called on well-formed '\#pragma omp for' after parsing
9029 /// of the associated statement.
9030 StmtResult
9031 ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9032 SourceLocation StartLoc, SourceLocation EndLoc,
9033 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9034 /// Called on well-formed '\#pragma omp for simd' after parsing
9035 /// of the associated statement.
9036 StmtResult
9037 ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9038 SourceLocation StartLoc, SourceLocation EndLoc,
9039 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9040 /// Called on well-formed '\#pragma omp sections' after parsing
9041 /// of the associated statement.
9042 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
9043 Stmt *AStmt, SourceLocation StartLoc,
9044 SourceLocation EndLoc);
9045 /// Called on well-formed '\#pragma omp section' after parsing of the
9046 /// associated statement.
9047 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
9048 SourceLocation EndLoc);
9049 /// Called on well-formed '\#pragma omp single' after parsing of the
9050 /// associated statement.
9051 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
9052 Stmt *AStmt, SourceLocation StartLoc,
9053 SourceLocation EndLoc);
9054 /// Called on well-formed '\#pragma omp master' after parsing of the
9055 /// associated statement.
9056 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
9057 SourceLocation EndLoc);
9058 /// Called on well-formed '\#pragma omp critical' after parsing of the
9059 /// associated statement.
9060 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
9061 ArrayRef<OMPClause *> Clauses,
9062 Stmt *AStmt, SourceLocation StartLoc,
9063 SourceLocation EndLoc);
9064 /// Called on well-formed '\#pragma omp parallel for' after parsing
9065 /// of the associated statement.
9066 StmtResult ActOnOpenMPParallelForDirective(
9067 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9068 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9069 /// Called on well-formed '\#pragma omp parallel for simd' after
9070 /// parsing of the associated statement.
9071 StmtResult ActOnOpenMPParallelForSimdDirective(
9072 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9073 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9074 /// Called on well-formed '\#pragma omp parallel sections' after
9075 /// parsing of the associated statement.
9076 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
9077 Stmt *AStmt,
9078 SourceLocation StartLoc,
9079 SourceLocation EndLoc);
9080 /// Called on well-formed '\#pragma omp task' after parsing of the
9081 /// associated statement.
9082 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
9083 Stmt *AStmt, SourceLocation StartLoc,
9084 SourceLocation EndLoc);
9085 /// Called on well-formed '\#pragma omp taskyield'.
9086 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
9087 SourceLocation EndLoc);
9088 /// Called on well-formed '\#pragma omp barrier'.
9089 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
9090 SourceLocation EndLoc);
9091 /// Called on well-formed '\#pragma omp taskwait'.
9092 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
9093 SourceLocation EndLoc);
9094 /// Called on well-formed '\#pragma omp taskgroup'.
9095 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
9096 Stmt *AStmt, SourceLocation StartLoc,
9097 SourceLocation EndLoc);
9098 /// Called on well-formed '\#pragma omp flush'.
9099 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
9100 SourceLocation StartLoc,
9101 SourceLocation EndLoc);
9102 /// Called on well-formed '\#pragma omp ordered' after parsing of the
9103 /// associated statement.
9104 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
9105 Stmt *AStmt, SourceLocation StartLoc,
9106 SourceLocation EndLoc);
9107 /// Called on well-formed '\#pragma omp atomic' after parsing of the
9108 /// associated statement.
9109 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
9110 Stmt *AStmt, SourceLocation StartLoc,
9111 SourceLocation EndLoc);
9112 /// Called on well-formed '\#pragma omp target' after parsing of the
9113 /// associated statement.
9114 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9115 Stmt *AStmt, SourceLocation StartLoc,
9116 SourceLocation EndLoc);
9117 /// Called on well-formed '\#pragma omp target data' after parsing of
9118 /// the associated statement.
9119 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9120 Stmt *AStmt, SourceLocation StartLoc,
9121 SourceLocation EndLoc);
9122 /// Called on well-formed '\#pragma omp target enter data' after
9123 /// parsing of the associated statement.
9124 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9125 SourceLocation StartLoc,
9126 SourceLocation EndLoc,
9127 Stmt *AStmt);
9128 /// Called on well-formed '\#pragma omp target exit data' after
9129 /// parsing of the associated statement.
9130 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9131 SourceLocation StartLoc,
9132 SourceLocation EndLoc,
9133 Stmt *AStmt);
9134 /// Called on well-formed '\#pragma omp target parallel' after
9135 /// parsing of the associated statement.
9136 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
9137 Stmt *AStmt,
9138 SourceLocation StartLoc,
9139 SourceLocation EndLoc);
9140 /// Called on well-formed '\#pragma omp target parallel for' after
9141 /// parsing of the associated statement.
9142 StmtResult ActOnOpenMPTargetParallelForDirective(
9143 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9144 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9145 /// Called on well-formed '\#pragma omp teams' after parsing of the
9146 /// associated statement.
9147 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9148 Stmt *AStmt, SourceLocation StartLoc,
9149 SourceLocation EndLoc);
9150 /// Called on well-formed '\#pragma omp cancellation point'.
9151 StmtResult
9152 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9153 SourceLocation EndLoc,
9154 OpenMPDirectiveKind CancelRegion);
9155 /// Called on well-formed '\#pragma omp cancel'.
9156 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9157 SourceLocation StartLoc,
9158 SourceLocation EndLoc,
9159 OpenMPDirectiveKind CancelRegion);
9160 /// Called on well-formed '\#pragma omp taskloop' after parsing of the
9161 /// associated statement.
9162 StmtResult
9163 ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9164 SourceLocation StartLoc, SourceLocation EndLoc,
9165 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9166 /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
9167 /// the associated statement.
9168 StmtResult ActOnOpenMPTaskLoopSimdDirective(
9169 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9170 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9171 /// Called on well-formed '\#pragma omp distribute' after parsing
9172 /// of the associated statement.
9173 StmtResult
9174 ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9175 SourceLocation StartLoc, SourceLocation EndLoc,
9176 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9177 /// Called on well-formed '\#pragma omp target update'.
9178 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9179 SourceLocation StartLoc,
9180 SourceLocation EndLoc,
9181 Stmt *AStmt);
9182 /// Called on well-formed '\#pragma omp distribute parallel for' after
9183 /// parsing of the associated statement.
9184 StmtResult ActOnOpenMPDistributeParallelForDirective(
9185 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9186 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9187 /// Called on well-formed '\#pragma omp distribute parallel for simd'
9188 /// after parsing of the associated statement.
9189 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
9190 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9191 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9192 /// Called on well-formed '\#pragma omp distribute simd' after
9193 /// parsing of the associated statement.
9194 StmtResult ActOnOpenMPDistributeSimdDirective(
9195 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9196 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9197 /// Called on well-formed '\#pragma omp target parallel for simd' after
9198 /// parsing of the associated statement.
9199 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
9200 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9201 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9202 /// Called on well-formed '\#pragma omp target simd' after parsing of
9203 /// the associated statement.
9204 StmtResult
9205 ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9206 SourceLocation StartLoc, SourceLocation EndLoc,
9207 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9208 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
9209 /// the associated statement.
9210 StmtResult ActOnOpenMPTeamsDistributeDirective(
9211 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9212 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9213 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
9214 /// of the associated statement.
9215 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
9216 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9217 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9218 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
9219 /// after parsing of the associated statement.
9220 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
9221 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9222 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9223 /// Called on well-formed '\#pragma omp teams distribute parallel for'
9224 /// after parsing of the associated statement.
9225 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
9226 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9227 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9228 /// Called on well-formed '\#pragma omp target teams' after parsing of the
9229 /// associated statement.
9230 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
9231 Stmt *AStmt,
9232 SourceLocation StartLoc,
9233 SourceLocation EndLoc);
9234 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
9235 /// of the associated statement.
9236 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
9237 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9238 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9239 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
9240 /// after parsing of the associated statement.
9241 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
9242 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9243 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9244 /// Called on well-formed '\#pragma omp target teams distribute parallel for
9245 /// simd' after parsing of the associated statement.
9246 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
9247 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9248 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9249 /// Called on well-formed '\#pragma omp target teams distribute simd' after
9250 /// parsing of the associated statement.
9251 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
9252 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9253 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9254
9255 /// Checks correctness of linear modifiers.
9256 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9257 SourceLocation LinLoc);
9258 /// Checks that the specified declaration matches requirements for the linear
9259 /// decls.
9260 bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
9261 OpenMPLinearClauseKind LinKind, QualType Type);
9262
9263 /// Called on well-formed '\#pragma omp declare simd' after parsing of
9264 /// the associated method/function.
9265 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
9266 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
9267 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
9268 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
9269 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
9270
9271 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
9272 Expr *Expr,
9273 SourceLocation StartLoc,
9274 SourceLocation LParenLoc,
9275 SourceLocation EndLoc);
9276 /// Called on well-formed 'allocator' clause.
9277 OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
9278 SourceLocation StartLoc,
9279 SourceLocation LParenLoc,
9280 SourceLocation EndLoc);
9281 /// Called on well-formed 'if' clause.
9282 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9283 Expr *Condition, SourceLocation StartLoc,
9284 SourceLocation LParenLoc,
9285 SourceLocation NameModifierLoc,
9286 SourceLocation ColonLoc,
9287 SourceLocation EndLoc);
9288 /// Called on well-formed 'final' clause.
9289 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
9290 SourceLocation LParenLoc,
9291 SourceLocation EndLoc);
9292 /// Called on well-formed 'num_threads' clause.
9293 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9294 SourceLocation StartLoc,
9295 SourceLocation LParenLoc,
9296 SourceLocation EndLoc);
9297 /// Called on well-formed 'safelen' clause.
9298 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
9299 SourceLocation StartLoc,
9300 SourceLocation LParenLoc,
9301 SourceLocation EndLoc);
9302 /// Called on well-formed 'simdlen' clause.
9303 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
9304 SourceLocation LParenLoc,
9305 SourceLocation EndLoc);
9306 /// Called on well-formed 'collapse' clause.
9307 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
9308 SourceLocation StartLoc,
9309 SourceLocation LParenLoc,
9310 SourceLocation EndLoc);
9311 /// Called on well-formed 'ordered' clause.
9312 OMPClause *
9313 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
9314 SourceLocation LParenLoc = SourceLocation(),
9315 Expr *NumForLoops = nullptr);
9316 /// Called on well-formed 'grainsize' clause.
9317 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
9318 SourceLocation LParenLoc,
9319 SourceLocation EndLoc);
9320 /// Called on well-formed 'num_tasks' clause.
9321 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
9322 SourceLocation LParenLoc,
9323 SourceLocation EndLoc);
9324 /// Called on well-formed 'hint' clause.
9325 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
9326 SourceLocation LParenLoc,
9327 SourceLocation EndLoc);
9328
9329 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
9330 unsigned Argument,
9331 SourceLocation ArgumentLoc,
9332 SourceLocation StartLoc,
9333 SourceLocation LParenLoc,
9334 SourceLocation EndLoc);
9335 /// Called on well-formed 'default' clause.
9336 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9337 SourceLocation KindLoc,
9338 SourceLocation StartLoc,
9339 SourceLocation LParenLoc,
9340 SourceLocation EndLoc);
9341 /// Called on well-formed 'proc_bind' clause.
9342 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9343 SourceLocation KindLoc,
9344 SourceLocation StartLoc,
9345 SourceLocation LParenLoc,
9346 SourceLocation EndLoc);
9347
9348 OMPClause *ActOnOpenMPSingleExprWithArgClause(
9349 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
9350 SourceLocation StartLoc, SourceLocation LParenLoc,
9351 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
9352 SourceLocation EndLoc);
9353 /// Called on well-formed 'schedule' clause.
9354 OMPClause *ActOnOpenMPScheduleClause(
9355 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
9356 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
9357 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9358 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
9359
9360 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
9361 SourceLocation EndLoc);
9362 /// Called on well-formed 'nowait' clause.
9363 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9364 SourceLocation EndLoc);
9365 /// Called on well-formed 'untied' clause.
9366 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9367 SourceLocation EndLoc);
9368 /// Called on well-formed 'mergeable' clause.
9369 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9370 SourceLocation EndLoc);
9371 /// Called on well-formed 'read' clause.
9372 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
9373 SourceLocation EndLoc);
9374 /// Called on well-formed 'write' clause.
9375 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
9376 SourceLocation EndLoc);
9377 /// Called on well-formed 'update' clause.
9378 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9379 SourceLocation EndLoc);
9380 /// Called on well-formed 'capture' clause.
9381 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9382 SourceLocation EndLoc);
9383 /// Called on well-formed 'seq_cst' clause.
9384 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9385 SourceLocation EndLoc);
9386 /// Called on well-formed 'threads' clause.
9387 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9388 SourceLocation EndLoc);
9389 /// Called on well-formed 'simd' clause.
9390 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9391 SourceLocation EndLoc);
9392 /// Called on well-formed 'nogroup' clause.
9393 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9394 SourceLocation EndLoc);
9395 /// Called on well-formed 'unified_address' clause.
9396 OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
9397 SourceLocation EndLoc);
9398
9399 /// Called on well-formed 'unified_address' clause.
9400 OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
9401 SourceLocation EndLoc);
9402
9403 /// Called on well-formed 'reverse_offload' clause.
9404 OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
9405 SourceLocation EndLoc);
9406
9407 /// Called on well-formed 'dynamic_allocators' clause.
9408 OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
9409 SourceLocation EndLoc);
9410
9411 /// Called on well-formed 'atomic_default_mem_order' clause.
9412 OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
9413 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
9414 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
9415
9416 OMPClause *ActOnOpenMPVarListClause(
9417 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
9418 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
9419 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
9420 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
9421 OpenMPLinearClauseKind LinKind,
9422 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
9423 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
9424 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc);
9425 /// Called on well-formed 'allocate' clause.
9426 OMPClause *
9427 ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
9428 SourceLocation StartLoc, SourceLocation ColonLoc,
9429 SourceLocation LParenLoc, SourceLocation EndLoc);
9430 /// Called on well-formed 'private' clause.
9431 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9432 SourceLocation StartLoc,
9433 SourceLocation LParenLoc,
9434 SourceLocation EndLoc);
9435 /// Called on well-formed 'firstprivate' clause.
9436 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9437 SourceLocation StartLoc,
9438 SourceLocation LParenLoc,
9439 SourceLocation EndLoc);
9440 /// Called on well-formed 'lastprivate' clause.
9441 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9442 SourceLocation StartLoc,
9443 SourceLocation LParenLoc,
9444 SourceLocation EndLoc);
9445 /// Called on well-formed 'shared' clause.
9446 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9447 SourceLocation StartLoc,
9448 SourceLocation LParenLoc,
9449 SourceLocation EndLoc);
9450 /// Called on well-formed 'reduction' clause.
9451 OMPClause *ActOnOpenMPReductionClause(
9452 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9453 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9454 CXXScopeSpec &ReductionIdScopeSpec,
9455 const DeclarationNameInfo &ReductionId,
9456 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9457 /// Called on well-formed 'task_reduction' clause.
9458 OMPClause *ActOnOpenMPTaskReductionClause(
9459 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9460 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9461 CXXScopeSpec &ReductionIdScopeSpec,
9462 const DeclarationNameInfo &ReductionId,
9463 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9464 /// Called on well-formed 'in_reduction' clause.
9465 OMPClause *ActOnOpenMPInReductionClause(
9466 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9467 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9468 CXXScopeSpec &ReductionIdScopeSpec,
9469 const DeclarationNameInfo &ReductionId,
9470 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9471 /// Called on well-formed 'linear' clause.
9472 OMPClause *
9473 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
9474 SourceLocation StartLoc, SourceLocation LParenLoc,
9475 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
9476 SourceLocation ColonLoc, SourceLocation EndLoc);
9477 /// Called on well-formed 'aligned' clause.
9478 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
9479 Expr *Alignment,
9480 SourceLocation StartLoc,
9481 SourceLocation LParenLoc,
9482 SourceLocation ColonLoc,
9483 SourceLocation EndLoc);
9484 /// Called on well-formed 'copyin' clause.
9485 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9486 SourceLocation StartLoc,
9487 SourceLocation LParenLoc,
9488 SourceLocation EndLoc);
9489 /// Called on well-formed 'copyprivate' clause.
9490 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9491 SourceLocation StartLoc,
9492 SourceLocation LParenLoc,
9493 SourceLocation EndLoc);
9494 /// Called on well-formed 'flush' pseudo clause.
9495 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9496 SourceLocation StartLoc,
9497 SourceLocation LParenLoc,
9498 SourceLocation EndLoc);
9499 /// Called on well-formed 'depend' clause.
9500 OMPClause *
9501 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
9502 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
9503 SourceLocation StartLoc, SourceLocation LParenLoc,
9504 SourceLocation EndLoc);
9505 /// Called on well-formed 'device' clause.
9506 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9507 SourceLocation LParenLoc,
9508 SourceLocation EndLoc);
9509 /// Called on well-formed 'map' clause.
9510 OMPClause *
9511 ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
9512 ArrayRef<SourceLocation> MapTypeModifiersLoc,
9513 CXXScopeSpec &MapperIdScopeSpec,
9514 DeclarationNameInfo &MapperId,
9515 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9516 SourceLocation MapLoc, SourceLocation ColonLoc,
9517 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
9518 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
9519 /// Called on well-formed 'num_teams' clause.
9520 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
9521 SourceLocation LParenLoc,
9522 SourceLocation EndLoc);
9523 /// Called on well-formed 'thread_limit' clause.
9524 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
9525 SourceLocation StartLoc,
9526 SourceLocation LParenLoc,
9527 SourceLocation EndLoc);
9528 /// Called on well-formed 'priority' clause.
9529 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
9530 SourceLocation LParenLoc,
9531 SourceLocation EndLoc);
9532 /// Called on well-formed 'dist_schedule' clause.
9533 OMPClause *ActOnOpenMPDistScheduleClause(
9534 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
9535 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
9536 SourceLocation CommaLoc, SourceLocation EndLoc);
9537 /// Called on well-formed 'defaultmap' clause.
9538 OMPClause *ActOnOpenMPDefaultmapClause(
9539 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
9540 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
9541 SourceLocation KindLoc, SourceLocation EndLoc);
9542 /// Called on well-formed 'to' clause.
9543 OMPClause *
9544 ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
9545 DeclarationNameInfo &MapperId,
9546 const OMPVarListLocTy &Locs,
9547 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
9548 /// Called on well-formed 'from' clause.
9549 OMPClause *ActOnOpenMPFromClause(
9550 ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
9551 DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs,
9552 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
9553 /// Called on well-formed 'use_device_ptr' clause.
9554 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
9555 const OMPVarListLocTy &Locs);
9556 /// Called on well-formed 'is_device_ptr' clause.
9557 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
9558 const OMPVarListLocTy &Locs);
9559
9560 /// The kind of conversion being performed.
9561 enum CheckedConversionKind {
9562 /// An implicit conversion.
9563 CCK_ImplicitConversion,
9564 /// A C-style cast.
9565 CCK_CStyleCast,
9566 /// A functional-style cast.
9567 CCK_FunctionalCast,
9568 /// A cast other than a C-style cast.
9569 CCK_OtherCast,
9570 /// A conversion for an operand of a builtin overloaded operator.
9571 CCK_ForBuiltinOverloadedOp
9572 };
9573
9574 static bool isCast(CheckedConversionKind CCK) {
9575 return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
9576 CCK == CCK_OtherCast;
9577 }
9578
9579 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
9580 /// cast. If there is already an implicit cast, merge into the existing one.
9581 /// If isLvalue, the result of the cast is an lvalue.
9582 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
9583 ExprValueKind VK = VK_RValue,
9584 const CXXCastPath *BasePath = nullptr,
9585 CheckedConversionKind CCK
9586 = CCK_ImplicitConversion);
9587
9588 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
9589 /// to the conversion from scalar type ScalarTy to the Boolean type.
9590 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
9591
9592 /// IgnoredValueConversions - Given that an expression's result is
9593 /// syntactically ignored, perform any conversions that are
9594 /// required.
9595 ExprResult IgnoredValueConversions(Expr *E);
9596
9597 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
9598 // functions and arrays to their respective pointers (C99 6.3.2.1).
9599 ExprResult UsualUnaryConversions(Expr *E);
9600
9601 /// CallExprUnaryConversions - a special case of an unary conversion
9602 /// performed on a function designator of a call expression.
9603 ExprResult CallExprUnaryConversions(Expr *E);
9604
9605 // DefaultFunctionArrayConversion - converts functions and arrays
9606 // to their respective pointers (C99 6.3.2.1).
9607 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
9608
9609 // DefaultFunctionArrayLvalueConversion - converts functions and
9610 // arrays to their respective pointers and performs the
9611 // lvalue-to-rvalue conversion.
9612 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
9613 bool Diagnose = true);
9614
9615 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
9616 // the operand. This is DefaultFunctionArrayLvalueConversion,
9617 // except that it assumes the operand isn't of function or array
9618 // type.
9619 ExprResult DefaultLvalueConversion(Expr *E);
9620
9621 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
9622 // do not have a prototype. Integer promotions are performed on each
9623 // argument, and arguments that have type float are promoted to double.
9624 ExprResult DefaultArgumentPromotion(Expr *E);
9625
9626 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9627 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9628 /// we don't have xvalues there.
9629 ExprResult TemporaryMaterializationConversion(Expr *E);
9630
9631 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9632 enum VariadicCallType {
9633 VariadicFunction,
9634 VariadicBlock,
9635 VariadicMethod,
9636 VariadicConstructor,
9637 VariadicDoesNotApply
9638 };
9639
9640 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9641 const FunctionProtoType *Proto,
9642 Expr *Fn);
9643
9644 // Used for determining in which context a type is allowed to be passed to a
9645 // vararg function.
9646 enum VarArgKind {
9647 VAK_Valid,
9648 VAK_ValidInCXX11,
9649 VAK_Undefined,
9650 VAK_MSVCUndefined,
9651 VAK_Invalid
9652 };
9653
9654 // Determines which VarArgKind fits an expression.
9655 VarArgKind isValidVarArgType(const QualType &Ty);
9656
9657 /// Check to see if the given expression is a valid argument to a variadic
9658 /// function, issuing a diagnostic if not.
9659 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9660
9661 /// Check to see if a given expression could have '.c_str()' called on it.
9662 bool hasCStrMethod(const Expr *E);
9663
9664 /// GatherArgumentsForCall - Collector argument expressions for various
9665 /// form of call prototypes.
9666 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9667 const FunctionProtoType *Proto,
9668 unsigned FirstParam, ArrayRef<Expr *> Args,
9669 SmallVectorImpl<Expr *> &AllArgs,
9670 VariadicCallType CallType = VariadicDoesNotApply,
9671 bool AllowExplicit = false,
9672 bool IsListInitialization = false);
9673
9674 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9675 // will create a runtime trap if the resulting type is not a POD type.
9676 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9677 FunctionDecl *FDecl);
9678
9679 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9680 // operands and then handles various conversions that are common to binary
9681 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9682 // routine returns the first non-arithmetic type found. The client is
9683 // responsible for emitting appropriate error diagnostics.
9684 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9685 bool IsCompAssign = false);
9686
9687 /// AssignConvertType - All of the 'assignment' semantic checks return this
9688 /// enum to indicate whether the assignment was allowed. These checks are
9689 /// done for simple assignments, as well as initialization, return from
9690 /// function, argument passing, etc. The query is phrased in terms of a
9691 /// source and destination type.
9692 enum AssignConvertType {
9693 /// Compatible - the types are compatible according to the standard.
9694 Compatible,
9695
9696 /// PointerToInt - The assignment converts a pointer to an int, which we
9697 /// accept as an extension.
9698 PointerToInt,
9699
9700 /// IntToPointer - The assignment converts an int to a pointer, which we
9701 /// accept as an extension.
9702 IntToPointer,
9703
9704 /// FunctionVoidPointer - The assignment is between a function pointer and
9705 /// void*, which the standard doesn't allow, but we accept as an extension.
9706 FunctionVoidPointer,
9707
9708 /// IncompatiblePointer - The assignment is between two pointers types that
9709 /// are not compatible, but we accept them as an extension.
9710 IncompatiblePointer,
9711
9712 /// IncompatiblePointerSign - The assignment is between two pointers types
9713 /// which point to integers which have a different sign, but are otherwise
9714 /// identical. This is a subset of the above, but broken out because it's by
9715 /// far the most common case of incompatible pointers.
9716 IncompatiblePointerSign,
9717
9718 /// CompatiblePointerDiscardsQualifiers - The assignment discards
9719 /// c/v/r qualifiers, which we accept as an extension.
9720 CompatiblePointerDiscardsQualifiers,
9721
9722 /// IncompatiblePointerDiscardsQualifiers - The assignment
9723 /// discards qualifiers that we don't permit to be discarded,
9724 /// like address spaces.
9725 IncompatiblePointerDiscardsQualifiers,
9726
9727 /// IncompatibleNestedPointerQualifiers - The assignment is between two
9728 /// nested pointer types, and the qualifiers other than the first two
9729 /// levels differ e.g. char ** -> const char **, but we accept them as an
9730 /// extension.
9731 IncompatibleNestedPointerQualifiers,
9732
9733 /// IncompatibleVectors - The assignment is between two vector types that
9734 /// have the same size, which we accept as an extension.
9735 IncompatibleVectors,
9736
9737 /// IntToBlockPointer - The assignment converts an int to a block
9738 /// pointer. We disallow this.
9739 IntToBlockPointer,
9740
9741 /// IncompatibleBlockPointer - The assignment is between two block
9742 /// pointers types that are not compatible.
9743 IncompatibleBlockPointer,
9744
9745 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9746 /// id type and something else (that is incompatible with it). For example,
9747 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9748 IncompatibleObjCQualifiedId,
9749
9750 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9751 /// object with __weak qualifier.
9752 IncompatibleObjCWeakRef,
9753
9754 /// Incompatible - We reject this conversion outright, it is invalid to
9755 /// represent it in the AST.
9756 Incompatible
9757 };
9758
9759 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9760 /// assignment conversion type specified by ConvTy. This returns true if the
9761 /// conversion was invalid or false if the conversion was accepted.
9762 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9763 SourceLocation Loc,
9764 QualType DstType, QualType SrcType,
9765 Expr *SrcExpr, AssignmentAction Action,
9766 bool *Complained = nullptr);
9767
9768 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9769 /// enum. If AllowMask is true, then we also allow the complement of a valid
9770 /// value, to be used as a mask.
9771 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9772 bool AllowMask) const;
9773
9774 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9775 /// integer not in the range of enum values.
9776 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9777 Expr *SrcExpr);
9778
9779 /// CheckAssignmentConstraints - Perform type checking for assignment,
9780 /// argument passing, variable initialization, and function return values.
9781 /// C99 6.5.16.
9782 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9783 QualType LHSType,
9784 QualType RHSType);
9785
9786 /// Check assignment constraints and optionally prepare for a conversion of
9787 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9788 /// is true.
9789 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9790 ExprResult &RHS,
9791 CastKind &Kind,
9792 bool ConvertRHS = true);
9793
9794 /// Check assignment constraints for an assignment of RHS to LHSType.
9795 ///
9796 /// \param LHSType The destination type for the assignment.
9797 /// \param RHS The source expression for the assignment.
9798 /// \param Diagnose If \c true, diagnostics may be produced when checking
9799 /// for assignability. If a diagnostic is produced, \p RHS will be
9800 /// set to ExprError(). Note that this function may still return
9801 /// without producing a diagnostic, even for an invalid assignment.
9802 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9803 /// in an audited Core Foundation API and does not need to be checked
9804 /// for ARC retain issues.
9805 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9806 /// conversions necessary to perform the assignment. If \c false,
9807 /// \p Diagnose must also be \c false.
9808 AssignConvertType CheckSingleAssignmentConstraints(
9809 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9810 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9811
9812 // If the lhs type is a transparent union, check whether we
9813 // can initialize the transparent union with the given expression.
9814 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9815 ExprResult &RHS);
9816
9817 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9818
9819 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9820
9821 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9822 AssignmentAction Action,
9823 bool AllowExplicit = false);
9824 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9825 AssignmentAction Action,
9826 bool AllowExplicit,
9827 ImplicitConversionSequence& ICS);
9828 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9829 const ImplicitConversionSequence& ICS,
9830 AssignmentAction Action,
9831 CheckedConversionKind CCK
9832 = CCK_ImplicitConversion);
9833 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9834 const StandardConversionSequence& SCS,
9835 AssignmentAction Action,
9836 CheckedConversionKind CCK);
9837
9838 ExprResult PerformQualificationConversion(
9839 Expr *E, QualType Ty, ExprValueKind VK = VK_RValue,
9840 CheckedConversionKind CCK = CCK_ImplicitConversion);
9841
9842 /// the following "Check" methods will return a valid/converted QualType
9843 /// or a null QualType (indicating an error diagnostic was issued).
9844
9845 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9846 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9847 ExprResult &RHS);
9848 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9849 ExprResult &RHS);
9850 QualType CheckPointerToMemberOperands( // C++ 5.5
9851 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9852 SourceLocation OpLoc, bool isIndirect);
9853 QualType CheckMultiplyDivideOperands( // C99 6.5.5
9854 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9855 bool IsDivide);
9856 QualType CheckRemainderOperands( // C99 6.5.5
9857 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9858 bool IsCompAssign = false);
9859 QualType CheckAdditionOperands( // C99 6.5.6
9860 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9861 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9862 QualType CheckSubtractionOperands( // C99 6.5.6
9863 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9864 QualType* CompLHSTy = nullptr);
9865 QualType CheckShiftOperands( // C99 6.5.7
9866 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9867 BinaryOperatorKind Opc, bool IsCompAssign = false);
9868 QualType CheckCompareOperands( // C99 6.5.8/9
9869 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9870 BinaryOperatorKind Opc);
9871 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9872 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9873 BinaryOperatorKind Opc);
9874 QualType CheckLogicalOperands( // C99 6.5.[13,14]
9875 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9876 BinaryOperatorKind Opc);
9877 // CheckAssignmentOperands is used for both simple and compound assignment.
9878 // For simple assignment, pass both expressions and a null converted type.
9879 // For compound assignment, pass both expressions and the converted type.
9880 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9881 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9882
9883 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9884 UnaryOperatorKind Opcode, Expr *Op);
9885 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9886 BinaryOperatorKind Opcode,
9887 Expr *LHS, Expr *RHS);
9888 ExprResult checkPseudoObjectRValue(Expr *E);
9889 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9890
9891 QualType CheckConditionalOperands( // C99 6.5.15
9892 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9893 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9894 QualType CXXCheckConditionalOperands( // C++ 5.16
9895 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9896 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9897 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9898 bool ConvertArgs = true);
9899 QualType FindCompositePointerType(SourceLocation Loc,
9900 ExprResult &E1, ExprResult &E2,
9901 bool ConvertArgs = true) {
9902 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9903 QualType Composite =
9904 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9905 E1 = E1Tmp;
9906 E2 = E2Tmp;
9907 return Composite;
9908 }
9909
9910 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9911 SourceLocation QuestionLoc);
9912
9913 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9914 SourceLocation QuestionLoc);
9915
9916 void DiagnoseAlwaysNonNullPointer(Expr *E,
9917 Expr::NullPointerConstantKind NullType,
9918 bool IsEqual, SourceRange Range);
9919
9920 /// type checking for vector binary operators.
9921 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9922 SourceLocation Loc, bool IsCompAssign,
9923 bool AllowBothBool, bool AllowBoolConversion);
9924 QualType GetSignedVectorType(QualType V);
9925 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9926 SourceLocation Loc,
9927 BinaryOperatorKind Opc);
9928 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9929 SourceLocation Loc);
9930
9931 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9932 bool isLaxVectorConversion(QualType srcType, QualType destType);
9933
9934 /// type checking declaration initializers (C99 6.7.8)
9935 bool CheckForConstantInitializer(Expr *e, QualType t);
9936
9937 // type checking C++ declaration initializers (C++ [dcl.init]).
9938
9939 /// ReferenceCompareResult - Expresses the result of comparing two
9940 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9941 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9942 enum ReferenceCompareResult {
9943 /// Ref_Incompatible - The two types are incompatible, so direct
9944 /// reference binding is not possible.
9945 Ref_Incompatible = 0,
9946 /// Ref_Related - The two types are reference-related, which means
9947 /// that their unqualified forms (T1 and T2) are either the same
9948 /// or T1 is a base class of T2.
9949 Ref_Related,
9950 /// Ref_Compatible - The two types are reference-compatible.
9951 Ref_Compatible
9952 };
9953
9954 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9955 QualType T1, QualType T2,
9956 bool &DerivedToBase,
9957 bool &ObjCConversion,
9958 bool &ObjCLifetimeConversion);
9959
9960 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9961 Expr *CastExpr, CastKind &CastKind,
9962 ExprValueKind &VK, CXXCastPath &Path);
9963
9964 /// Force an expression with unknown-type to an expression of the
9965 /// given type.
9966 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9967
9968 /// Type-check an expression that's being passed to an
9969 /// __unknown_anytype parameter.
9970 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9971 Expr *result, QualType &paramType);
9972
9973 // CheckVectorCast - check type constraints for vectors.
9974 // Since vectors are an extension, there are no C standard reference for this.
9975 // We allow casting between vectors and integer datatypes of the same size.
9976 // returns true if the cast is invalid
9977 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9978 CastKind &Kind);
9979
9980 /// Prepare `SplattedExpr` for a vector splat operation, adding
9981 /// implicit casts if necessary.
9982 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9983
9984 // CheckExtVectorCast - check type constraints for extended vectors.
9985 // Since vectors are an extension, there are no C standard reference for this.
9986 // We allow casting between vectors and integer datatypes of the same size,
9987 // or vectors and the element type of that vector.
9988 // returns the cast expr
9989 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9990 CastKind &Kind);
9991
9992 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9993 SourceLocation LParenLoc,
9994 Expr *CastExpr,
9995 SourceLocation RParenLoc);
9996
9997 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9998
9999 /// Checks for invalid conversions and casts between
10000 /// retainable pointers and other pointer kinds for ARC and Weak.
10001 ARCConversionResult CheckObjCConversion(SourceRange castRange,
10002 QualType castType, Expr *&op,
10003 CheckedConversionKind CCK,
10004 bool Diagnose = true,
10005 bool DiagnoseCFAudited = false,
10006 BinaryOperatorKind Opc = BO_PtrMemD
10007 );
10008
10009 Expr *stripARCUnbridgedCast(Expr *e);
10010 void diagnoseARCUnbridgedCast(Expr *e);
10011
10012 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
10013 QualType ExprType);
10014
10015 /// checkRetainCycles - Check whether an Objective-C message send
10016 /// might create an obvious retain cycle.
10017 void checkRetainCycles(ObjCMessageExpr *msg);
10018 void checkRetainCycles(Expr *receiver, Expr *argument);
10019 void checkRetainCycles(VarDecl *Var, Expr *Init);
10020
10021 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
10022 /// to weak/__unsafe_unretained type.
10023 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
10024
10025 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
10026 /// to weak/__unsafe_unretained expression.
10027 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
10028
10029 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
10030 /// \param Method - May be null.
10031 /// \param [out] ReturnType - The return type of the send.
10032 /// \return true iff there were any incompatible types.
10033 bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
10034 MultiExprArg Args, Selector Sel,
10035 ArrayRef<SourceLocation> SelectorLocs,
10036 ObjCMethodDecl *Method, bool isClassMessage,
10037 bool isSuperMessage, SourceLocation lbrac,
10038 SourceLocation rbrac, SourceRange RecRange,
10039 QualType &ReturnType, ExprValueKind &VK);
10040
10041 /// Determine the result of a message send expression based on
10042 /// the type of the receiver, the method expected to receive the message,
10043 /// and the form of the message send.
10044 QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
10045 ObjCMethodDecl *Method, bool isClassMessage,
10046 bool isSuperMessage);
10047
10048 /// If the given expression involves a message send to a method
10049 /// with a related result type, emit a note describing what happened.
10050 void EmitRelatedResultTypeNote(const Expr *E);
10051
10052 /// Given that we had incompatible pointer types in a return
10053 /// statement, check whether we're in a method with a related result
10054 /// type, and if so, emit a note describing what happened.
10055 void EmitRelatedResultTypeNoteForReturn(QualType destType);
10056
10057 class ConditionResult {
10058 Decl *ConditionVar;
10059 FullExprArg Condition;
10060 bool Invalid;
10061 bool HasKnownValue;
10062 bool KnownValue;
10063
10064 friend class Sema;
10065 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
10066 bool IsConstexpr)
10067 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
10068 HasKnownValue(IsConstexpr && Condition.get() &&
10069 !Condition.get()->isValueDependent()),
10070 KnownValue(HasKnownValue &&
10071 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
10072 explicit ConditionResult(bool Invalid)
10073 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
10074 HasKnownValue(false), KnownValue(false) {}
10075
10076 public:
10077 ConditionResult() : ConditionResult(false) {}
10078 bool isInvalid() const { return Invalid; }
10079 std::pair<VarDecl *, Expr *> get() const {
10080 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
10081 Condition.get());
10082 }
10083 llvm::Optional<bool> getKnownValue() const {
10084 if (!HasKnownValue)
10085 return None;
10086 return KnownValue;
10087 }
10088 };
10089 static ConditionResult ConditionError() { return ConditionResult(true); }
10090
10091 enum class ConditionKind {
10092 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
10093 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
10094 Switch ///< An integral condition for a 'switch' statement.
10095 };
10096
10097 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
10098 Expr *SubExpr, ConditionKind CK);
10099
10100 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
10101 SourceLocation StmtLoc,
10102 ConditionKind CK);
10103
10104 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
10105
10106 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
10107 SourceLocation StmtLoc,
10108 ConditionKind CK);
10109 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
10110
10111 /// CheckBooleanCondition - Diagnose problems involving the use of
10112 /// the given expression as a boolean condition (e.g. in an if
10113 /// statement). Also performs the standard function and array
10114 /// decays, possibly changing the input variable.
10115 ///
10116 /// \param Loc - A location associated with the condition, e.g. the
10117 /// 'if' keyword.
10118 /// \return true iff there were any errors
10119 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
10120 bool IsConstexpr = false);
10121
10122 /// DiagnoseAssignmentAsCondition - Given that an expression is
10123 /// being used as a boolean condition, warn if it's an assignment.
10124 void DiagnoseAssignmentAsCondition(Expr *E);
10125
10126 /// Redundant parentheses over an equality comparison can indicate
10127 /// that the user intended an assignment used as condition.
10128 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
10129
10130 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
10131 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
10132
10133 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
10134 /// the specified width and sign. If an overflow occurs, detect it and emit
10135 /// the specified diagnostic.
10136 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
10137 unsigned NewWidth, bool NewSign,
10138 SourceLocation Loc, unsigned DiagID);
10139
10140 /// Checks that the Objective-C declaration is declared in the global scope.
10141 /// Emits an error and marks the declaration as invalid if it's not declared
10142 /// in the global scope.
10143 bool CheckObjCDeclScope(Decl *D);
10144
10145 /// Abstract base class used for diagnosing integer constant
10146 /// expression violations.
10147 class VerifyICEDiagnoser {
10148 public:
10149 bool Suppress;
10150
10151 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
10152
10153 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
10154 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
10155 virtual ~VerifyICEDiagnoser() { }
10156 };
10157
10158 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
10159 /// and reports the appropriate diagnostics. Returns false on success.
10160 /// Can optionally return the value of the expression.
10161 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10162 VerifyICEDiagnoser &Diagnoser,
10163 bool AllowFold = true);
10164 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10165 unsigned DiagID,
10166 bool AllowFold = true);
10167 ExprResult VerifyIntegerConstantExpression(Expr *E,
10168 llvm::APSInt *Result = nullptr);
10169
10170 /// VerifyBitField - verifies that a bit field expression is an ICE and has
10171 /// the correct width, and that the field type is valid.
10172 /// Returns false on success.
10173 /// Can optionally return whether the bit-field is of width 0
10174 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
10175 QualType FieldTy, bool IsMsStruct,
10176 Expr *BitWidth, bool *ZeroWidth = nullptr);
10177
10178private:
10179 unsigned ForceCUDAHostDeviceDepth = 0;
10180
10181public:
10182 /// Increments our count of the number of times we've seen a pragma forcing
10183 /// functions to be __host__ __device__. So long as this count is greater
10184 /// than zero, all functions encountered will be __host__ __device__.
10185 void PushForceCUDAHostDevice();
10186
10187 /// Decrements our count of the number of times we've seen a pragma forcing
10188 /// functions to be __host__ __device__. Returns false if the count is 0
10189 /// before incrementing, so you can emit an error.
10190 bool PopForceCUDAHostDevice();
10191
10192 /// Diagnostics that are emitted only if we discover that the given function
10193 /// must be codegen'ed. Because handling these correctly adds overhead to
10194 /// compilation, this is currently only enabled for CUDA compilations.
10195 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
10196 std::vector<PartialDiagnosticAt>>
10197 DeviceDeferredDiags;
10198
10199 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
10200 /// key in a hashtable, both the FD and location are hashed.
10201 struct FunctionDeclAndLoc {
10202 CanonicalDeclPtr<FunctionDecl> FD;
10203 SourceLocation Loc;
10204 };
10205
10206 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
10207 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
10208 /// same deferred diag twice.
10209 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
10210
10211 /// An inverse call graph, mapping known-emitted functions to one of their
10212 /// known-emitted callers (plus the location of the call).
10213 ///
10214 /// Functions that we can tell a priori must be emitted aren't added to this
10215 /// map.
10216 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
10217 /* Caller = */ FunctionDeclAndLoc>
10218 DeviceKnownEmittedFns;
10219
10220 /// A partial call graph maintained during CUDA/OpenMP device code compilation
10221 /// to support deferred diagnostics.
10222 ///
10223 /// Functions are only added here if, at the time they're considered, they are
10224 /// not known-emitted. As soon as we discover that a function is
10225 /// known-emitted, we remove it and everything it transitively calls from this
10226 /// set and add those functions to DeviceKnownEmittedFns.
10227 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
10228 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
10229 SourceLocation>>
10230 DeviceCallGraph;
10231
10232 /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be
10233 /// deferred.
10234 ///
10235 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
10236 /// which are not allowed to appear inside __device__ functions and are
10237 /// allowed to appear in __host__ __device__ functions only if the host+device
10238 /// function is never codegen'ed.
10239 ///
10240 /// To handle this, we use the notion of "deferred diagnostics", where we
10241 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
10242 ///
10243 /// This class lets you emit either a regular diagnostic, a deferred
10244 /// diagnostic, or no diagnostic at all, according to an argument you pass to
10245 /// its constructor, thus simplifying the process of creating these "maybe
10246 /// deferred" diagnostics.
10247 class DeviceDiagBuilder {
10248 public:
10249 enum Kind {
10250 /// Emit no diagnostics.
10251 K_Nop,
10252 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
10253 K_Immediate,
10254 /// Emit the diagnostic immediately, and, if it's a warning or error, also
10255 /// emit a call stack showing how this function can be reached by an a
10256 /// priori known-emitted function.
10257 K_ImmediateWithCallStack,
10258 /// Create a deferred diagnostic, which is emitted only if the function
10259 /// it's attached to is codegen'ed. Also emit a call stack as with
10260 /// K_ImmediateWithCallStack.
10261 K_Deferred
10262 };
10263
10264 DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
10265 FunctionDecl *Fn, Sema &S);
10266 DeviceDiagBuilder(DeviceDiagBuilder &&D);
10267 DeviceDiagBuilder(const DeviceDiagBuilder &) = default;
10268 ~DeviceDiagBuilder();
10269
10270 /// Convertible to bool: True if we immediately emitted an error, false if
10271 /// we didn't emit an error or we created a deferred error.
10272 ///
10273 /// Example usage:
10274 ///
10275 /// if (DeviceDiagBuilder(...) << foo << bar)
10276 /// return ExprError();
10277 ///
10278 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
10279 /// want to use these instead of creating a DeviceDiagBuilder yourself.
10280 operator bool() const { return ImmediateDiag.hasValue(); }
10281
10282 template <typename T>
10283 friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag,
10284 const T &Value) {
10285 if (Diag.ImmediateDiag.hasValue())
10286 *Diag.ImmediateDiag << Value;
10287 else if (Diag.PartialDiagId.hasValue())
10288 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
10289 << Value;
10290 return Diag;
10291 }
10292
10293 private:
10294 Sema &S;
10295 SourceLocation Loc;
10296 unsigned DiagID;
10297 FunctionDecl *Fn;
10298 bool ShowCallStack;
10299
10300 // Invariant: At most one of these Optionals has a value.
10301 // FIXME: Switch these to a Variant once that exists.
10302 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
10303 llvm::Optional<unsigned> PartialDiagId;
10304 };
10305
10306 /// Indicate that this function (and thus everything it transtively calls)
10307 /// will be codegen'ed, and emit any deferred diagnostics on this function and
10308 /// its (transitive) callees.
10309 void markKnownEmitted(
10310 Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee,
10311 SourceLocation OrigLoc,
10312 const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted);
10313
10314 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
10315 /// is "used as device code".
10316 ///
10317 /// - If CurContext is a __host__ function, does not emit any diagnostics.
10318 /// - If CurContext is a __device__ or __global__ function, emits the
10319 /// diagnostics immediately.
10320 /// - If CurContext is a __host__ __device__ function and we are compiling for
10321 /// the device, creates a diagnostic which is emitted if and when we realize
10322 /// that the function will be codegen'ed.
10323 ///
10324 /// Example usage:
10325 ///
10326 /// // Variable-length arrays are not allowed in CUDA device code.
10327 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
10328 /// return ExprError();
10329 /// // Otherwise, continue parsing as normal.
10330 DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
10331
10332 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
10333 /// is "used as host code".
10334 ///
10335 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
10336 DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
10337
10338 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
10339 /// context is "used as device code".
10340 ///
10341 /// - If CurContext is a `declare target` function or it is known that the
10342 /// function is emitted for the device, emits the diagnostics immediately.
10343 /// - If CurContext is a non-`declare target` function and we are compiling
10344 /// for the device, creates a diagnostic which is emitted if and when we
10345 /// realize that the function will be codegen'ed.
10346 ///
10347 /// Example usage:
10348 ///
10349 /// // Variable-length arrays are not allowed in NVPTX device code.
10350 /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
10351 /// return ExprError();
10352 /// // Otherwise, continue parsing as normal.
10353 DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID);
10354
10355 DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
10356
10357 enum CUDAFunctionTarget {
10358 CFT_Device,
10359 CFT_Global,
10360 CFT_Host,
10361 CFT_HostDevice,
10362 CFT_InvalidTarget
10363 };
10364
10365 /// Determines whether the given function is a CUDA device/host/kernel/etc.
10366 /// function.
10367 ///
10368 /// Use this rather than examining the function's attributes yourself -- you
10369 /// will get it wrong. Returns CFT_Host if D is null.
10370 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
10371 bool IgnoreImplicitHDAttr = false);
10372 CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
10373
10374 /// Gets the CUDA target for the current context.
10375 CUDAFunctionTarget CurrentCUDATarget() {
10376 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
10377 }
10378
10379 // CUDA function call preference. Must be ordered numerically from
10380 // worst to best.
10381 enum CUDAFunctionPreference {
10382 CFP_Never, // Invalid caller/callee combination.
10383 CFP_WrongSide, // Calls from host-device to host or device
10384 // function that do not match current compilation
10385 // mode.
10386 CFP_HostDevice, // Any calls to host/device functions.
10387 CFP_SameSide, // Calls from host-device to host or device
10388 // function matching current compilation mode.
10389 CFP_Native, // host-to-host or device-to-device calls.
10390 };
10391
10392 /// Identifies relative preference of a given Caller/Callee
10393 /// combination, based on their host/device attributes.
10394 /// \param Caller function which needs address of \p Callee.
10395 /// nullptr in case of global context.
10396 /// \param Callee target function
10397 ///
10398 /// \returns preference value for particular Caller/Callee combination.
10399 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
10400 const FunctionDecl *Callee);
10401
10402 /// Determines whether Caller may invoke Callee, based on their CUDA
10403 /// host/device attributes. Returns false if the call is not allowed.
10404 ///
10405 /// Note: Will return true for CFP_WrongSide calls. These may appear in
10406 /// semantically correct CUDA programs, but only if they're never codegen'ed.
10407 bool IsAllowedCUDACall(const FunctionDecl *Caller,
10408 const FunctionDecl *Callee) {
10409 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
10410 }
10411
10412 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
10413 /// depending on FD and the current compilation settings.
10414 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
10415 const LookupResult &Previous);
10416
10417public:
10418 /// Check whether we're allowed to call Callee from the current context.
10419 ///
10420 /// - If the call is never allowed in a semantically-correct program
10421 /// (CFP_Never), emits an error and returns false.
10422 ///
10423 /// - If the call is allowed in semantically-correct programs, but only if
10424 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
10425 /// be emitted if and when the caller is codegen'ed, and returns true.
10426 ///
10427 /// Will only create deferred diagnostics for a given SourceLocation once,
10428 /// so you can safely call this multiple times without generating duplicate
10429 /// deferred errors.
10430 ///
10431 /// - Otherwise, returns true without emitting any diagnostics.
10432 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
10433
10434 /// Set __device__ or __host__ __device__ attributes on the given lambda
10435 /// operator() method.
10436 ///
10437 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
10438 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
10439 /// functions become __host__ __device__ themselves.
10440 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
10441
10442 /// Finds a function in \p Matches with highest calling priority
10443 /// from \p Caller context and erases all functions with lower
10444 /// calling priority.
10445 void EraseUnwantedCUDAMatches(
10446 const FunctionDecl *Caller,
10447 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
10448
10449 /// Given a implicit special member, infer its CUDA target from the
10450 /// calls it needs to make to underlying base/field special members.
10451 /// \param ClassDecl the class for which the member is being created.
10452 /// \param CSM the kind of special member.
10453 /// \param MemberDecl the special member itself.
10454 /// \param ConstRHS true if this is a copy operation with a const object on
10455 /// its RHS.
10456 /// \param Diagnose true if this call should emit diagnostics.
10457 /// \return true if there was an error inferring.
10458 /// The result of this call is implicit CUDA target attribute(s) attached to
10459 /// the member declaration.
10460 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
10461 CXXSpecialMember CSM,
10462 CXXMethodDecl *MemberDecl,
10463 bool ConstRHS,
10464 bool Diagnose);
10465
10466 /// \return true if \p CD can be considered empty according to CUDA
10467 /// (E.2.3.1 in CUDA 7.5 Programming guide).
10468 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
10469 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
10470
10471 // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
10472 // case of error emits appropriate diagnostic and invalidates \p Var.
10473 //
10474 // \details CUDA allows only empty constructors as initializers for global
10475 // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
10476 // __shared__ variables whether they are local or not (they all are implicitly
10477 // static in CUDA). One exception is that CUDA allows constant initializers
10478 // for __constant__ and __device__ variables.
10479 void checkAllowedCUDAInitializer(VarDecl *VD);
10480
10481 /// Check whether NewFD is a valid overload for CUDA. Emits
10482 /// diagnostics and invalidates NewFD if not.
10483 void checkCUDATargetOverload(FunctionDecl *NewFD,
10484 const LookupResult &Previous);
10485 /// Copies target attributes from the template TD to the function FD.
10486 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
10487
10488 /// Returns the name of the launch configuration function. This is the name
10489 /// of the function that will be called to configure kernel call, with the
10490 /// parameters specified via <<<>>>.
10491 std::string getCudaConfigureFuncName() const;
10492
10493 /// \name Code completion
10494 //@{
10495 /// Describes the context in which code completion occurs.
10496 enum ParserCompletionContext {
10497 /// Code completion occurs at top-level or namespace context.
10498 PCC_Namespace,
10499 /// Code completion occurs within a class, struct, or union.
10500 PCC_Class,
10501 /// Code completion occurs within an Objective-C interface, protocol,
10502 /// or category.
10503 PCC_ObjCInterface,
10504 /// Code completion occurs within an Objective-C implementation or
10505 /// category implementation
10506 PCC_ObjCImplementation,
10507 /// Code completion occurs within the list of instance variables
10508 /// in an Objective-C interface, protocol, category, or implementation.
10509 PCC_ObjCInstanceVariableList,
10510 /// Code completion occurs following one or more template
10511 /// headers.
10512 PCC_Template,
10513 /// Code completion occurs following one or more template
10514 /// headers within a class.
10515 PCC_MemberTemplate,
10516 /// Code completion occurs within an expression.
10517 PCC_Expression,
10518 /// Code completion occurs within a statement, which may
10519 /// also be an expression or a declaration.
10520 PCC_Statement,
10521 /// Code completion occurs at the beginning of the
10522 /// initialization statement (or expression) in a for loop.
10523 PCC_ForInit,
10524 /// Code completion occurs within the condition of an if,
10525 /// while, switch, or for statement.
10526 PCC_Condition,
10527 /// Code completion occurs within the body of a function on a
10528 /// recovery path, where we do not have a specific handle on our position
10529 /// in the grammar.
10530 PCC_RecoveryInFunction,
10531 /// Code completion occurs where only a type is permitted.
10532 PCC_Type,
10533 /// Code completion occurs in a parenthesized expression, which
10534 /// might also be a type cast.
10535 PCC_ParenthesizedExpression,
10536 /// Code completion occurs within a sequence of declaration
10537 /// specifiers within a function, method, or block.
10538 PCC_LocalDeclarationSpecifiers
10539 };
10540
10541 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
10542 void CodeCompleteOrdinaryName(Scope *S,
10543 ParserCompletionContext CompletionContext);
10544 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
10545 bool AllowNonIdentifiers,
10546 bool AllowNestedNameSpecifiers);
10547
10548 struct CodeCompleteExpressionData;
10549 void CodeCompleteExpression(Scope *S,
10550 const CodeCompleteExpressionData &Data);
10551 void CodeCompleteExpression(Scope *S, QualType PreferredType,
10552 bool IsParenthesized = false);
10553 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
10554 SourceLocation OpLoc, bool IsArrow,
10555 bool IsBaseExprStatement,
10556 QualType PreferredType);
10557 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
10558 QualType PreferredType);
10559 void CodeCompleteTag(Scope *S, unsigned TagSpec);
10560 void CodeCompleteTypeQualifiers(DeclSpec &DS);
10561 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
10562 const VirtSpecifiers *VS = nullptr);
10563 void CodeCompleteBracketDeclarator(Scope *S);
10564 void CodeCompleteCase(Scope *S);
10565 /// Reports signatures for a call to CodeCompleteConsumer and returns the
10566 /// preferred type for the current argument. Returned type can be null.
10567 QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
10568 SourceLocation OpenParLoc);
10569 QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
10570 SourceLocation Loc,
10571 ArrayRef<Expr *> Args,
10572 SourceLocation OpenParLoc);
10573 QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
10574 CXXScopeSpec SS,
10575 ParsedType TemplateTypeTy,
10576 ArrayRef<Expr *> ArgExprs,
10577 IdentifierInfo *II,
10578 SourceLocation OpenParLoc);
10579 void CodeCompleteInitializer(Scope *S, Decl *D);
10580 void CodeCompleteAfterIf(Scope *S);
10581
10582 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
10583 bool EnteringContext, QualType BaseType);
10584 void CodeCompleteUsing(Scope *S);
10585 void CodeCompleteUsingDirective(Scope *S);
10586 void CodeCompleteNamespaceDecl(Scope *S);
10587 void CodeCompleteNamespaceAliasDecl(Scope *S);
10588 void CodeCompleteOperatorName(Scope *S);
10589 void CodeCompleteConstructorInitializer(
10590 Decl *Constructor,
10591 ArrayRef<CXXCtorInitializer *> Initializers);
10592
10593 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
10594 bool AfterAmpersand);
10595
10596 void CodeCompleteObjCAtDirective(Scope *S);
10597 void CodeCompleteObjCAtVisibility(Scope *S);
10598 void CodeCompleteObjCAtStatement(Scope *S);
10599 void CodeCompleteObjCAtExpression(Scope *S);
10600 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
10601 void CodeCompleteObjCPropertyGetter(Scope *S);
10602 void CodeCompleteObjCPropertySetter(Scope *S);
10603 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
10604 bool IsParameter);
10605 void CodeCompleteObjCMessageReceiver(Scope *S);
10606 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
10607 ArrayRef<IdentifierInfo *> SelIdents,
10608 bool AtArgumentExpression);
10609 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
10610 ArrayRef<IdentifierInfo *> SelIdents,
10611 bool AtArgumentExpression,
10612 bool IsSuper = false);
10613 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
10614 ArrayRef<IdentifierInfo *> SelIdents,
10615 bool AtArgumentExpression,
10616 ObjCInterfaceDecl *Super = nullptr);
10617 void CodeCompleteObjCForCollection(Scope *S,
10618 DeclGroupPtrTy IterationVar);
10619 void CodeCompleteObjCSelector(Scope *S,
10620 ArrayRef<IdentifierInfo *> SelIdents);
10621 void CodeCompleteObjCProtocolReferences(
10622 ArrayRef<IdentifierLocPair> Protocols);
10623 void CodeCompleteObjCProtocolDecl(Scope *S);
10624 void CodeCompleteObjCInterfaceDecl(Scope *S);
10625 void CodeCompleteObjCSuperclass(Scope *S,
10626 IdentifierInfo *ClassName,
10627 SourceLocation ClassNameLoc);
10628 void CodeCompleteObjCImplementationDecl(Scope *S);
10629 void CodeCompleteObjCInterfaceCategory(Scope *S,
10630 IdentifierInfo *ClassName,
10631 SourceLocation ClassNameLoc);
10632 void CodeCompleteObjCImplementationCategory(Scope *S,
10633 IdentifierInfo *ClassName,
10634 SourceLocation ClassNameLoc);
10635 void CodeCompleteObjCPropertyDefinition(Scope *S);
10636 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
10637 IdentifierInfo *PropertyName);
10638 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
10639 ParsedType ReturnType);
10640 void CodeCompleteObjCMethodDeclSelector(Scope *S,
10641 bool IsInstanceMethod,
10642 bool AtParameterName,
10643 ParsedType ReturnType,
10644 ArrayRef<IdentifierInfo *> SelIdents);
10645 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
10646 SourceLocation ClassNameLoc,
10647 bool IsBaseExprStatement);
10648 void CodeCompletePreprocessorDirective(bool InConditional);
10649 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
10650 void CodeCompletePreprocessorMacroName(bool IsDefinition);
10651 void CodeCompletePreprocessorExpression();
10652 void CodeCompletePreprocessorMacroArgument(Scope *S,
10653 IdentifierInfo *Macro,
10654 MacroInfo *MacroInfo,
10655 unsigned Argument);
10656 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
10657 void CodeCompleteNaturalLanguage();
10658 void CodeCompleteAvailabilityPlatformName();
10659 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
10660 CodeCompletionTUInfo &CCTUInfo,
10661 SmallVectorImpl<CodeCompletionResult> &Results);
10662 //@}
10663
10664 //===--------------------------------------------------------------------===//
10665 // Extra semantic analysis beyond the C type system
10666
10667public:
10668 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10669 unsigned ByteNo) const;
10670
10671private:
10672 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10673 const ArraySubscriptExpr *ASE=nullptr,
10674 bool AllowOnePastEnd=true, bool IndexNegated=false);
10675 void CheckArrayAccess(const Expr *E);
10676 // Used to grab the relevant information from a FormatAttr and a
10677 // FunctionDeclaration.
10678 struct FormatStringInfo {
10679 unsigned FormatIdx;
10680 unsigned FirstDataArg;
10681 bool HasVAListArg;
10682 };
10683
10684 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
10685 FormatStringInfo *FSI);
10686 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
10687 const FunctionProtoType *Proto);
10688 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
10689 ArrayRef<const Expr *> Args);
10690 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
10691 const FunctionProtoType *Proto);
10692 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
10693 void CheckConstructorCall(FunctionDecl *FDecl,
10694 ArrayRef<const Expr *> Args,
10695 const FunctionProtoType *Proto,
10696 SourceLocation Loc);
10697
10698 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10699 const Expr *ThisArg, ArrayRef<const Expr *> Args,
10700 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10701 VariadicCallType CallType);
10702
10703 bool CheckObjCString(Expr *Arg);
10704 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10705
10706 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10707 unsigned BuiltinID, CallExpr *TheCall);
10708 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
10709
10710 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10711 unsigned MaxWidth);
10712 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10713 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10714
10715 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10716 bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10717 bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
10718 bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
10719 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10720 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10721 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10722 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10723 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10724 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10725
10726 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
10727 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
10728 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10729 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10730 bool SemaBuiltinVSX(CallExpr *TheCall);
10731 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10732
10733public:
10734 // Used by C++ template instantiation.
10735 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10736 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10737 SourceLocation BuiltinLoc,
10738 SourceLocation RParenLoc);
10739
10740private:
10741 bool SemaBuiltinPrefetch(CallExpr *TheCall);
10742 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10743 bool SemaBuiltinAssume(CallExpr *TheCall);
10744 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10745 bool SemaBuiltinLongjmp(CallExpr *TheCall);
10746 bool SemaBuiltinSetjmp(CallExpr *TheCall);
10747 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10748 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10749 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10750 AtomicExpr::AtomicOp Op);
10751 ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
10752 bool IsDelete);
10753 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10754 llvm::APSInt &Result);
10755 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
10756 int High, bool RangeIsError = true);
10757 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10758 unsigned Multiple);
10759 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10760 int ArgNum, unsigned ExpectedFieldNum,
10761 bool AllowName);
10762 bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
10763public:
10764 enum FormatStringType {
10765 FST_Scanf,
10766 FST_Printf,
10767 FST_NSString,
10768 FST_Strftime,
10769 FST_Strfmon,
10770 FST_Kprintf,
10771 FST_FreeBSDKPrintf,
10772 FST_OSTrace,
10773 FST_OSLog,
10774 FST_Unknown
10775 };
10776 static FormatStringType GetFormatStringType(const FormatAttr *Format);
10777
10778 bool FormatStringHasSArg(const StringLiteral *FExpr);
10779
10780 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10781
10782private:
10783 bool CheckFormatArguments(const FormatAttr *Format,
10784 ArrayRef<const Expr *> Args,
10785 bool IsCXXMember,
10786 VariadicCallType CallType,
10787 SourceLocation Loc, SourceRange Range,
10788 llvm::SmallBitVector &CheckedVarArgs);
10789 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10790 bool HasVAListArg, unsigned format_idx,
10791 unsigned firstDataArg, FormatStringType Type,
10792 VariadicCallType CallType,
10793 SourceLocation Loc, SourceRange range,
10794 llvm::SmallBitVector &CheckedVarArgs);
10795
10796 void CheckAbsoluteValueFunction(const CallExpr *Call,
10797 const FunctionDecl *FDecl);
10798
10799 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10800
10801 void CheckMemaccessArguments(const CallExpr *Call,
10802 unsigned BId,
10803 IdentifierInfo *FnName);
10804
10805 void CheckStrlcpycatArguments(const CallExpr *Call,
10806 IdentifierInfo *FnName);
10807
10808 void CheckStrncatArguments(const CallExpr *Call,
10809 IdentifierInfo *FnName);
10810
10811 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10812 SourceLocation ReturnLoc,
10813 bool isObjCMethod = false,
10814 const AttrVec *Attrs = nullptr,
10815 const FunctionDecl *FD = nullptr);
10816
10817public:
10818 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
10819
10820private:
10821 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10822 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10823 void CheckForIntOverflow(Expr *E);
10824 void CheckUnsequencedOperations(Expr *E);
10825
10826 /// Perform semantic checks on a completed expression. This will either
10827 /// be a full-expression or a default argument expression.
10828 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10829 bool IsConstexpr = false);
10830
10831 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10832 Expr *Init);
10833
10834 /// Check if there is a field shadowing.
10835 void CheckShadowInheritedFields(const SourceLocation &Loc,
10836 DeclarationName FieldName,
10837 const CXXRecordDecl *RD,
10838 bool DeclIsField = true);
10839
10840 /// Check if the given expression contains 'break' or 'continue'
10841 /// statement that produces control flow different from GCC.
10842 void CheckBreakContinueBinding(Expr *E);
10843
10844 /// Check whether receiver is mutable ObjC container which
10845 /// attempts to add itself into the container
10846 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10847
10848 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10849 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10850 bool DeleteWasArrayForm);
10851public:
10852 /// Register a magic integral constant to be used as a type tag.
10853 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10854 uint64_t MagicValue, QualType Type,
10855 bool LayoutCompatible, bool MustBeNull);
10856
10857 struct TypeTagData {
10858 TypeTagData() {}
10859
10860 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10861 Type(Type), LayoutCompatible(LayoutCompatible),
10862 MustBeNull(MustBeNull)
10863 {}
10864
10865 QualType Type;
10866
10867 /// If true, \c Type should be compared with other expression's types for
10868 /// layout-compatibility.
10869 unsigned LayoutCompatible : 1;
10870 unsigned MustBeNull : 1;
10871 };
10872
10873 /// A pair of ArgumentKind identifier and magic value. This uniquely
10874 /// identifies the magic value.
10875 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10876
10877private:
10878 /// A map from magic value to type information.
10879 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10880 TypeTagForDatatypeMagicValues;
10881
10882 /// Peform checks on a call of a function with argument_with_type_tag
10883 /// or pointer_with_type_tag attributes.
10884 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10885 const ArrayRef<const Expr *> ExprArgs,
10886 SourceLocation CallSiteLoc);
10887
10888 /// Check if we are taking the address of a packed field
10889 /// as this may be a problem if the pointer value is dereferenced.
10890 void CheckAddressOfPackedMember(Expr *rhs);
10891
10892 /// The parser's current scope.
10893 ///
10894 /// The parser maintains this state here.
10895 Scope *CurScope;
10896
10897 mutable IdentifierInfo *Ident_super;
10898 mutable IdentifierInfo *Ident___float128;
10899
10900 /// Nullability type specifiers.
10901 IdentifierInfo *Ident__Nonnull = nullptr;
10902 IdentifierInfo *Ident__Nullable = nullptr;
10903 IdentifierInfo *Ident__Null_unspecified = nullptr;
10904
10905 IdentifierInfo *Ident_NSError = nullptr;
10906
10907 /// The handler for the FileChanged preprocessor events.
10908 ///
10909 /// Used for diagnostics that implement custom semantic analysis for #include
10910 /// directives, like -Wpragma-pack.
10911 sema::SemaPPCallbacks *SemaPPCallbackHandler;
10912
10913protected:
10914 friend class Parser;
10915 friend class InitializationSequence;
10916 friend class ASTReader;
10917 friend class ASTDeclReader;
10918 friend class ASTWriter;
10919
10920public:
10921 /// Retrieve the keyword associated
10922 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10923
10924 /// The struct behind the CFErrorRef pointer.
10925 RecordDecl *CFError = nullptr;
10926
10927 /// Retrieve the identifier "NSError".
10928 IdentifierInfo *getNSErrorIdent();
10929
10930 /// Retrieve the parser's current scope.
10931 ///
10932 /// This routine must only be used when it is certain that semantic analysis
10933 /// and the parser are in precisely the same context, which is not the case
10934 /// when, e.g., we are performing any kind of template instantiation.
10935 /// Therefore, the only safe places to use this scope are in the parser
10936 /// itself and in routines directly invoked from the parser and *never* from
10937 /// template substitution or instantiation.
10938 Scope *getCurScope() const { return CurScope; }
10939
10940 void incrementMSManglingNumber() const {
10941 return CurScope->incrementMSManglingNumber();
10942 }
10943
10944 IdentifierInfo *getSuperIdentifier() const;
10945 IdentifierInfo *getFloat128Identifier() const;
10946
10947 Decl *getObjCDeclContext() const;
10948
10949 DeclContext *getCurLexicalContext() const {
10950 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10951 }
10952
10953 const DeclContext *getCurObjCLexicalContext() const {
10954 const DeclContext *DC = getCurLexicalContext();
10955 // A category implicitly has the attribute of the interface.
10956 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10957 DC = CatD->getClassInterface();
10958 return DC;
10959 }
10960
10961 /// To be used for checking whether the arguments being passed to
10962 /// function exceeds the number of parameters expected for it.
10963 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10964 bool PartialOverloading = false) {
10965 // We check whether we're just after a comma in code-completion.
10966 if (NumArgs > 0 && PartialOverloading)
10967 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10968 return NumArgs > NumParams;
10969 }
10970
10971 // Emitting members of dllexported classes is delayed until the class
10972 // (including field initializers) is fully parsed.
10973 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10974
10975private:
10976 class SavePendingParsedClassStateRAII {
10977 public:
10978 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
10979
10980 ~SavePendingParsedClassStateRAII() {
10981 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&((S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 10982, __PRETTY_FUNCTION__))
10982 "there shouldn't be any pending delayed exception spec checks")((S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 10982, __PRETTY_FUNCTION__))
;
10983 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&((S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 10984, __PRETTY_FUNCTION__))
10984 "there shouldn't be any pending delayed exception spec checks")((S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 10984, __PRETTY_FUNCTION__))
;
10985 assert(S.DelayedDefaultedMemberExceptionSpecs.empty() &&((S.DelayedDefaultedMemberExceptionSpecs.empty() && "there shouldn't be any pending delayed defaulted member "
"exception specs") ? static_cast<void> (0) : __assert_fail
("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 10987, __PRETTY_FUNCTION__))
10986 "there shouldn't be any pending delayed defaulted member "((S.DelayedDefaultedMemberExceptionSpecs.empty() && "there shouldn't be any pending delayed defaulted member "
"exception specs") ? static_cast<void> (0) : __assert_fail
("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 10987, __PRETTY_FUNCTION__))
10987 "exception specs")((S.DelayedDefaultedMemberExceptionSpecs.empty() && "there shouldn't be any pending delayed defaulted member "
"exception specs") ? static_cast<void> (0) : __assert_fail
("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 10987, __PRETTY_FUNCTION__))
;
10988 assert(S.DelayedDllExportClasses.empty() &&((S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 10989, __PRETTY_FUNCTION__))
10989 "there shouldn't be any pending delayed DLL export classes")((S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\""
, "/build/llvm-toolchain-snapshot-9~svn359941/tools/clang/include/clang/Sema/Sema.h"
, 10989, __PRETTY_FUNCTION__))
;
10990 swapSavedState();
10991 }
10992
10993 private:
10994 Sema &S;
10995 decltype(DelayedOverridingExceptionSpecChecks)
10996 SavedOverridingExceptionSpecChecks;
10997 decltype(DelayedEquivalentExceptionSpecChecks)
10998 SavedEquivalentExceptionSpecChecks;
10999 decltype(DelayedDefaultedMemberExceptionSpecs)
11000 SavedDefaultedMemberExceptionSpecs;
11001 decltype(DelayedDllExportClasses) SavedDllExportClasses;
11002
11003 void swapSavedState() {
11004 SavedOverridingExceptionSpecChecks.swap(
11005 S.DelayedOverridingExceptionSpecChecks);
11006 SavedEquivalentExceptionSpecChecks.swap(
11007 S.DelayedEquivalentExceptionSpecChecks);
11008 SavedDefaultedMemberExceptionSpecs.swap(
11009 S.DelayedDefaultedMemberExceptionSpecs);
11010 SavedDllExportClasses.swap(S.DelayedDllExportClasses);
11011 }
11012 };
11013
11014 /// Helper class that collects misaligned member designations and
11015 /// their location info for delayed diagnostics.
11016 struct MisalignedMember {
11017 Expr *E;
11018 RecordDecl *RD;
11019 ValueDecl *MD;
11020 CharUnits Alignment;
11021
11022 MisalignedMember() : E(), RD(), MD(), Alignment() {}
11023 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
11024 CharUnits Alignment)
11025 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
11026 explicit MisalignedMember(Expr *E)
11027 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
11028
11029 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
11030 };
11031 /// Small set of gathered accesses to potentially misaligned members
11032 /// due to the packed attribute.
11033 SmallVector<MisalignedMember, 4> MisalignedMembers;
11034
11035 /// Adds an expression to the set of gathered misaligned members.
11036 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11037 CharUnits Alignment);
11038
11039public:
11040 /// Diagnoses the current set of gathered accesses. This typically
11041 /// happens at full expression level. The set is cleared after emitting the
11042 /// diagnostics.
11043 void DiagnoseMisalignedMembers();
11044
11045 /// This function checks if the expression is in the sef of potentially
11046 /// misaligned members and it is converted to some pointer type T with lower
11047 /// or equal alignment requirements. If so it removes it. This is used when
11048 /// we do not want to diagnose such misaligned access (e.g. in conversions to
11049 /// void*).
11050 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
11051
11052 /// This function calls Action when it determines that E designates a
11053 /// misaligned member due to the packed attribute. This is used to emit
11054 /// local diagnostics like in reference binding.
11055 void RefersToMemberWithReducedAlignment(
11056 Expr *E,
11057 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
11058 Action);
11059
11060 /// Describes the reason a calling convention specification was ignored, used
11061 /// for diagnostics.
11062 enum class CallingConventionIgnoredReason {
11063 ForThisTarget = 0,
11064 VariadicFunction,
11065 ConstructorDestructor,
11066 BuiltinFunction
11067 };
11068};
11069
11070/// RAII object that enters a new expression evaluation context.
11071class EnterExpressionEvaluationContext {
11072 Sema &Actions;
11073 bool Entered = true;
11074
11075public:
11076 EnterExpressionEvaluationContext(
11077 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
11078 Decl *LambdaContextDecl = nullptr,
11079 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
11080 Sema::ExpressionEvaluationContextRecord::EK_Other,
11081 bool ShouldEnter = true)
11082 : Actions(Actions), Entered(ShouldEnter) {
11083 if (Entered)
11084 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
11085 ExprContext);
11086 }
11087 EnterExpressionEvaluationContext(
11088 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
11089 Sema::ReuseLambdaContextDecl_t,
11090 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
11091 Sema::ExpressionEvaluationContextRecord::EK_Other)
11092 : Actions(Actions) {
11093 Actions.PushExpressionEvaluationContext(
11094 NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
11095 }
11096
11097 enum InitListTag { InitList };
11098 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
11099 bool ShouldEnter = true)
11100 : Actions(Actions), Entered(false) {
11101 // In C++11 onwards, narrowing checks are performed on the contents of
11102 // braced-init-lists, even when they occur within unevaluated operands.
11103 // Therefore we still need to instantiate constexpr functions used in such
11104 // a context.
11105 if (ShouldEnter && Actions.isUnevaluatedContext() &&
11106 Actions.getLangOpts().CPlusPlus11) {
11107 Actions.PushExpressionEvaluationContext(
11108 Sema::ExpressionEvaluationContext::UnevaluatedList);
11109 Entered = true;
11110 }
11111 }
11112
11113 ~EnterExpressionEvaluationContext() {
11114 if (Entered)
11115 Actions.PopExpressionEvaluationContext();
11116 }
11117};
11118
11119DeductionFailureInfo
11120MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
11121 sema::TemplateDeductionInfo &Info);
11122
11123/// Contains a late templated function.
11124/// Will be parsed at the end of the translation unit, used by Sema & Parser.
11125struct LateParsedTemplate {
11126 CachedTokens Toks;
11127 /// The template function declaration to be late parsed.
11128 Decl *D;
11129};
11130} // end namespace clang
11131
11132namespace llvm {
11133// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
11134// SourceLocation.
11135template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
11136 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
11137 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
11138
11139 static FunctionDeclAndLoc getEmptyKey() {
11140 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
11141 }
11142
11143 static FunctionDeclAndLoc getTombstoneKey() {
11144 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
11145 }
11146
11147 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
11148 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
11149 FDL.Loc.getRawEncoding());
11150 }
11151
11152 static bool isEqual(const FunctionDeclAndLoc &LHS,
11153 const FunctionDeclAndLoc &RHS) {
11154 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
11155 }
11156};
11157} // namespace llvm
11158
11159#endif