Bug Summary

File:clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Warning:line 5068, 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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -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~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-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~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -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-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

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