[docs] Fix build-docs.sh
[llvm-project.git] / clang / lib / Sema / SemaTemplateInstantiateDecl.cpp
blobb0256a16babe75ac945353d3ddbd0d986b519246
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 //===----------------------------------------------------------------------===/
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/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateInstCallback.h"
31 #include "llvm/Support/TimeProfiler.h"
33 using namespace clang;
35 static bool isDeclWithinFunction(const Decl *D) {
36 const DeclContext *DC = D->getDeclContext();
37 if (DC->isFunctionOrMethod())
38 return true;
40 if (DC->isRecord())
41 return cast<CXXRecordDecl>(DC)->isLocalClass();
43 return false;
46 template<typename DeclT>
47 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
48 const MultiLevelTemplateArgumentList &TemplateArgs) {
49 if (!OldDecl->getQualifierLoc())
50 return false;
52 assert((NewDecl->getFriendObjectKind() ||
53 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
54 "non-friend with qualified name defined in dependent context");
55 Sema::ContextRAII SavedContext(
56 SemaRef,
57 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
58 ? NewDecl->getLexicalDeclContext()
59 : OldDecl->getLexicalDeclContext()));
61 NestedNameSpecifierLoc NewQualifierLoc
62 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
63 TemplateArgs);
65 if (!NewQualifierLoc)
66 return true;
68 NewDecl->setQualifierInfo(NewQualifierLoc);
69 return false;
72 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
73 DeclaratorDecl *NewDecl) {
74 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
77 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
78 TagDecl *NewDecl) {
79 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
82 // Include attribute instantiation code.
83 #include "clang/Sema/AttrTemplateInstantiate.inc"
85 static void instantiateDependentAlignedAttr(
86 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
87 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
88 if (Aligned->isAlignmentExpr()) {
89 // The alignment expression is a constant expression.
90 EnterExpressionEvaluationContext Unevaluated(
91 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
92 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
93 if (!Result.isInvalid())
94 S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
95 } else {
96 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
97 TemplateArgs, Aligned->getLocation(),
98 DeclarationName());
99 if (Result)
100 S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
104 static void instantiateDependentAlignedAttr(
105 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
106 const AlignedAttr *Aligned, Decl *New) {
107 if (!Aligned->isPackExpansion()) {
108 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
109 return;
112 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
113 if (Aligned->isAlignmentExpr())
114 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
115 Unexpanded);
116 else
117 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
118 Unexpanded);
119 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
121 // Determine whether we can expand this attribute pack yet.
122 bool Expand = true, RetainExpansion = false;
123 Optional<unsigned> NumExpansions;
124 // FIXME: Use the actual location of the ellipsis.
125 SourceLocation EllipsisLoc = Aligned->getLocation();
126 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
127 Unexpanded, TemplateArgs, Expand,
128 RetainExpansion, NumExpansions))
129 return;
131 if (!Expand) {
132 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
133 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
134 } else {
135 for (unsigned I = 0; I != *NumExpansions; ++I) {
136 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
137 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
142 static void instantiateDependentAssumeAlignedAttr(
143 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
144 const AssumeAlignedAttr *Aligned, Decl *New) {
145 // The alignment expression is a constant expression.
146 EnterExpressionEvaluationContext Unevaluated(
147 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
149 Expr *E, *OE = nullptr;
150 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
151 if (Result.isInvalid())
152 return;
153 E = Result.getAs<Expr>();
155 if (Aligned->getOffset()) {
156 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
157 if (Result.isInvalid())
158 return;
159 OE = Result.getAs<Expr>();
162 S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
165 static void instantiateDependentAlignValueAttr(
166 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
167 const AlignValueAttr *Aligned, Decl *New) {
168 // The alignment expression is a constant expression.
169 EnterExpressionEvaluationContext Unevaluated(
170 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
171 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
172 if (!Result.isInvalid())
173 S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
176 static void instantiateDependentAllocAlignAttr(
177 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
178 const AllocAlignAttr *Align, Decl *New) {
179 Expr *Param = IntegerLiteral::Create(
180 S.getASTContext(),
181 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
182 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
183 S.AddAllocAlignAttr(New, *Align, Param);
186 static void instantiateDependentAnnotationAttr(
187 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
188 const AnnotateAttr *Attr, Decl *New) {
189 EnterExpressionEvaluationContext Unevaluated(
190 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
192 // If the attribute has delayed arguments it will have to instantiate those
193 // and handle them as new arguments for the attribute.
194 bool HasDelayedArgs = Attr->delayedArgs_size();
196 ArrayRef<Expr *> ArgsToInstantiate =
197 HasDelayedArgs
198 ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
199 : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
201 SmallVector<Expr *, 4> Args;
202 if (S.SubstExprs(ArgsToInstantiate,
203 /*IsCall=*/false, TemplateArgs, Args))
204 return;
206 StringRef Str = Attr->getAnnotation();
207 if (HasDelayedArgs) {
208 if (Args.size() < 1) {
209 S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
210 << Attr << 1;
211 return;
214 if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
215 return;
217 llvm::SmallVector<Expr *, 4> ActualArgs;
218 ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
219 std::swap(Args, ActualArgs);
221 S.AddAnnotationAttr(New, *Attr, Str, Args);
224 static Expr *instantiateDependentFunctionAttrCondition(
225 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
226 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
227 Expr *Cond = nullptr;
229 Sema::ContextRAII SwitchContext(S, New);
230 EnterExpressionEvaluationContext Unevaluated(
231 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
232 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
233 if (Result.isInvalid())
234 return nullptr;
235 Cond = Result.getAs<Expr>();
237 if (!Cond->isTypeDependent()) {
238 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
239 if (Converted.isInvalid())
240 return nullptr;
241 Cond = Converted.get();
244 SmallVector<PartialDiagnosticAt, 8> Diags;
245 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
246 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
247 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
248 for (const auto &P : Diags)
249 S.Diag(P.first, P.second);
250 return nullptr;
252 return Cond;
255 static void instantiateDependentEnableIfAttr(
256 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
257 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
258 Expr *Cond = instantiateDependentFunctionAttrCondition(
259 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
261 if (Cond)
262 New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
263 Cond, EIA->getMessage()));
266 static void instantiateDependentDiagnoseIfAttr(
267 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
268 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
269 Expr *Cond = instantiateDependentFunctionAttrCondition(
270 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
272 if (Cond)
273 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
274 S.getASTContext(), *DIA, Cond, DIA->getMessage(),
275 DIA->getDiagnosticType(), DIA->getArgDependent(), New));
278 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
279 // template A as the base and arguments from TemplateArgs.
280 static void instantiateDependentCUDALaunchBoundsAttr(
281 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
282 const CUDALaunchBoundsAttr &Attr, Decl *New) {
283 // The alignment expression is a constant expression.
284 EnterExpressionEvaluationContext Unevaluated(
285 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
287 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
288 if (Result.isInvalid())
289 return;
290 Expr *MaxThreads = Result.getAs<Expr>();
292 Expr *MinBlocks = nullptr;
293 if (Attr.getMinBlocks()) {
294 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
295 if (Result.isInvalid())
296 return;
297 MinBlocks = Result.getAs<Expr>();
300 S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks);
303 static void
304 instantiateDependentModeAttr(Sema &S,
305 const MultiLevelTemplateArgumentList &TemplateArgs,
306 const ModeAttr &Attr, Decl *New) {
307 S.AddModeAttr(New, Attr, Attr.getMode(),
308 /*InInstantiation=*/true);
311 /// Instantiation of 'declare simd' attribute and its arguments.
312 static void instantiateOMPDeclareSimdDeclAttr(
313 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
314 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
315 // Allow 'this' in clauses with varlists.
316 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
317 New = FTD->getTemplatedDecl();
318 auto *FD = cast<FunctionDecl>(New);
319 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
320 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
321 SmallVector<unsigned, 4> LinModifiers;
323 auto SubstExpr = [&](Expr *E) -> ExprResult {
324 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
325 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
326 Sema::ContextRAII SavedContext(S, FD);
327 LocalInstantiationScope Local(S);
328 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
329 Local.InstantiatedLocal(
330 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
331 return S.SubstExpr(E, TemplateArgs);
333 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
334 FD->isCXXInstanceMember());
335 return S.SubstExpr(E, TemplateArgs);
338 // Substitute a single OpenMP clause, which is a potentially-evaluated
339 // full-expression.
340 auto Subst = [&](Expr *E) -> ExprResult {
341 EnterExpressionEvaluationContext Evaluated(
342 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
343 ExprResult Res = SubstExpr(E);
344 if (Res.isInvalid())
345 return Res;
346 return S.ActOnFinishFullExpr(Res.get(), false);
349 ExprResult Simdlen;
350 if (auto *E = Attr.getSimdlen())
351 Simdlen = Subst(E);
353 if (Attr.uniforms_size() > 0) {
354 for(auto *E : Attr.uniforms()) {
355 ExprResult Inst = Subst(E);
356 if (Inst.isInvalid())
357 continue;
358 Uniforms.push_back(Inst.get());
362 auto AI = Attr.alignments_begin();
363 for (auto *E : Attr.aligneds()) {
364 ExprResult Inst = Subst(E);
365 if (Inst.isInvalid())
366 continue;
367 Aligneds.push_back(Inst.get());
368 Inst = ExprEmpty();
369 if (*AI)
370 Inst = S.SubstExpr(*AI, TemplateArgs);
371 Alignments.push_back(Inst.get());
372 ++AI;
375 auto SI = Attr.steps_begin();
376 for (auto *E : Attr.linears()) {
377 ExprResult Inst = Subst(E);
378 if (Inst.isInvalid())
379 continue;
380 Linears.push_back(Inst.get());
381 Inst = ExprEmpty();
382 if (*SI)
383 Inst = S.SubstExpr(*SI, TemplateArgs);
384 Steps.push_back(Inst.get());
385 ++SI;
387 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
388 (void)S.ActOnOpenMPDeclareSimdDirective(
389 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
390 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
391 Attr.getRange());
394 /// Instantiation of 'declare variant' attribute and its arguments.
395 static void instantiateOMPDeclareVariantAttr(
396 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
397 const OMPDeclareVariantAttr &Attr, Decl *New) {
398 // Allow 'this' in clauses with varlists.
399 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
400 New = FTD->getTemplatedDecl();
401 auto *FD = cast<FunctionDecl>(New);
402 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
404 auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
405 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
406 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
407 Sema::ContextRAII SavedContext(S, FD);
408 LocalInstantiationScope Local(S);
409 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
410 Local.InstantiatedLocal(
411 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
412 return S.SubstExpr(E, TemplateArgs);
414 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
415 FD->isCXXInstanceMember());
416 return S.SubstExpr(E, TemplateArgs);
419 // Substitute a single OpenMP clause, which is a potentially-evaluated
420 // full-expression.
421 auto &&Subst = [&SubstExpr, &S](Expr *E) {
422 EnterExpressionEvaluationContext Evaluated(
423 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
424 ExprResult Res = SubstExpr(E);
425 if (Res.isInvalid())
426 return Res;
427 return S.ActOnFinishFullExpr(Res.get(), false);
430 ExprResult VariantFuncRef;
431 if (Expr *E = Attr.getVariantFuncRef()) {
432 // Do not mark function as is used to prevent its emission if this is the
433 // only place where it is used.
434 EnterExpressionEvaluationContext Unevaluated(
435 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
436 VariantFuncRef = Subst(E);
439 // Copy the template version of the OMPTraitInfo and run substitute on all
440 // score and condition expressiosn.
441 OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo();
442 TI = *Attr.getTraitInfos();
444 // Try to substitute template parameters in score and condition expressions.
445 auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
446 if (E) {
447 EnterExpressionEvaluationContext Unevaluated(
448 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
449 ExprResult ER = Subst(E);
450 if (ER.isUsable())
451 E = ER.get();
452 else
453 return true;
455 return false;
457 if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
458 return;
460 Expr *E = VariantFuncRef.get();
462 // Check function/variant ref for `omp declare variant` but not for `omp
463 // begin declare variant` (which use implicit attributes).
464 Optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
465 S.checkOpenMPDeclareVariantFunction(S.ConvertDeclToDeclGroup(New), E, TI,
466 Attr.appendArgs_size(),
467 Attr.getRange());
469 if (!DeclVarData)
470 return;
472 E = DeclVarData.value().second;
473 FD = DeclVarData.value().first;
475 if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
476 if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
477 if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
478 if (!VariantFTD->isThisDeclarationADefinition())
479 return;
480 Sema::TentativeAnalysisScope Trap(S);
481 const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy(
482 S.Context, TemplateArgs.getInnermost());
484 auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
485 New->getLocation());
486 if (!SubstFD)
487 return;
488 QualType NewType = S.Context.mergeFunctionTypes(
489 SubstFD->getType(), FD->getType(),
490 /* OfBlockPointer */ false,
491 /* Unqualified */ false, /* AllowCXX */ true);
492 if (NewType.isNull())
493 return;
494 S.InstantiateFunctionDefinition(
495 New->getLocation(), SubstFD, /* Recursive */ true,
496 /* DefinitionRequired */ false, /* AtEndOfTU */ false);
497 SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
498 E = DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(),
499 SourceLocation(), SubstFD,
500 /* RefersToEnclosingVariableOrCapture */ false,
501 /* NameLoc */ SubstFD->getLocation(),
502 SubstFD->getType(), ExprValueKind::VK_PRValue);
507 SmallVector<Expr *, 8> NothingExprs;
508 SmallVector<Expr *, 8> NeedDevicePtrExprs;
509 SmallVector<OMPInteropInfo, 4> AppendArgs;
511 for (Expr *E : Attr.adjustArgsNothing()) {
512 ExprResult ER = Subst(E);
513 if (ER.isInvalid())
514 continue;
515 NothingExprs.push_back(ER.get());
517 for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
518 ExprResult ER = Subst(E);
519 if (ER.isInvalid())
520 continue;
521 NeedDevicePtrExprs.push_back(ER.get());
523 for (OMPInteropInfo &II : Attr.appendArgs()) {
524 // When prefer_type is implemented for append_args handle them here too.
525 AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
528 S.ActOnOpenMPDeclareVariantDirective(
529 FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
530 SourceLocation(), Attr.getRange());
533 static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
534 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
535 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
536 // Both min and max expression are constant expressions.
537 EnterExpressionEvaluationContext Unevaluated(
538 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
540 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
541 if (Result.isInvalid())
542 return;
543 Expr *MinExpr = Result.getAs<Expr>();
545 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
546 if (Result.isInvalid())
547 return;
548 Expr *MaxExpr = Result.getAs<Expr>();
550 S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
553 static ExplicitSpecifier
554 instantiateExplicitSpecifier(Sema &S,
555 const MultiLevelTemplateArgumentList &TemplateArgs,
556 ExplicitSpecifier ES, FunctionDecl *New) {
557 if (!ES.getExpr())
558 return ES;
559 Expr *OldCond = ES.getExpr();
560 Expr *Cond = nullptr;
562 EnterExpressionEvaluationContext Unevaluated(
563 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
564 ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
565 if (SubstResult.isInvalid()) {
566 return ExplicitSpecifier::Invalid();
568 Cond = SubstResult.get();
570 ExplicitSpecifier Result(Cond, ES.getKind());
571 if (!Cond->isTypeDependent())
572 S.tryResolveExplicitSpecifier(Result);
573 return Result;
576 static void instantiateDependentAMDGPUWavesPerEUAttr(
577 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
578 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
579 // Both min and max expression are constant expressions.
580 EnterExpressionEvaluationContext Unevaluated(
581 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
583 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
584 if (Result.isInvalid())
585 return;
586 Expr *MinExpr = Result.getAs<Expr>();
588 Expr *MaxExpr = nullptr;
589 if (auto Max = Attr.getMax()) {
590 Result = S.SubstExpr(Max, TemplateArgs);
591 if (Result.isInvalid())
592 return;
593 MaxExpr = Result.getAs<Expr>();
596 S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
599 // This doesn't take any template parameters, but we have a custom action that
600 // needs to happen when the kernel itself is instantiated. We need to run the
601 // ItaniumMangler to mark the names required to name this kernel.
602 static void instantiateDependentSYCLKernelAttr(
603 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
604 const SYCLKernelAttr &Attr, Decl *New) {
605 New->addAttr(Attr.clone(S.getASTContext()));
608 /// Determine whether the attribute A might be relevant to the declaration D.
609 /// If not, we can skip instantiating it. The attribute may or may not have
610 /// been instantiated yet.
611 static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
612 // 'preferred_name' is only relevant to the matching specialization of the
613 // template.
614 if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
615 QualType T = PNA->getTypedefType();
616 const auto *RD = cast<CXXRecordDecl>(D);
617 if (!T->isDependentType() && !RD->isDependentContext() &&
618 !declaresSameEntity(T->getAsCXXRecordDecl(), RD))
619 return false;
620 for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
621 if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
622 PNA->getTypedefType()))
623 return false;
624 return true;
627 if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
628 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
629 switch (BA->getID()) {
630 case Builtin::BIforward:
631 // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
632 // type and returns an lvalue reference type. The library implementation
633 // will produce an error in this case; don't get in its way.
634 if (FD && FD->getNumParams() >= 1 &&
635 FD->getParamDecl(0)->getType()->isRValueReferenceType() &&
636 FD->getReturnType()->isLValueReferenceType()) {
637 return false;
639 [[fallthrough]];
640 case Builtin::BImove:
641 case Builtin::BImove_if_noexcept:
642 // HACK: Super-old versions of libc++ (3.1 and earlier) provide
643 // std::forward and std::move overloads that sometimes return by value
644 // instead of by reference when building in C++98 mode. Don't treat such
645 // cases as builtins.
646 if (FD && !FD->getReturnType()->isReferenceType())
647 return false;
648 break;
652 return true;
655 void Sema::InstantiateAttrsForDecl(
656 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
657 Decl *New, LateInstantiatedAttrVec *LateAttrs,
658 LocalInstantiationScope *OuterMostScope) {
659 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
660 // FIXME: This function is called multiple times for the same template
661 // specialization. We should only instantiate attributes that were added
662 // since the previous instantiation.
663 for (const auto *TmplAttr : Tmpl->attrs()) {
664 if (!isRelevantAttr(*this, New, TmplAttr))
665 continue;
667 // FIXME: If any of the special case versions from InstantiateAttrs become
668 // applicable to template declaration, we'll need to add them here.
669 CXXThisScopeRAII ThisScope(
670 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
671 Qualifiers(), ND->isCXXInstanceMember());
673 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
674 TmplAttr, Context, *this, TemplateArgs);
675 if (NewAttr && isRelevantAttr(*this, New, NewAttr))
676 New->addAttr(NewAttr);
681 static Sema::RetainOwnershipKind
682 attrToRetainOwnershipKind(const Attr *A) {
683 switch (A->getKind()) {
684 case clang::attr::CFConsumed:
685 return Sema::RetainOwnershipKind::CF;
686 case clang::attr::OSConsumed:
687 return Sema::RetainOwnershipKind::OS;
688 case clang::attr::NSConsumed:
689 return Sema::RetainOwnershipKind::NS;
690 default:
691 llvm_unreachable("Wrong argument supplied");
695 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
696 const Decl *Tmpl, Decl *New,
697 LateInstantiatedAttrVec *LateAttrs,
698 LocalInstantiationScope *OuterMostScope) {
699 for (const auto *TmplAttr : Tmpl->attrs()) {
700 if (!isRelevantAttr(*this, New, TmplAttr))
701 continue;
703 // FIXME: This should be generalized to more than just the AlignedAttr.
704 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
705 if (Aligned && Aligned->isAlignmentDependent()) {
706 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
707 continue;
710 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
711 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
712 continue;
715 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
716 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
717 continue;
720 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
721 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
722 continue;
725 if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
726 instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
727 continue;
730 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
731 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
732 cast<FunctionDecl>(New));
733 continue;
736 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
737 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
738 cast<FunctionDecl>(New));
739 continue;
742 if (const auto *CUDALaunchBounds =
743 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
744 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
745 *CUDALaunchBounds, New);
746 continue;
749 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
750 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
751 continue;
754 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
755 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
756 continue;
759 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
760 instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
761 continue;
764 if (const auto *AMDGPUFlatWorkGroupSize =
765 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
766 instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
767 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
770 if (const auto *AMDGPUFlatWorkGroupSize =
771 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
772 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
773 *AMDGPUFlatWorkGroupSize, New);
776 // Existing DLL attribute on the instantiation takes precedence.
777 if (TmplAttr->getKind() == attr::DLLExport ||
778 TmplAttr->getKind() == attr::DLLImport) {
779 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
780 continue;
784 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
785 AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
786 continue;
789 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
790 isa<CFConsumedAttr>(TmplAttr)) {
791 AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr),
792 /*template instantiation=*/true);
793 continue;
796 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
797 if (!New->hasAttr<PointerAttr>())
798 New->addAttr(A->clone(Context));
799 continue;
802 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
803 if (!New->hasAttr<OwnerAttr>())
804 New->addAttr(A->clone(Context));
805 continue;
808 if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
809 instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
810 continue;
813 assert(!TmplAttr->isPackExpansion());
814 if (TmplAttr->isLateParsed() && LateAttrs) {
815 // Late parsed attributes must be instantiated and attached after the
816 // enclosing class has been instantiated. See Sema::InstantiateClass.
817 LocalInstantiationScope *Saved = nullptr;
818 if (CurrentInstantiationScope)
819 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
820 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
821 } else {
822 // Allow 'this' within late-parsed attributes.
823 auto *ND = cast<NamedDecl>(New);
824 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
825 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
826 ND->isCXXInstanceMember());
828 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
829 *this, TemplateArgs);
830 if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
831 New->addAttr(NewAttr);
836 /// In the MS ABI, we need to instantiate default arguments of dllexported
837 /// default constructors along with the constructor definition. This allows IR
838 /// gen to emit a constructor closure which calls the default constructor with
839 /// its default arguments.
840 void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor) {
841 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
842 Ctor->isDefaultConstructor());
843 unsigned NumParams = Ctor->getNumParams();
844 if (NumParams == 0)
845 return;
846 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
847 if (!Attr)
848 return;
849 for (unsigned I = 0; I != NumParams; ++I) {
850 (void)CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
851 Ctor->getParamDecl(I));
852 CleanupVarDeclMarking();
856 /// Get the previous declaration of a declaration for the purposes of template
857 /// instantiation. If this finds a previous declaration, then the previous
858 /// declaration of the instantiation of D should be an instantiation of the
859 /// result of this function.
860 template<typename DeclT>
861 static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
862 DeclT *Result = D->getPreviousDecl();
864 // If the declaration is within a class, and the previous declaration was
865 // merged from a different definition of that class, then we don't have a
866 // previous declaration for the purpose of template instantiation.
867 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
868 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
869 return nullptr;
871 return Result;
874 Decl *
875 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
876 llvm_unreachable("Translation units cannot be instantiated");
879 Decl *
880 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
881 llvm_unreachable("pragma comment cannot be instantiated");
884 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
885 PragmaDetectMismatchDecl *D) {
886 llvm_unreachable("pragma comment cannot be instantiated");
889 Decl *
890 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
891 llvm_unreachable("extern \"C\" context cannot be instantiated");
894 Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
895 llvm_unreachable("GUID declaration cannot be instantiated");
898 Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
899 UnnamedGlobalConstantDecl *D) {
900 llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
903 Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
904 TemplateParamObjectDecl *D) {
905 llvm_unreachable("template parameter objects cannot be instantiated");
908 Decl *
909 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
910 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
911 D->getIdentifier());
912 Owner->addDecl(Inst);
913 return Inst;
916 Decl *
917 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
918 llvm_unreachable("Namespaces cannot be instantiated");
921 Decl *
922 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
923 NamespaceAliasDecl *Inst
924 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
925 D->getNamespaceLoc(),
926 D->getAliasLoc(),
927 D->getIdentifier(),
928 D->getQualifierLoc(),
929 D->getTargetNameLoc(),
930 D->getNamespace());
931 Owner->addDecl(Inst);
932 return Inst;
935 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
936 bool IsTypeAlias) {
937 bool Invalid = false;
938 TypeSourceInfo *DI = D->getTypeSourceInfo();
939 if (DI->getType()->isInstantiationDependentType() ||
940 DI->getType()->isVariablyModifiedType()) {
941 DI = SemaRef.SubstType(DI, TemplateArgs,
942 D->getLocation(), D->getDeclName());
943 if (!DI) {
944 Invalid = true;
945 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
947 } else {
948 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
951 // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
952 // libstdc++ relies upon this bug in its implementation of common_type. If we
953 // happen to be processing that implementation, fake up the g++ ?:
954 // semantics. See LWG issue 2141 for more information on the bug. The bugs
955 // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
956 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
957 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
958 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
959 DT->isReferenceType() &&
960 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
961 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
962 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
963 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
964 // Fold it to the (non-reference) type which g++ would have produced.
965 DI = SemaRef.Context.getTrivialTypeSourceInfo(
966 DI->getType().getNonReferenceType());
968 // Create the new typedef
969 TypedefNameDecl *Typedef;
970 if (IsTypeAlias)
971 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
972 D->getLocation(), D->getIdentifier(), DI);
973 else
974 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
975 D->getLocation(), D->getIdentifier(), DI);
976 if (Invalid)
977 Typedef->setInvalidDecl();
979 // If the old typedef was the name for linkage purposes of an anonymous
980 // tag decl, re-establish that relationship for the new typedef.
981 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
982 TagDecl *oldTag = oldTagType->getDecl();
983 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
984 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
985 assert(!newTag->hasNameForLinkage());
986 newTag->setTypedefNameForAnonDecl(Typedef);
990 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
991 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
992 TemplateArgs);
993 if (!InstPrev)
994 return nullptr;
996 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
998 // If the typedef types are not identical, reject them.
999 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1001 Typedef->setPreviousDecl(InstPrevTypedef);
1004 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1006 if (D->getUnderlyingType()->getAs<DependentNameType>())
1007 SemaRef.inferGslPointerAttribute(Typedef);
1009 Typedef->setAccess(D->getAccess());
1010 Typedef->setReferenced(D->isReferenced());
1012 return Typedef;
1015 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1016 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1017 if (Typedef)
1018 Owner->addDecl(Typedef);
1019 return Typedef;
1022 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1023 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1024 if (Typedef)
1025 Owner->addDecl(Typedef);
1026 return Typedef;
1029 Decl *
1030 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1031 // Create a local instantiation scope for this type alias template, which
1032 // will contain the instantiations of the template parameters.
1033 LocalInstantiationScope Scope(SemaRef);
1035 TemplateParameterList *TempParams = D->getTemplateParameters();
1036 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1037 if (!InstParams)
1038 return nullptr;
1040 TypeAliasDecl *Pattern = D->getTemplatedDecl();
1042 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1043 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
1044 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1045 if (!Found.empty()) {
1046 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1050 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1051 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1052 if (!AliasInst)
1053 return nullptr;
1055 TypeAliasTemplateDecl *Inst
1056 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1057 D->getDeclName(), InstParams, AliasInst);
1058 AliasInst->setDescribedAliasTemplate(Inst);
1059 if (PrevAliasTemplate)
1060 Inst->setPreviousDecl(PrevAliasTemplate);
1062 Inst->setAccess(D->getAccess());
1064 if (!PrevAliasTemplate)
1065 Inst->setInstantiatedFromMemberTemplate(D);
1067 Owner->addDecl(Inst);
1069 return Inst;
1072 Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1073 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1074 D->getIdentifier());
1075 NewBD->setReferenced(D->isReferenced());
1076 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
1077 return NewBD;
1080 Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1081 // Transform the bindings first.
1082 SmallVector<BindingDecl*, 16> NewBindings;
1083 for (auto *OldBD : D->bindings())
1084 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1085 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1087 auto *NewDD = cast_or_null<DecompositionDecl>(
1088 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1090 if (!NewDD || NewDD->isInvalidDecl())
1091 for (auto *NewBD : NewBindings)
1092 NewBD->setInvalidDecl();
1094 return NewDD;
1097 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
1098 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1101 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
1102 bool InstantiatingVarTemplate,
1103 ArrayRef<BindingDecl*> *Bindings) {
1105 // Do substitution on the type of the declaration
1106 TypeSourceInfo *DI = SemaRef.SubstType(
1107 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1108 D->getDeclName(), /*AllowDeducedTST*/true);
1109 if (!DI)
1110 return nullptr;
1112 if (DI->getType()->isFunctionType()) {
1113 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1114 << D->isStaticDataMember() << DI->getType();
1115 return nullptr;
1118 DeclContext *DC = Owner;
1119 if (D->isLocalExternDecl())
1120 SemaRef.adjustContextForLocalExternDecl(DC);
1122 // Build the instantiated declaration.
1123 VarDecl *Var;
1124 if (Bindings)
1125 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1126 D->getLocation(), DI->getType(), DI,
1127 D->getStorageClass(), *Bindings);
1128 else
1129 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1130 D->getLocation(), D->getIdentifier(), DI->getType(),
1131 DI, D->getStorageClass());
1133 // In ARC, infer 'retaining' for variables of retainable type.
1134 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1135 SemaRef.inferObjCARCLifetime(Var))
1136 Var->setInvalidDecl();
1138 if (SemaRef.getLangOpts().OpenCL)
1139 SemaRef.deduceOpenCLAddressSpace(Var);
1141 // Substitute the nested name specifier, if any.
1142 if (SubstQualifier(D, Var))
1143 return nullptr;
1145 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1146 StartingScope, InstantiatingVarTemplate);
1147 if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1148 QualType RT;
1149 if (auto *F = dyn_cast<FunctionDecl>(DC))
1150 RT = F->getReturnType();
1151 else if (isa<BlockDecl>(DC))
1152 RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1153 ->getReturnType();
1154 else
1155 llvm_unreachable("Unknown context type");
1157 // This is the last chance we have of checking copy elision eligibility
1158 // for functions in dependent contexts. The sema actions for building
1159 // the return statement during template instantiation will have no effect
1160 // regarding copy elision, since NRVO propagation runs on the scope exit
1161 // actions, and these are not run on instantiation.
1162 // This might run through some VarDecls which were returned from non-taken
1163 // 'if constexpr' branches, and these will end up being constructed on the
1164 // return slot even if they will never be returned, as a sort of accidental
1165 // 'optimization'. Notably, functions with 'auto' return types won't have it
1166 // deduced by this point. Coupled with the limitation described
1167 // previously, this makes it very hard to support copy elision for these.
1168 Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1169 bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1170 Var->setNRVOVariable(NRVO);
1173 Var->setImplicit(D->isImplicit());
1175 if (Var->isStaticLocal())
1176 SemaRef.CheckStaticLocalForDllExport(Var);
1178 return Var;
1181 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1182 AccessSpecDecl* AD
1183 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1184 D->getAccessSpecifierLoc(), D->getColonLoc());
1185 Owner->addHiddenDecl(AD);
1186 return AD;
1189 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1190 bool Invalid = false;
1191 TypeSourceInfo *DI = D->getTypeSourceInfo();
1192 if (DI->getType()->isInstantiationDependentType() ||
1193 DI->getType()->isVariablyModifiedType()) {
1194 DI = SemaRef.SubstType(DI, TemplateArgs,
1195 D->getLocation(), D->getDeclName());
1196 if (!DI) {
1197 DI = D->getTypeSourceInfo();
1198 Invalid = true;
1199 } else if (DI->getType()->isFunctionType()) {
1200 // C++ [temp.arg.type]p3:
1201 // If a declaration acquires a function type through a type
1202 // dependent on a template-parameter and this causes a
1203 // declaration that does not use the syntactic form of a
1204 // function declarator to have function type, the program is
1205 // ill-formed.
1206 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1207 << DI->getType();
1208 Invalid = true;
1210 } else {
1211 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1214 Expr *BitWidth = D->getBitWidth();
1215 if (Invalid)
1216 BitWidth = nullptr;
1217 else if (BitWidth) {
1218 // The bit-width expression is a constant expression.
1219 EnterExpressionEvaluationContext Unevaluated(
1220 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1222 ExprResult InstantiatedBitWidth
1223 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1224 if (InstantiatedBitWidth.isInvalid()) {
1225 Invalid = true;
1226 BitWidth = nullptr;
1227 } else
1228 BitWidth = InstantiatedBitWidth.getAs<Expr>();
1231 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1232 DI->getType(), DI,
1233 cast<RecordDecl>(Owner),
1234 D->getLocation(),
1235 D->isMutable(),
1236 BitWidth,
1237 D->getInClassInitStyle(),
1238 D->getInnerLocStart(),
1239 D->getAccess(),
1240 nullptr);
1241 if (!Field) {
1242 cast<Decl>(Owner)->setInvalidDecl();
1243 return nullptr;
1246 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1248 if (Field->hasAttrs())
1249 SemaRef.CheckAlignasUnderalignment(Field);
1251 if (Invalid)
1252 Field->setInvalidDecl();
1254 if (!Field->getDeclName()) {
1255 // Keep track of where this decl came from.
1256 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1258 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1259 if (Parent->isAnonymousStructOrUnion() &&
1260 Parent->getRedeclContext()->isFunctionOrMethod())
1261 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1264 Field->setImplicit(D->isImplicit());
1265 Field->setAccess(D->getAccess());
1266 Owner->addDecl(Field);
1268 return Field;
1271 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1272 bool Invalid = false;
1273 TypeSourceInfo *DI = D->getTypeSourceInfo();
1275 if (DI->getType()->isVariablyModifiedType()) {
1276 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1277 << D;
1278 Invalid = true;
1279 } else if (DI->getType()->isInstantiationDependentType()) {
1280 DI = SemaRef.SubstType(DI, TemplateArgs,
1281 D->getLocation(), D->getDeclName());
1282 if (!DI) {
1283 DI = D->getTypeSourceInfo();
1284 Invalid = true;
1285 } else if (DI->getType()->isFunctionType()) {
1286 // C++ [temp.arg.type]p3:
1287 // If a declaration acquires a function type through a type
1288 // dependent on a template-parameter and this causes a
1289 // declaration that does not use the syntactic form of a
1290 // function declarator to have function type, the program is
1291 // ill-formed.
1292 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1293 << DI->getType();
1294 Invalid = true;
1296 } else {
1297 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1300 MSPropertyDecl *Property = MSPropertyDecl::Create(
1301 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1302 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1304 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1305 StartingScope);
1307 if (Invalid)
1308 Property->setInvalidDecl();
1310 Property->setAccess(D->getAccess());
1311 Owner->addDecl(Property);
1313 return Property;
1316 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1317 NamedDecl **NamedChain =
1318 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1320 int i = 0;
1321 for (auto *PI : D->chain()) {
1322 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1323 TemplateArgs);
1324 if (!Next)
1325 return nullptr;
1327 NamedChain[i++] = Next;
1330 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1331 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1332 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1333 {NamedChain, D->getChainingSize()});
1335 for (const auto *Attr : D->attrs())
1336 IndirectField->addAttr(Attr->clone(SemaRef.Context));
1338 IndirectField->setImplicit(D->isImplicit());
1339 IndirectField->setAccess(D->getAccess());
1340 Owner->addDecl(IndirectField);
1341 return IndirectField;
1344 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1345 // Handle friend type expressions by simply substituting template
1346 // parameters into the pattern type and checking the result.
1347 if (TypeSourceInfo *Ty = D->getFriendType()) {
1348 TypeSourceInfo *InstTy;
1349 // If this is an unsupported friend, don't bother substituting template
1350 // arguments into it. The actual type referred to won't be used by any
1351 // parts of Clang, and may not be valid for instantiating. Just use the
1352 // same info for the instantiated friend.
1353 if (D->isUnsupportedFriend()) {
1354 InstTy = Ty;
1355 } else {
1356 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1357 D->getLocation(), DeclarationName());
1359 if (!InstTy)
1360 return nullptr;
1362 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
1363 D->getFriendLoc(), InstTy);
1364 if (!FD)
1365 return nullptr;
1367 FD->setAccess(AS_public);
1368 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1369 Owner->addDecl(FD);
1370 return FD;
1373 NamedDecl *ND = D->getFriendDecl();
1374 assert(ND && "friend decl must be a decl or a type!");
1376 // All of the Visit implementations for the various potential friend
1377 // declarations have to be carefully written to work for friend
1378 // objects, with the most important detail being that the target
1379 // decl should almost certainly not be placed in Owner.
1380 Decl *NewND = Visit(ND);
1381 if (!NewND) return nullptr;
1383 FriendDecl *FD =
1384 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1385 cast<NamedDecl>(NewND), D->getFriendLoc());
1386 FD->setAccess(AS_public);
1387 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1388 Owner->addDecl(FD);
1389 return FD;
1392 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1393 Expr *AssertExpr = D->getAssertExpr();
1395 // The expression in a static assertion is a constant expression.
1396 EnterExpressionEvaluationContext Unevaluated(
1397 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1399 ExprResult InstantiatedAssertExpr
1400 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1401 if (InstantiatedAssertExpr.isInvalid())
1402 return nullptr;
1404 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
1405 InstantiatedAssertExpr.get(),
1406 D->getMessage(),
1407 D->getRParenLoc(),
1408 D->isFailed());
1411 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1412 EnumDecl *PrevDecl = nullptr;
1413 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1414 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1415 PatternPrev,
1416 TemplateArgs);
1417 if (!Prev) return nullptr;
1418 PrevDecl = cast<EnumDecl>(Prev);
1421 EnumDecl *Enum =
1422 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1423 D->getLocation(), D->getIdentifier(), PrevDecl,
1424 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1425 if (D->isFixed()) {
1426 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1427 // If we have type source information for the underlying type, it means it
1428 // has been explicitly set by the user. Perform substitution on it before
1429 // moving on.
1430 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1431 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1432 DeclarationName());
1433 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1434 Enum->setIntegerType(SemaRef.Context.IntTy);
1435 else
1436 Enum->setIntegerTypeSourceInfo(NewTI);
1437 } else {
1438 assert(!D->getIntegerType()->isDependentType()
1439 && "Dependent type without type source info");
1440 Enum->setIntegerType(D->getIntegerType());
1444 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1446 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1447 Enum->setAccess(D->getAccess());
1448 // Forward the mangling number from the template to the instantiated decl.
1449 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1450 // See if the old tag was defined along with a declarator.
1451 // If it did, mark the new tag as being associated with that declarator.
1452 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1453 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1454 // See if the old tag was defined along with a typedef.
1455 // If it did, mark the new tag as being associated with that typedef.
1456 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1457 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1458 if (SubstQualifier(D, Enum)) return nullptr;
1459 Owner->addDecl(Enum);
1461 EnumDecl *Def = D->getDefinition();
1462 if (Def && Def != D) {
1463 // If this is an out-of-line definition of an enum member template, check
1464 // that the underlying types match in the instantiation of both
1465 // declarations.
1466 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1467 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1468 QualType DefnUnderlying =
1469 SemaRef.SubstType(TI->getType(), TemplateArgs,
1470 UnderlyingLoc, DeclarationName());
1471 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1472 DefnUnderlying, /*IsFixed=*/true, Enum);
1476 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1477 // specialization causes the implicit instantiation of the declarations, but
1478 // not the definitions of scoped member enumerations.
1480 // DR1484 clarifies that enumeration definitions inside of a template
1481 // declaration aren't considered entities that can be separately instantiated
1482 // from the rest of the entity they are declared inside of.
1483 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1484 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1485 InstantiateEnumDefinition(Enum, Def);
1488 return Enum;
1491 void TemplateDeclInstantiator::InstantiateEnumDefinition(
1492 EnumDecl *Enum, EnumDecl *Pattern) {
1493 Enum->startDefinition();
1495 // Update the location to refer to the definition.
1496 Enum->setLocation(Pattern->getLocation());
1498 SmallVector<Decl*, 4> Enumerators;
1500 EnumConstantDecl *LastEnumConst = nullptr;
1501 for (auto *EC : Pattern->enumerators()) {
1502 // The specified value for the enumerator.
1503 ExprResult Value((Expr *)nullptr);
1504 if (Expr *UninstValue = EC->getInitExpr()) {
1505 // The enumerator's value expression is a constant expression.
1506 EnterExpressionEvaluationContext Unevaluated(
1507 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1509 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1512 // Drop the initial value and continue.
1513 bool isInvalid = false;
1514 if (Value.isInvalid()) {
1515 Value = nullptr;
1516 isInvalid = true;
1519 EnumConstantDecl *EnumConst
1520 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1521 EC->getLocation(), EC->getIdentifier(),
1522 Value.get());
1524 if (isInvalid) {
1525 if (EnumConst)
1526 EnumConst->setInvalidDecl();
1527 Enum->setInvalidDecl();
1530 if (EnumConst) {
1531 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1533 EnumConst->setAccess(Enum->getAccess());
1534 Enum->addDecl(EnumConst);
1535 Enumerators.push_back(EnumConst);
1536 LastEnumConst = EnumConst;
1538 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1539 !Enum->isScoped()) {
1540 // If the enumeration is within a function or method, record the enum
1541 // constant as a local.
1542 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1547 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1548 Enumerators, nullptr, ParsedAttributesView());
1551 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1552 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1555 Decl *
1556 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1557 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1560 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1561 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1563 // Create a local instantiation scope for this class template, which
1564 // will contain the instantiations of the template parameters.
1565 LocalInstantiationScope Scope(SemaRef);
1566 TemplateParameterList *TempParams = D->getTemplateParameters();
1567 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1568 if (!InstParams)
1569 return nullptr;
1571 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1573 // Instantiate the qualifier. We have to do this first in case
1574 // we're a friend declaration, because if we are then we need to put
1575 // the new declaration in the appropriate context.
1576 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1577 if (QualifierLoc) {
1578 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1579 TemplateArgs);
1580 if (!QualifierLoc)
1581 return nullptr;
1584 CXXRecordDecl *PrevDecl = nullptr;
1585 ClassTemplateDecl *PrevClassTemplate = nullptr;
1587 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1588 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1589 if (!Found.empty()) {
1590 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1591 if (PrevClassTemplate)
1592 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1596 // If this isn't a friend, then it's a member template, in which
1597 // case we just want to build the instantiation in the
1598 // specialization. If it is a friend, we want to build it in
1599 // the appropriate context.
1600 DeclContext *DC = Owner;
1601 if (isFriend) {
1602 if (QualifierLoc) {
1603 CXXScopeSpec SS;
1604 SS.Adopt(QualifierLoc);
1605 DC = SemaRef.computeDeclContext(SS);
1606 if (!DC) return nullptr;
1607 } else {
1608 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1609 Pattern->getDeclContext(),
1610 TemplateArgs);
1613 // Look for a previous declaration of the template in the owning
1614 // context.
1615 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1616 Sema::LookupOrdinaryName,
1617 SemaRef.forRedeclarationInCurContext());
1618 SemaRef.LookupQualifiedName(R, DC);
1620 if (R.isSingleResult()) {
1621 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1622 if (PrevClassTemplate)
1623 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1626 if (!PrevClassTemplate && QualifierLoc) {
1627 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1628 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1629 << QualifierLoc.getSourceRange();
1630 return nullptr;
1633 if (PrevClassTemplate) {
1634 TemplateParameterList *PrevParams
1635 = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters();
1637 // Make sure the parameter lists match.
1638 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, true,
1639 Sema::TPL_TemplateMatch))
1640 return nullptr;
1642 // Do some additional validation, then merge default arguments
1643 // from the existing declarations.
1644 if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1645 Sema::TPC_ClassTemplate))
1646 return nullptr;
1650 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1651 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1652 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1653 /*DelayTypeCreation=*/true);
1655 if (QualifierLoc)
1656 RecordInst->setQualifierInfo(QualifierLoc);
1658 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1659 StartingScope);
1661 ClassTemplateDecl *Inst
1662 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1663 D->getIdentifier(), InstParams, RecordInst);
1664 assert(!(isFriend && Owner->isDependentContext()));
1665 Inst->setPreviousDecl(PrevClassTemplate);
1667 RecordInst->setDescribedClassTemplate(Inst);
1669 if (isFriend) {
1670 if (PrevClassTemplate)
1671 Inst->setAccess(PrevClassTemplate->getAccess());
1672 else
1673 Inst->setAccess(D->getAccess());
1675 Inst->setObjectOfFriendDecl();
1676 // TODO: do we want to track the instantiation progeny of this
1677 // friend target decl?
1678 } else {
1679 Inst->setAccess(D->getAccess());
1680 if (!PrevClassTemplate)
1681 Inst->setInstantiatedFromMemberTemplate(D);
1684 // Trigger creation of the type for the instantiation.
1685 SemaRef.Context.getInjectedClassNameType(RecordInst,
1686 Inst->getInjectedClassNameSpecialization());
1688 // Finish handling of friends.
1689 if (isFriend) {
1690 DC->makeDeclVisibleInContext(Inst);
1691 Inst->setLexicalDeclContext(Owner);
1692 RecordInst->setLexicalDeclContext(Owner);
1693 return Inst;
1696 if (D->isOutOfLine()) {
1697 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1698 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1701 Owner->addDecl(Inst);
1703 if (!PrevClassTemplate) {
1704 // Queue up any out-of-line partial specializations of this member
1705 // class template; the client will force their instantiation once
1706 // the enclosing class has been instantiated.
1707 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1708 D->getPartialSpecializations(PartialSpecs);
1709 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1710 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1711 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1714 return Inst;
1717 Decl *
1718 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1719 ClassTemplatePartialSpecializationDecl *D) {
1720 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1722 // Lookup the already-instantiated declaration in the instantiation
1723 // of the class template and return that.
1724 DeclContext::lookup_result Found
1725 = Owner->lookup(ClassTemplate->getDeclName());
1726 if (Found.empty())
1727 return nullptr;
1729 ClassTemplateDecl *InstClassTemplate
1730 = dyn_cast<ClassTemplateDecl>(Found.front());
1731 if (!InstClassTemplate)
1732 return nullptr;
1734 if (ClassTemplatePartialSpecializationDecl *Result
1735 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1736 return Result;
1738 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1741 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1742 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1743 "Only static data member templates are allowed.");
1745 // Create a local instantiation scope for this variable template, which
1746 // will contain the instantiations of the template parameters.
1747 LocalInstantiationScope Scope(SemaRef);
1748 TemplateParameterList *TempParams = D->getTemplateParameters();
1749 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1750 if (!InstParams)
1751 return nullptr;
1753 VarDecl *Pattern = D->getTemplatedDecl();
1754 VarTemplateDecl *PrevVarTemplate = nullptr;
1756 if (getPreviousDeclForInstantiation(Pattern)) {
1757 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1758 if (!Found.empty())
1759 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1762 VarDecl *VarInst =
1763 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1764 /*InstantiatingVarTemplate=*/true));
1765 if (!VarInst) return nullptr;
1767 DeclContext *DC = Owner;
1769 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1770 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1771 VarInst);
1772 VarInst->setDescribedVarTemplate(Inst);
1773 Inst->setPreviousDecl(PrevVarTemplate);
1775 Inst->setAccess(D->getAccess());
1776 if (!PrevVarTemplate)
1777 Inst->setInstantiatedFromMemberTemplate(D);
1779 if (D->isOutOfLine()) {
1780 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1781 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1784 Owner->addDecl(Inst);
1786 if (!PrevVarTemplate) {
1787 // Queue up any out-of-line partial specializations of this member
1788 // variable template; the client will force their instantiation once
1789 // the enclosing class has been instantiated.
1790 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1791 D->getPartialSpecializations(PartialSpecs);
1792 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1793 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1794 OutOfLineVarPartialSpecs.push_back(
1795 std::make_pair(Inst, PartialSpecs[I]));
1798 return Inst;
1801 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1802 VarTemplatePartialSpecializationDecl *D) {
1803 assert(D->isStaticDataMember() &&
1804 "Only static data member templates are allowed.");
1806 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1808 // Lookup the already-instantiated declaration and return that.
1809 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1810 assert(!Found.empty() && "Instantiation found nothing?");
1812 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1813 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1815 if (VarTemplatePartialSpecializationDecl *Result =
1816 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1817 return Result;
1819 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1822 Decl *
1823 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1824 // Create a local instantiation scope for this function template, which
1825 // will contain the instantiations of the template parameters and then get
1826 // merged with the local instantiation scope for the function template
1827 // itself.
1828 LocalInstantiationScope Scope(SemaRef);
1830 TemplateParameterList *TempParams = D->getTemplateParameters();
1831 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1832 if (!InstParams)
1833 return nullptr;
1835 FunctionDecl *Instantiated = nullptr;
1836 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1837 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1838 InstParams));
1839 else
1840 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1841 D->getTemplatedDecl(),
1842 InstParams));
1844 if (!Instantiated)
1845 return nullptr;
1847 // Link the instantiated function template declaration to the function
1848 // template from which it was instantiated.
1849 FunctionTemplateDecl *InstTemplate
1850 = Instantiated->getDescribedFunctionTemplate();
1851 InstTemplate->setAccess(D->getAccess());
1852 assert(InstTemplate &&
1853 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1855 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1857 // Link the instantiation back to the pattern *unless* this is a
1858 // non-definition friend declaration.
1859 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1860 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1861 InstTemplate->setInstantiatedFromMemberTemplate(D);
1863 // Make declarations visible in the appropriate context.
1864 if (!isFriend) {
1865 Owner->addDecl(InstTemplate);
1866 } else if (InstTemplate->getDeclContext()->isRecord() &&
1867 !getPreviousDeclForInstantiation(D)) {
1868 SemaRef.CheckFriendAccess(InstTemplate);
1871 return InstTemplate;
1874 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1875 CXXRecordDecl *PrevDecl = nullptr;
1876 if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1877 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1878 PatternPrev,
1879 TemplateArgs);
1880 if (!Prev) return nullptr;
1881 PrevDecl = cast<CXXRecordDecl>(Prev);
1884 CXXRecordDecl *Record = nullptr;
1885 bool IsInjectedClassName = D->isInjectedClassName();
1886 if (D->isLambda())
1887 Record = CXXRecordDecl::CreateLambda(
1888 SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
1889 D->getLambdaDependencyKind(), D->isGenericLambda(),
1890 D->getLambdaCaptureDefault());
1891 else
1892 Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1893 D->getBeginLoc(), D->getLocation(),
1894 D->getIdentifier(), PrevDecl,
1895 /*DelayTypeCreation=*/IsInjectedClassName);
1896 // Link the type of the injected-class-name to that of the outer class.
1897 if (IsInjectedClassName)
1898 (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
1900 // Substitute the nested name specifier, if any.
1901 if (SubstQualifier(D, Record))
1902 return nullptr;
1904 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1905 StartingScope);
1907 Record->setImplicit(D->isImplicit());
1908 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1909 // the tag decls introduced by friend class declarations don't have an access
1910 // specifier. Remove once this area of the code gets sorted out.
1911 if (D->getAccess() != AS_none)
1912 Record->setAccess(D->getAccess());
1913 if (!IsInjectedClassName)
1914 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1916 // If the original function was part of a friend declaration,
1917 // inherit its namespace state.
1918 if (D->getFriendObjectKind())
1919 Record->setObjectOfFriendDecl();
1921 // Make sure that anonymous structs and unions are recorded.
1922 if (D->isAnonymousStructOrUnion())
1923 Record->setAnonymousStructOrUnion(true);
1925 if (D->isLocalClass())
1926 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1928 // Forward the mangling number from the template to the instantiated decl.
1929 SemaRef.Context.setManglingNumber(Record,
1930 SemaRef.Context.getManglingNumber(D));
1932 // See if the old tag was defined along with a declarator.
1933 // If it did, mark the new tag as being associated with that declarator.
1934 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1935 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1937 // See if the old tag was defined along with a typedef.
1938 // If it did, mark the new tag as being associated with that typedef.
1939 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1940 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1942 Owner->addDecl(Record);
1944 // DR1484 clarifies that the members of a local class are instantiated as part
1945 // of the instantiation of their enclosing entity.
1946 if (D->isCompleteDefinition() && D->isLocalClass()) {
1947 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
1949 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1950 TSK_ImplicitInstantiation,
1951 /*Complain=*/true);
1953 // For nested local classes, we will instantiate the members when we
1954 // reach the end of the outermost (non-nested) local class.
1955 if (!D->isCXXClassMember())
1956 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1957 TSK_ImplicitInstantiation);
1959 // This class may have local implicit instantiations that need to be
1960 // performed within this scope.
1961 LocalInstantiations.perform();
1964 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1966 if (IsInjectedClassName)
1967 assert(Record->isInjectedClassName() && "Broken injected-class-name");
1969 return Record;
1972 /// Adjust the given function type for an instantiation of the
1973 /// given declaration, to cope with modifications to the function's type that
1974 /// aren't reflected in the type-source information.
1976 /// \param D The declaration we're instantiating.
1977 /// \param TInfo The already-instantiated type.
1978 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1979 FunctionDecl *D,
1980 TypeSourceInfo *TInfo) {
1981 const FunctionProtoType *OrigFunc
1982 = D->getType()->castAs<FunctionProtoType>();
1983 const FunctionProtoType *NewFunc
1984 = TInfo->getType()->castAs<FunctionProtoType>();
1985 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1986 return TInfo->getType();
1988 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1989 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1990 return Context.getFunctionType(NewFunc->getReturnType(),
1991 NewFunc->getParamTypes(), NewEPI);
1994 /// Normal class members are of more specific types and therefore
1995 /// don't make it here. This function serves three purposes:
1996 /// 1) instantiating function templates
1997 /// 2) substituting friend declarations
1998 /// 3) substituting deduction guide declarations for nested class templates
1999 Decl *TemplateDeclInstantiator::VisitFunctionDecl(
2000 FunctionDecl *D, TemplateParameterList *TemplateParams,
2001 RewriteKind FunctionRewriteKind) {
2002 // Check whether there is already a function template specialization for
2003 // this declaration.
2004 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2005 if (FunctionTemplate && !TemplateParams) {
2006 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2008 void *InsertPos = nullptr;
2009 FunctionDecl *SpecFunc
2010 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2012 // If we already have a function template specialization, return it.
2013 if (SpecFunc)
2014 return SpecFunc;
2017 bool isFriend;
2018 if (FunctionTemplate)
2019 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2020 else
2021 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2023 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2024 Owner->isFunctionOrMethod() ||
2025 !(isa<Decl>(Owner) &&
2026 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2027 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2029 ExplicitSpecifier InstantiatedExplicitSpecifier;
2030 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2031 InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
2032 SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
2033 if (InstantiatedExplicitSpecifier.isInvalid())
2034 return nullptr;
2037 SmallVector<ParmVarDecl *, 4> Params;
2038 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2039 if (!TInfo)
2040 return nullptr;
2041 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2043 if (TemplateParams && TemplateParams->size()) {
2044 auto *LastParam =
2045 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2046 if (LastParam && LastParam->isImplicit() &&
2047 LastParam->hasTypeConstraint()) {
2048 // In abbreviated templates, the type-constraints of invented template
2049 // type parameters are instantiated with the function type, invalidating
2050 // the TemplateParameterList which relied on the template type parameter
2051 // not having a type constraint. Recreate the TemplateParameterList with
2052 // the updated parameter list.
2053 TemplateParams = TemplateParameterList::Create(
2054 SemaRef.Context, TemplateParams->getTemplateLoc(),
2055 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2056 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2060 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2061 if (QualifierLoc) {
2062 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2063 TemplateArgs);
2064 if (!QualifierLoc)
2065 return nullptr;
2068 // FIXME: Concepts: Do not substitute into constraint expressions
2069 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2070 if (TrailingRequiresClause) {
2071 EnterExpressionEvaluationContext ConstantEvaluated(
2072 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
2073 ExprResult SubstRC = SemaRef.SubstExpr(TrailingRequiresClause,
2074 TemplateArgs);
2075 if (SubstRC.isInvalid())
2076 return nullptr;
2077 TrailingRequiresClause = SubstRC.get();
2078 if (!SemaRef.CheckConstraintExpression(TrailingRequiresClause))
2079 return nullptr;
2082 // If we're instantiating a local function declaration, put the result
2083 // in the enclosing namespace; otherwise we need to find the instantiated
2084 // context.
2085 DeclContext *DC;
2086 if (D->isLocalExternDecl()) {
2087 DC = Owner;
2088 SemaRef.adjustContextForLocalExternDecl(DC);
2089 } else if (isFriend && QualifierLoc) {
2090 CXXScopeSpec SS;
2091 SS.Adopt(QualifierLoc);
2092 DC = SemaRef.computeDeclContext(SS);
2093 if (!DC) return nullptr;
2094 } else {
2095 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
2096 TemplateArgs);
2099 DeclarationNameInfo NameInfo
2100 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2102 if (FunctionRewriteKind != RewriteKind::None)
2103 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2105 FunctionDecl *Function;
2106 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2107 Function = CXXDeductionGuideDecl::Create(
2108 SemaRef.Context, DC, D->getInnerLocStart(),
2109 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2110 D->getSourceRange().getEnd());
2111 if (DGuide->isCopyDeductionCandidate())
2112 cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
2113 Function->setAccess(D->getAccess());
2114 } else {
2115 Function = FunctionDecl::Create(
2116 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2117 D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(),
2118 D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(),
2119 TrailingRequiresClause);
2120 Function->setRangeEnd(D->getSourceRange().getEnd());
2123 if (D->isInlined())
2124 Function->setImplicitlyInline();
2126 if (QualifierLoc)
2127 Function->setQualifierInfo(QualifierLoc);
2129 if (D->isLocalExternDecl())
2130 Function->setLocalExternDecl();
2132 DeclContext *LexicalDC = Owner;
2133 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2134 assert(D->getDeclContext()->isFileContext());
2135 LexicalDC = D->getDeclContext();
2138 Function->setLexicalDeclContext(LexicalDC);
2140 // Attach the parameters
2141 for (unsigned P = 0; P < Params.size(); ++P)
2142 if (Params[P])
2143 Params[P]->setOwningFunction(Function);
2144 Function->setParams(Params);
2146 if (TrailingRequiresClause)
2147 Function->setTrailingRequiresClause(TrailingRequiresClause);
2149 if (TemplateParams) {
2150 // Our resulting instantiation is actually a function template, since we
2151 // are substituting only the outer template parameters. For example, given
2153 // template<typename T>
2154 // struct X {
2155 // template<typename U> friend void f(T, U);
2156 // };
2158 // X<int> x;
2160 // We are instantiating the friend function template "f" within X<int>,
2161 // which means substituting int for T, but leaving "f" as a friend function
2162 // template.
2163 // Build the function template itself.
2164 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2165 Function->getLocation(),
2166 Function->getDeclName(),
2167 TemplateParams, Function);
2168 Function->setDescribedFunctionTemplate(FunctionTemplate);
2170 FunctionTemplate->setLexicalDeclContext(LexicalDC);
2172 if (isFriend && D->isThisDeclarationADefinition()) {
2173 FunctionTemplate->setInstantiatedFromMemberTemplate(
2174 D->getDescribedFunctionTemplate());
2176 } else if (FunctionTemplate) {
2177 // Record this function template specialization.
2178 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2179 Function->setFunctionTemplateSpecialization(FunctionTemplate,
2180 TemplateArgumentList::CreateCopy(SemaRef.Context,
2181 Innermost),
2182 /*InsertPos=*/nullptr);
2183 } else if (isFriend && D->isThisDeclarationADefinition()) {
2184 // Do not connect the friend to the template unless it's actually a
2185 // definition. We don't want non-template functions to be marked as being
2186 // template instantiations.
2187 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2188 } else if (!isFriend) {
2189 // If this is not a function template, and this is not a friend (that is,
2190 // this is a locally declared function), save the instantiation relationship
2191 // for the purposes of constraint instantiation.
2192 Function->setInstantiatedFromDecl(D);
2195 if (isFriend) {
2196 Function->setObjectOfFriendDecl();
2197 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2198 FT->setObjectOfFriendDecl();
2201 if (InitFunctionInstantiation(Function, D))
2202 Function->setInvalidDecl();
2204 bool IsExplicitSpecialization = false;
2206 LookupResult Previous(
2207 SemaRef, Function->getDeclName(), SourceLocation(),
2208 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
2209 : Sema::LookupOrdinaryName,
2210 D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
2211 : SemaRef.forRedeclarationInCurContext());
2213 if (DependentFunctionTemplateSpecializationInfo *Info
2214 = D->getDependentSpecializationInfo()) {
2215 assert(isFriend && "non-friend has dependent specialization info?");
2217 // Instantiate the explicit template arguments.
2218 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2219 Info->getRAngleLoc());
2220 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2221 ExplicitArgs))
2222 return nullptr;
2224 // Map the candidate templates to their instantiations.
2225 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2226 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2227 Info->getTemplate(I),
2228 TemplateArgs);
2229 if (!Temp) return nullptr;
2231 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2234 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2235 &ExplicitArgs,
2236 Previous))
2237 Function->setInvalidDecl();
2239 IsExplicitSpecialization = true;
2240 } else if (const ASTTemplateArgumentListInfo *Info =
2241 D->getTemplateSpecializationArgsAsWritten()) {
2242 // The name of this function was written as a template-id.
2243 SemaRef.LookupQualifiedName(Previous, DC);
2245 // Instantiate the explicit template arguments.
2246 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2247 Info->getRAngleLoc());
2248 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2249 ExplicitArgs))
2250 return nullptr;
2252 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2253 &ExplicitArgs,
2254 Previous))
2255 Function->setInvalidDecl();
2257 IsExplicitSpecialization = true;
2258 } else if (TemplateParams || !FunctionTemplate) {
2259 // Look only into the namespace where the friend would be declared to
2260 // find a previous declaration. This is the innermost enclosing namespace,
2261 // as described in ActOnFriendFunctionDecl.
2262 SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
2264 // In C++, the previous declaration we find might be a tag type
2265 // (class or enum). In this case, the new declaration will hide the
2266 // tag type. Note that this does does not apply if we're declaring a
2267 // typedef (C++ [dcl.typedef]p4).
2268 if (Previous.isSingleTagDecl())
2269 Previous.clear();
2271 // Filter out previous declarations that don't match the scope. The only
2272 // effect this has is to remove declarations found in inline namespaces
2273 // for friend declarations with unqualified names.
2274 SemaRef.FilterLookupForScope(Previous, DC, /*Scope*/ nullptr,
2275 /*ConsiderLinkage*/ true,
2276 QualifierLoc.hasQualifier());
2279 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2280 IsExplicitSpecialization,
2281 Function->isThisDeclarationADefinition());
2283 // Check the template parameter list against the previous declaration. The
2284 // goal here is to pick up default arguments added since the friend was
2285 // declared; we know the template parameter lists match, since otherwise
2286 // we would not have picked this template as the previous declaration.
2287 if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
2288 SemaRef.CheckTemplateParameterList(
2289 TemplateParams,
2290 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2291 Function->isThisDeclarationADefinition()
2292 ? Sema::TPC_FriendFunctionTemplateDefinition
2293 : Sema::TPC_FriendFunctionTemplate);
2296 // If we're introducing a friend definition after the first use, trigger
2297 // instantiation.
2298 // FIXME: If this is a friend function template definition, we should check
2299 // to see if any specializations have been used.
2300 if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2301 if (MemberSpecializationInfo *MSInfo =
2302 Function->getMemberSpecializationInfo()) {
2303 if (MSInfo->getPointOfInstantiation().isInvalid()) {
2304 SourceLocation Loc = D->getLocation(); // FIXME
2305 MSInfo->setPointOfInstantiation(Loc);
2306 SemaRef.PendingLocalImplicitInstantiations.push_back(
2307 std::make_pair(Function, Loc));
2312 if (D->isExplicitlyDefaulted()) {
2313 if (SubstDefaultedFunction(Function, D))
2314 return nullptr;
2316 if (D->isDeleted())
2317 SemaRef.SetDeclDeleted(Function, D->getLocation());
2319 NamedDecl *PrincipalDecl =
2320 (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2322 // If this declaration lives in a different context from its lexical context,
2323 // add it to the corresponding lookup table.
2324 if (isFriend ||
2325 (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
2326 DC->makeDeclVisibleInContext(PrincipalDecl);
2328 if (Function->isOverloadedOperator() && !DC->isRecord() &&
2329 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
2330 PrincipalDecl->setNonMemberOperator();
2332 return Function;
2335 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
2336 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2337 Optional<const ASTTemplateArgumentListInfo *> ClassScopeSpecializationArgs,
2338 RewriteKind FunctionRewriteKind) {
2339 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2340 if (FunctionTemplate && !TemplateParams) {
2341 // We are creating a function template specialization from a function
2342 // template. Check whether there is already a function template
2343 // specialization for this particular set of template arguments.
2344 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2346 void *InsertPos = nullptr;
2347 FunctionDecl *SpecFunc
2348 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2350 // If we already have a function template specialization, return it.
2351 if (SpecFunc)
2352 return SpecFunc;
2355 bool isFriend;
2356 if (FunctionTemplate)
2357 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2358 else
2359 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2361 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2362 !(isa<Decl>(Owner) &&
2363 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2364 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2366 // Instantiate enclosing template arguments for friends.
2367 SmallVector<TemplateParameterList *, 4> TempParamLists;
2368 unsigned NumTempParamLists = 0;
2369 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2370 TempParamLists.resize(NumTempParamLists);
2371 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2372 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2373 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2374 if (!InstParams)
2375 return nullptr;
2376 TempParamLists[I] = InstParams;
2380 ExplicitSpecifier InstantiatedExplicitSpecifier =
2381 instantiateExplicitSpecifier(SemaRef, TemplateArgs,
2382 ExplicitSpecifier::getFromDecl(D), D);
2383 if (InstantiatedExplicitSpecifier.isInvalid())
2384 return nullptr;
2386 // Implicit destructors/constructors created for local classes in
2387 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2388 // Unfortunately there isn't enough context in those functions to
2389 // conditionally populate the TSI without breaking non-template related use
2390 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2391 // a proper transformation.
2392 if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
2393 !D->getTypeSourceInfo() &&
2394 isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
2395 TypeSourceInfo *TSI =
2396 SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
2397 D->setTypeSourceInfo(TSI);
2400 SmallVector<ParmVarDecl *, 4> Params;
2401 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2402 if (!TInfo)
2403 return nullptr;
2404 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2406 if (TemplateParams && TemplateParams->size()) {
2407 auto *LastParam =
2408 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2409 if (LastParam && LastParam->isImplicit() &&
2410 LastParam->hasTypeConstraint()) {
2411 // In abbreviated templates, the type-constraints of invented template
2412 // type parameters are instantiated with the function type, invalidating
2413 // the TemplateParameterList which relied on the template type parameter
2414 // not having a type constraint. Recreate the TemplateParameterList with
2415 // the updated parameter list.
2416 TemplateParams = TemplateParameterList::Create(
2417 SemaRef.Context, TemplateParams->getTemplateLoc(),
2418 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2419 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2423 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2424 if (QualifierLoc) {
2425 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2426 TemplateArgs);
2427 if (!QualifierLoc)
2428 return nullptr;
2431 // FIXME: Concepts: Do not substitute into constraint expressions
2432 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2433 if (TrailingRequiresClause) {
2434 EnterExpressionEvaluationContext ConstantEvaluated(
2435 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
2436 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
2437 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext,
2438 D->getMethodQualifiers(), ThisContext);
2439 ExprResult SubstRC = SemaRef.SubstExpr(TrailingRequiresClause,
2440 TemplateArgs);
2441 if (SubstRC.isInvalid())
2442 return nullptr;
2443 TrailingRequiresClause = SubstRC.get();
2444 if (!SemaRef.CheckConstraintExpression(TrailingRequiresClause))
2445 return nullptr;
2448 DeclContext *DC = Owner;
2449 if (isFriend) {
2450 if (QualifierLoc) {
2451 CXXScopeSpec SS;
2452 SS.Adopt(QualifierLoc);
2453 DC = SemaRef.computeDeclContext(SS);
2455 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2456 return nullptr;
2457 } else {
2458 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2459 D->getDeclContext(),
2460 TemplateArgs);
2462 if (!DC) return nullptr;
2465 DeclarationNameInfo NameInfo
2466 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2468 if (FunctionRewriteKind != RewriteKind::None)
2469 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2471 // Build the instantiated method declaration.
2472 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2473 CXXMethodDecl *Method = nullptr;
2475 SourceLocation StartLoc = D->getInnerLocStart();
2476 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2477 Method = CXXConstructorDecl::Create(
2478 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2479 InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
2480 Constructor->isInlineSpecified(), false,
2481 Constructor->getConstexprKind(), InheritedConstructor(),
2482 TrailingRequiresClause);
2483 Method->setRangeEnd(Constructor->getEndLoc());
2484 if (Constructor->isDefaultConstructor() ||
2485 Constructor->isCopyOrMoveConstructor())
2486 Method->setIneligibleOrNotSelected(true);
2487 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2488 Method = CXXDestructorDecl::Create(
2489 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2490 Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
2491 Destructor->getConstexprKind(), TrailingRequiresClause);
2492 Method->setIneligibleOrNotSelected(true);
2493 Method->setRangeEnd(Destructor->getEndLoc());
2494 Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName(
2495 SemaRef.Context.getCanonicalType(
2496 SemaRef.Context.getTypeDeclType(Record))));
2497 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2498 Method = CXXConversionDecl::Create(
2499 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2500 Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
2501 InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
2502 Conversion->getEndLoc(), TrailingRequiresClause);
2503 } else {
2504 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2505 Method = CXXMethodDecl::Create(
2506 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
2507 D->UsesFPIntrin(), D->isInlineSpecified(), D->getConstexprKind(),
2508 D->getEndLoc(), TrailingRequiresClause);
2509 if (D->isMoveAssignmentOperator() || D->isCopyAssignmentOperator())
2510 Method->setIneligibleOrNotSelected(true);
2513 if (D->isInlined())
2514 Method->setImplicitlyInline();
2516 if (QualifierLoc)
2517 Method->setQualifierInfo(QualifierLoc);
2519 if (TemplateParams) {
2520 // Our resulting instantiation is actually a function template, since we
2521 // are substituting only the outer template parameters. For example, given
2523 // template<typename T>
2524 // struct X {
2525 // template<typename U> void f(T, U);
2526 // };
2528 // X<int> x;
2530 // We are instantiating the member template "f" within X<int>, which means
2531 // substituting int for T, but leaving "f" as a member function template.
2532 // Build the function template itself.
2533 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2534 Method->getLocation(),
2535 Method->getDeclName(),
2536 TemplateParams, Method);
2537 if (isFriend) {
2538 FunctionTemplate->setLexicalDeclContext(Owner);
2539 FunctionTemplate->setObjectOfFriendDecl();
2540 } else if (D->isOutOfLine())
2541 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2542 Method->setDescribedFunctionTemplate(FunctionTemplate);
2543 } else if (FunctionTemplate) {
2544 // Record this function template specialization.
2545 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2546 Method->setFunctionTemplateSpecialization(FunctionTemplate,
2547 TemplateArgumentList::CreateCopy(SemaRef.Context,
2548 Innermost),
2549 /*InsertPos=*/nullptr);
2550 } else if (!isFriend) {
2551 // Record that this is an instantiation of a member function.
2552 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2555 // If we are instantiating a member function defined
2556 // out-of-line, the instantiation will have the same lexical
2557 // context (which will be a namespace scope) as the template.
2558 if (isFriend) {
2559 if (NumTempParamLists)
2560 Method->setTemplateParameterListsInfo(
2561 SemaRef.Context,
2562 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
2564 Method->setLexicalDeclContext(Owner);
2565 Method->setObjectOfFriendDecl();
2566 } else if (D->isOutOfLine())
2567 Method->setLexicalDeclContext(D->getLexicalDeclContext());
2569 // Attach the parameters
2570 for (unsigned P = 0; P < Params.size(); ++P)
2571 Params[P]->setOwningFunction(Method);
2572 Method->setParams(Params);
2574 if (InitMethodInstantiation(Method, D))
2575 Method->setInvalidDecl();
2577 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2578 Sema::ForExternalRedeclaration);
2580 bool IsExplicitSpecialization = false;
2582 // If the name of this function was written as a template-id, instantiate
2583 // the explicit template arguments.
2584 if (DependentFunctionTemplateSpecializationInfo *Info
2585 = D->getDependentSpecializationInfo()) {
2586 assert(isFriend && "non-friend has dependent specialization info?");
2588 // Instantiate the explicit template arguments.
2589 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2590 Info->getRAngleLoc());
2591 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2592 ExplicitArgs))
2593 return nullptr;
2595 // Map the candidate templates to their instantiations.
2596 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2597 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2598 Info->getTemplate(I),
2599 TemplateArgs);
2600 if (!Temp) return nullptr;
2602 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2605 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2606 &ExplicitArgs,
2607 Previous))
2608 Method->setInvalidDecl();
2610 IsExplicitSpecialization = true;
2611 } else if (const ASTTemplateArgumentListInfo *Info =
2612 ClassScopeSpecializationArgs.value_or(
2613 D->getTemplateSpecializationArgsAsWritten())) {
2614 SemaRef.LookupQualifiedName(Previous, DC);
2616 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2617 Info->getRAngleLoc());
2618 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2619 ExplicitArgs))
2620 return nullptr;
2622 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2623 &ExplicitArgs,
2624 Previous))
2625 Method->setInvalidDecl();
2627 IsExplicitSpecialization = true;
2628 } else if (ClassScopeSpecializationArgs) {
2629 // Class-scope explicit specialization written without explicit template
2630 // arguments.
2631 SemaRef.LookupQualifiedName(Previous, DC);
2632 if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
2633 Method->setInvalidDecl();
2635 IsExplicitSpecialization = true;
2636 } else if (!FunctionTemplate || TemplateParams || isFriend) {
2637 SemaRef.LookupQualifiedName(Previous, Record);
2639 // In C++, the previous declaration we find might be a tag type
2640 // (class or enum). In this case, the new declaration will hide the
2641 // tag type. Note that this does does not apply if we're declaring a
2642 // typedef (C++ [dcl.typedef]p4).
2643 if (Previous.isSingleTagDecl())
2644 Previous.clear();
2647 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2648 IsExplicitSpecialization,
2649 Method->isThisDeclarationADefinition());
2651 if (D->isPure())
2652 SemaRef.CheckPureMethod(Method, SourceRange());
2654 // Propagate access. For a non-friend declaration, the access is
2655 // whatever we're propagating from. For a friend, it should be the
2656 // previous declaration we just found.
2657 if (isFriend && Method->getPreviousDecl())
2658 Method->setAccess(Method->getPreviousDecl()->getAccess());
2659 else
2660 Method->setAccess(D->getAccess());
2661 if (FunctionTemplate)
2662 FunctionTemplate->setAccess(Method->getAccess());
2664 SemaRef.CheckOverrideControl(Method);
2666 // If a function is defined as defaulted or deleted, mark it as such now.
2667 if (D->isExplicitlyDefaulted()) {
2668 if (SubstDefaultedFunction(Method, D))
2669 return nullptr;
2671 if (D->isDeletedAsWritten())
2672 SemaRef.SetDeclDeleted(Method, Method->getLocation());
2674 // If this is an explicit specialization, mark the implicitly-instantiated
2675 // template specialization as being an explicit specialization too.
2676 // FIXME: Is this necessary?
2677 if (IsExplicitSpecialization && !isFriend)
2678 SemaRef.CompleteMemberSpecialization(Method, Previous);
2680 // If there's a function template, let our caller handle it.
2681 if (FunctionTemplate) {
2682 // do nothing
2684 // Don't hide a (potentially) valid declaration with an invalid one.
2685 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2686 // do nothing
2688 // Otherwise, check access to friends and make them visible.
2689 } else if (isFriend) {
2690 // We only need to re-check access for methods which we didn't
2691 // manage to match during parsing.
2692 if (!D->getPreviousDecl())
2693 SemaRef.CheckFriendAccess(Method);
2695 Record->makeDeclVisibleInContext(Method);
2697 // Otherwise, add the declaration. We don't need to do this for
2698 // class-scope specializations because we'll have matched them with
2699 // the appropriate template.
2700 } else {
2701 Owner->addDecl(Method);
2704 // PR17480: Honor the used attribute to instantiate member function
2705 // definitions
2706 if (Method->hasAttr<UsedAttr>()) {
2707 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2708 SourceLocation Loc;
2709 if (const MemberSpecializationInfo *MSInfo =
2710 A->getMemberSpecializationInfo())
2711 Loc = MSInfo->getPointOfInstantiation();
2712 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2713 Loc = Spec->getPointOfInstantiation();
2714 SemaRef.MarkFunctionReferenced(Loc, Method);
2718 return Method;
2721 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2722 return VisitCXXMethodDecl(D);
2725 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2726 return VisitCXXMethodDecl(D);
2729 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2730 return VisitCXXMethodDecl(D);
2733 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2734 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2735 /*ExpectParameterPack=*/ false);
2738 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2739 TemplateTypeParmDecl *D) {
2740 assert(D->getTypeForDecl()->isTemplateTypeParmType());
2742 Optional<unsigned> NumExpanded;
2744 if (const TypeConstraint *TC = D->getTypeConstraint()) {
2745 if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
2746 assert(TC->getTemplateArgsAsWritten() &&
2747 "type parameter can only be an expansion when explicit arguments "
2748 "are specified");
2749 // The template type parameter pack's type is a pack expansion of types.
2750 // Determine whether we need to expand this parameter pack into separate
2751 // types.
2752 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2753 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2754 SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2756 // Determine whether the set of unexpanded parameter packs can and should
2757 // be expanded.
2758 bool Expand = true;
2759 bool RetainExpansion = false;
2760 if (SemaRef.CheckParameterPacksForExpansion(
2761 cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2762 ->getEllipsisLoc(),
2763 SourceRange(TC->getConceptNameLoc(),
2764 TC->hasExplicitTemplateArgs() ?
2765 TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2766 TC->getConceptNameInfo().getEndLoc()),
2767 Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2768 return nullptr;
2772 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2773 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2774 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2775 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
2776 D->hasTypeConstraint(), NumExpanded);
2778 Inst->setAccess(AS_public);
2779 Inst->setImplicit(D->isImplicit());
2780 if (auto *TC = D->getTypeConstraint()) {
2781 if (!D->isImplicit()) {
2782 // Invented template parameter type constraints will be instantiated with
2783 // the corresponding auto-typed parameter as it might reference other
2784 // parameters.
2786 // TODO: Concepts: do not instantiate the constraint (delayed constraint
2787 // substitution)
2788 if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs))
2789 return nullptr;
2792 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2793 TypeSourceInfo *InstantiatedDefaultArg =
2794 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2795 D->getDefaultArgumentLoc(), D->getDeclName());
2796 if (InstantiatedDefaultArg)
2797 Inst->setDefaultArgument(InstantiatedDefaultArg);
2800 // Introduce this template parameter's instantiation into the instantiation
2801 // scope.
2802 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2804 return Inst;
2807 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2808 NonTypeTemplateParmDecl *D) {
2809 // Substitute into the type of the non-type template parameter.
2810 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2811 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2812 SmallVector<QualType, 4> ExpandedParameterPackTypes;
2813 bool IsExpandedParameterPack = false;
2814 TypeSourceInfo *DI;
2815 QualType T;
2816 bool Invalid = false;
2818 if (D->isExpandedParameterPack()) {
2819 // The non-type template parameter pack is an already-expanded pack
2820 // expansion of types. Substitute into each of the expanded types.
2821 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2822 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2823 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2824 TypeSourceInfo *NewDI =
2825 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2826 D->getLocation(), D->getDeclName());
2827 if (!NewDI)
2828 return nullptr;
2830 QualType NewT =
2831 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2832 if (NewT.isNull())
2833 return nullptr;
2835 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2836 ExpandedParameterPackTypes.push_back(NewT);
2839 IsExpandedParameterPack = true;
2840 DI = D->getTypeSourceInfo();
2841 T = DI->getType();
2842 } else if (D->isPackExpansion()) {
2843 // The non-type template parameter pack's type is a pack expansion of types.
2844 // Determine whether we need to expand this parameter pack into separate
2845 // types.
2846 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2847 TypeLoc Pattern = Expansion.getPatternLoc();
2848 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2849 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2851 // Determine whether the set of unexpanded parameter packs can and should
2852 // be expanded.
2853 bool Expand = true;
2854 bool RetainExpansion = false;
2855 Optional<unsigned> OrigNumExpansions
2856 = Expansion.getTypePtr()->getNumExpansions();
2857 Optional<unsigned> NumExpansions = OrigNumExpansions;
2858 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2859 Pattern.getSourceRange(),
2860 Unexpanded,
2861 TemplateArgs,
2862 Expand, RetainExpansion,
2863 NumExpansions))
2864 return nullptr;
2866 if (Expand) {
2867 for (unsigned I = 0; I != *NumExpansions; ++I) {
2868 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2869 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2870 D->getLocation(),
2871 D->getDeclName());
2872 if (!NewDI)
2873 return nullptr;
2875 QualType NewT =
2876 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2877 if (NewT.isNull())
2878 return nullptr;
2880 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2881 ExpandedParameterPackTypes.push_back(NewT);
2884 // Note that we have an expanded parameter pack. The "type" of this
2885 // expanded parameter pack is the original expansion type, but callers
2886 // will end up using the expanded parameter pack types for type-checking.
2887 IsExpandedParameterPack = true;
2888 DI = D->getTypeSourceInfo();
2889 T = DI->getType();
2890 } else {
2891 // We cannot fully expand the pack expansion now, so substitute into the
2892 // pattern and create a new pack expansion type.
2893 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2894 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2895 D->getLocation(),
2896 D->getDeclName());
2897 if (!NewPattern)
2898 return nullptr;
2900 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
2901 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2902 NumExpansions);
2903 if (!DI)
2904 return nullptr;
2906 T = DI->getType();
2908 } else {
2909 // Simple case: substitution into a parameter that is not a parameter pack.
2910 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2911 D->getLocation(), D->getDeclName());
2912 if (!DI)
2913 return nullptr;
2915 // Check that this type is acceptable for a non-type template parameter.
2916 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
2917 if (T.isNull()) {
2918 T = SemaRef.Context.IntTy;
2919 Invalid = true;
2923 NonTypeTemplateParmDecl *Param;
2924 if (IsExpandedParameterPack)
2925 Param = NonTypeTemplateParmDecl::Create(
2926 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2927 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2928 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
2929 ExpandedParameterPackTypesAsWritten);
2930 else
2931 Param = NonTypeTemplateParmDecl::Create(
2932 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2933 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2934 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
2936 if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
2937 if (AutoLoc.isConstrained())
2938 if (SemaRef.AttachTypeConstraint(
2939 AutoLoc, Param,
2940 IsExpandedParameterPack
2941 ? DI->getTypeLoc().getAs<PackExpansionTypeLoc>()
2942 .getEllipsisLoc()
2943 : SourceLocation()))
2944 Invalid = true;
2946 Param->setAccess(AS_public);
2947 Param->setImplicit(D->isImplicit());
2948 if (Invalid)
2949 Param->setInvalidDecl();
2951 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2952 EnterExpressionEvaluationContext ConstantEvaluated(
2953 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2954 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2955 if (!Value.isInvalid())
2956 Param->setDefaultArgument(Value.get());
2959 // Introduce this template parameter's instantiation into the instantiation
2960 // scope.
2961 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2962 return Param;
2965 static void collectUnexpandedParameterPacks(
2966 Sema &S,
2967 TemplateParameterList *Params,
2968 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
2969 for (const auto &P : *Params) {
2970 if (P->isTemplateParameterPack())
2971 continue;
2972 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
2973 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2974 Unexpanded);
2975 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
2976 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2977 Unexpanded);
2981 Decl *
2982 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2983 TemplateTemplateParmDecl *D) {
2984 // Instantiate the template parameter list of the template template parameter.
2985 TemplateParameterList *TempParams = D->getTemplateParameters();
2986 TemplateParameterList *InstParams;
2987 SmallVector<TemplateParameterList*, 8> ExpandedParams;
2989 bool IsExpandedParameterPack = false;
2991 if (D->isExpandedParameterPack()) {
2992 // The template template parameter pack is an already-expanded pack
2993 // expansion of template parameters. Substitute into each of the expanded
2994 // parameters.
2995 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2996 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2997 I != N; ++I) {
2998 LocalInstantiationScope Scope(SemaRef);
2999 TemplateParameterList *Expansion =
3000 SubstTemplateParams(D->getExpansionTemplateParameters(I));
3001 if (!Expansion)
3002 return nullptr;
3003 ExpandedParams.push_back(Expansion);
3006 IsExpandedParameterPack = true;
3007 InstParams = TempParams;
3008 } else if (D->isPackExpansion()) {
3009 // The template template parameter pack expands to a pack of template
3010 // template parameters. Determine whether we need to expand this parameter
3011 // pack into separate parameters.
3012 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3013 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
3014 Unexpanded);
3016 // Determine whether the set of unexpanded parameter packs can and should
3017 // be expanded.
3018 bool Expand = true;
3019 bool RetainExpansion = false;
3020 Optional<unsigned> NumExpansions;
3021 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
3022 TempParams->getSourceRange(),
3023 Unexpanded,
3024 TemplateArgs,
3025 Expand, RetainExpansion,
3026 NumExpansions))
3027 return nullptr;
3029 if (Expand) {
3030 for (unsigned I = 0; I != *NumExpansions; ++I) {
3031 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3032 LocalInstantiationScope Scope(SemaRef);
3033 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3034 if (!Expansion)
3035 return nullptr;
3036 ExpandedParams.push_back(Expansion);
3039 // Note that we have an expanded parameter pack. The "type" of this
3040 // expanded parameter pack is the original expansion type, but callers
3041 // will end up using the expanded parameter pack types for type-checking.
3042 IsExpandedParameterPack = true;
3043 InstParams = TempParams;
3044 } else {
3045 // We cannot fully expand the pack expansion now, so just substitute
3046 // into the pattern.
3047 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3049 LocalInstantiationScope Scope(SemaRef);
3050 InstParams = SubstTemplateParams(TempParams);
3051 if (!InstParams)
3052 return nullptr;
3054 } else {
3055 // Perform the actual substitution of template parameters within a new,
3056 // local instantiation scope.
3057 LocalInstantiationScope Scope(SemaRef);
3058 InstParams = SubstTemplateParams(TempParams);
3059 if (!InstParams)
3060 return nullptr;
3063 // Build the template template parameter.
3064 TemplateTemplateParmDecl *Param;
3065 if (IsExpandedParameterPack)
3066 Param = TemplateTemplateParmDecl::Create(
3067 SemaRef.Context, Owner, D->getLocation(),
3068 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3069 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
3070 else
3071 Param = TemplateTemplateParmDecl::Create(
3072 SemaRef.Context, Owner, D->getLocation(),
3073 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3074 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
3075 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3076 NestedNameSpecifierLoc QualifierLoc =
3077 D->getDefaultArgument().getTemplateQualifierLoc();
3078 QualifierLoc =
3079 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3080 TemplateName TName = SemaRef.SubstTemplateName(
3081 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3082 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3083 if (!TName.isNull())
3084 Param->setDefaultArgument(
3085 SemaRef.Context,
3086 TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
3087 D->getDefaultArgument().getTemplateQualifierLoc(),
3088 D->getDefaultArgument().getTemplateNameLoc()));
3090 Param->setAccess(AS_public);
3091 Param->setImplicit(D->isImplicit());
3093 // Introduce this template parameter's instantiation into the instantiation
3094 // scope.
3095 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3097 return Param;
3100 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3101 // Using directives are never dependent (and never contain any types or
3102 // expressions), so they require no explicit instantiation work.
3104 UsingDirectiveDecl *Inst
3105 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3106 D->getNamespaceKeyLocation(),
3107 D->getQualifierLoc(),
3108 D->getIdentLocation(),
3109 D->getNominatedNamespace(),
3110 D->getCommonAncestor());
3112 // Add the using directive to its declaration context
3113 // only if this is not a function or method.
3114 if (!Owner->isFunctionOrMethod())
3115 Owner->addDecl(Inst);
3117 return Inst;
3120 Decl *TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl *D,
3121 BaseUsingDecl *Inst,
3122 LookupResult *Lookup) {
3124 bool isFunctionScope = Owner->isFunctionOrMethod();
3126 for (auto *Shadow : D->shadows()) {
3127 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3128 // reconstruct it in the case where it matters. Hm, can we extract it from
3129 // the DeclSpec when parsing and save it in the UsingDecl itself?
3130 NamedDecl *OldTarget = Shadow->getTargetDecl();
3131 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3132 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3133 OldTarget = BaseShadow;
3135 NamedDecl *InstTarget = nullptr;
3136 if (auto *EmptyD =
3137 dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3138 InstTarget = UnresolvedUsingIfExistsDecl::Create(
3139 SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3140 } else {
3141 InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3142 Shadow->getLocation(), OldTarget, TemplateArgs));
3144 if (!InstTarget)
3145 return nullptr;
3147 UsingShadowDecl *PrevDecl = nullptr;
3148 if (Lookup &&
3149 SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3150 continue;
3152 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3153 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3154 Shadow->getLocation(), OldPrev, TemplateArgs));
3156 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3157 /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3158 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3160 if (isFunctionScope)
3161 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3164 return Inst;
3167 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3169 // The nested name specifier may be dependent, for example
3170 // template <typename T> struct t {
3171 // struct s1 { T f1(); };
3172 // struct s2 : s1 { using s1::f1; };
3173 // };
3174 // template struct t<int>;
3175 // Here, in using s1::f1, s1 refers to t<T>::s1;
3176 // we need to substitute for t<int>::s1.
3177 NestedNameSpecifierLoc QualifierLoc
3178 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3179 TemplateArgs);
3180 if (!QualifierLoc)
3181 return nullptr;
3183 // For an inheriting constructor declaration, the name of the using
3184 // declaration is the name of a constructor in this class, not in the
3185 // base class.
3186 DeclarationNameInfo NameInfo = D->getNameInfo();
3187 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3188 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3189 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
3190 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3192 // We only need to do redeclaration lookups if we're in a class scope (in
3193 // fact, it's not really even possible in non-class scopes).
3194 bool CheckRedeclaration = Owner->isRecord();
3195 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3196 Sema::ForVisibleRedeclaration);
3198 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3199 D->getUsingLoc(),
3200 QualifierLoc,
3201 NameInfo,
3202 D->hasTypename());
3204 CXXScopeSpec SS;
3205 SS.Adopt(QualifierLoc);
3206 if (CheckRedeclaration) {
3207 Prev.setHideTags(false);
3208 SemaRef.LookupQualifiedName(Prev, Owner);
3210 // Check for invalid redeclarations.
3211 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3212 D->hasTypename(), SS,
3213 D->getLocation(), Prev))
3214 NewUD->setInvalidDecl();
3217 if (!NewUD->isInvalidDecl() &&
3218 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3219 NameInfo, D->getLocation(), nullptr, D))
3220 NewUD->setInvalidDecl();
3222 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3223 NewUD->setAccess(D->getAccess());
3224 Owner->addDecl(NewUD);
3226 // Don't process the shadow decls for an invalid decl.
3227 if (NewUD->isInvalidDecl())
3228 return NewUD;
3230 // If the using scope was dependent, or we had dependent bases, we need to
3231 // recheck the inheritance
3232 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3233 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
3235 return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3238 Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3239 // Cannot be a dependent type, but still could be an instantiation
3240 EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3241 D->getLocation(), D->getEnumDecl(), TemplateArgs));
3243 if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3244 return nullptr;
3246 UsingEnumDecl *NewUD =
3247 UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3248 D->getEnumLoc(), D->getLocation(), EnumD);
3250 SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
3251 NewUD->setAccess(D->getAccess());
3252 Owner->addDecl(NewUD);
3254 // Don't process the shadow decls for an invalid decl.
3255 if (NewUD->isInvalidDecl())
3256 return NewUD;
3258 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3259 // cannot be dependent, and will therefore have been checked during template
3260 // definition.
3262 return VisitBaseUsingDecls(D, NewUD, nullptr);
3265 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3266 // Ignore these; we handle them in bulk when processing the UsingDecl.
3267 return nullptr;
3270 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3271 ConstructorUsingShadowDecl *D) {
3272 // Ignore these; we handle them in bulk when processing the UsingDecl.
3273 return nullptr;
3276 template <typename T>
3277 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3278 T *D, bool InstantiatingPackElement) {
3279 // If this is a pack expansion, expand it now.
3280 if (D->isPackExpansion() && !InstantiatingPackElement) {
3281 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3282 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3283 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3285 // Determine whether the set of unexpanded parameter packs can and should
3286 // be expanded.
3287 bool Expand = true;
3288 bool RetainExpansion = false;
3289 Optional<unsigned> NumExpansions;
3290 if (SemaRef.CheckParameterPacksForExpansion(
3291 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3292 Expand, RetainExpansion, NumExpansions))
3293 return nullptr;
3295 // This declaration cannot appear within a function template signature,
3296 // so we can't have a partial argument list for a parameter pack.
3297 assert(!RetainExpansion &&
3298 "should never need to retain an expansion for UsingPackDecl");
3300 if (!Expand) {
3301 // We cannot fully expand the pack expansion now, so substitute into the
3302 // pattern and create a new pack expansion.
3303 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3304 return instantiateUnresolvedUsingDecl(D, true);
3307 // Within a function, we don't have any normal way to check for conflicts
3308 // between shadow declarations from different using declarations in the
3309 // same pack expansion, but this is always ill-formed because all expansions
3310 // must produce (conflicting) enumerators.
3312 // Sadly we can't just reject this in the template definition because it
3313 // could be valid if the pack is empty or has exactly one expansion.
3314 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
3315 SemaRef.Diag(D->getEllipsisLoc(),
3316 diag::err_using_decl_redeclaration_expansion);
3317 return nullptr;
3320 // Instantiate the slices of this pack and build a UsingPackDecl.
3321 SmallVector<NamedDecl*, 8> Expansions;
3322 for (unsigned I = 0; I != *NumExpansions; ++I) {
3323 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3324 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3325 if (!Slice)
3326 return nullptr;
3327 // Note that we can still get unresolved using declarations here, if we
3328 // had arguments for all packs but the pattern also contained other
3329 // template arguments (this only happens during partial substitution, eg
3330 // into the body of a generic lambda in a function template).
3331 Expansions.push_back(cast<NamedDecl>(Slice));
3334 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3335 if (isDeclWithinFunction(D))
3336 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3337 return NewD;
3340 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3341 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
3343 NestedNameSpecifierLoc QualifierLoc
3344 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3345 TemplateArgs);
3346 if (!QualifierLoc)
3347 return nullptr;
3349 CXXScopeSpec SS;
3350 SS.Adopt(QualifierLoc);
3352 DeclarationNameInfo NameInfo
3353 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3355 // Produce a pack expansion only if we're not instantiating a particular
3356 // slice of a pack expansion.
3357 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3358 SemaRef.ArgumentPackSubstitutionIndex != -1;
3359 SourceLocation EllipsisLoc =
3360 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
3362 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3363 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3364 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3365 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3366 ParsedAttributesView(),
3367 /*IsInstantiation*/ true, IsUsingIfExists);
3368 if (UD) {
3369 SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3370 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3373 return UD;
3376 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3377 UnresolvedUsingTypenameDecl *D) {
3378 return instantiateUnresolvedUsingDecl(D);
3381 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3382 UnresolvedUsingValueDecl *D) {
3383 return instantiateUnresolvedUsingDecl(D);
3386 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3387 UnresolvedUsingIfExistsDecl *D) {
3388 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3391 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3392 SmallVector<NamedDecl*, 8> Expansions;
3393 for (auto *UD : D->expansions()) {
3394 if (NamedDecl *NewUD =
3395 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3396 Expansions.push_back(NewUD);
3397 else
3398 return nullptr;
3401 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3402 if (isDeclWithinFunction(D))
3403 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3404 return NewD;
3407 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
3408 ClassScopeFunctionSpecializationDecl *Decl) {
3409 CXXMethodDecl *OldFD = Decl->getSpecialization();
3410 return cast_or_null<CXXMethodDecl>(
3411 VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
3414 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3415 OMPThreadPrivateDecl *D) {
3416 SmallVector<Expr *, 5> Vars;
3417 for (auto *I : D->varlists()) {
3418 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3419 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
3420 Vars.push_back(Var);
3423 OMPThreadPrivateDecl *TD =
3424 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3426 TD->setAccess(AS_public);
3427 Owner->addDecl(TD);
3429 return TD;
3432 Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3433 SmallVector<Expr *, 5> Vars;
3434 for (auto *I : D->varlists()) {
3435 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3436 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
3437 Vars.push_back(Var);
3439 SmallVector<OMPClause *, 4> Clauses;
3440 // Copy map clauses from the original mapper.
3441 for (OMPClause *C : D->clauselists()) {
3442 OMPClause *IC = nullptr;
3443 if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
3444 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3445 if (!NewE.isUsable())
3446 continue;
3447 IC = SemaRef.ActOnOpenMPAllocatorClause(
3448 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3449 } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
3450 ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
3451 if (!NewE.isUsable())
3452 continue;
3453 IC = SemaRef.ActOnOpenMPAlignClause(NewE.get(), AC->getBeginLoc(),
3454 AC->getLParenLoc(), AC->getEndLoc());
3455 // If align clause value ends up being invalid, this can end up null.
3456 if (!IC)
3457 continue;
3459 Clauses.push_back(IC);
3462 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
3463 D->getLocation(), Vars, Clauses, Owner);
3464 if (Res.get().isNull())
3465 return nullptr;
3466 return Res.get().getSingleDecl();
3469 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3470 llvm_unreachable(
3471 "Requires directive cannot be instantiated within a dependent context");
3474 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3475 OMPDeclareReductionDecl *D) {
3476 // Instantiate type and check if it is allowed.
3477 const bool RequiresInstantiation =
3478 D->getType()->isDependentType() ||
3479 D->getType()->isInstantiationDependentType() ||
3480 D->getType()->containsUnexpandedParameterPack();
3481 QualType SubstReductionType;
3482 if (RequiresInstantiation) {
3483 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
3484 D->getLocation(),
3485 ParsedType::make(SemaRef.SubstType(
3486 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3487 } else {
3488 SubstReductionType = D->getType();
3490 if (SubstReductionType.isNull())
3491 return nullptr;
3492 Expr *Combiner = D->getCombiner();
3493 Expr *Init = D->getInitializer();
3494 bool IsCorrect = true;
3495 // Create instantiated copy.
3496 std::pair<QualType, SourceLocation> ReductionTypes[] = {
3497 std::make_pair(SubstReductionType, D->getLocation())};
3498 auto *PrevDeclInScope = D->getPrevDeclInScope();
3499 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3500 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3501 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3502 ->get<Decl *>());
3504 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
3505 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3506 PrevDeclInScope);
3507 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3508 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
3509 Expr *SubstCombiner = nullptr;
3510 Expr *SubstInitializer = nullptr;
3511 // Combiners instantiation sequence.
3512 if (Combiner) {
3513 SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
3514 /*S=*/nullptr, NewDRD);
3515 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3516 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3517 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3518 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3519 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3520 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3521 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3522 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3523 ThisContext);
3524 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3525 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3527 // Initializers instantiation sequence.
3528 if (Init) {
3529 VarDecl *OmpPrivParm = SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
3530 /*S=*/nullptr, NewDRD);
3531 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3532 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3533 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3534 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3535 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3536 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3537 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
3538 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3539 } else {
3540 auto *OldPrivParm =
3541 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3542 IsCorrect = IsCorrect && OldPrivParm->hasInit();
3543 if (IsCorrect)
3544 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3545 TemplateArgs);
3547 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD, SubstInitializer,
3548 OmpPrivParm);
3550 IsCorrect = IsCorrect && SubstCombiner &&
3551 (!Init ||
3552 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
3553 SubstInitializer) ||
3554 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
3555 !SubstInitializer));
3557 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
3558 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3560 return NewDRD;
3563 Decl *
3564 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3565 // Instantiate type and check if it is allowed.
3566 const bool RequiresInstantiation =
3567 D->getType()->isDependentType() ||
3568 D->getType()->isInstantiationDependentType() ||
3569 D->getType()->containsUnexpandedParameterPack();
3570 QualType SubstMapperTy;
3571 DeclarationName VN = D->getVarName();
3572 if (RequiresInstantiation) {
3573 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
3574 D->getLocation(),
3575 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3576 D->getLocation(), VN)));
3577 } else {
3578 SubstMapperTy = D->getType();
3580 if (SubstMapperTy.isNull())
3581 return nullptr;
3582 // Create an instantiated copy of mapper.
3583 auto *PrevDeclInScope = D->getPrevDeclInScope();
3584 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3585 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3586 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3587 ->get<Decl *>());
3589 bool IsCorrect = true;
3590 SmallVector<OMPClause *, 6> Clauses;
3591 // Instantiate the mapper variable.
3592 DeclarationNameInfo DirName;
3593 SemaRef.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3594 /*S=*/nullptr,
3595 (*D->clauselist_begin())->getBeginLoc());
3596 ExprResult MapperVarRef = SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3597 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3598 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3599 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3600 cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3601 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3602 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3603 ThisContext);
3604 // Instantiate map clauses.
3605 for (OMPClause *C : D->clauselists()) {
3606 auto *OldC = cast<OMPMapClause>(C);
3607 SmallVector<Expr *, 4> NewVars;
3608 for (Expr *OE : OldC->varlists()) {
3609 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3610 if (!NE) {
3611 IsCorrect = false;
3612 break;
3614 NewVars.push_back(NE);
3616 if (!IsCorrect)
3617 break;
3618 NestedNameSpecifierLoc NewQualifierLoc =
3619 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3620 TemplateArgs);
3621 CXXScopeSpec SS;
3622 SS.Adopt(NewQualifierLoc);
3623 DeclarationNameInfo NewNameInfo =
3624 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3625 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3626 OldC->getEndLoc());
3627 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
3628 OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS,
3629 NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(),
3630 OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs);
3631 Clauses.push_back(NewC);
3633 SemaRef.EndOpenMPDSABlock(nullptr);
3634 if (!IsCorrect)
3635 return nullptr;
3636 Sema::DeclGroupPtrTy DG = SemaRef.ActOnOpenMPDeclareMapperDirective(
3637 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3638 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3639 Decl *NewDMD = DG.get().getSingleDecl();
3640 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3641 return NewDMD;
3644 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3645 OMPCapturedExprDecl * /*D*/) {
3646 llvm_unreachable("Should not be met in templates");
3649 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
3650 return VisitFunctionDecl(D, nullptr);
3653 Decl *
3654 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3655 Decl *Inst = VisitFunctionDecl(D, nullptr);
3656 if (Inst && !D->getDescribedFunctionTemplate())
3657 Owner->addDecl(Inst);
3658 return Inst;
3661 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
3662 return VisitCXXMethodDecl(D, nullptr);
3665 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3666 llvm_unreachable("There are only CXXRecordDecls in C++");
3669 Decl *
3670 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3671 ClassTemplateSpecializationDecl *D) {
3672 // As a MS extension, we permit class-scope explicit specialization
3673 // of member class templates.
3674 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3675 assert(ClassTemplate->getDeclContext()->isRecord() &&
3676 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3677 "can only instantiate an explicit specialization "
3678 "for a member class template");
3680 // Lookup the already-instantiated declaration in the instantiation
3681 // of the class template.
3682 ClassTemplateDecl *InstClassTemplate =
3683 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3684 D->getLocation(), ClassTemplate, TemplateArgs));
3685 if (!InstClassTemplate)
3686 return nullptr;
3688 // Substitute into the template arguments of the class template explicit
3689 // specialization.
3690 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
3691 castAs<TemplateSpecializationTypeLoc>();
3692 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3693 Loc.getRAngleLoc());
3694 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
3695 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
3696 ArgLocs.push_back(Loc.getArgLoc(I));
3697 if (SemaRef.SubstTemplateArguments(ArgLocs, TemplateArgs, InstTemplateArgs))
3698 return nullptr;
3700 // Check that the template argument list is well-formed for this
3701 // class template.
3702 SmallVector<TemplateArgument, 4> Converted;
3703 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
3704 D->getLocation(),
3705 InstTemplateArgs,
3706 false,
3707 Converted,
3708 /*UpdateArgsWithConversions=*/true))
3709 return nullptr;
3711 // Figure out where to insert this class template explicit specialization
3712 // in the member template's set of class template explicit specializations.
3713 void *InsertPos = nullptr;
3714 ClassTemplateSpecializationDecl *PrevDecl =
3715 InstClassTemplate->findSpecialization(Converted, InsertPos);
3717 // Check whether we've already seen a conflicting instantiation of this
3718 // declaration (for instance, if there was a prior implicit instantiation).
3719 bool Ignored;
3720 if (PrevDecl &&
3721 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3722 D->getSpecializationKind(),
3723 PrevDecl,
3724 PrevDecl->getSpecializationKind(),
3725 PrevDecl->getPointOfInstantiation(),
3726 Ignored))
3727 return nullptr;
3729 // If PrevDecl was a definition and D is also a definition, diagnose.
3730 // This happens in cases like:
3732 // template<typename T, typename U>
3733 // struct Outer {
3734 // template<typename X> struct Inner;
3735 // template<> struct Inner<T> {};
3736 // template<> struct Inner<U> {};
3737 // };
3739 // Outer<int, int> outer; // error: the explicit specializations of Inner
3740 // // have the same signature.
3741 if (PrevDecl && PrevDecl->getDefinition() &&
3742 D->isThisDeclarationADefinition()) {
3743 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3744 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3745 diag::note_previous_definition);
3746 return nullptr;
3749 // Create the class template partial specialization declaration.
3750 ClassTemplateSpecializationDecl *InstD =
3751 ClassTemplateSpecializationDecl::Create(
3752 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3753 D->getLocation(), InstClassTemplate, Converted, PrevDecl);
3755 // Add this partial specialization to the set of class template partial
3756 // specializations.
3757 if (!PrevDecl)
3758 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3760 // Substitute the nested name specifier, if any.
3761 if (SubstQualifier(D, InstD))
3762 return nullptr;
3764 // Build the canonical type that describes the converted template
3765 // arguments of the class template explicit specialization.
3766 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3767 TemplateName(InstClassTemplate), Converted,
3768 SemaRef.Context.getRecordType(InstD));
3770 // Build the fully-sugared type for this class template
3771 // specialization as the user wrote in the specialization
3772 // itself. This means that we'll pretty-print the type retrieved
3773 // from the specialization's declaration the way that the user
3774 // actually wrote the specialization, rather than formatting the
3775 // name based on the "canonical" representation used to store the
3776 // template arguments in the specialization.
3777 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3778 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3779 CanonType);
3781 InstD->setAccess(D->getAccess());
3782 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3783 InstD->setSpecializationKind(D->getSpecializationKind());
3784 InstD->setTypeAsWritten(WrittenTy);
3785 InstD->setExternLoc(D->getExternLoc());
3786 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3788 Owner->addDecl(InstD);
3790 // Instantiate the members of the class-scope explicit specialization eagerly.
3791 // We don't have support for lazy instantiation of an explicit specialization
3792 // yet, and MSVC eagerly instantiates in this case.
3793 // FIXME: This is wrong in standard C++.
3794 if (D->isThisDeclarationADefinition() &&
3795 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3796 TSK_ImplicitInstantiation,
3797 /*Complain=*/true))
3798 return nullptr;
3800 return InstD;
3803 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3804 VarTemplateSpecializationDecl *D) {
3806 TemplateArgumentListInfo VarTemplateArgsInfo;
3807 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3808 assert(VarTemplate &&
3809 "A template specialization without specialized template?");
3811 VarTemplateDecl *InstVarTemplate =
3812 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3813 D->getLocation(), VarTemplate, TemplateArgs));
3814 if (!InstVarTemplate)
3815 return nullptr;
3817 // Substitute the current template arguments.
3818 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3819 D->getTemplateArgsInfo()) {
3820 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3821 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3823 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3824 TemplateArgs, VarTemplateArgsInfo))
3825 return nullptr;
3828 // Check that the template argument list is well-formed for this template.
3829 SmallVector<TemplateArgument, 4> Converted;
3830 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3831 VarTemplateArgsInfo, false, Converted,
3832 /*UpdateArgsWithConversions=*/true))
3833 return nullptr;
3835 // Check whether we've already seen a declaration of this specialization.
3836 void *InsertPos = nullptr;
3837 VarTemplateSpecializationDecl *PrevDecl =
3838 InstVarTemplate->findSpecialization(Converted, InsertPos);
3840 // Check whether we've already seen a conflicting instantiation of this
3841 // declaration (for instance, if there was a prior implicit instantiation).
3842 bool Ignored;
3843 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
3844 D->getLocation(), D->getSpecializationKind(), PrevDecl,
3845 PrevDecl->getSpecializationKind(),
3846 PrevDecl->getPointOfInstantiation(), Ignored))
3847 return nullptr;
3849 return VisitVarTemplateSpecializationDecl(
3850 InstVarTemplate, D, VarTemplateArgsInfo, Converted, PrevDecl);
3853 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3854 VarTemplateDecl *VarTemplate, VarDecl *D,
3855 const TemplateArgumentListInfo &TemplateArgsInfo,
3856 ArrayRef<TemplateArgument> Converted,
3857 VarTemplateSpecializationDecl *PrevDecl) {
3859 // Do substitution on the type of the declaration
3860 TypeSourceInfo *DI =
3861 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3862 D->getTypeSpecStartLoc(), D->getDeclName());
3863 if (!DI)
3864 return nullptr;
3866 if (DI->getType()->isFunctionType()) {
3867 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3868 << D->isStaticDataMember() << DI->getType();
3869 return nullptr;
3872 // Build the instantiated declaration
3873 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3874 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3875 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
3876 Var->setTemplateArgsInfo(TemplateArgsInfo);
3877 if (!PrevDecl) {
3878 void *InsertPos = nullptr;
3879 VarTemplate->findSpecialization(Converted, InsertPos);
3880 VarTemplate->AddSpecialization(Var, InsertPos);
3883 if (SemaRef.getLangOpts().OpenCL)
3884 SemaRef.deduceOpenCLAddressSpace(Var);
3886 // Substitute the nested name specifier, if any.
3887 if (SubstQualifier(D, Var))
3888 return nullptr;
3890 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
3891 StartingScope, false, PrevDecl);
3893 return Var;
3896 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3897 llvm_unreachable("@defs is not supported in Objective-C++");
3900 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3901 // FIXME: We need to be able to instantiate FriendTemplateDecls.
3902 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3903 DiagnosticsEngine::Error,
3904 "cannot instantiate %0 yet");
3905 SemaRef.Diag(D->getLocation(), DiagID)
3906 << D->getDeclKindName();
3908 return nullptr;
3911 Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
3912 llvm_unreachable("Concept definitions cannot reside inside a template");
3915 Decl *
3916 TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
3917 return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
3918 D->getBeginLoc());
3921 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
3922 llvm_unreachable("Unexpected decl");
3925 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
3926 const MultiLevelTemplateArgumentList &TemplateArgs) {
3927 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3928 if (D->isInvalidDecl())
3929 return nullptr;
3931 Decl *SubstD;
3932 runWithSufficientStackSpace(D->getLocation(), [&] {
3933 SubstD = Instantiator.Visit(D);
3935 return SubstD;
3938 void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK,
3939 FunctionDecl *Orig, QualType &T,
3940 TypeSourceInfo *&TInfo,
3941 DeclarationNameInfo &NameInfo) {
3942 assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual);
3944 // C++2a [class.compare.default]p3:
3945 // the return type is replaced with bool
3946 auto *FPT = T->castAs<FunctionProtoType>();
3947 T = SemaRef.Context.getFunctionType(
3948 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
3950 // Update the return type in the source info too. The most straightforward
3951 // way is to create new TypeSourceInfo for the new type. Use the location of
3952 // the '= default' as the location of the new type.
3954 // FIXME: Set the correct return type when we initially transform the type,
3955 // rather than delaying it to now.
3956 TypeSourceInfo *NewTInfo =
3957 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
3958 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
3959 assert(OldLoc && "type of function is not a function type?");
3960 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
3961 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
3962 NewLoc.setParam(I, OldLoc.getParam(I));
3963 TInfo = NewTInfo;
3965 // and the declarator-id is replaced with operator==
3966 NameInfo.setName(
3967 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
3970 FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
3971 FunctionDecl *Spaceship) {
3972 if (Spaceship->isInvalidDecl())
3973 return nullptr;
3975 // C++2a [class.compare.default]p3:
3976 // an == operator function is declared implicitly [...] with the same
3977 // access and function-definition and in the same class scope as the
3978 // three-way comparison operator function
3979 MultiLevelTemplateArgumentList NoTemplateArgs;
3980 NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite);
3981 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
3982 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
3983 Decl *R;
3984 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
3985 R = Instantiator.VisitCXXMethodDecl(
3986 MD, nullptr, None,
3987 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
3988 } else {
3989 assert(Spaceship->getFriendObjectKind() &&
3990 "defaulted spaceship is neither a member nor a friend");
3992 R = Instantiator.VisitFunctionDecl(
3993 Spaceship, nullptr,
3994 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
3995 if (!R)
3996 return nullptr;
3998 FriendDecl *FD =
3999 FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4000 cast<NamedDecl>(R), Spaceship->getBeginLoc());
4001 FD->setAccess(AS_public);
4002 RD->addDecl(FD);
4004 return cast_or_null<FunctionDecl>(R);
4007 /// Instantiates a nested template parameter list in the current
4008 /// instantiation context.
4010 /// \param L The parameter list to instantiate
4012 /// \returns NULL if there was an error
4013 TemplateParameterList *
4014 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
4015 // Get errors for all the parameters before bailing out.
4016 bool Invalid = false;
4018 unsigned N = L->size();
4019 typedef SmallVector<NamedDecl *, 8> ParamVector;
4020 ParamVector Params;
4021 Params.reserve(N);
4022 for (auto &P : *L) {
4023 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4024 Params.push_back(D);
4025 Invalid = Invalid || !D || D->isInvalidDecl();
4028 // Clean up if we had an error.
4029 if (Invalid)
4030 return nullptr;
4032 // FIXME: Concepts: Substitution into requires clause should only happen when
4033 // checking satisfaction.
4034 Expr *InstRequiresClause = nullptr;
4035 if (Expr *E = L->getRequiresClause()) {
4036 EnterExpressionEvaluationContext ConstantEvaluated(
4037 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
4038 ExprResult Res = SemaRef.SubstExpr(E, TemplateArgs);
4039 if (Res.isInvalid() || !Res.isUsable()) {
4040 return nullptr;
4042 InstRequiresClause = Res.get();
4045 TemplateParameterList *InstL
4046 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
4047 L->getLAngleLoc(), Params,
4048 L->getRAngleLoc(), InstRequiresClause);
4049 return InstL;
4052 TemplateParameterList *
4053 Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
4054 const MultiLevelTemplateArgumentList &TemplateArgs) {
4055 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4056 return Instantiator.SubstTemplateParams(Params);
4059 /// Instantiate the declaration of a class template partial
4060 /// specialization.
4062 /// \param ClassTemplate the (instantiated) class template that is partially
4063 // specialized by the instantiation of \p PartialSpec.
4065 /// \param PartialSpec the (uninstantiated) class template partial
4066 /// specialization that we are instantiating.
4068 /// \returns The instantiated partial specialization, if successful; otherwise,
4069 /// NULL to indicate an error.
4070 ClassTemplatePartialSpecializationDecl *
4071 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
4072 ClassTemplateDecl *ClassTemplate,
4073 ClassTemplatePartialSpecializationDecl *PartialSpec) {
4074 // Create a local instantiation scope for this class template partial
4075 // specialization, which will contain the instantiations of the template
4076 // parameters.
4077 LocalInstantiationScope Scope(SemaRef);
4079 // Substitute into the template parameters of the class template partial
4080 // specialization.
4081 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4082 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4083 if (!InstParams)
4084 return nullptr;
4086 // Substitute into the template arguments of the class template partial
4087 // specialization.
4088 const ASTTemplateArgumentListInfo *TemplArgInfo
4089 = PartialSpec->getTemplateArgsAsWritten();
4090 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4091 TemplArgInfo->RAngleLoc);
4092 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4093 InstTemplateArgs))
4094 return nullptr;
4096 // Check that the template argument list is well-formed for this
4097 // class template.
4098 SmallVector<TemplateArgument, 4> Converted;
4099 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
4100 PartialSpec->getLocation(),
4101 InstTemplateArgs,
4102 false,
4103 Converted))
4104 return nullptr;
4106 // Check these arguments are valid for a template partial specialization.
4107 if (SemaRef.CheckTemplatePartialSpecializationArgs(
4108 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4109 Converted))
4110 return nullptr;
4112 // Figure out where to insert this class template partial specialization
4113 // in the member template's set of class template partial specializations.
4114 void *InsertPos = nullptr;
4115 ClassTemplateSpecializationDecl *PrevDecl
4116 = ClassTemplate->findPartialSpecialization(Converted, InstParams,
4117 InsertPos);
4119 // Build the canonical type that describes the converted template
4120 // arguments of the class template partial specialization.
4121 QualType CanonType
4122 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
4123 Converted);
4125 // Build the fully-sugared type for this class template
4126 // specialization as the user wrote in the specialization
4127 // itself. This means that we'll pretty-print the type retrieved
4128 // from the specialization's declaration the way that the user
4129 // actually wrote the specialization, rather than formatting the
4130 // name based on the "canonical" representation used to store the
4131 // template arguments in the specialization.
4132 TypeSourceInfo *WrittenTy
4133 = SemaRef.Context.getTemplateSpecializationTypeInfo(
4134 TemplateName(ClassTemplate),
4135 PartialSpec->getLocation(),
4136 InstTemplateArgs,
4137 CanonType);
4139 if (PrevDecl) {
4140 // We've already seen a partial specialization with the same template
4141 // parameters and template arguments. This can happen, for example, when
4142 // substituting the outer template arguments ends up causing two
4143 // class template partial specializations of a member class template
4144 // to have identical forms, e.g.,
4146 // template<typename T, typename U>
4147 // struct Outer {
4148 // template<typename X, typename Y> struct Inner;
4149 // template<typename Y> struct Inner<T, Y>;
4150 // template<typename Y> struct Inner<U, Y>;
4151 // };
4153 // Outer<int, int> outer; // error: the partial specializations of Inner
4154 // // have the same signature.
4155 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
4156 << WrittenTy->getType();
4157 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4158 << SemaRef.Context.getTypeDeclType(PrevDecl);
4159 return nullptr;
4163 // Create the class template partial specialization declaration.
4164 ClassTemplatePartialSpecializationDecl *InstPartialSpec =
4165 ClassTemplatePartialSpecializationDecl::Create(
4166 SemaRef.Context, PartialSpec->getTagKind(), Owner,
4167 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4168 ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
4169 // Substitute the nested name specifier, if any.
4170 if (SubstQualifier(PartialSpec, InstPartialSpec))
4171 return nullptr;
4173 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4174 InstPartialSpec->setTypeAsWritten(WrittenTy);
4176 // Check the completed partial specialization.
4177 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4179 // Add this partial specialization to the set of class template partial
4180 // specializations.
4181 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4182 /*InsertPos=*/nullptr);
4183 return InstPartialSpec;
4186 /// Instantiate the declaration of a variable template partial
4187 /// specialization.
4189 /// \param VarTemplate the (instantiated) variable template that is partially
4190 /// specialized by the instantiation of \p PartialSpec.
4192 /// \param PartialSpec the (uninstantiated) variable template partial
4193 /// specialization that we are instantiating.
4195 /// \returns The instantiated partial specialization, if successful; otherwise,
4196 /// NULL to indicate an error.
4197 VarTemplatePartialSpecializationDecl *
4198 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
4199 VarTemplateDecl *VarTemplate,
4200 VarTemplatePartialSpecializationDecl *PartialSpec) {
4201 // Create a local instantiation scope for this variable template partial
4202 // specialization, which will contain the instantiations of the template
4203 // parameters.
4204 LocalInstantiationScope Scope(SemaRef);
4206 // Substitute into the template parameters of the variable template partial
4207 // specialization.
4208 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4209 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4210 if (!InstParams)
4211 return nullptr;
4213 // Substitute into the template arguments of the variable template partial
4214 // specialization.
4215 const ASTTemplateArgumentListInfo *TemplArgInfo
4216 = PartialSpec->getTemplateArgsAsWritten();
4217 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4218 TemplArgInfo->RAngleLoc);
4219 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4220 InstTemplateArgs))
4221 return nullptr;
4223 // Check that the template argument list is well-formed for this
4224 // class template.
4225 SmallVector<TemplateArgument, 4> Converted;
4226 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
4227 InstTemplateArgs, false, Converted))
4228 return nullptr;
4230 // Check these arguments are valid for a template partial specialization.
4231 if (SemaRef.CheckTemplatePartialSpecializationArgs(
4232 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4233 Converted))
4234 return nullptr;
4236 // Figure out where to insert this variable template partial specialization
4237 // in the member template's set of variable template partial specializations.
4238 void *InsertPos = nullptr;
4239 VarTemplateSpecializationDecl *PrevDecl =
4240 VarTemplate->findPartialSpecialization(Converted, InstParams, InsertPos);
4242 // Build the canonical type that describes the converted template
4243 // arguments of the variable template partial specialization.
4244 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4245 TemplateName(VarTemplate), Converted);
4247 // Build the fully-sugared type for this variable template
4248 // specialization as the user wrote in the specialization
4249 // itself. This means that we'll pretty-print the type retrieved
4250 // from the specialization's declaration the way that the user
4251 // actually wrote the specialization, rather than formatting the
4252 // name based on the "canonical" representation used to store the
4253 // template arguments in the specialization.
4254 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
4255 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
4256 CanonType);
4258 if (PrevDecl) {
4259 // We've already seen a partial specialization with the same template
4260 // parameters and template arguments. This can happen, for example, when
4261 // substituting the outer template arguments ends up causing two
4262 // variable template partial specializations of a member variable template
4263 // to have identical forms, e.g.,
4265 // template<typename T, typename U>
4266 // struct Outer {
4267 // template<typename X, typename Y> pair<X,Y> p;
4268 // template<typename Y> pair<T, Y> p;
4269 // template<typename Y> pair<U, Y> p;
4270 // };
4272 // Outer<int, int> outer; // error: the partial specializations of Inner
4273 // // have the same signature.
4274 SemaRef.Diag(PartialSpec->getLocation(),
4275 diag::err_var_partial_spec_redeclared)
4276 << WrittenTy->getType();
4277 SemaRef.Diag(PrevDecl->getLocation(),
4278 diag::note_var_prev_partial_spec_here);
4279 return nullptr;
4282 // Do substitution on the type of the declaration
4283 TypeSourceInfo *DI = SemaRef.SubstType(
4284 PartialSpec->getTypeSourceInfo(), TemplateArgs,
4285 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4286 if (!DI)
4287 return nullptr;
4289 if (DI->getType()->isFunctionType()) {
4290 SemaRef.Diag(PartialSpec->getLocation(),
4291 diag::err_variable_instantiates_to_function)
4292 << PartialSpec->isStaticDataMember() << DI->getType();
4293 return nullptr;
4296 // Create the variable template partial specialization declaration.
4297 VarTemplatePartialSpecializationDecl *InstPartialSpec =
4298 VarTemplatePartialSpecializationDecl::Create(
4299 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4300 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4301 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
4303 // Substitute the nested name specifier, if any.
4304 if (SubstQualifier(PartialSpec, InstPartialSpec))
4305 return nullptr;
4307 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4308 InstPartialSpec->setTypeAsWritten(WrittenTy);
4310 // Check the completed partial specialization.
4311 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4313 // Add this partial specialization to the set of variable template partial
4314 // specializations. The instantiation of the initializer is not necessary.
4315 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4317 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4318 LateAttrs, Owner, StartingScope);
4320 return InstPartialSpec;
4323 TypeSourceInfo*
4324 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
4325 SmallVectorImpl<ParmVarDecl *> &Params) {
4326 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4327 assert(OldTInfo && "substituting function without type source info");
4328 assert(Params.empty() && "parameter vector is non-empty at start");
4330 CXXRecordDecl *ThisContext = nullptr;
4331 Qualifiers ThisTypeQuals;
4332 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4333 ThisContext = cast<CXXRecordDecl>(Owner);
4334 ThisTypeQuals = Method->getMethodQualifiers();
4337 TypeSourceInfo *NewTInfo
4338 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
4339 D->getTypeSpecStartLoc(),
4340 D->getDeclName(),
4341 ThisContext, ThisTypeQuals);
4342 if (!NewTInfo)
4343 return nullptr;
4345 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4346 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4347 if (NewTInfo != OldTInfo) {
4348 // Get parameters from the new type info.
4349 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4350 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4351 unsigned NewIdx = 0;
4352 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4353 OldIdx != NumOldParams; ++OldIdx) {
4354 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4355 if (!OldParam)
4356 return nullptr;
4358 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
4360 Optional<unsigned> NumArgumentsInExpansion;
4361 if (OldParam->isParameterPack())
4362 NumArgumentsInExpansion =
4363 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4364 TemplateArgs);
4365 if (!NumArgumentsInExpansion) {
4366 // Simple case: normal parameter, or a parameter pack that's
4367 // instantiated to a (still-dependent) parameter pack.
4368 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4369 Params.push_back(NewParam);
4370 Scope->InstantiatedLocal(OldParam, NewParam);
4371 } else {
4372 // Parameter pack expansion: make the instantiation an argument pack.
4373 Scope->MakeInstantiatedLocalArgPack(OldParam);
4374 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
4375 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4376 Params.push_back(NewParam);
4377 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4381 } else {
4382 // The function type itself was not dependent and therefore no
4383 // substitution occurred. However, we still need to instantiate
4384 // the function parameters themselves.
4385 const FunctionProtoType *OldProto =
4386 cast<FunctionProtoType>(OldProtoLoc.getType());
4387 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4388 ++i) {
4389 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4390 if (!OldParam) {
4391 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4392 D, D->getLocation(), OldProto->getParamType(i)));
4393 continue;
4396 ParmVarDecl *Parm =
4397 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4398 if (!Parm)
4399 return nullptr;
4400 Params.push_back(Parm);
4403 } else {
4404 // If the type of this function, after ignoring parentheses, is not
4405 // *directly* a function type, then we're instantiating a function that
4406 // was declared via a typedef or with attributes, e.g.,
4408 // typedef int functype(int, int);
4409 // functype func;
4410 // int __cdecl meth(int, int);
4412 // In this case, we'll just go instantiate the ParmVarDecls that we
4413 // synthesized in the method declaration.
4414 SmallVector<QualType, 4> ParamTypes;
4415 Sema::ExtParameterInfoBuilder ExtParamInfos;
4416 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4417 TemplateArgs, ParamTypes, &Params,
4418 ExtParamInfos))
4419 return nullptr;
4422 return NewTInfo;
4425 /// Introduce the instantiated function parameters into the local
4426 /// instantiation scope, and set the parameter names to those used
4427 /// in the template.
4428 bool Sema::addInstantiatedParametersToScope(
4429 FunctionDecl *Function, const FunctionDecl *PatternDecl,
4430 LocalInstantiationScope &Scope,
4431 const MultiLevelTemplateArgumentList &TemplateArgs) {
4432 unsigned FParamIdx = 0;
4433 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4434 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4435 if (!PatternParam->isParameterPack()) {
4436 // Simple case: not a parameter pack.
4437 assert(FParamIdx < Function->getNumParams());
4438 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4439 FunctionParam->setDeclName(PatternParam->getDeclName());
4440 // If the parameter's type is not dependent, update it to match the type
4441 // in the pattern. They can differ in top-level cv-qualifiers, and we want
4442 // the pattern's type here. If the type is dependent, they can't differ,
4443 // per core issue 1668. Substitute into the type from the pattern, in case
4444 // it's instantiation-dependent.
4445 // FIXME: Updating the type to work around this is at best fragile.
4446 if (!PatternDecl->getType()->isDependentType()) {
4447 QualType T = SubstType(PatternParam->getType(), TemplateArgs,
4448 FunctionParam->getLocation(),
4449 FunctionParam->getDeclName());
4450 if (T.isNull())
4451 return true;
4452 FunctionParam->setType(T);
4455 Scope.InstantiatedLocal(PatternParam, FunctionParam);
4456 ++FParamIdx;
4457 continue;
4460 // Expand the parameter pack.
4461 Scope.MakeInstantiatedLocalArgPack(PatternParam);
4462 Optional<unsigned> NumArgumentsInExpansion =
4463 getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4464 if (NumArgumentsInExpansion) {
4465 QualType PatternType =
4466 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4467 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4468 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4469 FunctionParam->setDeclName(PatternParam->getDeclName());
4470 if (!PatternDecl->getType()->isDependentType()) {
4471 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
4472 QualType T =
4473 SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
4474 FunctionParam->getDeclName());
4475 if (T.isNull())
4476 return true;
4477 FunctionParam->setType(T);
4480 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4481 ++FParamIdx;
4486 return false;
4489 bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
4490 ParmVarDecl *Param) {
4491 assert(Param->hasUninstantiatedDefaultArg());
4492 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4494 EnterExpressionEvaluationContext EvalContext(
4495 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4497 // Instantiate the expression.
4499 // FIXME: Pass in a correct Pattern argument, otherwise
4500 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4502 // template<typename T>
4503 // struct A {
4504 // static int FooImpl();
4506 // template<typename Tp>
4507 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4508 // // template argument list [[T], [Tp]], should be [[Tp]].
4509 // friend A<Tp> Foo(int a);
4510 // };
4512 // template<typename T>
4513 // A<T> Foo(int a = A<T>::FooImpl());
4514 MultiLevelTemplateArgumentList TemplateArgs
4515 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4517 InstantiatingTemplate Inst(*this, CallLoc, Param,
4518 TemplateArgs.getInnermost());
4519 if (Inst.isInvalid())
4520 return true;
4521 if (Inst.isAlreadyInstantiating()) {
4522 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4523 Param->setInvalidDecl();
4524 return true;
4527 ExprResult Result;
4529 // C++ [dcl.fct.default]p5:
4530 // The names in the [default argument] expression are bound, and
4531 // the semantic constraints are checked, at the point where the
4532 // default argument expression appears.
4533 ContextRAII SavedContext(*this, FD);
4534 LocalInstantiationScope Local(*this);
4536 FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(
4537 /*ForDefinition*/ false);
4538 if (addInstantiatedParametersToScope(FD, Pattern, Local, TemplateArgs))
4539 return true;
4541 runWithSufficientStackSpace(CallLoc, [&] {
4542 Result = SubstInitializer(UninstExpr, TemplateArgs,
4543 /*DirectInit*/false);
4546 if (Result.isInvalid())
4547 return true;
4549 // Check the expression as an initializer for the parameter.
4550 InitializedEntity Entity
4551 = InitializedEntity::InitializeParameter(Context, Param);
4552 InitializationKind Kind = InitializationKind::CreateCopy(
4553 Param->getLocation(),
4554 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4555 Expr *ResultE = Result.getAs<Expr>();
4557 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4558 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4559 if (Result.isInvalid())
4560 return true;
4562 Result =
4563 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4564 /*DiscardedValue*/ false);
4565 if (Result.isInvalid())
4566 return true;
4568 // Remember the instantiated default argument.
4569 Param->setDefaultArg(Result.getAs<Expr>());
4570 if (ASTMutationListener *L = getASTMutationListener())
4571 L->DefaultArgumentInstantiated(Param);
4573 return false;
4576 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
4577 FunctionDecl *Decl) {
4578 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4579 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
4580 return;
4582 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4583 InstantiatingTemplate::ExceptionSpecification());
4584 if (Inst.isInvalid()) {
4585 // We hit the instantiation depth limit. Clear the exception specification
4586 // so that our callers don't have to cope with EST_Uninstantiated.
4587 UpdateExceptionSpec(Decl, EST_None);
4588 return;
4590 if (Inst.isAlreadyInstantiating()) {
4591 // This exception specification indirectly depends on itself. Reject.
4592 // FIXME: Corresponding rule in the standard?
4593 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4594 UpdateExceptionSpec(Decl, EST_None);
4595 return;
4598 // Enter the scope of this instantiation. We don't use
4599 // PushDeclContext because we don't have a scope.
4600 Sema::ContextRAII savedContext(*this, Decl);
4601 LocalInstantiationScope Scope(*this);
4603 MultiLevelTemplateArgumentList TemplateArgs =
4604 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
4606 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4607 // here, because for a non-defining friend declaration in a class template,
4608 // we don't store enough information to map back to the friend declaration in
4609 // the template.
4610 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4611 if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
4612 UpdateExceptionSpec(Decl, EST_None);
4613 return;
4616 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
4617 TemplateArgs);
4620 /// Initializes the common fields of an instantiation function
4621 /// declaration (New) from the corresponding fields of its template (Tmpl).
4623 /// \returns true if there was an error
4624 bool
4625 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
4626 FunctionDecl *Tmpl) {
4627 New->setImplicit(Tmpl->isImplicit());
4629 // Forward the mangling number from the template to the instantiated decl.
4630 SemaRef.Context.setManglingNumber(New,
4631 SemaRef.Context.getManglingNumber(Tmpl));
4633 // If we are performing substituting explicitly-specified template arguments
4634 // or deduced template arguments into a function template and we reach this
4635 // point, we are now past the point where SFINAE applies and have committed
4636 // to keeping the new function template specialization. We therefore
4637 // convert the active template instantiation for the function template
4638 // into a template instantiation for this specific function template
4639 // specialization, which is not a SFINAE context, so that we diagnose any
4640 // further errors in the declaration itself.
4642 // FIXME: This is a hack.
4643 typedef Sema::CodeSynthesisContext ActiveInstType;
4644 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4645 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4646 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4647 if (FunctionTemplateDecl *FunTmpl
4648 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
4649 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
4650 "Deduction from the wrong function template?");
4651 (void) FunTmpl;
4652 SemaRef.InstantiatingSpecializations.erase(
4653 {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
4654 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4655 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4656 ActiveInst.Entity = New;
4657 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4661 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4662 assert(Proto && "Function template without prototype?");
4664 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4665 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4667 // DR1330: In C++11, defer instantiation of a non-trivial
4668 // exception specification.
4669 // DR1484: Local classes and their members are instantiated along with the
4670 // containing function.
4671 if (SemaRef.getLangOpts().CPlusPlus11 &&
4672 EPI.ExceptionSpec.Type != EST_None &&
4673 EPI.ExceptionSpec.Type != EST_DynamicNone &&
4674 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
4675 !Tmpl->isInLocalScopeForInstantiation()) {
4676 FunctionDecl *ExceptionSpecTemplate = Tmpl;
4677 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
4678 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4679 ExceptionSpecificationType NewEST = EST_Uninstantiated;
4680 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
4681 NewEST = EST_Unevaluated;
4683 // Mark the function has having an uninstantiated exception specification.
4684 const FunctionProtoType *NewProto
4685 = New->getType()->getAs<FunctionProtoType>();
4686 assert(NewProto && "Template instantiation without function prototype?");
4687 EPI = NewProto->getExtProtoInfo();
4688 EPI.ExceptionSpec.Type = NewEST;
4689 EPI.ExceptionSpec.SourceDecl = New;
4690 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4691 New->setType(SemaRef.Context.getFunctionType(
4692 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4693 } else {
4694 Sema::ContextRAII SwitchContext(SemaRef, New);
4695 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4699 // Get the definition. Leaves the variable unchanged if undefined.
4700 const FunctionDecl *Definition = Tmpl;
4701 Tmpl->isDefined(Definition);
4703 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4704 LateAttrs, StartingScope);
4706 return false;
4709 /// Initializes common fields of an instantiated method
4710 /// declaration (New) from the corresponding fields of its template
4711 /// (Tmpl).
4713 /// \returns true if there was an error
4714 bool
4715 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4716 CXXMethodDecl *Tmpl) {
4717 if (InitFunctionInstantiation(New, Tmpl))
4718 return true;
4720 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4721 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4723 New->setAccess(Tmpl->getAccess());
4724 if (Tmpl->isVirtualAsWritten())
4725 New->setVirtualAsWritten(true);
4727 // FIXME: New needs a pointer to Tmpl
4728 return false;
4731 bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
4732 FunctionDecl *Tmpl) {
4733 // Transfer across any unqualified lookups.
4734 if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) {
4735 SmallVector<DeclAccessPair, 32> Lookups;
4736 Lookups.reserve(DFI->getUnqualifiedLookups().size());
4737 bool AnyChanged = false;
4738 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4739 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4740 DA.getDecl(), TemplateArgs);
4741 if (!D)
4742 return true;
4743 AnyChanged |= (D != DA.getDecl());
4744 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4747 // It's unlikely that substitution will change any declarations. Don't
4748 // store an unnecessary copy in that case.
4749 New->setDefaultedFunctionInfo(
4750 AnyChanged ? FunctionDecl::DefaultedFunctionInfo::Create(
4751 SemaRef.Context, Lookups)
4752 : DFI);
4755 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4756 return false;
4759 /// Instantiate (or find existing instantiation of) a function template with a
4760 /// given set of template arguments.
4762 /// Usually this should not be used, and template argument deduction should be
4763 /// used in its place.
4764 FunctionDecl *
4765 Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
4766 const TemplateArgumentList *Args,
4767 SourceLocation Loc) {
4768 FunctionDecl *FD = FTD->getTemplatedDecl();
4770 sema::TemplateDeductionInfo Info(Loc);
4771 InstantiatingTemplate Inst(
4772 *this, Loc, FTD, Args->asArray(),
4773 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
4774 if (Inst.isInvalid())
4775 return nullptr;
4777 ContextRAII SavedContext(*this, FD);
4778 MultiLevelTemplateArgumentList MArgs(*Args);
4780 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4783 /// Instantiate the definition of the given function from its
4784 /// template.
4786 /// \param PointOfInstantiation the point at which the instantiation was
4787 /// required. Note that this is not precisely a "point of instantiation"
4788 /// for the function, but it's close.
4790 /// \param Function the already-instantiated declaration of a
4791 /// function template specialization or member function of a class template
4792 /// specialization.
4794 /// \param Recursive if true, recursively instantiates any functions that
4795 /// are required by this instantiation.
4797 /// \param DefinitionRequired if true, then we are performing an explicit
4798 /// instantiation where the body of the function is required. Complain if
4799 /// there is no such body.
4800 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4801 FunctionDecl *Function,
4802 bool Recursive,
4803 bool DefinitionRequired,
4804 bool AtEndOfTU) {
4805 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
4806 return;
4808 // Never instantiate an explicit specialization except if it is a class scope
4809 // explicit specialization.
4810 TemplateSpecializationKind TSK =
4811 Function->getTemplateSpecializationKindForInstantiation();
4812 if (TSK == TSK_ExplicitSpecialization)
4813 return;
4815 // Never implicitly instantiate a builtin; we don't actually need a function
4816 // body.
4817 if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
4818 !DefinitionRequired)
4819 return;
4821 // Don't instantiate a definition if we already have one.
4822 const FunctionDecl *ExistingDefn = nullptr;
4823 if (Function->isDefined(ExistingDefn,
4824 /*CheckForPendingFriendDefinition=*/true)) {
4825 if (ExistingDefn->isThisDeclarationADefinition())
4826 return;
4828 // If we're asked to instantiate a function whose body comes from an
4829 // instantiated friend declaration, attach the instantiated body to the
4830 // corresponding declaration of the function.
4831 assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition());
4832 Function = const_cast<FunctionDecl*>(ExistingDefn);
4835 // Find the function body that we'll be substituting.
4836 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4837 assert(PatternDecl && "instantiating a non-template");
4839 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4840 Stmt *Pattern = nullptr;
4841 if (PatternDef) {
4842 Pattern = PatternDef->getBody(PatternDef);
4843 PatternDecl = PatternDef;
4844 if (PatternDef->willHaveBody())
4845 PatternDef = nullptr;
4848 // FIXME: We need to track the instantiation stack in order to know which
4849 // definitions should be visible within this instantiation.
4850 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
4851 Function->getInstantiatedFromMemberFunction(),
4852 PatternDecl, PatternDef, TSK,
4853 /*Complain*/DefinitionRequired)) {
4854 if (DefinitionRequired)
4855 Function->setInvalidDecl();
4856 else if (TSK == TSK_ExplicitInstantiationDefinition ||
4857 (Function->isConstexpr() && !Recursive)) {
4858 // Try again at the end of the translation unit (at which point a
4859 // definition will be required).
4860 assert(!Recursive);
4861 Function->setInstantiationIsPending(true);
4862 PendingInstantiations.push_back(
4863 std::make_pair(Function, PointOfInstantiation));
4864 } else if (TSK == TSK_ImplicitInstantiation) {
4865 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4866 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4867 Diag(PointOfInstantiation, diag::warn_func_template_missing)
4868 << Function;
4869 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4870 if (getLangOpts().CPlusPlus11)
4871 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4872 << Function;
4876 return;
4879 // Postpone late parsed template instantiations.
4880 if (PatternDecl->isLateTemplateParsed() &&
4881 !LateTemplateParser) {
4882 Function->setInstantiationIsPending(true);
4883 LateParsedInstantiations.push_back(
4884 std::make_pair(Function, PointOfInstantiation));
4885 return;
4888 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
4889 std::string Name;
4890 llvm::raw_string_ostream OS(Name);
4891 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4892 /*Qualified=*/true);
4893 return Name;
4896 // If we're performing recursive template instantiation, create our own
4897 // queue of pending implicit instantiations that we will instantiate later,
4898 // while we're still within our own instantiation context.
4899 // This has to happen before LateTemplateParser below is called, so that
4900 // it marks vtables used in late parsed templates as used.
4901 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4902 /*Enabled=*/Recursive);
4903 LocalEagerInstantiationScope LocalInstantiations(*this);
4905 // Call the LateTemplateParser callback if there is a need to late parse
4906 // a templated function definition.
4907 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
4908 LateTemplateParser) {
4909 // FIXME: Optimize to allow individual templates to be deserialized.
4910 if (PatternDecl->isFromASTFile())
4911 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
4913 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
4914 assert(LPTIter != LateParsedTemplateMap.end() &&
4915 "missing LateParsedTemplate");
4916 LateTemplateParser(OpaqueParser, *LPTIter->second);
4917 Pattern = PatternDecl->getBody(PatternDecl);
4920 // Note, we should never try to instantiate a deleted function template.
4921 assert((Pattern || PatternDecl->isDefaulted() ||
4922 PatternDecl->hasSkippedBody()) &&
4923 "unexpected kind of function template definition");
4925 // C++1y [temp.explicit]p10:
4926 // Except for inline functions, declarations with types deduced from their
4927 // initializer or return value, and class template specializations, other
4928 // explicit instantiation declarations have the effect of suppressing the
4929 // implicit instantiation of the entity to which they refer.
4930 if (TSK == TSK_ExplicitInstantiationDeclaration &&
4931 !PatternDecl->isInlined() &&
4932 !PatternDecl->getReturnType()->getContainedAutoType())
4933 return;
4935 if (PatternDecl->isInlined()) {
4936 // Function, and all later redeclarations of it (from imported modules,
4937 // for instance), are now implicitly inline.
4938 for (auto *D = Function->getMostRecentDecl(); /**/;
4939 D = D->getPreviousDecl()) {
4940 D->setImplicitlyInline();
4941 if (D == Function)
4942 break;
4946 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
4947 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4948 return;
4949 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
4950 "instantiating function definition");
4952 // The instantiation is visible here, even if it was first declared in an
4953 // unimported module.
4954 Function->setVisibleDespiteOwningModule();
4956 // Copy the inner loc start from the pattern.
4957 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
4959 EnterExpressionEvaluationContext EvalContext(
4960 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4962 // Introduce a new scope where local variable instantiations will be
4963 // recorded, unless we're actually a member function within a local
4964 // class, in which case we need to merge our results with the parent
4965 // scope (of the enclosing function). The exception is instantiating
4966 // a function template specialization, since the template to be
4967 // instantiated already has references to locals properly substituted.
4968 bool MergeWithParentScope = false;
4969 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
4970 MergeWithParentScope =
4971 Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
4973 LocalInstantiationScope Scope(*this, MergeWithParentScope);
4974 auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
4975 // Special members might get their TypeSourceInfo set up w.r.t the
4976 // PatternDecl context, in which case parameters could still be pointing
4977 // back to the original class, make sure arguments are bound to the
4978 // instantiated record instead.
4979 assert(PatternDecl->isDefaulted() &&
4980 "Special member needs to be defaulted");
4981 auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
4982 if (!(PatternSM == Sema::CXXCopyConstructor ||
4983 PatternSM == Sema::CXXCopyAssignment ||
4984 PatternSM == Sema::CXXMoveConstructor ||
4985 PatternSM == Sema::CXXMoveAssignment))
4986 return;
4988 auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
4989 const auto *PatternRec =
4990 dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
4991 if (!NewRec || !PatternRec)
4992 return;
4993 if (!PatternRec->isLambda())
4994 return;
4996 struct SpecialMemberTypeInfoRebuilder
4997 : TreeTransform<SpecialMemberTypeInfoRebuilder> {
4998 using Base = TreeTransform<SpecialMemberTypeInfoRebuilder>;
4999 const CXXRecordDecl *OldDecl;
5000 CXXRecordDecl *NewDecl;
5002 SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5003 CXXRecordDecl *N)
5004 : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5006 bool TransformExceptionSpec(SourceLocation Loc,
5007 FunctionProtoType::ExceptionSpecInfo &ESI,
5008 SmallVectorImpl<QualType> &Exceptions,
5009 bool &Changed) {
5010 return false;
5013 QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5014 const RecordType *T = TL.getTypePtr();
5015 RecordDecl *Record = cast_or_null<RecordDecl>(
5016 getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
5017 if (Record != OldDecl)
5018 return Base::TransformRecordType(TLB, TL);
5020 QualType Result = getDerived().RebuildRecordType(NewDecl);
5021 if (Result.isNull())
5022 return QualType();
5024 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5025 NewTL.setNameLoc(TL.getNameLoc());
5026 return Result;
5028 } IR{*this, PatternRec, NewRec};
5030 TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5031 Function->setType(NewSI->getType());
5032 Function->setTypeSourceInfo(NewSI);
5034 ParmVarDecl *Parm = Function->getParamDecl(0);
5035 TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5036 Parm->setType(NewParmSI->getType());
5037 Parm->setTypeSourceInfo(NewParmSI);
5040 if (PatternDecl->isDefaulted()) {
5041 RebuildTypeSourceInfoForDefaultSpecialMembers();
5042 SetDeclDefaulted(Function, PatternDecl->getLocation());
5043 } else {
5044 MultiLevelTemplateArgumentList TemplateArgs =
5045 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
5047 // Substitute into the qualifier; we can get a substitution failure here
5048 // through evil use of alias templates.
5049 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5050 // of the) lexical context of the pattern?
5051 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5053 ActOnStartOfFunctionDef(nullptr, Function);
5055 // Enter the scope of this instantiation. We don't use
5056 // PushDeclContext because we don't have a scope.
5057 Sema::ContextRAII savedContext(*this, Function);
5059 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
5060 TemplateArgs))
5061 return;
5063 StmtResult Body;
5064 if (PatternDecl->hasSkippedBody()) {
5065 ActOnSkippedFunctionBody(Function);
5066 Body = nullptr;
5067 } else {
5068 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5069 // If this is a constructor, instantiate the member initializers.
5070 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
5071 TemplateArgs);
5073 // If this is an MS ABI dllexport default constructor, instantiate any
5074 // default arguments.
5075 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5076 Ctor->isDefaultConstructor()) {
5077 InstantiateDefaultCtorDefaultArgs(Ctor);
5081 // Instantiate the function body.
5082 Body = SubstStmt(Pattern, TemplateArgs);
5084 if (Body.isInvalid())
5085 Function->setInvalidDecl();
5087 // FIXME: finishing the function body while in an expression evaluation
5088 // context seems wrong. Investigate more.
5089 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5091 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5093 if (auto *Listener = getASTMutationListener())
5094 Listener->FunctionDefinitionInstantiated(Function);
5096 savedContext.pop();
5099 DeclGroupRef DG(Function);
5100 Consumer.HandleTopLevelDecl(DG);
5102 // This class may have local implicit instantiations that need to be
5103 // instantiation within this scope.
5104 LocalInstantiations.perform();
5105 Scope.Exit();
5106 GlobalInstantiations.perform();
5109 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
5110 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
5111 const TemplateArgumentList &TemplateArgList,
5112 const TemplateArgumentListInfo &TemplateArgsInfo,
5113 SmallVectorImpl<TemplateArgument> &Converted,
5114 SourceLocation PointOfInstantiation,
5115 LateInstantiatedAttrVec *LateAttrs,
5116 LocalInstantiationScope *StartingScope) {
5117 if (FromVar->isInvalidDecl())
5118 return nullptr;
5120 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
5121 if (Inst.isInvalid())
5122 return nullptr;
5124 MultiLevelTemplateArgumentList TemplateArgLists;
5125 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
5127 // Instantiate the first declaration of the variable template: for a partial
5128 // specialization of a static data member template, the first declaration may
5129 // or may not be the declaration in the class; if it's in the class, we want
5130 // to instantiate a member in the class (a declaration), and if it's outside,
5131 // we want to instantiate a definition.
5133 // If we're instantiating an explicitly-specialized member template or member
5134 // partial specialization, don't do this. The member specialization completely
5135 // replaces the original declaration in this case.
5136 bool IsMemberSpec = false;
5137 if (VarTemplatePartialSpecializationDecl *PartialSpec =
5138 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
5139 IsMemberSpec = PartialSpec->isMemberSpecialization();
5140 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
5141 IsMemberSpec = FromTemplate->isMemberSpecialization();
5142 if (!IsMemberSpec)
5143 FromVar = FromVar->getFirstDecl();
5145 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
5146 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
5147 MultiLevelList);
5149 // TODO: Set LateAttrs and StartingScope ...
5151 return cast_or_null<VarTemplateSpecializationDecl>(
5152 Instantiator.VisitVarTemplateSpecializationDecl(
5153 VarTemplate, FromVar, TemplateArgsInfo, Converted));
5156 /// Instantiates a variable template specialization by completing it
5157 /// with appropriate type information and initializer.
5158 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
5159 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
5160 const MultiLevelTemplateArgumentList &TemplateArgs) {
5161 assert(PatternDecl->isThisDeclarationADefinition() &&
5162 "don't have a definition to instantiate from");
5164 // Do substitution on the type of the declaration
5165 TypeSourceInfo *DI =
5166 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
5167 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
5168 if (!DI)
5169 return nullptr;
5171 // Update the type of this variable template specialization.
5172 VarSpec->setType(DI->getType());
5174 // Convert the declaration into a definition now.
5175 VarSpec->setCompleteDefinition();
5177 // Instantiate the initializer.
5178 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
5180 if (getLangOpts().OpenCL)
5181 deduceOpenCLAddressSpace(VarSpec);
5183 return VarSpec;
5186 /// BuildVariableInstantiation - Used after a new variable has been created.
5187 /// Sets basic variable data and decides whether to postpone the
5188 /// variable instantiation.
5189 void Sema::BuildVariableInstantiation(
5190 VarDecl *NewVar, VarDecl *OldVar,
5191 const MultiLevelTemplateArgumentList &TemplateArgs,
5192 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
5193 LocalInstantiationScope *StartingScope,
5194 bool InstantiatingVarTemplate,
5195 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
5196 // Instantiating a partial specialization to produce a partial
5197 // specialization.
5198 bool InstantiatingVarTemplatePartialSpec =
5199 isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
5200 isa<VarTemplatePartialSpecializationDecl>(NewVar);
5201 // Instantiating from a variable template (or partial specialization) to
5202 // produce a variable template specialization.
5203 bool InstantiatingSpecFromTemplate =
5204 isa<VarTemplateSpecializationDecl>(NewVar) &&
5205 (OldVar->getDescribedVarTemplate() ||
5206 isa<VarTemplatePartialSpecializationDecl>(OldVar));
5208 // If we are instantiating a local extern declaration, the
5209 // instantiation belongs lexically to the containing function.
5210 // If we are instantiating a static data member defined
5211 // out-of-line, the instantiation will have the same lexical
5212 // context (which will be a namespace scope) as the template.
5213 if (OldVar->isLocalExternDecl()) {
5214 NewVar->setLocalExternDecl();
5215 NewVar->setLexicalDeclContext(Owner);
5216 } else if (OldVar->isOutOfLine())
5217 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
5218 NewVar->setTSCSpec(OldVar->getTSCSpec());
5219 NewVar->setInitStyle(OldVar->getInitStyle());
5220 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
5221 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
5222 NewVar->setConstexpr(OldVar->isConstexpr());
5223 NewVar->setInitCapture(OldVar->isInitCapture());
5224 NewVar->setPreviousDeclInSameBlockScope(
5225 OldVar->isPreviousDeclInSameBlockScope());
5226 NewVar->setAccess(OldVar->getAccess());
5228 if (!OldVar->isStaticDataMember()) {
5229 if (OldVar->isUsed(false))
5230 NewVar->setIsUsed();
5231 NewVar->setReferenced(OldVar->isReferenced());
5234 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
5236 LookupResult Previous(
5237 *this, NewVar->getDeclName(), NewVar->getLocation(),
5238 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
5239 : Sema::LookupOrdinaryName,
5240 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
5241 : forRedeclarationInCurContext());
5243 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
5244 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
5245 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
5246 // We have a previous declaration. Use that one, so we merge with the
5247 // right type.
5248 if (NamedDecl *NewPrev = FindInstantiatedDecl(
5249 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
5250 Previous.addDecl(NewPrev);
5251 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
5252 OldVar->hasLinkage()) {
5253 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
5254 } else if (PrevDeclForVarTemplateSpecialization) {
5255 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
5257 CheckVariableDeclaration(NewVar, Previous);
5259 if (!InstantiatingVarTemplate) {
5260 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
5261 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
5262 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
5265 if (!OldVar->isOutOfLine()) {
5266 if (NewVar->getDeclContext()->isFunctionOrMethod())
5267 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
5270 // Link instantiations of static data members back to the template from
5271 // which they were instantiated.
5273 // Don't do this when instantiating a template (we link the template itself
5274 // back in that case) nor when instantiating a static data member template
5275 // (that's not a member specialization).
5276 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
5277 !InstantiatingSpecFromTemplate)
5278 NewVar->setInstantiationOfStaticDataMember(OldVar,
5279 TSK_ImplicitInstantiation);
5281 // If the pattern is an (in-class) explicit specialization, then the result
5282 // is also an explicit specialization.
5283 if (VarTemplateSpecializationDecl *OldVTSD =
5284 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
5285 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
5286 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
5287 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
5288 TSK_ExplicitSpecialization);
5291 // Forward the mangling number from the template to the instantiated decl.
5292 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
5293 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
5295 // Figure out whether to eagerly instantiate the initializer.
5296 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
5297 // We're producing a template. Don't instantiate the initializer yet.
5298 } else if (NewVar->getType()->isUndeducedType()) {
5299 // We need the type to complete the declaration of the variable.
5300 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5301 } else if (InstantiatingSpecFromTemplate ||
5302 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
5303 !NewVar->isThisDeclarationADefinition())) {
5304 // Delay instantiation of the initializer for variable template
5305 // specializations or inline static data members until a definition of the
5306 // variable is needed.
5307 } else {
5308 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5311 // Diagnose unused local variables with dependent types, where the diagnostic
5312 // will have been deferred.
5313 if (!NewVar->isInvalidDecl() &&
5314 NewVar->getDeclContext()->isFunctionOrMethod() &&
5315 OldVar->getType()->isDependentType())
5316 DiagnoseUnusedDecl(NewVar);
5319 /// Instantiate the initializer of a variable.
5320 void Sema::InstantiateVariableInitializer(
5321 VarDecl *Var, VarDecl *OldVar,
5322 const MultiLevelTemplateArgumentList &TemplateArgs) {
5323 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
5324 L->VariableDefinitionInstantiated(Var);
5326 // We propagate the 'inline' flag with the initializer, because it
5327 // would otherwise imply that the variable is a definition for a
5328 // non-static data member.
5329 if (OldVar->isInlineSpecified())
5330 Var->setInlineSpecified();
5331 else if (OldVar->isInline())
5332 Var->setImplicitlyInline();
5334 if (OldVar->getInit()) {
5335 EnterExpressionEvaluationContext Evaluated(
5336 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
5338 // Instantiate the initializer.
5339 ExprResult Init;
5342 ContextRAII SwitchContext(*this, Var->getDeclContext());
5343 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
5344 OldVar->getInitStyle() == VarDecl::CallInit);
5347 if (!Init.isInvalid()) {
5348 Expr *InitExpr = Init.get();
5350 if (Var->hasAttr<DLLImportAttr>() &&
5351 (!InitExpr ||
5352 !InitExpr->isConstantInitializer(getASTContext(), false))) {
5353 // Do not dynamically initialize dllimport variables.
5354 } else if (InitExpr) {
5355 bool DirectInit = OldVar->isDirectInit();
5356 AddInitializerToDecl(Var, InitExpr, DirectInit);
5357 } else
5358 ActOnUninitializedDecl(Var);
5359 } else {
5360 // FIXME: Not too happy about invalidating the declaration
5361 // because of a bogus initializer.
5362 Var->setInvalidDecl();
5364 } else {
5365 // `inline` variables are a definition and declaration all in one; we won't
5366 // pick up an initializer from anywhere else.
5367 if (Var->isStaticDataMember() && !Var->isInline()) {
5368 if (!Var->isOutOfLine())
5369 return;
5371 // If the declaration inside the class had an initializer, don't add
5372 // another one to the out-of-line definition.
5373 if (OldVar->getFirstDecl()->hasInit())
5374 return;
5377 // We'll add an initializer to a for-range declaration later.
5378 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
5379 return;
5381 ActOnUninitializedDecl(Var);
5384 if (getLangOpts().CUDA)
5385 checkAllowedCUDAInitializer(Var);
5388 /// Instantiate the definition of the given variable from its
5389 /// template.
5391 /// \param PointOfInstantiation the point at which the instantiation was
5392 /// required. Note that this is not precisely a "point of instantiation"
5393 /// for the variable, but it's close.
5395 /// \param Var the already-instantiated declaration of a templated variable.
5397 /// \param Recursive if true, recursively instantiates any functions that
5398 /// are required by this instantiation.
5400 /// \param DefinitionRequired if true, then we are performing an explicit
5401 /// instantiation where a definition of the variable is required. Complain
5402 /// if there is no such definition.
5403 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
5404 VarDecl *Var, bool Recursive,
5405 bool DefinitionRequired, bool AtEndOfTU) {
5406 if (Var->isInvalidDecl())
5407 return;
5409 // Never instantiate an explicitly-specialized entity.
5410 TemplateSpecializationKind TSK =
5411 Var->getTemplateSpecializationKindForInstantiation();
5412 if (TSK == TSK_ExplicitSpecialization)
5413 return;
5415 // Find the pattern and the arguments to substitute into it.
5416 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
5417 assert(PatternDecl && "no pattern for templated variable");
5418 MultiLevelTemplateArgumentList TemplateArgs =
5419 getTemplateInstantiationArgs(Var);
5421 VarTemplateSpecializationDecl *VarSpec =
5422 dyn_cast<VarTemplateSpecializationDecl>(Var);
5423 if (VarSpec) {
5424 // If this is a static data member template, there might be an
5425 // uninstantiated initializer on the declaration. If so, instantiate
5426 // it now.
5428 // FIXME: This largely duplicates what we would do below. The difference
5429 // is that along this path we may instantiate an initializer from an
5430 // in-class declaration of the template and instantiate the definition
5431 // from a separate out-of-class definition.
5432 if (PatternDecl->isStaticDataMember() &&
5433 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
5434 !Var->hasInit()) {
5435 // FIXME: Factor out the duplicated instantiation context setup/tear down
5436 // code here.
5437 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5438 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5439 return;
5440 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5441 "instantiating variable initializer");
5443 // The instantiation is visible here, even if it was first declared in an
5444 // unimported module.
5445 Var->setVisibleDespiteOwningModule();
5447 // If we're performing recursive template instantiation, create our own
5448 // queue of pending implicit instantiations that we will instantiate
5449 // later, while we're still within our own instantiation context.
5450 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5451 /*Enabled=*/Recursive);
5452 LocalInstantiationScope Local(*this);
5453 LocalEagerInstantiationScope LocalInstantiations(*this);
5455 // Enter the scope of this instantiation. We don't use
5456 // PushDeclContext because we don't have a scope.
5457 ContextRAII PreviousContext(*this, Var->getDeclContext());
5458 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
5459 PreviousContext.pop();
5461 // This variable may have local implicit instantiations that need to be
5462 // instantiated within this scope.
5463 LocalInstantiations.perform();
5464 Local.Exit();
5465 GlobalInstantiations.perform();
5467 } else {
5468 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
5469 "not a static data member?");
5472 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
5474 // If we don't have a definition of the variable template, we won't perform
5475 // any instantiation. Rather, we rely on the user to instantiate this
5476 // definition (or provide a specialization for it) in another translation
5477 // unit.
5478 if (!Def && !DefinitionRequired) {
5479 if (TSK == TSK_ExplicitInstantiationDefinition) {
5480 PendingInstantiations.push_back(
5481 std::make_pair(Var, PointOfInstantiation));
5482 } else if (TSK == TSK_ImplicitInstantiation) {
5483 // Warn about missing definition at the end of translation unit.
5484 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5485 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5486 Diag(PointOfInstantiation, diag::warn_var_template_missing)
5487 << Var;
5488 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5489 if (getLangOpts().CPlusPlus11)
5490 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
5492 return;
5496 // FIXME: We need to track the instantiation stack in order to know which
5497 // definitions should be visible within this instantiation.
5498 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
5499 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
5500 /*InstantiatedFromMember*/false,
5501 PatternDecl, Def, TSK,
5502 /*Complain*/DefinitionRequired))
5503 return;
5505 // C++11 [temp.explicit]p10:
5506 // Except for inline functions, const variables of literal types, variables
5507 // of reference types, [...] explicit instantiation declarations
5508 // have the effect of suppressing the implicit instantiation of the entity
5509 // to which they refer.
5511 // FIXME: That's not exactly the same as "might be usable in constant
5512 // expressions", which only allows constexpr variables and const integral
5513 // types, not arbitrary const literal types.
5514 if (TSK == TSK_ExplicitInstantiationDeclaration &&
5515 !Var->mightBeUsableInConstantExpressions(getASTContext()))
5516 return;
5518 // Make sure to pass the instantiated variable to the consumer at the end.
5519 struct PassToConsumerRAII {
5520 ASTConsumer &Consumer;
5521 VarDecl *Var;
5523 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
5524 : Consumer(Consumer), Var(Var) { }
5526 ~PassToConsumerRAII() {
5527 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
5529 } PassToConsumerRAII(Consumer, Var);
5531 // If we already have a definition, we're done.
5532 if (VarDecl *Def = Var->getDefinition()) {
5533 // We may be explicitly instantiating something we've already implicitly
5534 // instantiated.
5535 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
5536 PointOfInstantiation);
5537 return;
5540 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5541 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5542 return;
5543 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5544 "instantiating variable definition");
5546 // If we're performing recursive template instantiation, create our own
5547 // queue of pending implicit instantiations that we will instantiate later,
5548 // while we're still within our own instantiation context.
5549 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5550 /*Enabled=*/Recursive);
5552 // Enter the scope of this instantiation. We don't use
5553 // PushDeclContext because we don't have a scope.
5554 ContextRAII PreviousContext(*this, Var->getDeclContext());
5555 LocalInstantiationScope Local(*this);
5557 LocalEagerInstantiationScope LocalInstantiations(*this);
5559 VarDecl *OldVar = Var;
5560 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
5561 // We're instantiating an inline static data member whose definition was
5562 // provided inside the class.
5563 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5564 } else if (!VarSpec) {
5565 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
5566 TemplateArgs));
5567 } else if (Var->isStaticDataMember() &&
5568 Var->getLexicalDeclContext()->isRecord()) {
5569 // We need to instantiate the definition of a static data member template,
5570 // and all we have is the in-class declaration of it. Instantiate a separate
5571 // declaration of the definition.
5572 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
5573 TemplateArgs);
5575 TemplateArgumentListInfo TemplateArgInfo;
5576 if (const ASTTemplateArgumentListInfo *ArgInfo =
5577 VarSpec->getTemplateArgsInfo()) {
5578 TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
5579 TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
5580 for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
5581 TemplateArgInfo.addArgument(Arg);
5584 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
5585 VarSpec->getSpecializedTemplate(), Def, TemplateArgInfo,
5586 VarSpec->getTemplateArgs().asArray(), VarSpec));
5587 if (Var) {
5588 llvm::PointerUnion<VarTemplateDecl *,
5589 VarTemplatePartialSpecializationDecl *> PatternPtr =
5590 VarSpec->getSpecializedTemplateOrPartial();
5591 if (VarTemplatePartialSpecializationDecl *Partial =
5592 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
5593 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
5594 Partial, &VarSpec->getTemplateInstantiationArgs());
5596 // Attach the initializer.
5597 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5599 } else
5600 // Complete the existing variable's definition with an appropriately
5601 // substituted type and initializer.
5602 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
5604 PreviousContext.pop();
5606 if (Var) {
5607 PassToConsumerRAII.Var = Var;
5608 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
5609 OldVar->getPointOfInstantiation());
5612 // This variable may have local implicit instantiations that need to be
5613 // instantiated within this scope.
5614 LocalInstantiations.perform();
5615 Local.Exit();
5616 GlobalInstantiations.perform();
5619 void
5620 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
5621 const CXXConstructorDecl *Tmpl,
5622 const MultiLevelTemplateArgumentList &TemplateArgs) {
5624 SmallVector<CXXCtorInitializer*, 4> NewInits;
5625 bool AnyErrors = Tmpl->isInvalidDecl();
5627 // Instantiate all the initializers.
5628 for (const auto *Init : Tmpl->inits()) {
5629 // Only instantiate written initializers, let Sema re-construct implicit
5630 // ones.
5631 if (!Init->isWritten())
5632 continue;
5634 SourceLocation EllipsisLoc;
5636 if (Init->isPackExpansion()) {
5637 // This is a pack expansion. We should expand it now.
5638 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
5639 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5640 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
5641 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
5642 bool ShouldExpand = false;
5643 bool RetainExpansion = false;
5644 Optional<unsigned> NumExpansions;
5645 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
5646 BaseTL.getSourceRange(),
5647 Unexpanded,
5648 TemplateArgs, ShouldExpand,
5649 RetainExpansion,
5650 NumExpansions)) {
5651 AnyErrors = true;
5652 New->setInvalidDecl();
5653 continue;
5655 assert(ShouldExpand && "Partial instantiation of base initializer?");
5657 // Loop over all of the arguments in the argument pack(s),
5658 for (unsigned I = 0; I != *NumExpansions; ++I) {
5659 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
5661 // Instantiate the initializer.
5662 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5663 /*CXXDirectInit=*/true);
5664 if (TempInit.isInvalid()) {
5665 AnyErrors = true;
5666 break;
5669 // Instantiate the base type.
5670 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
5671 TemplateArgs,
5672 Init->getSourceLocation(),
5673 New->getDeclName());
5674 if (!BaseTInfo) {
5675 AnyErrors = true;
5676 break;
5679 // Build the initializer.
5680 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
5681 BaseTInfo, TempInit.get(),
5682 New->getParent(),
5683 SourceLocation());
5684 if (NewInit.isInvalid()) {
5685 AnyErrors = true;
5686 break;
5689 NewInits.push_back(NewInit.get());
5692 continue;
5695 // Instantiate the initializer.
5696 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5697 /*CXXDirectInit=*/true);
5698 if (TempInit.isInvalid()) {
5699 AnyErrors = true;
5700 continue;
5703 MemInitResult NewInit;
5704 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
5705 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
5706 TemplateArgs,
5707 Init->getSourceLocation(),
5708 New->getDeclName());
5709 if (!TInfo) {
5710 AnyErrors = true;
5711 New->setInvalidDecl();
5712 continue;
5715 if (Init->isBaseInitializer())
5716 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
5717 New->getParent(), EllipsisLoc);
5718 else
5719 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
5720 cast<CXXRecordDecl>(CurContext->getParent()));
5721 } else if (Init->isMemberInitializer()) {
5722 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
5723 Init->getMemberLocation(),
5724 Init->getMember(),
5725 TemplateArgs));
5726 if (!Member) {
5727 AnyErrors = true;
5728 New->setInvalidDecl();
5729 continue;
5732 NewInit = BuildMemberInitializer(Member, TempInit.get(),
5733 Init->getSourceLocation());
5734 } else if (Init->isIndirectMemberInitializer()) {
5735 IndirectFieldDecl *IndirectMember =
5736 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
5737 Init->getMemberLocation(),
5738 Init->getIndirectMember(), TemplateArgs));
5740 if (!IndirectMember) {
5741 AnyErrors = true;
5742 New->setInvalidDecl();
5743 continue;
5746 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
5747 Init->getSourceLocation());
5750 if (NewInit.isInvalid()) {
5751 AnyErrors = true;
5752 New->setInvalidDecl();
5753 } else {
5754 NewInits.push_back(NewInit.get());
5758 // Assign all the initializers to the new constructor.
5759 ActOnMemInitializers(New,
5760 /*FIXME: ColonLoc */
5761 SourceLocation(),
5762 NewInits,
5763 AnyErrors);
5766 // TODO: this could be templated if the various decl types used the
5767 // same method name.
5768 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
5769 ClassTemplateDecl *Instance) {
5770 Pattern = Pattern->getCanonicalDecl();
5772 do {
5773 Instance = Instance->getCanonicalDecl();
5774 if (Pattern == Instance) return true;
5775 Instance = Instance->getInstantiatedFromMemberTemplate();
5776 } while (Instance);
5778 return false;
5781 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
5782 FunctionTemplateDecl *Instance) {
5783 Pattern = Pattern->getCanonicalDecl();
5785 do {
5786 Instance = Instance->getCanonicalDecl();
5787 if (Pattern == Instance) return true;
5788 Instance = Instance->getInstantiatedFromMemberTemplate();
5789 } while (Instance);
5791 return false;
5794 static bool
5795 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
5796 ClassTemplatePartialSpecializationDecl *Instance) {
5797 Pattern
5798 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
5799 do {
5800 Instance = cast<ClassTemplatePartialSpecializationDecl>(
5801 Instance->getCanonicalDecl());
5802 if (Pattern == Instance)
5803 return true;
5804 Instance = Instance->getInstantiatedFromMember();
5805 } while (Instance);
5807 return false;
5810 static bool isInstantiationOf(CXXRecordDecl *Pattern,
5811 CXXRecordDecl *Instance) {
5812 Pattern = Pattern->getCanonicalDecl();
5814 do {
5815 Instance = Instance->getCanonicalDecl();
5816 if (Pattern == Instance) return true;
5817 Instance = Instance->getInstantiatedFromMemberClass();
5818 } while (Instance);
5820 return false;
5823 static bool isInstantiationOf(FunctionDecl *Pattern,
5824 FunctionDecl *Instance) {
5825 Pattern = Pattern->getCanonicalDecl();
5827 do {
5828 Instance = Instance->getCanonicalDecl();
5829 if (Pattern == Instance) return true;
5830 Instance = Instance->getInstantiatedFromMemberFunction();
5831 } while (Instance);
5833 return false;
5836 static bool isInstantiationOf(EnumDecl *Pattern,
5837 EnumDecl *Instance) {
5838 Pattern = Pattern->getCanonicalDecl();
5840 do {
5841 Instance = Instance->getCanonicalDecl();
5842 if (Pattern == Instance) return true;
5843 Instance = Instance->getInstantiatedFromMemberEnum();
5844 } while (Instance);
5846 return false;
5849 static bool isInstantiationOf(UsingShadowDecl *Pattern,
5850 UsingShadowDecl *Instance,
5851 ASTContext &C) {
5852 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
5853 Pattern);
5856 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
5857 ASTContext &C) {
5858 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
5861 template<typename T>
5862 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
5863 ASTContext &Ctx) {
5864 // An unresolved using declaration can instantiate to an unresolved using
5865 // declaration, or to a using declaration or a using declaration pack.
5867 // Multiple declarations can claim to be instantiated from an unresolved
5868 // using declaration if it's a pack expansion. We want the UsingPackDecl
5869 // in that case, not the individual UsingDecls within the pack.
5870 bool OtherIsPackExpansion;
5871 NamedDecl *OtherFrom;
5872 if (auto *OtherUUD = dyn_cast<T>(Other)) {
5873 OtherIsPackExpansion = OtherUUD->isPackExpansion();
5874 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
5875 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
5876 OtherIsPackExpansion = true;
5877 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
5878 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
5879 OtherIsPackExpansion = false;
5880 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
5881 } else {
5882 return false;
5884 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
5885 declaresSameEntity(OtherFrom, Pattern);
5888 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
5889 VarDecl *Instance) {
5890 assert(Instance->isStaticDataMember());
5892 Pattern = Pattern->getCanonicalDecl();
5894 do {
5895 Instance = Instance->getCanonicalDecl();
5896 if (Pattern == Instance) return true;
5897 Instance = Instance->getInstantiatedFromStaticDataMember();
5898 } while (Instance);
5900 return false;
5903 // Other is the prospective instantiation
5904 // D is the prospective pattern
5905 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
5906 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
5907 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5909 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
5910 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5912 if (D->getKind() != Other->getKind())
5913 return false;
5915 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
5916 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
5918 if (auto *Function = dyn_cast<FunctionDecl>(Other))
5919 return isInstantiationOf(cast<FunctionDecl>(D), Function);
5921 if (auto *Enum = dyn_cast<EnumDecl>(Other))
5922 return isInstantiationOf(cast<EnumDecl>(D), Enum);
5924 if (auto *Var = dyn_cast<VarDecl>(Other))
5925 if (Var->isStaticDataMember())
5926 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
5928 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
5929 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
5931 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
5932 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
5934 if (auto *PartialSpec =
5935 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
5936 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
5937 PartialSpec);
5939 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
5940 if (!Field->getDeclName()) {
5941 // This is an unnamed field.
5942 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
5943 cast<FieldDecl>(D));
5947 if (auto *Using = dyn_cast<UsingDecl>(Other))
5948 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
5950 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
5951 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
5953 return D->getDeclName() &&
5954 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
5957 template<typename ForwardIterator>
5958 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
5959 NamedDecl *D,
5960 ForwardIterator first,
5961 ForwardIterator last) {
5962 for (; first != last; ++first)
5963 if (isInstantiationOf(Ctx, D, *first))
5964 return cast<NamedDecl>(*first);
5966 return nullptr;
5969 /// Finds the instantiation of the given declaration context
5970 /// within the current instantiation.
5972 /// \returns NULL if there was an error
5973 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
5974 const MultiLevelTemplateArgumentList &TemplateArgs) {
5975 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
5976 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
5977 return cast_or_null<DeclContext>(ID);
5978 } else return DC;
5981 /// Determine whether the given context is dependent on template parameters at
5982 /// level \p Level or below.
5984 /// Sometimes we only substitute an inner set of template arguments and leave
5985 /// the outer templates alone. In such cases, contexts dependent only on the
5986 /// outer levels are not effectively dependent.
5987 static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
5988 if (!DC->isDependentContext())
5989 return false;
5990 if (!Level)
5991 return true;
5992 return cast<Decl>(DC)->getTemplateDepth() > Level;
5995 /// Find the instantiation of the given declaration within the
5996 /// current instantiation.
5998 /// This routine is intended to be used when \p D is a declaration
5999 /// referenced from within a template, that needs to mapped into the
6000 /// corresponding declaration within an instantiation. For example,
6001 /// given:
6003 /// \code
6004 /// template<typename T>
6005 /// struct X {
6006 /// enum Kind {
6007 /// KnownValue = sizeof(T)
6008 /// };
6010 /// bool getKind() const { return KnownValue; }
6011 /// };
6013 /// template struct X<int>;
6014 /// \endcode
6016 /// In the instantiation of X<int>::getKind(), we need to map the \p
6017 /// EnumConstantDecl for \p KnownValue (which refers to
6018 /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
6019 /// \p FindInstantiatedDecl performs this mapping from within the instantiation
6020 /// of X<int>.
6021 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6022 const MultiLevelTemplateArgumentList &TemplateArgs,
6023 bool FindingInstantiatedContext) {
6024 DeclContext *ParentDC = D->getDeclContext();
6025 // Determine whether our parent context depends on any of the template
6026 // arguments we're currently substituting.
6027 bool ParentDependsOnArgs = isDependentContextAtLevel(
6028 ParentDC, TemplateArgs.getNumRetainedOuterLevels());
6029 // FIXME: Parameters of pointer to functions (y below) that are themselves
6030 // parameters (p below) can have their ParentDC set to the translation-unit
6031 // - thus we can not consistently check if the ParentDC of such a parameter
6032 // is Dependent or/and a FunctionOrMethod.
6033 // For e.g. this code, during Template argument deduction tries to
6034 // find an instantiated decl for (T y) when the ParentDC for y is
6035 // the translation unit.
6036 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6037 // float baz(float(*)()) { return 0.0; }
6038 // Foo(baz);
6039 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6040 // it gets here, always has a FunctionOrMethod as its ParentDC??
6041 // For now:
6042 // - as long as we have a ParmVarDecl whose parent is non-dependent and
6043 // whose type is not instantiation dependent, do nothing to the decl
6044 // - otherwise find its instantiated decl.
6045 if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
6046 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
6047 return D;
6048 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
6049 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
6050 (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
6051 isa<OMPDeclareReductionDecl>(ParentDC) ||
6052 isa<OMPDeclareMapperDecl>(ParentDC))) ||
6053 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
6054 cast<CXXRecordDecl>(D)->getTemplateDepth() >
6055 TemplateArgs.getNumRetainedOuterLevels())) {
6056 // D is a local of some kind. Look into the map of local
6057 // declarations to their instantiations.
6058 if (CurrentInstantiationScope) {
6059 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
6060 if (Decl *FD = Found->dyn_cast<Decl *>())
6061 return cast<NamedDecl>(FD);
6063 int PackIdx = ArgumentPackSubstitutionIndex;
6064 assert(PackIdx != -1 &&
6065 "found declaration pack but not pack expanding");
6066 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
6067 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
6071 // If we're performing a partial substitution during template argument
6072 // deduction, we may not have values for template parameters yet. They
6073 // just map to themselves.
6074 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
6075 isa<TemplateTemplateParmDecl>(D))
6076 return D;
6078 if (D->isInvalidDecl())
6079 return nullptr;
6081 // Normally this function only searches for already instantiated declaration
6082 // however we have to make an exclusion for local types used before
6083 // definition as in the code:
6085 // template<typename T> void f1() {
6086 // void g1(struct x1);
6087 // struct x1 {};
6088 // }
6090 // In this case instantiation of the type of 'g1' requires definition of
6091 // 'x1', which is defined later. Error recovery may produce an enum used
6092 // before definition. In these cases we need to instantiate relevant
6093 // declarations here.
6094 bool NeedInstantiate = false;
6095 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6096 NeedInstantiate = RD->isLocalClass();
6097 else if (isa<TypedefNameDecl>(D) &&
6098 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
6099 NeedInstantiate = true;
6100 else
6101 NeedInstantiate = isa<EnumDecl>(D);
6102 if (NeedInstantiate) {
6103 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6104 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6105 return cast<TypeDecl>(Inst);
6108 // If we didn't find the decl, then we must have a label decl that hasn't
6109 // been found yet. Lazily instantiate it and return it now.
6110 assert(isa<LabelDecl>(D));
6112 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6113 assert(Inst && "Failed to instantiate label??");
6115 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6116 return cast<LabelDecl>(Inst);
6119 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
6120 if (!Record->isDependentContext())
6121 return D;
6123 // Determine whether this record is the "templated" declaration describing
6124 // a class template or class template partial specialization.
6125 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
6126 if (ClassTemplate)
6127 ClassTemplate = ClassTemplate->getCanonicalDecl();
6128 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
6129 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
6130 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
6132 // Walk the current context to find either the record or an instantiation of
6133 // it.
6134 DeclContext *DC = CurContext;
6135 while (!DC->isFileContext()) {
6136 // If we're performing substitution while we're inside the template
6137 // definition, we'll find our own context. We're done.
6138 if (DC->Equals(Record))
6139 return Record;
6141 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
6142 // Check whether we're in the process of instantiating a class template
6143 // specialization of the template we're mapping.
6144 if (ClassTemplateSpecializationDecl *InstSpec
6145 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
6146 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
6147 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
6148 return InstRecord;
6151 // Check whether we're in the process of instantiating a member class.
6152 if (isInstantiationOf(Record, InstRecord))
6153 return InstRecord;
6156 // Move to the outer template scope.
6157 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
6158 // FIXME: We should use `getNonTransparentDeclContext()` here instead
6159 // of `getDeclContext()` once we find the invalid test case.
6160 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
6161 DC = FD->getLexicalDeclContext();
6162 continue;
6164 // An implicit deduction guide acts as if it's within the class template
6165 // specialization described by its name and first N template params.
6166 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
6167 if (Guide && Guide->isImplicit()) {
6168 TemplateDecl *TD = Guide->getDeducedTemplate();
6169 // Convert the arguments to an "as-written" list.
6170 TemplateArgumentListInfo Args(Loc, Loc);
6171 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
6172 TD->getTemplateParameters()->size())) {
6173 ArrayRef<TemplateArgument> Unpacked(Arg);
6174 if (Arg.getKind() == TemplateArgument::Pack)
6175 Unpacked = Arg.pack_elements();
6176 for (TemplateArgument UnpackedArg : Unpacked)
6177 Args.addArgument(
6178 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
6180 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
6181 if (T.isNull())
6182 return nullptr;
6183 auto *SubstRecord = T->getAsCXXRecordDecl();
6184 assert(SubstRecord && "class template id not a class type?");
6185 // Check that this template-id names the primary template and not a
6186 // partial or explicit specialization. (In the latter cases, it's
6187 // meaningless to attempt to find an instantiation of D within the
6188 // specialization.)
6189 // FIXME: The standard doesn't say what should happen here.
6190 if (FindingInstantiatedContext &&
6191 usesPartialOrExplicitSpecialization(
6192 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
6193 Diag(Loc, diag::err_specialization_not_primary_template)
6194 << T << (SubstRecord->getTemplateSpecializationKind() ==
6195 TSK_ExplicitSpecialization);
6196 return nullptr;
6198 DC = SubstRecord;
6199 continue;
6203 DC = DC->getParent();
6206 // Fall through to deal with other dependent record types (e.g.,
6207 // anonymous unions in class templates).
6210 if (!ParentDependsOnArgs)
6211 return D;
6213 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
6214 if (!ParentDC)
6215 return nullptr;
6217 if (ParentDC != D->getDeclContext()) {
6218 // We performed some kind of instantiation in the parent context,
6219 // so now we need to look into the instantiated parent context to
6220 // find the instantiation of the declaration D.
6222 // If our context used to be dependent, we may need to instantiate
6223 // it before performing lookup into that context.
6224 bool IsBeingInstantiated = false;
6225 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
6226 if (!Spec->isDependentContext()) {
6227 QualType T = Context.getTypeDeclType(Spec);
6228 const RecordType *Tag = T->getAs<RecordType>();
6229 assert(Tag && "type of non-dependent record is not a RecordType");
6230 if (Tag->isBeingDefined())
6231 IsBeingInstantiated = true;
6232 if (!Tag->isBeingDefined() &&
6233 RequireCompleteType(Loc, T, diag::err_incomplete_type))
6234 return nullptr;
6236 ParentDC = Tag->getDecl();
6240 NamedDecl *Result = nullptr;
6241 // FIXME: If the name is a dependent name, this lookup won't necessarily
6242 // find it. Does that ever matter?
6243 if (auto Name = D->getDeclName()) {
6244 DeclarationNameInfo NameInfo(Name, D->getLocation());
6245 DeclarationNameInfo NewNameInfo =
6246 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
6247 Name = NewNameInfo.getName();
6248 if (!Name)
6249 return nullptr;
6250 DeclContext::lookup_result Found = ParentDC->lookup(Name);
6252 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
6253 } else {
6254 // Since we don't have a name for the entity we're looking for,
6255 // our only option is to walk through all of the declarations to
6256 // find that name. This will occur in a few cases:
6258 // - anonymous struct/union within a template
6259 // - unnamed class/struct/union/enum within a template
6261 // FIXME: Find a better way to find these instantiations!
6262 Result = findInstantiationOf(Context, D,
6263 ParentDC->decls_begin(),
6264 ParentDC->decls_end());
6267 if (!Result) {
6268 if (isa<UsingShadowDecl>(D)) {
6269 // UsingShadowDecls can instantiate to nothing because of using hiding.
6270 } else if (hasUncompilableErrorOccurred()) {
6271 // We've already complained about some ill-formed code, so most likely
6272 // this declaration failed to instantiate. There's no point in
6273 // complaining further, since this is normal in invalid code.
6274 // FIXME: Use more fine-grained 'invalid' tracking for this.
6275 } else if (IsBeingInstantiated) {
6276 // The class in which this member exists is currently being
6277 // instantiated, and we haven't gotten around to instantiating this
6278 // member yet. This can happen when the code uses forward declarations
6279 // of member classes, and introduces ordering dependencies via
6280 // template instantiation.
6281 Diag(Loc, diag::err_member_not_yet_instantiated)
6282 << D->getDeclName()
6283 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
6284 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
6285 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
6286 // This enumeration constant was found when the template was defined,
6287 // but can't be found in the instantiation. This can happen if an
6288 // unscoped enumeration member is explicitly specialized.
6289 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
6290 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
6291 TemplateArgs));
6292 assert(Spec->getTemplateSpecializationKind() ==
6293 TSK_ExplicitSpecialization);
6294 Diag(Loc, diag::err_enumerator_does_not_exist)
6295 << D->getDeclName()
6296 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
6297 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
6298 << Context.getTypeDeclType(Spec);
6299 } else {
6300 // We should have found something, but didn't.
6301 llvm_unreachable("Unable to find instantiation of declaration!");
6305 D = Result;
6308 return D;
6311 /// Performs template instantiation for all implicit template
6312 /// instantiations we have seen until this point.
6313 void Sema::PerformPendingInstantiations(bool LocalOnly) {
6314 std::deque<PendingImplicitInstantiation> delayedPCHInstantiations;
6315 while (!PendingLocalImplicitInstantiations.empty() ||
6316 (!LocalOnly && !PendingInstantiations.empty())) {
6317 PendingImplicitInstantiation Inst;
6319 if (PendingLocalImplicitInstantiations.empty()) {
6320 Inst = PendingInstantiations.front();
6321 PendingInstantiations.pop_front();
6322 } else {
6323 Inst = PendingLocalImplicitInstantiations.front();
6324 PendingLocalImplicitInstantiations.pop_front();
6327 // Instantiate function definitions
6328 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
6329 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
6330 TSK_ExplicitInstantiationDefinition;
6331 if (Function->isMultiVersion()) {
6332 getASTContext().forEachMultiversionedFunctionVersion(
6333 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
6334 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
6335 DefinitionRequired, true);
6336 if (CurFD->isDefined())
6337 CurFD->setInstantiationIsPending(false);
6339 } else {
6340 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
6341 DefinitionRequired, true);
6342 if (Function->isDefined())
6343 Function->setInstantiationIsPending(false);
6345 // Definition of a PCH-ed template declaration may be available only in the TU.
6346 if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
6347 TUKind == TU_Prefix && Function->instantiationIsPending())
6348 delayedPCHInstantiations.push_back(Inst);
6349 continue;
6352 // Instantiate variable definitions
6353 VarDecl *Var = cast<VarDecl>(Inst.first);
6355 assert((Var->isStaticDataMember() ||
6356 isa<VarTemplateSpecializationDecl>(Var)) &&
6357 "Not a static data member, nor a variable template"
6358 " specialization?");
6360 // Don't try to instantiate declarations if the most recent redeclaration
6361 // is invalid.
6362 if (Var->getMostRecentDecl()->isInvalidDecl())
6363 continue;
6365 // Check if the most recent declaration has changed the specialization kind
6366 // and removed the need for implicit instantiation.
6367 switch (Var->getMostRecentDecl()
6368 ->getTemplateSpecializationKindForInstantiation()) {
6369 case TSK_Undeclared:
6370 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
6371 case TSK_ExplicitInstantiationDeclaration:
6372 case TSK_ExplicitSpecialization:
6373 continue; // No longer need to instantiate this type.
6374 case TSK_ExplicitInstantiationDefinition:
6375 // We only need an instantiation if the pending instantiation *is* the
6376 // explicit instantiation.
6377 if (Var != Var->getMostRecentDecl())
6378 continue;
6379 break;
6380 case TSK_ImplicitInstantiation:
6381 break;
6384 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
6385 "instantiating variable definition");
6386 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
6387 TSK_ExplicitInstantiationDefinition;
6389 // Instantiate static data member definitions or variable template
6390 // specializations.
6391 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
6392 DefinitionRequired, true);
6395 if (!LocalOnly && LangOpts.PCHInstantiateTemplates)
6396 PendingInstantiations.swap(delayedPCHInstantiations);
6399 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
6400 const MultiLevelTemplateArgumentList &TemplateArgs) {
6401 for (auto *DD : Pattern->ddiags()) {
6402 switch (DD->getKind()) {
6403 case DependentDiagnostic::Access:
6404 HandleDependentAccessCheck(*DD, TemplateArgs);
6405 break;