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