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