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