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