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