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