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