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