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