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