Bug Summary

File:tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Warning:line 4854, 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 -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

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

/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/Attr.h"
18#include "clang/AST/Availability.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/LocInfoType.h"
27#include "clang/AST/MangleNumberingContext.h"
28#include "clang/AST/NSAPI.h"
29#include "clang/AST/PrettyPrinter.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/TypeOrdering.h"
33#include "clang/Basic/ExpressionTraits.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/OpenMPKinds.h"
36#include "clang/Basic/PragmaKinds.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TemplateKinds.h"
39#include "clang/Basic/TypeTraits.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/CleanupInfo.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/ExternalSemaSource.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/ObjCMethodList.h"
46#include "clang/Sema/Ownership.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/TypoCorrection.h"
49#include "clang/Sema/Weak.h"
50#include "llvm/ADT/ArrayRef.h"
51#include "llvm/ADT/Optional.h"
52#include "llvm/ADT/SetVector.h"
53#include "llvm/ADT/SmallBitVector.h"
54#include "llvm/ADT/SmallPtrSet.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include <deque>
58#include <memory>
59#include <string>
60#include <tuple>
61#include <vector>
62
63namespace llvm {
64 class APSInt;
65 template <typename ValueT> struct DenseMapInfo;
66 template <typename ValueT, typename ValueInfoT> class DenseSet;
67 class SmallBitVector;
68 struct InlineAsmIdentifierInfo;
69}
70
71namespace clang {
72 class ADLResult;
73 class ASTConsumer;
74 class ASTContext;
75 class ASTMutationListener;
76 class ASTReader;
77 class ASTWriter;
78 class ArrayType;
79 class ParsedAttr;
80 class BindingDecl;
81 class BlockDecl;
82 class CapturedDecl;
83 class CXXBasePath;
84 class CXXBasePaths;
85 class CXXBindTemporaryExpr;
86 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
87 class CXXConstructorDecl;
88 class CXXConversionDecl;
89 class CXXDeleteExpr;
90 class CXXDestructorDecl;
91 class CXXFieldCollector;
92 class CXXMemberCallExpr;
93 class CXXMethodDecl;
94 class CXXScopeSpec;
95 class CXXTemporary;
96 class CXXTryStmt;
97 class CallExpr;
98 class ClassTemplateDecl;
99 class ClassTemplatePartialSpecializationDecl;
100 class ClassTemplateSpecializationDecl;
101 class VarTemplatePartialSpecializationDecl;
102 class CodeCompleteConsumer;
103 class CodeCompletionAllocator;
104 class CodeCompletionTUInfo;
105 class CodeCompletionResult;
106 class CoroutineBodyStmt;
107 class Decl;
108 class DeclAccessPair;
109 class DeclContext;
110 class DeclRefExpr;
111 class DeclaratorDecl;
112 class DeducedTemplateArgument;
113 class DependentDiagnostic;
114 class DesignatedInitExpr;
115 class Designation;
116 class EnableIfAttr;
117 class EnumConstantDecl;
118 class Expr;
119 class ExtVectorType;
120 class FormatAttr;
121 class FriendDecl;
122 class FunctionDecl;
123 class FunctionProtoType;
124 class FunctionTemplateDecl;
125 class ImplicitConversionSequence;
126 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
127 class InitListExpr;
128 class InitializationKind;
129 class InitializationSequence;
130 class InitializedEntity;
131 class IntegerLiteral;
132 class LabelStmt;
133 class LambdaExpr;
134