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