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