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