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