Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

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