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