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