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