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