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