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