Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiateDecl.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

/build/source/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

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