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, InsertPos);
3710 
3711   // Build the canonical type that describes the converted template
3712   // arguments of the class template partial specialization.
3713   QualType CanonType
3714     = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
3715                                                     Converted);
3716 
3717   // Build the fully-sugared type for this class template
3718   // specialization as the user wrote in the specialization
3719   // itself. This means that we'll pretty-print the type retrieved
3720   // from the specialization's declaration the way that the user
3721   // actually wrote the specialization, rather than formatting the
3722   // name based on the "canonical" representation used to store the
3723   // template arguments in the specialization.
3724   TypeSourceInfo *WrittenTy
3725     = SemaRef.Context.getTemplateSpecializationTypeInfo(
3726                                                     TemplateName(ClassTemplate),
3727                                                     PartialSpec->getLocation(),
3728                                                     InstTemplateArgs,
3729                                                     CanonType);
3730 
3731   if (PrevDecl) {
3732     // We've already seen a partial specialization with the same template
3733     // parameters and template arguments. This can happen, for example, when
3734     // substituting the outer template arguments ends up causing two
3735     // class template partial specializations of a member class template
3736     // to have identical forms, e.g.,
3737     //
3738     //   template<typename T, typename U>
3739     //   struct Outer {
3740     //     template<typename X, typename Y> struct Inner;
3741     //     template<typename Y> struct Inner<T, Y>;
3742     //     template<typename Y> struct Inner<U, Y>;
3743     //   };
3744     //
3745     //   Outer<int, int> outer; // error: the partial specializations of Inner
3746     //                          // have the same signature.
3747     SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
3748       << WrittenTy->getType();
3749     SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3750       << SemaRef.Context.getTypeDeclType(PrevDecl);
3751     return nullptr;
3752   }
3753 
3754 
3755   // Create the class template partial specialization declaration.
3756   ClassTemplatePartialSpecializationDecl *InstPartialSpec =
3757       ClassTemplatePartialSpecializationDecl::Create(
3758           SemaRef.Context, PartialSpec->getTagKind(), Owner,
3759           PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
3760           ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
3761   // Substitute the nested name specifier, if any.
3762   if (SubstQualifier(PartialSpec, InstPartialSpec))
3763     return nullptr;
3764 
3765   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3766   InstPartialSpec->setTypeAsWritten(WrittenTy);
3767 
3768   // Check the completed partial specialization.
3769   SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3770 
3771   // Add this partial specialization to the set of class template partial
3772   // specializations.
3773   ClassTemplate->AddPartialSpecialization(InstPartialSpec,
3774                                           /*InsertPos=*/nullptr);
3775   return InstPartialSpec;
3776 }
3777 
3778 /// Instantiate the declaration of a variable template partial
3779 /// specialization.
3780 ///
3781 /// \param VarTemplate the (instantiated) variable template that is partially
3782 /// specialized by the instantiation of \p PartialSpec.
3783 ///
3784 /// \param PartialSpec the (uninstantiated) variable template partial
3785 /// specialization that we are instantiating.
3786 ///
3787 /// \returns The instantiated partial specialization, if successful; otherwise,
3788 /// NULL to indicate an error.
3789 VarTemplatePartialSpecializationDecl *
3790 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
3791     VarTemplateDecl *VarTemplate,
3792     VarTemplatePartialSpecializationDecl *PartialSpec) {
3793   // Create a local instantiation scope for this variable template partial
3794   // specialization, which will contain the instantiations of the template
3795   // parameters.
3796   LocalInstantiationScope Scope(SemaRef);
3797 
3798   // Substitute into the template parameters of the variable template partial
3799   // specialization.
3800   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3801   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3802   if (!InstParams)
3803     return nullptr;
3804 
3805   // Substitute into the template arguments of the variable template partial
3806   // specialization.
3807   const ASTTemplateArgumentListInfo *TemplArgInfo
3808     = PartialSpec->getTemplateArgsAsWritten();
3809   TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3810                                             TemplArgInfo->RAngleLoc);
3811   if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3812                     TemplArgInfo->NumTemplateArgs,
3813                     InstTemplateArgs, TemplateArgs))
3814     return nullptr;
3815 
3816   // Check that the template argument list is well-formed for this
3817   // class template.
3818   SmallVector<TemplateArgument, 4> Converted;
3819   if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3820                                         InstTemplateArgs, false, Converted))
3821     return nullptr;
3822 
3823   // Check these arguments are valid for a template partial specialization.
3824   if (SemaRef.CheckTemplatePartialSpecializationArgs(
3825           PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
3826           Converted))
3827     return nullptr;
3828 
3829   // Figure out where to insert this variable template partial specialization
3830   // in the member template's set of variable template partial specializations.
3831   void *InsertPos = nullptr;
3832   VarTemplateSpecializationDecl *PrevDecl =
3833       VarTemplate->findPartialSpecialization(Converted, InsertPos);
3834 
3835   // Build the canonical type that describes the converted template
3836   // arguments of the variable template partial specialization.
3837   QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3838       TemplateName(VarTemplate), Converted);
3839 
3840   // Build the fully-sugared type for this variable template
3841   // specialization as the user wrote in the specialization
3842   // itself. This means that we'll pretty-print the type retrieved
3843   // from the specialization's declaration the way that the user
3844   // actually wrote the specialization, rather than formatting the
3845   // name based on the "canonical" representation used to store the
3846   // template arguments in the specialization.
3847   TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3848       TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
3849       CanonType);
3850 
3851   if (PrevDecl) {
3852     // We've already seen a partial specialization with the same template
3853     // parameters and template arguments. This can happen, for example, when
3854     // substituting the outer template arguments ends up causing two
3855     // variable template partial specializations of a member variable template
3856     // to have identical forms, e.g.,
3857     //
3858     //   template<typename T, typename U>
3859     //   struct Outer {
3860     //     template<typename X, typename Y> pair<X,Y> p;
3861     //     template<typename Y> pair<T, Y> p;
3862     //     template<typename Y> pair<U, Y> p;
3863     //   };
3864     //
3865     //   Outer<int, int> outer; // error: the partial specializations of Inner
3866     //                          // have the same signature.
3867     SemaRef.Diag(PartialSpec->getLocation(),
3868                  diag::err_var_partial_spec_redeclared)
3869         << WrittenTy->getType();
3870     SemaRef.Diag(PrevDecl->getLocation(),
3871                  diag::note_var_prev_partial_spec_here);
3872     return nullptr;
3873   }
3874 
3875   // Do substitution on the type of the declaration
3876   TypeSourceInfo *DI = SemaRef.SubstType(
3877       PartialSpec->getTypeSourceInfo(), TemplateArgs,
3878       PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3879   if (!DI)
3880     return nullptr;
3881 
3882   if (DI->getType()->isFunctionType()) {
3883     SemaRef.Diag(PartialSpec->getLocation(),
3884                  diag::err_variable_instantiates_to_function)
3885         << PartialSpec->isStaticDataMember() << DI->getType();
3886     return nullptr;
3887   }
3888 
3889   // Create the variable template partial specialization declaration.
3890   VarTemplatePartialSpecializationDecl *InstPartialSpec =
3891       VarTemplatePartialSpecializationDecl::Create(
3892           SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3893           PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
3894           DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
3895 
3896   // Substitute the nested name specifier, if any.
3897   if (SubstQualifier(PartialSpec, InstPartialSpec))
3898     return nullptr;
3899 
3900   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3901   InstPartialSpec->setTypeAsWritten(WrittenTy);
3902 
3903   // Check the completed partial specialization.
3904   SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3905 
3906   // Add this partial specialization to the set of variable template partial
3907   // specializations. The instantiation of the initializer is not necessary.
3908   VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
3909 
3910   SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
3911                                      LateAttrs, Owner, StartingScope);
3912 
3913   return InstPartialSpec;
3914 }
3915 
3916 TypeSourceInfo*
3917 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
3918                               SmallVectorImpl<ParmVarDecl *> &Params) {
3919   TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
3920   assert(OldTInfo && "substituting function without type source info");
3921   assert(Params.empty() && "parameter vector is non-empty at start");
3922 
3923   CXXRecordDecl *ThisContext = nullptr;
3924   Qualifiers ThisTypeQuals;
3925   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3926     ThisContext = cast<CXXRecordDecl>(Owner);
3927     ThisTypeQuals = Method->getMethodQualifiers();
3928   }
3929 
3930   TypeSourceInfo *NewTInfo
3931     = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
3932                                     D->getTypeSpecStartLoc(),
3933                                     D->getDeclName(),
3934                                     ThisContext, ThisTypeQuals);
3935   if (!NewTInfo)
3936     return nullptr;
3937 
3938   TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3939   if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3940     if (NewTInfo != OldTInfo) {
3941       // Get parameters from the new type info.
3942       TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
3943       FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
3944       unsigned NewIdx = 0;
3945       for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
3946            OldIdx != NumOldParams; ++OldIdx) {
3947         ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
3948         LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3949 
3950         Optional<unsigned> NumArgumentsInExpansion;
3951         if (OldParam->isParameterPack())
3952           NumArgumentsInExpansion =
3953               SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3954                                                  TemplateArgs);
3955         if (!NumArgumentsInExpansion) {
3956           // Simple case: normal parameter, or a parameter pack that's
3957           // instantiated to a (still-dependent) parameter pack.
3958           ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3959           Params.push_back(NewParam);
3960           Scope->InstantiatedLocal(OldParam, NewParam);
3961         } else {
3962           // Parameter pack expansion: make the instantiation an argument pack.
3963           Scope->MakeInstantiatedLocalArgPack(OldParam);
3964           for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
3965             ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3966             Params.push_back(NewParam);
3967             Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3968           }
3969         }
3970       }
3971     } else {
3972       // The function type itself was not dependent and therefore no
3973       // substitution occurred. However, we still need to instantiate
3974       // the function parameters themselves.
3975       const FunctionProtoType *OldProto =
3976           cast<FunctionProtoType>(OldProtoLoc.getType());
3977       for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3978            ++i) {
3979         ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
3980         if (!OldParam) {
3981           Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
3982               D, D->getLocation(), OldProto->getParamType(i)));
3983           continue;
3984         }
3985 
3986         ParmVarDecl *Parm =
3987             cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
3988         if (!Parm)
3989           return nullptr;
3990         Params.push_back(Parm);
3991       }
3992     }
3993   } else {
3994     // If the type of this function, after ignoring parentheses, is not
3995     // *directly* a function type, then we're instantiating a function that
3996     // was declared via a typedef or with attributes, e.g.,
3997     //
3998     //   typedef int functype(int, int);
3999     //   functype func;
4000     //   int __cdecl meth(int, int);
4001     //
4002     // In this case, we'll just go instantiate the ParmVarDecls that we
4003     // synthesized in the method declaration.
4004     SmallVector<QualType, 4> ParamTypes;
4005     Sema::ExtParameterInfoBuilder ExtParamInfos;
4006     if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4007                                TemplateArgs, ParamTypes, &Params,
4008                                ExtParamInfos))
4009       return nullptr;
4010   }
4011 
4012   return NewTInfo;
4013 }
4014 
4015 /// Introduce the instantiated function parameters into the local
4016 /// instantiation scope, and set the parameter names to those used
4017 /// in the template.
4018 static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
4019                                              const FunctionDecl *PatternDecl,
4020                                              LocalInstantiationScope &Scope,
4021                            const MultiLevelTemplateArgumentList &TemplateArgs) {
4022   unsigned FParamIdx = 0;
4023   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4024     const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4025     if (!PatternParam->isParameterPack()) {
4026       // Simple case: not a parameter pack.
4027       assert(FParamIdx < Function->getNumParams());
4028       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4029       FunctionParam->setDeclName(PatternParam->getDeclName());
4030       // If the parameter's type is not dependent, update it to match the type
4031       // in the pattern. They can differ in top-level cv-qualifiers, and we want
4032       // the pattern's type here. If the type is dependent, they can't differ,
4033       // per core issue 1668. Substitute into the type from the pattern, in case
4034       // it's instantiation-dependent.
4035       // FIXME: Updating the type to work around this is at best fragile.
4036       if (!PatternDecl->getType()->isDependentType()) {
4037         QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
4038                                  FunctionParam->getLocation(),
4039                                  FunctionParam->getDeclName());
4040         if (T.isNull())
4041           return true;
4042         FunctionParam->setType(T);
4043       }
4044 
4045       Scope.InstantiatedLocal(PatternParam, FunctionParam);
4046       ++FParamIdx;
4047       continue;
4048     }
4049 
4050     // Expand the parameter pack.
4051     Scope.MakeInstantiatedLocalArgPack(PatternParam);
4052     Optional<unsigned> NumArgumentsInExpansion
4053       = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4054     if (NumArgumentsInExpansion) {
4055       QualType PatternType =
4056           PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4057       for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4058         ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4059         FunctionParam->setDeclName(PatternParam->getDeclName());
4060         if (!PatternDecl->getType()->isDependentType()) {
4061           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
4062           QualType T = S.SubstType(PatternType, TemplateArgs,
4063                                    FunctionParam->getLocation(),
4064                                    FunctionParam->getDeclName());
4065           if (T.isNull())
4066             return true;
4067           FunctionParam->setType(T);
4068         }
4069 
4070         Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4071         ++FParamIdx;
4072       }
4073     }
4074   }
4075 
4076   return false;
4077 }
4078 
4079 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
4080                                     FunctionDecl *Decl) {
4081   const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4082   if (Proto->getExceptionSpecType() != EST_Uninstantiated)
4083     return;
4084 
4085   InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4086                              InstantiatingTemplate::ExceptionSpecification());
4087   if (Inst.isInvalid()) {
4088     // We hit the instantiation depth limit. Clear the exception specification
4089     // so that our callers don't have to cope with EST_Uninstantiated.
4090     UpdateExceptionSpec(Decl, EST_None);
4091     return;
4092   }
4093   if (Inst.isAlreadyInstantiating()) {
4094     // This exception specification indirectly depends on itself. Reject.
4095     // FIXME: Corresponding rule in the standard?
4096     Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4097     UpdateExceptionSpec(Decl, EST_None);
4098     return;
4099   }
4100 
4101   // Enter the scope of this instantiation. We don't use
4102   // PushDeclContext because we don't have a scope.
4103   Sema::ContextRAII savedContext(*this, Decl);
4104   LocalInstantiationScope Scope(*this);
4105 
4106   MultiLevelTemplateArgumentList TemplateArgs =
4107     getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
4108 
4109   FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4110   if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
4111                                        TemplateArgs)) {
4112     UpdateExceptionSpec(Decl, EST_None);
4113     return;
4114   }
4115 
4116   SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
4117                      TemplateArgs);
4118 }
4119 
4120 /// Initializes the common fields of an instantiation function
4121 /// declaration (New) from the corresponding fields of its template (Tmpl).
4122 ///
4123 /// \returns true if there was an error
4124 bool
4125 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
4126                                                     FunctionDecl *Tmpl) {
4127   New->setImplicit(Tmpl->isImplicit());
4128 
4129   // Forward the mangling number from the template to the instantiated decl.
4130   SemaRef.Context.setManglingNumber(New,
4131                                     SemaRef.Context.getManglingNumber(Tmpl));
4132 
4133   // If we are performing substituting explicitly-specified template arguments
4134   // or deduced template arguments into a function template and we reach this
4135   // point, we are now past the point where SFINAE applies and have committed
4136   // to keeping the new function template specialization. We therefore
4137   // convert the active template instantiation for the function template
4138   // into a template instantiation for this specific function template
4139   // specialization, which is not a SFINAE context, so that we diagnose any
4140   // further errors in the declaration itself.
4141   typedef Sema::CodeSynthesisContext ActiveInstType;
4142   ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4143   if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4144       ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4145     if (FunctionTemplateDecl *FunTmpl
4146           = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
4147       assert(FunTmpl->getTemplatedDecl() == Tmpl &&
4148              "Deduction from the wrong function template?");
4149       (void) FunTmpl;
4150       atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4151       ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4152       ActiveInst.Entity = New;
4153       atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4154     }
4155   }
4156 
4157   const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4158   assert(Proto && "Function template without prototype?");
4159 
4160   if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4161     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4162 
4163     // DR1330: In C++11, defer instantiation of a non-trivial
4164     // exception specification.
4165     // DR1484: Local classes and their members are instantiated along with the
4166     // containing function.
4167     if (SemaRef.getLangOpts().CPlusPlus11 &&
4168         EPI.ExceptionSpec.Type != EST_None &&
4169         EPI.ExceptionSpec.Type != EST_DynamicNone &&
4170         EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
4171         !Tmpl->isLexicallyWithinFunctionOrMethod()) {
4172       FunctionDecl *ExceptionSpecTemplate = Tmpl;
4173       if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
4174         ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4175       ExceptionSpecificationType NewEST = EST_Uninstantiated;
4176       if (EPI.ExceptionSpec.Type == EST_Unevaluated)
4177         NewEST = EST_Unevaluated;
4178 
4179       // Mark the function has having an uninstantiated exception specification.
4180       const FunctionProtoType *NewProto
4181         = New->getType()->getAs<FunctionProtoType>();
4182       assert(NewProto && "Template instantiation without function prototype?");
4183       EPI = NewProto->getExtProtoInfo();
4184       EPI.ExceptionSpec.Type = NewEST;
4185       EPI.ExceptionSpec.SourceDecl = New;
4186       EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4187       New->setType(SemaRef.Context.getFunctionType(
4188           NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4189     } else {
4190       Sema::ContextRAII SwitchContext(SemaRef, New);
4191       SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4192     }
4193   }
4194 
4195   // Get the definition. Leaves the variable unchanged if undefined.
4196   const FunctionDecl *Definition = Tmpl;
4197   Tmpl->isDefined(Definition);
4198 
4199   SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4200                            LateAttrs, StartingScope);
4201 
4202   return false;
4203 }
4204 
4205 /// Initializes common fields of an instantiated method
4206 /// declaration (New) from the corresponding fields of its template
4207 /// (Tmpl).
4208 ///
4209 /// \returns true if there was an error
4210 bool
4211 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4212                                                   CXXMethodDecl *Tmpl) {
4213   if (InitFunctionInstantiation(New, Tmpl))
4214     return true;
4215 
4216   if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4217     SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4218 
4219   New->setAccess(Tmpl->getAccess());
4220   if (Tmpl->isVirtualAsWritten())
4221     New->setVirtualAsWritten(true);
4222 
4223   // FIXME: New needs a pointer to Tmpl
4224   return false;
4225 }
4226 
4227 bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
4228                                                       FunctionDecl *Tmpl) {
4229   // Transfer across any unqualified lookups.
4230   if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) {
4231     SmallVector<DeclAccessPair, 32> Lookups;
4232     Lookups.reserve(DFI->getUnqualifiedLookups().size());
4233     bool AnyChanged = false;
4234     for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4235       NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4236                                                   DA.getDecl(), TemplateArgs);
4237       if (!D)
4238         return true;
4239       AnyChanged |= (D != DA.getDecl());
4240       Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4241     }
4242 
4243     // It's unlikely that substitution will change any declarations. Don't
4244     // store an unnecessary copy in that case.
4245     New->setDefaultedFunctionInfo(
4246         AnyChanged ? FunctionDecl::DefaultedFunctionInfo::Create(
4247                          SemaRef.Context, Lookups)
4248                    : DFI);
4249   }
4250 
4251   SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4252   return false;
4253 }
4254 
4255 /// Instantiate (or find existing instantiation of) a function template with a
4256 /// given set of template arguments.
4257 ///
4258 /// Usually this should not be used, and template argument deduction should be
4259 /// used in its place.
4260 FunctionDecl *
4261 Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
4262                                      const TemplateArgumentList *Args,
4263                                      SourceLocation Loc) {
4264   FunctionDecl *FD = FTD->getTemplatedDecl();
4265 
4266   sema::TemplateDeductionInfo Info(Loc);
4267   InstantiatingTemplate Inst(
4268       *this, Loc, FTD, Args->asArray(),
4269       CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
4270   if (Inst.isInvalid())
4271     return nullptr;
4272 
4273   ContextRAII SavedContext(*this, FD);
4274   MultiLevelTemplateArgumentList MArgs(*Args);
4275 
4276   return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4277 }
4278 
4279 /// In the MS ABI, we need to instantiate default arguments of dllexported
4280 /// default constructors along with the constructor definition. This allows IR
4281 /// gen to emit a constructor closure which calls the default constructor with
4282 /// its default arguments.
4283 static void InstantiateDefaultCtorDefaultArgs(Sema &S,
4284                                               CXXConstructorDecl *Ctor) {
4285   assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4286          Ctor->isDefaultConstructor());
4287   unsigned NumParams = Ctor->getNumParams();
4288   if (NumParams == 0)
4289     return;
4290   DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
4291   if (!Attr)
4292     return;
4293   for (unsigned I = 0; I != NumParams; ++I) {
4294     (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
4295                                    Ctor->getParamDecl(I));
4296     S.DiscardCleanupsInEvaluationContext();
4297   }
4298 }
4299 
4300 /// Instantiate the definition of the given function from its
4301 /// template.
4302 ///
4303 /// \param PointOfInstantiation the point at which the instantiation was
4304 /// required. Note that this is not precisely a "point of instantiation"
4305 /// for the function, but it's close.
4306 ///
4307 /// \param Function the already-instantiated declaration of a
4308 /// function template specialization or member function of a class template
4309 /// specialization.
4310 ///
4311 /// \param Recursive if true, recursively instantiates any functions that
4312 /// are required by this instantiation.
4313 ///
4314 /// \param DefinitionRequired if true, then we are performing an explicit
4315 /// instantiation where the body of the function is required. Complain if
4316 /// there is no such body.
4317 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4318                                          FunctionDecl *Function,
4319                                          bool Recursive,
4320                                          bool DefinitionRequired,
4321                                          bool AtEndOfTU) {
4322   if (Function->isInvalidDecl() || Function->isDefined() ||
4323       isa<CXXDeductionGuideDecl>(Function))
4324     return;
4325 
4326   // Never instantiate an explicit specialization except if it is a class scope
4327   // explicit specialization.
4328   TemplateSpecializationKind TSK =
4329       Function->getTemplateSpecializationKindForInstantiation();
4330   if (TSK == TSK_ExplicitSpecialization)
4331     return;
4332 
4333   // Find the function body that we'll be substituting.
4334   const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4335   assert(PatternDecl && "instantiating a non-template");
4336 
4337   const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4338   Stmt *Pattern = nullptr;
4339   if (PatternDef) {
4340     Pattern = PatternDef->getBody(PatternDef);
4341     PatternDecl = PatternDef;
4342     if (PatternDef->willHaveBody())
4343       PatternDef = nullptr;
4344   }
4345 
4346   // FIXME: We need to track the instantiation stack in order to know which
4347   // definitions should be visible within this instantiation.
4348   if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
4349                                 Function->getInstantiatedFromMemberFunction(),
4350                                      PatternDecl, PatternDef, TSK,
4351                                      /*Complain*/DefinitionRequired)) {
4352     if (DefinitionRequired)
4353       Function->setInvalidDecl();
4354     else if (TSK == TSK_ExplicitInstantiationDefinition) {
4355       // Try again at the end of the translation unit (at which point a
4356       // definition will be required).
4357       assert(!Recursive);
4358       Function->setInstantiationIsPending(true);
4359       PendingInstantiations.push_back(
4360         std::make_pair(Function, PointOfInstantiation));
4361     } else if (TSK == TSK_ImplicitInstantiation) {
4362       if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4363           !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4364         Diag(PointOfInstantiation, diag::warn_func_template_missing)
4365           << Function;
4366         Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4367         if (getLangOpts().CPlusPlus11)
4368           Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4369             << Function;
4370       }
4371     }
4372 
4373     return;
4374   }
4375 
4376   // Postpone late parsed template instantiations.
4377   if (PatternDecl->isLateTemplateParsed() &&
4378       !LateTemplateParser) {
4379     Function->setInstantiationIsPending(true);
4380     LateParsedInstantiations.push_back(
4381         std::make_pair(Function, PointOfInstantiation));
4382     return;
4383   }
4384 
4385   llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
4386     std::string Name;
4387     llvm::raw_string_ostream OS(Name);
4388     Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4389                                    /*Qualified=*/true);
4390     return Name;
4391   });
4392 
4393   // If we're performing recursive template instantiation, create our own
4394   // queue of pending implicit instantiations that we will instantiate later,
4395   // while we're still within our own instantiation context.
4396   // This has to happen before LateTemplateParser below is called, so that
4397   // it marks vtables used in late parsed templates as used.
4398   GlobalEagerInstantiationScope GlobalInstantiations(*this,
4399                                                      /*Enabled=*/Recursive);
4400   LocalEagerInstantiationScope LocalInstantiations(*this);
4401 
4402   // Call the LateTemplateParser callback if there is a need to late parse
4403   // a templated function definition.
4404   if (!Pattern && PatternDecl->isLateTemplateParsed() &&
4405       LateTemplateParser) {
4406     // FIXME: Optimize to allow individual templates to be deserialized.
4407     if (PatternDecl->isFromASTFile())
4408       ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
4409 
4410     auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
4411     assert(LPTIter != LateParsedTemplateMap.end() &&
4412            "missing LateParsedTemplate");
4413     LateTemplateParser(OpaqueParser, *LPTIter->second);
4414     Pattern = PatternDecl->getBody(PatternDecl);
4415   }
4416 
4417   // Note, we should never try to instantiate a deleted function template.
4418   assert((Pattern || PatternDecl->isDefaulted() ||
4419           PatternDecl->hasSkippedBody()) &&
4420          "unexpected kind of function template definition");
4421 
4422   // C++1y [temp.explicit]p10:
4423   //   Except for inline functions, declarations with types deduced from their
4424   //   initializer or return value, and class template specializations, other
4425   //   explicit instantiation declarations have the effect of suppressing the
4426   //   implicit instantiation of the entity to which they refer.
4427   if (TSK == TSK_ExplicitInstantiationDeclaration &&
4428       !PatternDecl->isInlined() &&
4429       !PatternDecl->getReturnType()->getContainedAutoType())
4430     return;
4431 
4432   if (PatternDecl->isInlined()) {
4433     // Function, and all later redeclarations of it (from imported modules,
4434     // for instance), are now implicitly inline.
4435     for (auto *D = Function->getMostRecentDecl(); /**/;
4436          D = D->getPreviousDecl()) {
4437       D->setImplicitlyInline();
4438       if (D == Function)
4439         break;
4440     }
4441   }
4442 
4443   InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
4444   if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4445     return;
4446   PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
4447                                       "instantiating function definition");
4448 
4449   // The instantiation is visible here, even if it was first declared in an
4450   // unimported module.
4451   Function->setVisibleDespiteOwningModule();
4452 
4453   // Copy the inner loc start from the pattern.
4454   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
4455 
4456   EnterExpressionEvaluationContext EvalContext(
4457       *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4458 
4459   // Introduce a new scope where local variable instantiations will be
4460   // recorded, unless we're actually a member function within a local
4461   // class, in which case we need to merge our results with the parent
4462   // scope (of the enclosing function).
4463   bool MergeWithParentScope = false;
4464   if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
4465     MergeWithParentScope = Rec->isLocalClass();
4466 
4467   LocalInstantiationScope Scope(*this, MergeWithParentScope);
4468 
4469   if (PatternDecl->isDefaulted())
4470     SetDeclDefaulted(Function, PatternDecl->getLocation());
4471   else {
4472     MultiLevelTemplateArgumentList TemplateArgs =
4473       getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
4474 
4475     // Substitute into the qualifier; we can get a substitution failure here
4476     // through evil use of alias templates.
4477     // FIXME: Is CurContext correct for this? Should we go to the (instantiation
4478     // of the) lexical context of the pattern?
4479     SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
4480 
4481     ActOnStartOfFunctionDef(nullptr, Function);
4482 
4483     // Enter the scope of this instantiation. We don't use
4484     // PushDeclContext because we don't have a scope.
4485     Sema::ContextRAII savedContext(*this, Function);
4486 
4487     if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
4488                                          TemplateArgs))
4489       return;
4490 
4491     StmtResult Body;
4492     if (PatternDecl->hasSkippedBody()) {
4493       ActOnSkippedFunctionBody(Function);
4494       Body = nullptr;
4495     } else {
4496       if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
4497         // If this is a constructor, instantiate the member initializers.
4498         InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
4499                                    TemplateArgs);
4500 
4501         // If this is an MS ABI dllexport default constructor, instantiate any
4502         // default arguments.
4503         if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4504             Ctor->isDefaultConstructor()) {
4505           InstantiateDefaultCtorDefaultArgs(*this, Ctor);
4506         }
4507       }
4508 
4509       // Instantiate the function body.
4510       Body = SubstStmt(Pattern, TemplateArgs);
4511 
4512       if (Body.isInvalid())
4513         Function->setInvalidDecl();
4514     }
4515     // FIXME: finishing the function body while in an expression evaluation
4516     // context seems wrong. Investigate more.
4517     ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
4518 
4519     PerformDependentDiagnostics(PatternDecl, TemplateArgs);
4520 
4521     if (auto *Listener = getASTMutationListener())
4522       Listener->FunctionDefinitionInstantiated(Function);
4523 
4524     savedContext.pop();
4525   }
4526 
4527   DeclGroupRef DG(Function);
4528   Consumer.HandleTopLevelDecl(DG);
4529 
4530   // This class may have local implicit instantiations that need to be
4531   // instantiation within this scope.
4532   LocalInstantiations.perform();
4533   Scope.Exit();
4534   GlobalInstantiations.perform();
4535 }
4536 
4537 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
4538     VarTemplateDecl *VarTemplate, VarDecl *FromVar,
4539     const TemplateArgumentList &TemplateArgList,
4540     const TemplateArgumentListInfo &TemplateArgsInfo,
4541     SmallVectorImpl<TemplateArgument> &Converted,
4542     SourceLocation PointOfInstantiation, void *InsertPos,
4543     LateInstantiatedAttrVec *LateAttrs,
4544     LocalInstantiationScope *StartingScope) {
4545   if (FromVar->isInvalidDecl())
4546     return nullptr;
4547 
4548   InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
4549   if (Inst.isInvalid())
4550     return nullptr;
4551 
4552   MultiLevelTemplateArgumentList TemplateArgLists;
4553   TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
4554 
4555   // Instantiate the first declaration of the variable template: for a partial
4556   // specialization of a static data member template, the first declaration may
4557   // or may not be the declaration in the class; if it's in the class, we want
4558   // to instantiate a member in the class (a declaration), and if it's outside,
4559   // we want to instantiate a definition.
4560   //
4561   // If we're instantiating an explicitly-specialized member template or member
4562   // partial specialization, don't do this. The member specialization completely
4563   // replaces the original declaration in this case.
4564   bool IsMemberSpec = false;
4565   if (VarTemplatePartialSpecializationDecl *PartialSpec =
4566           dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
4567     IsMemberSpec = PartialSpec->isMemberSpecialization();
4568   else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
4569     IsMemberSpec = FromTemplate->isMemberSpecialization();
4570   if (!IsMemberSpec)
4571     FromVar = FromVar->getFirstDecl();
4572 
4573   MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
4574   TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
4575                                         MultiLevelList);
4576 
4577   // TODO: Set LateAttrs and StartingScope ...
4578 
4579   return cast_or_null<VarTemplateSpecializationDecl>(
4580       Instantiator.VisitVarTemplateSpecializationDecl(
4581           VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
4582 }
4583 
4584 /// Instantiates a variable template specialization by completing it
4585 /// with appropriate type information and initializer.
4586 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
4587     VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
4588     const MultiLevelTemplateArgumentList &TemplateArgs) {
4589   assert(PatternDecl->isThisDeclarationADefinition() &&
4590          "don't have a definition to instantiate from");
4591 
4592   // Do substitution on the type of the declaration
4593   TypeSourceInfo *DI =
4594       SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
4595                 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
4596   if (!DI)
4597     return nullptr;
4598 
4599   // Update the type of this variable template specialization.
4600   VarSpec->setType(DI->getType());
4601 
4602   // Convert the declaration into a definition now.
4603   VarSpec->setCompleteDefinition();
4604 
4605   // Instantiate the initializer.
4606   InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
4607 
4608   return VarSpec;
4609 }
4610 
4611 /// BuildVariableInstantiation - Used after a new variable has been created.
4612 /// Sets basic variable data and decides whether to postpone the
4613 /// variable instantiation.
4614 void Sema::BuildVariableInstantiation(
4615     VarDecl *NewVar, VarDecl *OldVar,
4616     const MultiLevelTemplateArgumentList &TemplateArgs,
4617     LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
4618     LocalInstantiationScope *StartingScope,
4619     bool InstantiatingVarTemplate,
4620     VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
4621   // Instantiating a partial specialization to produce a partial
4622   // specialization.
4623   bool InstantiatingVarTemplatePartialSpec =
4624       isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
4625       isa<VarTemplatePartialSpecializationDecl>(NewVar);
4626   // Instantiating from a variable template (or partial specialization) to
4627   // produce a variable template specialization.
4628   bool InstantiatingSpecFromTemplate =
4629       isa<VarTemplateSpecializationDecl>(NewVar) &&
4630       (OldVar->getDescribedVarTemplate() ||
4631        isa<VarTemplatePartialSpecializationDecl>(OldVar));
4632 
4633   // If we are instantiating a local extern declaration, the
4634   // instantiation belongs lexically to the containing function.
4635   // If we are instantiating a static data member defined
4636   // out-of-line, the instantiation will have the same lexical
4637   // context (which will be a namespace scope) as the template.
4638   if (OldVar->isLocalExternDecl()) {
4639     NewVar->setLocalExternDecl();
4640     NewVar->setLexicalDeclContext(Owner);
4641   } else if (OldVar->isOutOfLine())
4642     NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
4643   NewVar->setTSCSpec(OldVar->getTSCSpec());
4644   NewVar->setInitStyle(OldVar->getInitStyle());
4645   NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
4646   NewVar->setObjCForDecl(OldVar->isObjCForDecl());
4647   NewVar->setConstexpr(OldVar->isConstexpr());
4648   NewVar->setInitCapture(OldVar->isInitCapture());
4649   NewVar->setPreviousDeclInSameBlockScope(
4650       OldVar->isPreviousDeclInSameBlockScope());
4651   NewVar->setAccess(OldVar->getAccess());
4652 
4653   if (!OldVar->isStaticDataMember()) {
4654     if (OldVar->isUsed(false))
4655       NewVar->setIsUsed();
4656     NewVar->setReferenced(OldVar->isReferenced());
4657   }
4658 
4659   InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
4660 
4661   LookupResult Previous(
4662       *this, NewVar->getDeclName(), NewVar->getLocation(),
4663       NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
4664                                   : Sema::LookupOrdinaryName,
4665       NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
4666                                   : forRedeclarationInCurContext());
4667 
4668   if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
4669       (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
4670        OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
4671     // We have a previous declaration. Use that one, so we merge with the
4672     // right type.
4673     if (NamedDecl *NewPrev = FindInstantiatedDecl(
4674             NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
4675       Previous.addDecl(NewPrev);
4676   } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
4677              OldVar->hasLinkage()) {
4678     LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
4679   } else if (PrevDeclForVarTemplateSpecialization) {
4680     Previous.addDecl(PrevDeclForVarTemplateSpecialization);
4681   }
4682   CheckVariableDeclaration(NewVar, Previous);
4683 
4684   if (!InstantiatingVarTemplate) {
4685     NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
4686     if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
4687       NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
4688   }
4689 
4690   if (!OldVar->isOutOfLine()) {
4691     if (NewVar->getDeclContext()->isFunctionOrMethod())
4692       CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
4693   }
4694 
4695   // Link instantiations of static data members back to the template from
4696   // which they were instantiated.
4697   //
4698   // Don't do this when instantiating a template (we link the template itself
4699   // back in that case) nor when instantiating a static data member template
4700   // (that's not a member specialization).
4701   if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
4702       !InstantiatingSpecFromTemplate)
4703     NewVar->setInstantiationOfStaticDataMember(OldVar,
4704                                                TSK_ImplicitInstantiation);
4705 
4706   // If the pattern is an (in-class) explicit specialization, then the result
4707   // is also an explicit specialization.
4708   if (VarTemplateSpecializationDecl *OldVTSD =
4709           dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
4710     if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
4711         !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
4712       cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
4713           TSK_ExplicitSpecialization);
4714   }
4715 
4716   // Forward the mangling number from the template to the instantiated decl.
4717   Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
4718   Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
4719 
4720   // Figure out whether to eagerly instantiate the initializer.
4721   if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
4722     // We're producing a template. Don't instantiate the initializer yet.
4723   } else if (NewVar->getType()->isUndeducedType()) {
4724     // We need the type to complete the declaration of the variable.
4725     InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4726   } else if (InstantiatingSpecFromTemplate ||
4727              (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
4728               !NewVar->isThisDeclarationADefinition())) {
4729     // Delay instantiation of the initializer for variable template
4730     // specializations or inline static data members until a definition of the
4731     // variable is needed.
4732   } else {
4733     InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4734   }
4735 
4736   // Diagnose unused local variables with dependent types, where the diagnostic
4737   // will have been deferred.
4738   if (!NewVar->isInvalidDecl() &&
4739       NewVar->getDeclContext()->isFunctionOrMethod() &&
4740       OldVar->getType()->isDependentType())
4741     DiagnoseUnusedDecl(NewVar);
4742 }
4743 
4744 /// Instantiate the initializer of a variable.
4745 void Sema::InstantiateVariableInitializer(
4746     VarDecl *Var, VarDecl *OldVar,
4747     const MultiLevelTemplateArgumentList &TemplateArgs) {
4748   if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4749     L->VariableDefinitionInstantiated(Var);
4750 
4751   // We propagate the 'inline' flag with the initializer, because it
4752   // would otherwise imply that the variable is a definition for a
4753   // non-static data member.
4754   if (OldVar->isInlineSpecified())
4755     Var->setInlineSpecified();
4756   else if (OldVar->isInline())
4757     Var->setImplicitlyInline();
4758 
4759   if (OldVar->getInit()) {
4760     EnterExpressionEvaluationContext Evaluated(
4761         *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
4762 
4763     // Instantiate the initializer.
4764     ExprResult Init;
4765 
4766     {
4767       ContextRAII SwitchContext(*this, Var->getDeclContext());
4768       Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
4769                               OldVar->getInitStyle() == VarDecl::CallInit);
4770     }
4771 
4772     if (!Init.isInvalid()) {
4773       Expr *InitExpr = Init.get();
4774 
4775       if (Var->hasAttr<DLLImportAttr>() &&
4776           (!InitExpr ||
4777            !InitExpr->isConstantInitializer(getASTContext(), false))) {
4778         // Do not dynamically initialize dllimport variables.
4779       } else if (InitExpr) {
4780         bool DirectInit = OldVar->isDirectInit();
4781         AddInitializerToDecl(Var, InitExpr, DirectInit);
4782       } else
4783         ActOnUninitializedDecl(Var);
4784     } else {
4785       // FIXME: Not too happy about invalidating the declaration
4786       // because of a bogus initializer.
4787       Var->setInvalidDecl();
4788     }
4789   } else {
4790     // `inline` variables are a definition and declaration all in one; we won't
4791     // pick up an initializer from anywhere else.
4792     if (Var->isStaticDataMember() && !Var->isInline()) {
4793       if (!Var->isOutOfLine())
4794         return;
4795 
4796       // If the declaration inside the class had an initializer, don't add
4797       // another one to the out-of-line definition.
4798       if (OldVar->getFirstDecl()->hasInit())
4799         return;
4800     }
4801 
4802     // We'll add an initializer to a for-range declaration later.
4803     if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
4804       return;
4805 
4806     ActOnUninitializedDecl(Var);
4807   }
4808 
4809   if (getLangOpts().CUDA)
4810     checkAllowedCUDAInitializer(Var);
4811 }
4812 
4813 /// Instantiate the definition of the given variable from its
4814 /// template.
4815 ///
4816 /// \param PointOfInstantiation the point at which the instantiation was
4817 /// required. Note that this is not precisely a "point of instantiation"
4818 /// for the variable, but it's close.
4819 ///
4820 /// \param Var the already-instantiated declaration of a templated variable.
4821 ///
4822 /// \param Recursive if true, recursively instantiates any functions that
4823 /// are required by this instantiation.
4824 ///
4825 /// \param DefinitionRequired if true, then we are performing an explicit
4826 /// instantiation where a definition of the variable is required. Complain
4827 /// if there is no such definition.
4828 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
4829                                          VarDecl *Var, bool Recursive,
4830                                       bool DefinitionRequired, bool AtEndOfTU) {
4831   if (Var->isInvalidDecl())
4832     return;
4833 
4834   // Never instantiate an explicitly-specialized entity.
4835   TemplateSpecializationKind TSK =
4836       Var->getTemplateSpecializationKindForInstantiation();
4837   if (TSK == TSK_ExplicitSpecialization)
4838     return;
4839 
4840   // Find the pattern and the arguments to substitute into it.
4841   VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
4842   assert(PatternDecl && "no pattern for templated variable");
4843   MultiLevelTemplateArgumentList TemplateArgs =
4844       getTemplateInstantiationArgs(Var);
4845 
4846   VarTemplateSpecializationDecl *VarSpec =
4847       dyn_cast<VarTemplateSpecializationDecl>(Var);
4848   if (VarSpec) {
4849     // If this is a variable template specialization, make sure that it is
4850     // non-dependent.
4851     bool InstantiationDependent = false;
4852     assert(!TemplateSpecializationType::anyDependentTemplateArguments(
4853                VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
4854            "Only instantiate variable template specializations that are "
4855            "not type-dependent");
4856     (void)InstantiationDependent;
4857 
4858     // If this is a static data member template, there might be an
4859     // uninstantiated initializer on the declaration. If so, instantiate
4860     // it now.
4861     //
4862     // FIXME: This largely duplicates what we would do below. The difference
4863     // is that along this path we may instantiate an initializer from an
4864     // in-class declaration of the template and instantiate the definition
4865     // from a separate out-of-class definition.
4866     if (PatternDecl->isStaticDataMember() &&
4867         (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
4868         !Var->hasInit()) {
4869       // FIXME: Factor out the duplicated instantiation context setup/tear down
4870       // code here.
4871       InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4872       if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4873         return;
4874       PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
4875                                           "instantiating variable initializer");
4876 
4877       // The instantiation is visible here, even if it was first declared in an
4878       // unimported module.
4879       Var->setVisibleDespiteOwningModule();
4880 
4881       // If we're performing recursive template instantiation, create our own
4882       // queue of pending implicit instantiations that we will instantiate
4883       // later, while we're still within our own instantiation context.
4884       GlobalEagerInstantiationScope GlobalInstantiations(*this,
4885                                                          /*Enabled=*/Recursive);
4886       LocalInstantiationScope Local(*this);
4887       LocalEagerInstantiationScope LocalInstantiations(*this);
4888 
4889       // Enter the scope of this instantiation. We don't use
4890       // PushDeclContext because we don't have a scope.
4891       ContextRAII PreviousContext(*this, Var->getDeclContext());
4892       InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
4893       PreviousContext.pop();
4894 
4895       // This variable may have local implicit instantiations that need to be
4896       // instantiated within this scope.
4897       LocalInstantiations.perform();
4898       Local.Exit();
4899       GlobalInstantiations.perform();
4900     }
4901   } else {
4902     assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
4903            "not a static data member?");
4904   }
4905 
4906   VarDecl *Def = PatternDecl->getDefinition(getASTContext());
4907 
4908   // If we don't have a definition of the variable template, we won't perform
4909   // any instantiation. Rather, we rely on the user to instantiate this
4910   // definition (or provide a specialization for it) in another translation
4911   // unit.
4912   if (!Def && !DefinitionRequired) {
4913     if (TSK == TSK_ExplicitInstantiationDefinition) {
4914       PendingInstantiations.push_back(
4915         std::make_pair(Var, PointOfInstantiation));
4916     } else if (TSK == TSK_ImplicitInstantiation) {
4917       // Warn about missing definition at the end of translation unit.
4918       if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4919           !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4920         Diag(PointOfInstantiation, diag::warn_var_template_missing)
4921           << Var;
4922         Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4923         if (getLangOpts().CPlusPlus11)
4924           Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
4925       }
4926       return;
4927     }
4928   }
4929 
4930   // FIXME: We need to track the instantiation stack in order to know which
4931   // definitions should be visible within this instantiation.
4932   // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
4933   if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
4934                                      /*InstantiatedFromMember*/false,
4935                                      PatternDecl, Def, TSK,
4936                                      /*Complain*/DefinitionRequired))
4937     return;
4938 
4939   // C++11 [temp.explicit]p10:
4940   //   Except for inline functions, const variables of literal types, variables
4941   //   of reference types, [...] explicit instantiation declarations
4942   //   have the effect of suppressing the implicit instantiation of the entity
4943   //   to which they refer.
4944   //
4945   // FIXME: That's not exactly the same as "might be usable in constant
4946   // expressions", which only allows constexpr variables and const integral
4947   // types, not arbitrary const literal types.
4948   if (TSK == TSK_ExplicitInstantiationDeclaration &&
4949       !Var->mightBeUsableInConstantExpressions(getASTContext()))
4950     return;
4951 
4952   // Make sure to pass the instantiated variable to the consumer at the end.
4953   struct PassToConsumerRAII {
4954     ASTConsumer &Consumer;
4955     VarDecl *Var;
4956 
4957     PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
4958       : Consumer(Consumer), Var(Var) { }
4959 
4960     ~PassToConsumerRAII() {
4961       Consumer.HandleCXXStaticMemberVarInstantiation(Var);
4962     }
4963   } PassToConsumerRAII(Consumer, Var);
4964 
4965   // If we already have a definition, we're done.
4966   if (VarDecl *Def = Var->getDefinition()) {
4967     // We may be explicitly instantiating something we've already implicitly
4968     // instantiated.
4969     Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
4970                                        PointOfInstantiation);
4971     return;
4972   }
4973 
4974   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4975   if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4976     return;
4977   PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
4978                                       "instantiating variable definition");
4979 
4980   // If we're performing recursive template instantiation, create our own
4981   // queue of pending implicit instantiations that we will instantiate later,
4982   // while we're still within our own instantiation context.
4983   GlobalEagerInstantiationScope GlobalInstantiations(*this,
4984                                                      /*Enabled=*/Recursive);
4985 
4986   // Enter the scope of this instantiation. We don't use
4987   // PushDeclContext because we don't have a scope.
4988   ContextRAII PreviousContext(*this, Var->getDeclContext());
4989   LocalInstantiationScope Local(*this);
4990 
4991   LocalEagerInstantiationScope LocalInstantiations(*this);
4992 
4993   VarDecl *OldVar = Var;
4994   if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
4995     // We're instantiating an inline static data member whose definition was
4996     // provided inside the class.
4997     InstantiateVariableInitializer(Var, Def, TemplateArgs);
4998   } else if (!VarSpec) {
4999     Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
5000                                           TemplateArgs));
5001   } else if (Var->isStaticDataMember() &&
5002              Var->getLexicalDeclContext()->isRecord()) {
5003     // We need to instantiate the definition of a static data member template,
5004     // and all we have is the in-class declaration of it. Instantiate a separate
5005     // declaration of the definition.
5006     TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
5007                                           TemplateArgs);
5008     Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
5009         VarSpec->getSpecializedTemplate(), Def, nullptr,
5010         VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
5011     if (Var) {
5012       llvm::PointerUnion<VarTemplateDecl *,
5013                          VarTemplatePartialSpecializationDecl *> PatternPtr =
5014           VarSpec->getSpecializedTemplateOrPartial();
5015       if (VarTemplatePartialSpecializationDecl *Partial =
5016           PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
5017         cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
5018             Partial, &VarSpec->getTemplateInstantiationArgs());
5019 
5020       // Merge the definition with the declaration.
5021       LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
5022                      LookupOrdinaryName, forRedeclarationInCurContext());
5023       R.addDecl(OldVar);
5024       MergeVarDecl(Var, R);
5025 
5026       // Attach the initializer.
5027       InstantiateVariableInitializer(Var, Def, TemplateArgs);
5028     }
5029   } else
5030     // Complete the existing variable's definition with an appropriately
5031     // substituted type and initializer.
5032     Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
5033 
5034   PreviousContext.pop();
5035 
5036   if (Var) {
5037     PassToConsumerRAII.Var = Var;
5038     Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
5039                                        OldVar->getPointOfInstantiation());
5040   }
5041 
5042   // This variable may have local implicit instantiations that need to be
5043   // instantiated within this scope.
5044   LocalInstantiations.perform();
5045   Local.Exit();
5046   GlobalInstantiations.perform();
5047 }
5048 
5049 void
5050 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
5051                                  const CXXConstructorDecl *Tmpl,
5052                            const MultiLevelTemplateArgumentList &TemplateArgs) {
5053 
5054   SmallVector<CXXCtorInitializer*, 4> NewInits;
5055   bool AnyErrors = Tmpl->isInvalidDecl();
5056 
5057   // Instantiate all the initializers.
5058   for (const auto *Init : Tmpl->inits()) {
5059     // Only instantiate written initializers, let Sema re-construct implicit
5060     // ones.
5061     if (!Init->isWritten())
5062       continue;
5063 
5064     SourceLocation EllipsisLoc;
5065 
5066     if (Init->isPackExpansion()) {
5067       // This is a pack expansion. We should expand it now.
5068       TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
5069       SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5070       collectUnexpandedParameterPacks(BaseTL, Unexpanded);
5071       collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
5072       bool ShouldExpand = false;
5073       bool RetainExpansion = false;
5074       Optional<unsigned> NumExpansions;
5075       if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
5076                                           BaseTL.getSourceRange(),
5077                                           Unexpanded,
5078                                           TemplateArgs, ShouldExpand,
5079                                           RetainExpansion,
5080                                           NumExpansions)) {
5081         AnyErrors = true;
5082         New->setInvalidDecl();
5083         continue;
5084       }
5085       assert(ShouldExpand && "Partial instantiation of base initializer?");
5086 
5087       // Loop over all of the arguments in the argument pack(s),
5088       for (unsigned I = 0; I != *NumExpansions; ++I) {
5089         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
5090 
5091         // Instantiate the initializer.
5092         ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5093                                                /*CXXDirectInit=*/true);
5094         if (TempInit.isInvalid()) {
5095           AnyErrors = true;
5096           break;
5097         }
5098 
5099         // Instantiate the base type.
5100         TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
5101                                               TemplateArgs,
5102                                               Init->getSourceLocation(),
5103                                               New->getDeclName());
5104         if (!BaseTInfo) {
5105           AnyErrors = true;
5106           break;
5107         }
5108 
5109         // Build the initializer.
5110         MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
5111                                                      BaseTInfo, TempInit.get(),
5112                                                      New->getParent(),
5113                                                      SourceLocation());
5114         if (NewInit.isInvalid()) {
5115           AnyErrors = true;
5116           break;
5117         }
5118 
5119         NewInits.push_back(NewInit.get());
5120       }
5121 
5122       continue;
5123     }
5124 
5125     // Instantiate the initializer.
5126     ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5127                                            /*CXXDirectInit=*/true);
5128     if (TempInit.isInvalid()) {
5129       AnyErrors = true;
5130       continue;
5131     }
5132 
5133     MemInitResult NewInit;
5134     if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
5135       TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
5136                                         TemplateArgs,
5137                                         Init->getSourceLocation(),
5138                                         New->getDeclName());
5139       if (!TInfo) {
5140         AnyErrors = true;
5141         New->setInvalidDecl();
5142         continue;
5143       }
5144 
5145       if (Init->isBaseInitializer())
5146         NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
5147                                        New->getParent(), EllipsisLoc);
5148       else
5149         NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
5150                                   cast<CXXRecordDecl>(CurContext->getParent()));
5151     } else if (Init->isMemberInitializer()) {
5152       FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
5153                                                      Init->getMemberLocation(),
5154                                                      Init->getMember(),
5155                                                      TemplateArgs));
5156       if (!Member) {
5157         AnyErrors = true;
5158         New->setInvalidDecl();
5159         continue;
5160       }
5161 
5162       NewInit = BuildMemberInitializer(Member, TempInit.get(),
5163                                        Init->getSourceLocation());
5164     } else if (Init->isIndirectMemberInitializer()) {
5165       IndirectFieldDecl *IndirectMember =
5166          cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
5167                                  Init->getMemberLocation(),
5168                                  Init->getIndirectMember(), TemplateArgs));
5169 
5170       if (!IndirectMember) {
5171         AnyErrors = true;
5172         New->setInvalidDecl();
5173         continue;
5174       }
5175 
5176       NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
5177                                        Init->getSourceLocation());
5178     }
5179 
5180     if (NewInit.isInvalid()) {
5181       AnyErrors = true;
5182       New->setInvalidDecl();
5183     } else {
5184       NewInits.push_back(NewInit.get());
5185     }
5186   }
5187 
5188   // Assign all the initializers to the new constructor.
5189   ActOnMemInitializers(New,
5190                        /*FIXME: ColonLoc */
5191                        SourceLocation(),
5192                        NewInits,
5193                        AnyErrors);
5194 }
5195 
5196 // TODO: this could be templated if the various decl types used the
5197 // same method name.
5198 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
5199                               ClassTemplateDecl *Instance) {
5200   Pattern = Pattern->getCanonicalDecl();
5201 
5202   do {
5203     Instance = Instance->getCanonicalDecl();
5204     if (Pattern == Instance) return true;
5205     Instance = Instance->getInstantiatedFromMemberTemplate();
5206   } while (Instance);
5207 
5208   return false;
5209 }
5210 
5211 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
5212                               FunctionTemplateDecl *Instance) {
5213   Pattern = Pattern->getCanonicalDecl();
5214 
5215   do {
5216     Instance = Instance->getCanonicalDecl();
5217     if (Pattern == Instance) return true;
5218     Instance = Instance->getInstantiatedFromMemberTemplate();
5219   } while (Instance);
5220 
5221   return false;
5222 }
5223 
5224 static bool
5225 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
5226                   ClassTemplatePartialSpecializationDecl *Instance) {
5227   Pattern
5228     = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
5229   do {
5230     Instance = cast<ClassTemplatePartialSpecializationDecl>(
5231                                                 Instance->getCanonicalDecl());
5232     if (Pattern == Instance)
5233       return true;
5234     Instance = Instance->getInstantiatedFromMember();
5235   } while (Instance);
5236 
5237   return false;
5238 }
5239 
5240 static bool isInstantiationOf(CXXRecordDecl *Pattern,
5241                               CXXRecordDecl *Instance) {
5242   Pattern = Pattern->getCanonicalDecl();
5243 
5244   do {
5245     Instance = Instance->getCanonicalDecl();
5246     if (Pattern == Instance) return true;
5247     Instance = Instance->getInstantiatedFromMemberClass();
5248   } while (Instance);
5249 
5250   return false;
5251 }
5252 
5253 static bool isInstantiationOf(FunctionDecl *Pattern,
5254                               FunctionDecl *Instance) {
5255   Pattern = Pattern->getCanonicalDecl();
5256 
5257   do {
5258     Instance = Instance->getCanonicalDecl();
5259     if (Pattern == Instance) return true;
5260     Instance = Instance->getInstantiatedFromMemberFunction();
5261   } while (Instance);
5262 
5263   return false;
5264 }
5265 
5266 static bool isInstantiationOf(EnumDecl *Pattern,
5267                               EnumDecl *Instance) {
5268   Pattern = Pattern->getCanonicalDecl();
5269 
5270   do {
5271     Instance = Instance->getCanonicalDecl();
5272     if (Pattern == Instance) return true;
5273     Instance = Instance->getInstantiatedFromMemberEnum();
5274   } while (Instance);
5275 
5276   return false;
5277 }
5278 
5279 static bool isInstantiationOf(UsingShadowDecl *Pattern,
5280                               UsingShadowDecl *Instance,
5281                               ASTContext &C) {
5282   return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
5283                             Pattern);
5284 }
5285 
5286 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
5287                               ASTContext &C) {
5288   return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
5289 }
5290 
5291 template<typename T>
5292 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
5293                                                  ASTContext &Ctx) {
5294   // An unresolved using declaration can instantiate to an unresolved using
5295   // declaration, or to a using declaration or a using declaration pack.
5296   //
5297   // Multiple declarations can claim to be instantiated from an unresolved
5298   // using declaration if it's a pack expansion. We want the UsingPackDecl
5299   // in that case, not the individual UsingDecls within the pack.
5300   bool OtherIsPackExpansion;
5301   NamedDecl *OtherFrom;
5302   if (auto *OtherUUD = dyn_cast<T>(Other)) {
5303     OtherIsPackExpansion = OtherUUD->isPackExpansion();
5304     OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
5305   } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
5306     OtherIsPackExpansion = true;
5307     OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
5308   } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
5309     OtherIsPackExpansion = false;
5310     OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
5311   } else {
5312     return false;
5313   }
5314   return Pattern->isPackExpansion() == OtherIsPackExpansion &&
5315          declaresSameEntity(OtherFrom, Pattern);
5316 }
5317 
5318 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
5319                                               VarDecl *Instance) {
5320   assert(Instance->isStaticDataMember());
5321 
5322   Pattern = Pattern->getCanonicalDecl();
5323 
5324   do {
5325     Instance = Instance->getCanonicalDecl();
5326     if (Pattern == Instance) return true;
5327     Instance = Instance->getInstantiatedFromStaticDataMember();
5328   } while (Instance);
5329 
5330   return false;
5331 }
5332 
5333 // Other is the prospective instantiation
5334 // D is the prospective pattern
5335 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
5336   if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
5337     return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5338 
5339   if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
5340     return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5341 
5342   if (D->getKind() != Other->getKind())
5343     return false;
5344 
5345   if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
5346     return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
5347 
5348   if (auto *Function = dyn_cast<FunctionDecl>(Other))
5349     return isInstantiationOf(cast<FunctionDecl>(D), Function);
5350 
5351   if (auto *Enum = dyn_cast<EnumDecl>(Other))
5352     return isInstantiationOf(cast<EnumDecl>(D), Enum);
5353 
5354   if (auto *Var = dyn_cast<VarDecl>(Other))
5355     if (Var->isStaticDataMember())
5356       return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
5357 
5358   if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
5359     return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
5360 
5361   if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
5362     return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
5363 
5364   if (auto *PartialSpec =
5365           dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
5366     return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
5367                              PartialSpec);
5368 
5369   if (auto *Field = dyn_cast<FieldDecl>(Other)) {
5370     if (!Field->getDeclName()) {
5371       // This is an unnamed field.
5372       return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
5373                                 cast<FieldDecl>(D));
5374     }
5375   }
5376 
5377   if (auto *Using = dyn_cast<UsingDecl>(Other))
5378     return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
5379 
5380   if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
5381     return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
5382 
5383   return D->getDeclName() &&
5384          D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
5385 }
5386 
5387 template<typename ForwardIterator>
5388 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
5389                                       NamedDecl *D,
5390                                       ForwardIterator first,
5391                                       ForwardIterator last) {
5392   for (; first != last; ++first)
5393     if (isInstantiationOf(Ctx, D, *first))
5394       return cast<NamedDecl>(*first);
5395 
5396   return nullptr;
5397 }
5398 
5399 /// Finds the instantiation of the given declaration context
5400 /// within the current instantiation.
5401 ///
5402 /// \returns NULL if there was an error
5403 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
5404                           const MultiLevelTemplateArgumentList &TemplateArgs) {
5405   if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
5406     Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
5407     return cast_or_null<DeclContext>(ID);
5408   } else return DC;
5409 }
5410 
5411 /// Find the instantiation of the given declaration within the
5412 /// current instantiation.
5413 ///
5414 /// This routine is intended to be used when \p D is a declaration
5415 /// referenced from within a template, that needs to mapped into the
5416 /// corresponding declaration within an instantiation. For example,
5417 /// given:
5418 ///
5419 /// \code
5420 /// template<typename T>
5421 /// struct X {
5422 ///   enum Kind {
5423 ///     KnownValue = sizeof(T)
5424 ///   };
5425 ///
5426 ///   bool getKind() const { return KnownValue; }
5427 /// };
5428 ///
5429 /// template struct X<int>;
5430 /// \endcode
5431 ///
5432 /// In the instantiation of X<int>::getKind(), we need to map the \p
5433 /// EnumConstantDecl for \p KnownValue (which refers to
5434 /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
5435 /// \p FindInstantiatedDecl performs this mapping from within the instantiation
5436 /// of X<int>.
5437 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
5438                           const MultiLevelTemplateArgumentList &TemplateArgs,
5439                           bool FindingInstantiatedContext) {
5440   DeclContext *ParentDC = D->getDeclContext();
5441   // FIXME: Parmeters of pointer to functions (y below) that are themselves
5442   // parameters (p below) can have their ParentDC set to the translation-unit
5443   // - thus we can not consistently check if the ParentDC of such a parameter
5444   // is Dependent or/and a FunctionOrMethod.
5445   // For e.g. this code, during Template argument deduction tries to
5446   // find an instantiated decl for (T y) when the ParentDC for y is
5447   // the translation unit.
5448   //   e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
5449   //   float baz(float(*)()) { return 0.0; }
5450   //   Foo(baz);
5451   // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
5452   // it gets here, always has a FunctionOrMethod as its ParentDC??
5453   // For now:
5454   //  - as long as we have a ParmVarDecl whose parent is non-dependent and
5455   //    whose type is not instantiation dependent, do nothing to the decl
5456   //  - otherwise find its instantiated decl.
5457   if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
5458       !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
5459     return D;
5460   if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
5461       isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
5462       ((ParentDC->isFunctionOrMethod() ||
5463         isa<OMPDeclareReductionDecl>(ParentDC) ||
5464         isa<OMPDeclareMapperDecl>(ParentDC)) &&
5465        ParentDC->isDependentContext()) ||
5466       (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
5467     // D is a local of some kind. Look into the map of local
5468     // declarations to their instantiations.
5469     if (CurrentInstantiationScope) {
5470       if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
5471         if (Decl *FD = Found->dyn_cast<Decl *>())
5472           return cast<NamedDecl>(FD);
5473 
5474         int PackIdx = ArgumentPackSubstitutionIndex;
5475         assert(PackIdx != -1 &&
5476                "found declaration pack but not pack expanding");
5477         typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
5478         return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
5479       }
5480     }
5481 
5482     // If we're performing a partial substitution during template argument
5483     // deduction, we may not have values for template parameters yet. They
5484     // just map to themselves.
5485     if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
5486         isa<TemplateTemplateParmDecl>(D))
5487       return D;
5488 
5489     if (D->isInvalidDecl())
5490       return nullptr;
5491 
5492     // Normally this function only searches for already instantiated declaration
5493     // however we have to make an exclusion for local types used before
5494     // definition as in the code:
5495     //
5496     //   template<typename T> void f1() {
5497     //     void g1(struct x1);
5498     //     struct x1 {};
5499     //   }
5500     //
5501     // In this case instantiation of the type of 'g1' requires definition of
5502     // 'x1', which is defined later. Error recovery may produce an enum used
5503     // before definition. In these cases we need to instantiate relevant
5504     // declarations here.
5505     bool NeedInstantiate = false;
5506     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5507       NeedInstantiate = RD->isLocalClass();
5508     else
5509       NeedInstantiate = isa<EnumDecl>(D);
5510     if (NeedInstantiate) {
5511       Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5512       CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5513       return cast<TypeDecl>(Inst);
5514     }
5515 
5516     // If we didn't find the decl, then we must have a label decl that hasn't
5517     // been found yet.  Lazily instantiate it and return it now.
5518     assert(isa<LabelDecl>(D));
5519 
5520     Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5521     assert(Inst && "Failed to instantiate label??");
5522 
5523     CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5524     return cast<LabelDecl>(Inst);
5525   }
5526 
5527   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
5528     if (!Record->isDependentContext())
5529       return D;
5530 
5531     // Determine whether this record is the "templated" declaration describing
5532     // a class template or class template partial specialization.
5533     ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
5534     if (ClassTemplate)
5535       ClassTemplate = ClassTemplate->getCanonicalDecl();
5536     else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5537                = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
5538       ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
5539 
5540     // Walk the current context to find either the record or an instantiation of
5541     // it.
5542     DeclContext *DC = CurContext;
5543     while (!DC->isFileContext()) {
5544       // If we're performing substitution while we're inside the template
5545       // definition, we'll find our own context. We're done.
5546       if (DC->Equals(Record))
5547         return Record;
5548 
5549       if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
5550         // Check whether we're in the process of instantiating a class template
5551         // specialization of the template we're mapping.
5552         if (ClassTemplateSpecializationDecl *InstSpec
5553                       = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
5554           ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
5555           if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
5556             return InstRecord;
5557         }
5558 
5559         // Check whether we're in the process of instantiating a member class.
5560         if (isInstantiationOf(Record, InstRecord))
5561           return InstRecord;
5562       }
5563 
5564       // Move to the outer template scope.
5565       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
5566         if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
5567           DC = FD->getLexicalDeclContext();
5568           continue;
5569         }
5570         // An implicit deduction guide acts as if it's within the class template
5571         // specialization described by its name and first N template params.
5572         auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
5573         if (Guide && Guide->isImplicit()) {
5574           TemplateDecl *TD = Guide->getDeducedTemplate();
5575           // Convert the arguments to an "as-written" list.
5576           TemplateArgumentListInfo Args(Loc, Loc);
5577           for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
5578                                         TD->getTemplateParameters()->size())) {
5579             ArrayRef<TemplateArgument> Unpacked(Arg);
5580             if (Arg.getKind() == TemplateArgument::Pack)
5581               Unpacked = Arg.pack_elements();
5582             for (TemplateArgument UnpackedArg : Unpacked)
5583               Args.addArgument(
5584                   getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
5585           }
5586           QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
5587           if (T.isNull())
5588             return nullptr;
5589           auto *SubstRecord = T->getAsCXXRecordDecl();
5590           assert(SubstRecord && "class template id not a class type?");
5591           // Check that this template-id names the primary template and not a
5592           // partial or explicit specialization. (In the latter cases, it's
5593           // meaningless to attempt to find an instantiation of D within the
5594           // specialization.)
5595           // FIXME: The standard doesn't say what should happen here.
5596           if (FindingInstantiatedContext &&
5597               usesPartialOrExplicitSpecialization(
5598                   Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
5599             Diag(Loc, diag::err_specialization_not_primary_template)
5600               << T << (SubstRecord->getTemplateSpecializationKind() ==
5601                            TSK_ExplicitSpecialization);
5602             return nullptr;
5603           }
5604           DC = SubstRecord;
5605           continue;
5606         }
5607       }
5608 
5609       DC = DC->getParent();
5610     }
5611 
5612     // Fall through to deal with other dependent record types (e.g.,
5613     // anonymous unions in class templates).
5614   }
5615 
5616   if (!ParentDC->isDependentContext())
5617     return D;
5618 
5619   ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
5620   if (!ParentDC)
5621     return nullptr;
5622 
5623   if (ParentDC != D->getDeclContext()) {
5624     // We performed some kind of instantiation in the parent context,
5625     // so now we need to look into the instantiated parent context to
5626     // find the instantiation of the declaration D.
5627 
5628     // If our context used to be dependent, we may need to instantiate
5629     // it before performing lookup into that context.
5630     bool IsBeingInstantiated = false;
5631     if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
5632       if (!Spec->isDependentContext()) {
5633         QualType T = Context.getTypeDeclType(Spec);
5634         const RecordType *Tag = T->getAs<RecordType>();
5635         assert(Tag && "type of non-dependent record is not a RecordType");
5636         if (Tag->isBeingDefined())
5637           IsBeingInstantiated = true;
5638         if (!Tag->isBeingDefined() &&
5639             RequireCompleteType(Loc, T, diag::err_incomplete_type))
5640           return nullptr;
5641 
5642         ParentDC = Tag->getDecl();
5643       }
5644     }
5645 
5646     NamedDecl *Result = nullptr;
5647     // FIXME: If the name is a dependent name, this lookup won't necessarily
5648     // find it. Does that ever matter?
5649     if (auto Name = D->getDeclName()) {
5650       DeclarationNameInfo NameInfo(Name, D->getLocation());
5651       DeclarationNameInfo NewNameInfo =
5652           SubstDeclarationNameInfo(NameInfo, TemplateArgs);
5653       Name = NewNameInfo.getName();
5654       if (!Name)
5655         return nullptr;
5656       DeclContext::lookup_result Found = ParentDC->lookup(Name);
5657 
5658       if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
5659         VarTemplateDecl *Templ = cast_or_null<VarTemplateDecl>(
5660             findInstantiationOf(Context, VTSD->getSpecializedTemplate(),
5661                                 Found.begin(), Found.end()));
5662         if (!Templ)
5663           return nullptr;
5664         Result = getVarTemplateSpecialization(
5665             Templ, &VTSD->getTemplateArgsInfo(), NewNameInfo, SourceLocation());
5666       } else
5667         Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
5668     } else {
5669       // Since we don't have a name for the entity we're looking for,
5670       // our only option is to walk through all of the declarations to
5671       // find that name. This will occur in a few cases:
5672       //
5673       //   - anonymous struct/union within a template
5674       //   - unnamed class/struct/union/enum within a template
5675       //
5676       // FIXME: Find a better way to find these instantiations!
5677       Result = findInstantiationOf(Context, D,
5678                                    ParentDC->decls_begin(),
5679                                    ParentDC->decls_end());
5680     }
5681 
5682     if (!Result) {
5683       if (isa<UsingShadowDecl>(D)) {
5684         // UsingShadowDecls can instantiate to nothing because of using hiding.
5685       } else if (Diags.hasErrorOccurred()) {
5686         // We've already complained about something, so most likely this
5687         // declaration failed to instantiate. There's no point in complaining
5688         // further, since this is normal in invalid code.
5689       } else if (IsBeingInstantiated) {
5690         // The class in which this member exists is currently being
5691         // instantiated, and we haven't gotten around to instantiating this
5692         // member yet. This can happen when the code uses forward declarations
5693         // of member classes, and introduces ordering dependencies via
5694         // template instantiation.
5695         Diag(Loc, diag::err_member_not_yet_instantiated)
5696           << D->getDeclName()
5697           << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
5698         Diag(D->getLocation(), diag::note_non_instantiated_member_here);
5699       } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
5700         // This enumeration constant was found when the template was defined,
5701         // but can't be found in the instantiation. This can happen if an
5702         // unscoped enumeration member is explicitly specialized.
5703         EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
5704         EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
5705                                                              TemplateArgs));
5706         assert(Spec->getTemplateSpecializationKind() ==
5707                  TSK_ExplicitSpecialization);
5708         Diag(Loc, diag::err_enumerator_does_not_exist)
5709           << D->getDeclName()
5710           << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
5711         Diag(Spec->getLocation(), diag::note_enum_specialized_here)
5712           << Context.getTypeDeclType(Spec);
5713       } else {
5714         // We should have found something, but didn't.
5715         llvm_unreachable("Unable to find instantiation of declaration!");
5716       }
5717     }
5718 
5719     D = Result;
5720   }
5721 
5722   return D;
5723 }
5724 
5725 /// Performs template instantiation for all implicit template
5726 /// instantiations we have seen until this point.
5727 void Sema::PerformPendingInstantiations(bool LocalOnly) {
5728   while (!PendingLocalImplicitInstantiations.empty() ||
5729          (!LocalOnly && !PendingInstantiations.empty())) {
5730     PendingImplicitInstantiation Inst;
5731 
5732     if (PendingLocalImplicitInstantiations.empty()) {
5733       Inst = PendingInstantiations.front();
5734       PendingInstantiations.pop_front();
5735     } else {
5736       Inst = PendingLocalImplicitInstantiations.front();
5737       PendingLocalImplicitInstantiations.pop_front();
5738     }
5739 
5740     // Instantiate function definitions
5741     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
5742       bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
5743                                 TSK_ExplicitInstantiationDefinition;
5744       if (Function->isMultiVersion()) {
5745         getASTContext().forEachMultiversionedFunctionVersion(
5746             Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
5747               InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
5748                                             DefinitionRequired, true);
5749               if (CurFD->isDefined())
5750                 CurFD->setInstantiationIsPending(false);
5751             });
5752       } else {
5753         InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
5754                                       DefinitionRequired, true);
5755         if (Function->isDefined())
5756           Function->setInstantiationIsPending(false);
5757       }
5758       continue;
5759     }
5760 
5761     // Instantiate variable definitions
5762     VarDecl *Var = cast<VarDecl>(Inst.first);
5763 
5764     assert((Var->isStaticDataMember() ||
5765             isa<VarTemplateSpecializationDecl>(Var)) &&
5766            "Not a static data member, nor a variable template"
5767            " specialization?");
5768 
5769     // Don't try to instantiate declarations if the most recent redeclaration
5770     // is invalid.
5771     if (Var->getMostRecentDecl()->isInvalidDecl())
5772       continue;
5773 
5774     // Check if the most recent declaration has changed the specialization kind
5775     // and removed the need for implicit instantiation.
5776     switch (Var->getMostRecentDecl()
5777                 ->getTemplateSpecializationKindForInstantiation()) {
5778     case TSK_Undeclared:
5779       llvm_unreachable("Cannot instantitiate an undeclared specialization.");
5780     case TSK_ExplicitInstantiationDeclaration:
5781     case TSK_ExplicitSpecialization:
5782       continue;  // No longer need to instantiate this type.
5783     case TSK_ExplicitInstantiationDefinition:
5784       // We only need an instantiation if the pending instantiation *is* the
5785       // explicit instantiation.
5786       if (Var != Var->getMostRecentDecl())
5787         continue;
5788       break;
5789     case TSK_ImplicitInstantiation:
5790       break;
5791     }
5792 
5793     PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5794                                         "instantiating variable definition");
5795     bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
5796                               TSK_ExplicitInstantiationDefinition;
5797 
5798     // Instantiate static data member definitions or variable template
5799     // specializations.
5800     InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
5801                                   DefinitionRequired, true);
5802   }
5803 }
5804 
5805 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
5806                        const MultiLevelTemplateArgumentList &TemplateArgs) {
5807   for (auto DD : Pattern->ddiags()) {
5808     switch (DD->getKind()) {
5809     case DependentDiagnostic::Access:
5810       HandleDependentAccessCheck(*DD, TemplateArgs);
5811       break;
5812     }
5813   }
5814 }
5815