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/Sema/Lookup.h"
14 #include "clang/Sema/PrettyDeclStackTrace.h"
15 #include "clang/Sema/Template.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/AST/DependentDiagnostic.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/Lex/Preprocessor.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 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
64                             const Decl *Tmpl, Decl *New,
65                             LateInstantiatedAttrVec *LateAttrs,
66                             LocalInstantiationScope *OuterMostScope) {
67   for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
68        i != e; ++i) {
69     const Attr *TmplAttr = *i;
70 
71     // FIXME: This should be generalized to more than just the AlignedAttr.
72     if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
73       if (Aligned->isAlignmentDependent()) {
74         if (Aligned->isAlignmentExpr()) {
75           // The alignment expression is a constant expression.
76           EnterExpressionEvaluationContext Unevaluated(*this,
77                                                        Sema::ConstantEvaluated);
78 
79           ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
80                                         TemplateArgs);
81           if (!Result.isInvalid())
82             AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>());
83         } else {
84           TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
85                                              TemplateArgs,
86                                              Aligned->getLocation(),
87                                              DeclarationName());
88           if (Result)
89             AddAlignedAttr(Aligned->getLocation(), New, Result);
90         }
91         continue;
92       }
93     }
94 
95     if (TmplAttr->isLateParsed() && LateAttrs) {
96       // Late parsed attributes must be instantiated and attached after the
97       // enclosing class has been instantiated.  See Sema::InstantiateClass.
98       LocalInstantiationScope *Saved = 0;
99       if (CurrentInstantiationScope)
100         Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
101       LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
102     } else {
103       Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
104                                                          *this, TemplateArgs);
105       New->addAttr(NewAttr);
106     }
107   }
108 }
109 
110 Decl *
111 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
112   llvm_unreachable("Translation units cannot be instantiated");
113 }
114 
115 Decl *
116 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
117   LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
118                                       D->getIdentifier());
119   Owner->addDecl(Inst);
120   return Inst;
121 }
122 
123 Decl *
124 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
125   llvm_unreachable("Namespaces cannot be instantiated");
126 }
127 
128 Decl *
129 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
130   NamespaceAliasDecl *Inst
131     = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
132                                  D->getNamespaceLoc(),
133                                  D->getAliasLoc(),
134                                  D->getIdentifier(),
135                                  D->getQualifierLoc(),
136                                  D->getTargetNameLoc(),
137                                  D->getNamespace());
138   Owner->addDecl(Inst);
139   return Inst;
140 }
141 
142 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
143                                                            bool IsTypeAlias) {
144   bool Invalid = false;
145   TypeSourceInfo *DI = D->getTypeSourceInfo();
146   if (DI->getType()->isInstantiationDependentType() ||
147       DI->getType()->isVariablyModifiedType()) {
148     DI = SemaRef.SubstType(DI, TemplateArgs,
149                            D->getLocation(), D->getDeclName());
150     if (!DI) {
151       Invalid = true;
152       DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
153     }
154   } else {
155     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
156   }
157 
158   // Create the new typedef
159   TypedefNameDecl *Typedef;
160   if (IsTypeAlias)
161     Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
162                                     D->getLocation(), D->getIdentifier(), DI);
163   else
164     Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
165                                   D->getLocation(), D->getIdentifier(), DI);
166   if (Invalid)
167     Typedef->setInvalidDecl();
168 
169   // If the old typedef was the name for linkage purposes of an anonymous
170   // tag decl, re-establish that relationship for the new typedef.
171   if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
172     TagDecl *oldTag = oldTagType->getDecl();
173     if (oldTag->getTypedefNameForAnonDecl() == D) {
174       TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
175       assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
176       newTag->setTypedefNameForAnonDecl(Typedef);
177     }
178   }
179 
180   if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
181     NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
182                                                        TemplateArgs);
183     if (!InstPrev)
184       return 0;
185 
186     TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
187 
188     // If the typedef types are not identical, reject them.
189     SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
190 
191     Typedef->setPreviousDeclaration(InstPrevTypedef);
192   }
193 
194   SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
195 
196   Typedef->setAccess(D->getAccess());
197 
198   return Typedef;
199 }
200 
201 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
202   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
203   Owner->addDecl(Typedef);
204   return Typedef;
205 }
206 
207 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
208   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
209   Owner->addDecl(Typedef);
210   return Typedef;
211 }
212 
213 Decl *
214 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
215   // Create a local instantiation scope for this type alias template, which
216   // will contain the instantiations of the template parameters.
217   LocalInstantiationScope Scope(SemaRef);
218 
219   TemplateParameterList *TempParams = D->getTemplateParameters();
220   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
221   if (!InstParams)
222     return 0;
223 
224   TypeAliasDecl *Pattern = D->getTemplatedDecl();
225 
226   TypeAliasTemplateDecl *PrevAliasTemplate = 0;
227   if (Pattern->getPreviousDecl()) {
228     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
229     if (Found.first != Found.second) {
230       PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first);
231     }
232   }
233 
234   TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
235     InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
236   if (!AliasInst)
237     return 0;
238 
239   TypeAliasTemplateDecl *Inst
240     = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
241                                     D->getDeclName(), InstParams, AliasInst);
242   if (PrevAliasTemplate)
243     Inst->setPreviousDeclaration(PrevAliasTemplate);
244 
245   Inst->setAccess(D->getAccess());
246 
247   if (!PrevAliasTemplate)
248     Inst->setInstantiatedFromMemberTemplate(D);
249 
250   Owner->addDecl(Inst);
251 
252   return Inst;
253 }
254 
255 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
256   // If this is the variable for an anonymous struct or union,
257   // instantiate the anonymous struct/union type first.
258   if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
259     if (RecordTy->getDecl()->isAnonymousStructOrUnion())
260       if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
261         return 0;
262 
263   // Do substitution on the type of the declaration
264   TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
265                                          TemplateArgs,
266                                          D->getTypeSpecStartLoc(),
267                                          D->getDeclName());
268   if (!DI)
269     return 0;
270 
271   if (DI->getType()->isFunctionType()) {
272     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
273       << D->isStaticDataMember() << DI->getType();
274     return 0;
275   }
276 
277   // Build the instantiated declaration
278   VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
279                                  D->getInnerLocStart(),
280                                  D->getLocation(), D->getIdentifier(),
281                                  DI->getType(), DI,
282                                  D->getStorageClass(),
283                                  D->getStorageClassAsWritten());
284   Var->setThreadSpecified(D->isThreadSpecified());
285   Var->setInitStyle(D->getInitStyle());
286   Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
287   Var->setConstexpr(D->isConstexpr());
288 
289   // Substitute the nested name specifier, if any.
290   if (SubstQualifier(D, Var))
291     return 0;
292 
293   // If we are instantiating a static data member defined
294   // out-of-line, the instantiation will have the same lexical
295   // context (which will be a namespace scope) as the template.
296   if (D->isOutOfLine())
297     Var->setLexicalDeclContext(D->getLexicalDeclContext());
298 
299   Var->setAccess(D->getAccess());
300 
301   if (!D->isStaticDataMember()) {
302     Var->setUsed(D->isUsed(false));
303     Var->setReferenced(D->isReferenced());
304   }
305 
306   // FIXME: In theory, we could have a previous declaration for variables that
307   // are not static data members.
308   // FIXME: having to fake up a LookupResult is dumb.
309   LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
310                         Sema::LookupOrdinaryName, Sema::ForRedeclaration);
311   if (D->isStaticDataMember())
312     SemaRef.LookupQualifiedName(Previous, Owner, false);
313 
314   // In ARC, infer 'retaining' for variables of retainable type.
315   if (SemaRef.getLangOptions().ObjCAutoRefCount &&
316       SemaRef.inferObjCARCLifetime(Var))
317     Var->setInvalidDecl();
318 
319   SemaRef.CheckVariableDeclaration(Var, Previous);
320 
321   if (D->isOutOfLine()) {
322     D->getLexicalDeclContext()->addDecl(Var);
323     Owner->makeDeclVisibleInContext(Var);
324   } else {
325     Owner->addDecl(Var);
326     if (Owner->isFunctionOrMethod())
327       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
328   }
329   SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
330 
331   // Link instantiations of static data members back to the template from
332   // which they were instantiated.
333   if (Var->isStaticDataMember())
334     SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
335                                                      TSK_ImplicitInstantiation);
336 
337   if (Var->getAnyInitializer()) {
338     // We already have an initializer in the class.
339   } else if (D->getInit()) {
340     if (Var->isStaticDataMember() && !D->isOutOfLine())
341       SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated);
342     else
343       SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
344 
345     // Instantiate the initializer.
346     ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs,
347                                         D->getInitStyle() == VarDecl::CallInit);
348     if (!Init.isInvalid()) {
349       bool TypeMayContainAuto = true;
350       if (Init.get()) {
351         bool DirectInit = D->isDirectInit();
352         SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
353                                      TypeMayContainAuto);
354       } else
355         SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
356     } else {
357       // FIXME: Not too happy about invalidating the declaration
358       // because of a bogus initializer.
359       Var->setInvalidDecl();
360     }
361 
362     SemaRef.PopExpressionEvaluationContext();
363   } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
364              !Var->isCXXForRangeDecl())
365     SemaRef.ActOnUninitializedDecl(Var, false);
366 
367   // Diagnose unused local variables with dependent types, where the diagnostic
368   // will have been deferred.
369   if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
370       D->getType()->isDependentType())
371     SemaRef.DiagnoseUnusedDecl(Var);
372 
373   return Var;
374 }
375 
376 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
377   AccessSpecDecl* AD
378     = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
379                              D->getAccessSpecifierLoc(), D->getColonLoc());
380   Owner->addHiddenDecl(AD);
381   return AD;
382 }
383 
384 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
385   bool Invalid = false;
386   TypeSourceInfo *DI = D->getTypeSourceInfo();
387   if (DI->getType()->isInstantiationDependentType() ||
388       DI->getType()->isVariablyModifiedType())  {
389     DI = SemaRef.SubstType(DI, TemplateArgs,
390                            D->getLocation(), D->getDeclName());
391     if (!DI) {
392       DI = D->getTypeSourceInfo();
393       Invalid = true;
394     } else if (DI->getType()->isFunctionType()) {
395       // C++ [temp.arg.type]p3:
396       //   If a declaration acquires a function type through a type
397       //   dependent on a template-parameter and this causes a
398       //   declaration that does not use the syntactic form of a
399       //   function declarator to have function type, the program is
400       //   ill-formed.
401       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
402         << DI->getType();
403       Invalid = true;
404     }
405   } else {
406     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
407   }
408 
409   Expr *BitWidth = D->getBitWidth();
410   if (Invalid)
411     BitWidth = 0;
412   else if (BitWidth) {
413     // The bit-width expression is a constant expression.
414     EnterExpressionEvaluationContext Unevaluated(SemaRef,
415                                                  Sema::ConstantEvaluated);
416 
417     ExprResult InstantiatedBitWidth
418       = SemaRef.SubstExpr(BitWidth, TemplateArgs);
419     if (InstantiatedBitWidth.isInvalid()) {
420       Invalid = true;
421       BitWidth = 0;
422     } else
423       BitWidth = InstantiatedBitWidth.takeAs<Expr>();
424   }
425 
426   FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
427                                             DI->getType(), DI,
428                                             cast<RecordDecl>(Owner),
429                                             D->getLocation(),
430                                             D->isMutable(),
431                                             BitWidth,
432                                             D->hasInClassInitializer(),
433                                             D->getTypeSpecStartLoc(),
434                                             D->getAccess(),
435                                             0);
436   if (!Field) {
437     cast<Decl>(Owner)->setInvalidDecl();
438     return 0;
439   }
440 
441   SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
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::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
464   NamedDecl **NamedChain =
465     new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
466 
467   int i = 0;
468   for (IndirectFieldDecl::chain_iterator PI =
469        D->chain_begin(), PE = D->chain_end();
470        PI != PE; ++PI) {
471     NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
472                                               TemplateArgs);
473     if (!Next)
474       return 0;
475 
476     NamedChain[i++] = Next;
477   }
478 
479   QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
480   IndirectFieldDecl* IndirectField
481     = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
482                                 D->getIdentifier(), T,
483                                 NamedChain, D->getChainingSize());
484 
485 
486   IndirectField->setImplicit(D->isImplicit());
487   IndirectField->setAccess(D->getAccess());
488   Owner->addDecl(IndirectField);
489   return IndirectField;
490 }
491 
492 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
493   // Handle friend type expressions by simply substituting template
494   // parameters into the pattern type and checking the result.
495   if (TypeSourceInfo *Ty = D->getFriendType()) {
496     TypeSourceInfo *InstTy;
497     // If this is an unsupported friend, don't bother substituting template
498     // arguments into it. The actual type referred to won't be used by any
499     // parts of Clang, and may not be valid for instantiating. Just use the
500     // same info for the instantiated friend.
501     if (D->isUnsupportedFriend()) {
502       InstTy = Ty;
503     } else {
504       InstTy = SemaRef.SubstType(Ty, TemplateArgs,
505                                  D->getLocation(), DeclarationName());
506     }
507     if (!InstTy)
508       return 0;
509 
510     FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocation(),
511                                                  D->getFriendLoc(), InstTy);
512     if (!FD)
513       return 0;
514 
515     FD->setAccess(AS_public);
516     FD->setUnsupportedFriend(D->isUnsupportedFriend());
517     Owner->addDecl(FD);
518     return FD;
519   }
520 
521   NamedDecl *ND = D->getFriendDecl();
522   assert(ND && "friend decl must be a decl or a type!");
523 
524   // All of the Visit implementations for the various potential friend
525   // declarations have to be carefully written to work for friend
526   // objects, with the most important detail being that the target
527   // decl should almost certainly not be placed in Owner.
528   Decl *NewND = Visit(ND);
529   if (!NewND) return 0;
530 
531   FriendDecl *FD =
532     FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
533                        cast<NamedDecl>(NewND), D->getFriendLoc());
534   FD->setAccess(AS_public);
535   FD->setUnsupportedFriend(D->isUnsupportedFriend());
536   Owner->addDecl(FD);
537   return FD;
538 }
539 
540 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
541   Expr *AssertExpr = D->getAssertExpr();
542 
543   // The expression in a static assertion is a constant expression.
544   EnterExpressionEvaluationContext Unevaluated(SemaRef,
545                                                Sema::ConstantEvaluated);
546 
547   ExprResult InstantiatedAssertExpr
548     = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
549   if (InstantiatedAssertExpr.isInvalid())
550     return 0;
551 
552   ExprResult Message(D->getMessage());
553   D->getMessage();
554   return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
555                                               InstantiatedAssertExpr.get(),
556                                               Message.get(),
557                                               D->getRParenLoc());
558 }
559 
560 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
561   EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
562                                     D->getLocation(), D->getIdentifier(),
563                                     /*PrevDecl=*/0, D->isScoped(),
564                                     D->isScopedUsingClassTag(), D->isFixed());
565   if (D->isFixed()) {
566     if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
567       // If we have type source information for the underlying type, it means it
568       // has been explicitly set by the user. Perform substitution on it before
569       // moving on.
570       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
571       Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
572                                                        TemplateArgs,
573                                                        UnderlyingLoc,
574                                                        DeclarationName()));
575 
576       if (!Enum->getIntegerTypeSourceInfo())
577         Enum->setIntegerType(SemaRef.Context.IntTy);
578     }
579     else {
580       assert(!D->getIntegerType()->isDependentType()
581              && "Dependent type without type source info");
582       Enum->setIntegerType(D->getIntegerType());
583     }
584   }
585 
586   SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
587 
588   Enum->setInstantiationOfMemberEnum(D);
589   Enum->setAccess(D->getAccess());
590   if (SubstQualifier(D, Enum)) return 0;
591   Owner->addDecl(Enum);
592   Enum->startDefinition();
593 
594   if (D->getDeclContext()->isFunctionOrMethod())
595     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
596 
597   SmallVector<Decl*, 4> Enumerators;
598 
599   EnumConstantDecl *LastEnumConst = 0;
600   for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
601          ECEnd = D->enumerator_end();
602        EC != ECEnd; ++EC) {
603     // The specified value for the enumerator.
604     ExprResult Value = SemaRef.Owned((Expr *)0);
605     if (Expr *UninstValue = EC->getInitExpr()) {
606       // The enumerator's value expression is a constant expression.
607       EnterExpressionEvaluationContext Unevaluated(SemaRef,
608                                                    Sema::ConstantEvaluated);
609 
610       Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
611     }
612 
613     // Drop the initial value and continue.
614     bool isInvalid = false;
615     if (Value.isInvalid()) {
616       Value = SemaRef.Owned((Expr *)0);
617       isInvalid = true;
618     }
619 
620     EnumConstantDecl *EnumConst
621       = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
622                                   EC->getLocation(), EC->getIdentifier(),
623                                   Value.get());
624 
625     if (isInvalid) {
626       if (EnumConst)
627         EnumConst->setInvalidDecl();
628       Enum->setInvalidDecl();
629     }
630 
631     if (EnumConst) {
632       SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
633 
634       EnumConst->setAccess(Enum->getAccess());
635       Enum->addDecl(EnumConst);
636       Enumerators.push_back(EnumConst);
637       LastEnumConst = EnumConst;
638 
639       if (D->getDeclContext()->isFunctionOrMethod()) {
640         // If the enumeration is within a function or method, record the enum
641         // constant as a local.
642         SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
643       }
644     }
645   }
646 
647   // FIXME: Fixup LBraceLoc and RBraceLoc
648   // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
649   SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
650                         Enum,
651                         Enumerators.data(), Enumerators.size(),
652                         0, 0);
653 
654   return Enum;
655 }
656 
657 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
658   llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
659 }
660 
661 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
662   bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
663 
664   // Create a local instantiation scope for this class template, which
665   // will contain the instantiations of the template parameters.
666   LocalInstantiationScope Scope(SemaRef);
667   TemplateParameterList *TempParams = D->getTemplateParameters();
668   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
669   if (!InstParams)
670     return NULL;
671 
672   CXXRecordDecl *Pattern = D->getTemplatedDecl();
673 
674   // Instantiate the qualifier.  We have to do this first in case
675   // we're a friend declaration, because if we are then we need to put
676   // the new declaration in the appropriate context.
677   NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
678   if (QualifierLoc) {
679     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
680                                                        TemplateArgs);
681     if (!QualifierLoc)
682       return 0;
683   }
684 
685   CXXRecordDecl *PrevDecl = 0;
686   ClassTemplateDecl *PrevClassTemplate = 0;
687 
688   if (!isFriend && Pattern->getPreviousDecl()) {
689     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
690     if (Found.first != Found.second) {
691       PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
692       if (PrevClassTemplate)
693         PrevDecl = PrevClassTemplate->getTemplatedDecl();
694     }
695   }
696 
697   // If this isn't a friend, then it's a member template, in which
698   // case we just want to build the instantiation in the
699   // specialization.  If it is a friend, we want to build it in
700   // the appropriate context.
701   DeclContext *DC = Owner;
702   if (isFriend) {
703     if (QualifierLoc) {
704       CXXScopeSpec SS;
705       SS.Adopt(QualifierLoc);
706       DC = SemaRef.computeDeclContext(SS);
707       if (!DC) return 0;
708     } else {
709       DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
710                                            Pattern->getDeclContext(),
711                                            TemplateArgs);
712     }
713 
714     // Look for a previous declaration of the template in the owning
715     // context.
716     LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
717                    Sema::LookupOrdinaryName, Sema::ForRedeclaration);
718     SemaRef.LookupQualifiedName(R, DC);
719 
720     if (R.isSingleResult()) {
721       PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
722       if (PrevClassTemplate)
723         PrevDecl = PrevClassTemplate->getTemplatedDecl();
724     }
725 
726     if (!PrevClassTemplate && QualifierLoc) {
727       SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
728         << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
729         << QualifierLoc.getSourceRange();
730       return 0;
731     }
732 
733     bool AdoptedPreviousTemplateParams = false;
734     if (PrevClassTemplate) {
735       bool Complain = true;
736 
737       // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
738       // template for struct std::tr1::__detail::_Map_base, where the
739       // template parameters of the friend declaration don't match the
740       // template parameters of the original declaration. In this one
741       // case, we don't complain about the ill-formed friend
742       // declaration.
743       if (isFriend && Pattern->getIdentifier() &&
744           Pattern->getIdentifier()->isStr("_Map_base") &&
745           DC->isNamespace() &&
746           cast<NamespaceDecl>(DC)->getIdentifier() &&
747           cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
748         DeclContext *DCParent = DC->getParent();
749         if (DCParent->isNamespace() &&
750             cast<NamespaceDecl>(DCParent)->getIdentifier() &&
751             cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
752           DeclContext *DCParent2 = DCParent->getParent();
753           if (DCParent2->isNamespace() &&
754               cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
755               cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
756               DCParent2->getParent()->isTranslationUnit())
757             Complain = false;
758         }
759       }
760 
761       TemplateParameterList *PrevParams
762         = PrevClassTemplate->getTemplateParameters();
763 
764       // Make sure the parameter lists match.
765       if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
766                                                   Complain,
767                                                   Sema::TPL_TemplateMatch)) {
768         if (Complain)
769           return 0;
770 
771         AdoptedPreviousTemplateParams = true;
772         InstParams = PrevParams;
773       }
774 
775       // Do some additional validation, then merge default arguments
776       // from the existing declarations.
777       if (!AdoptedPreviousTemplateParams &&
778           SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
779                                              Sema::TPC_ClassTemplate))
780         return 0;
781     }
782   }
783 
784   CXXRecordDecl *RecordInst
785     = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
786                             Pattern->getLocStart(), Pattern->getLocation(),
787                             Pattern->getIdentifier(), PrevDecl,
788                             /*DelayTypeCreation=*/true);
789 
790   if (QualifierLoc)
791     RecordInst->setQualifierInfo(QualifierLoc);
792 
793   ClassTemplateDecl *Inst
794     = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
795                                 D->getIdentifier(), InstParams, RecordInst,
796                                 PrevClassTemplate);
797   RecordInst->setDescribedClassTemplate(Inst);
798 
799   if (isFriend) {
800     if (PrevClassTemplate)
801       Inst->setAccess(PrevClassTemplate->getAccess());
802     else
803       Inst->setAccess(D->getAccess());
804 
805     Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
806     // TODO: do we want to track the instantiation progeny of this
807     // friend target decl?
808   } else {
809     Inst->setAccess(D->getAccess());
810     if (!PrevClassTemplate)
811       Inst->setInstantiatedFromMemberTemplate(D);
812   }
813 
814   // Trigger creation of the type for the instantiation.
815   SemaRef.Context.getInjectedClassNameType(RecordInst,
816                                     Inst->getInjectedClassNameSpecialization());
817 
818   // Finish handling of friends.
819   if (isFriend) {
820     DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
821     Inst->setLexicalDeclContext(Owner);
822     RecordInst->setLexicalDeclContext(Owner);
823     return Inst;
824   }
825 
826   if (D->isOutOfLine()) {
827     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
828     RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
829   }
830 
831   Owner->addDecl(Inst);
832 
833   if (!PrevClassTemplate) {
834     // Queue up any out-of-line partial specializations of this member
835     // class template; the client will force their instantiation once
836     // the enclosing class has been instantiated.
837     SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
838     D->getPartialSpecializations(PartialSpecs);
839     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
840       if (PartialSpecs[I]->isOutOfLine())
841         OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
842   }
843 
844   return Inst;
845 }
846 
847 Decl *
848 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
849                                    ClassTemplatePartialSpecializationDecl *D) {
850   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
851 
852   // Lookup the already-instantiated declaration in the instantiation
853   // of the class template and return that.
854   DeclContext::lookup_result Found
855     = Owner->lookup(ClassTemplate->getDeclName());
856   if (Found.first == Found.second)
857     return 0;
858 
859   ClassTemplateDecl *InstClassTemplate
860     = dyn_cast<ClassTemplateDecl>(*Found.first);
861   if (!InstClassTemplate)
862     return 0;
863 
864   if (ClassTemplatePartialSpecializationDecl *Result
865         = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
866     return Result;
867 
868   return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
869 }
870 
871 Decl *
872 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
873   // Create a local instantiation scope for this function template, which
874   // will contain the instantiations of the template parameters and then get
875   // merged with the local instantiation scope for the function template
876   // itself.
877   LocalInstantiationScope Scope(SemaRef);
878 
879   TemplateParameterList *TempParams = D->getTemplateParameters();
880   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
881   if (!InstParams)
882     return NULL;
883 
884   FunctionDecl *Instantiated = 0;
885   if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
886     Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
887                                                                  InstParams));
888   else
889     Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
890                                                           D->getTemplatedDecl(),
891                                                                 InstParams));
892 
893   if (!Instantiated)
894     return 0;
895 
896   Instantiated->setAccess(D->getAccess());
897 
898   // Link the instantiated function template declaration to the function
899   // template from which it was instantiated.
900   FunctionTemplateDecl *InstTemplate
901     = Instantiated->getDescribedFunctionTemplate();
902   InstTemplate->setAccess(D->getAccess());
903   assert(InstTemplate &&
904          "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
905 
906   bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
907 
908   // Link the instantiation back to the pattern *unless* this is a
909   // non-definition friend declaration.
910   if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
911       !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
912     InstTemplate->setInstantiatedFromMemberTemplate(D);
913 
914   // Make declarations visible in the appropriate context.
915   if (!isFriend)
916     Owner->addDecl(InstTemplate);
917 
918   return InstTemplate;
919 }
920 
921 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
922   CXXRecordDecl *PrevDecl = 0;
923   if (D->isInjectedClassName())
924     PrevDecl = cast<CXXRecordDecl>(Owner);
925   else if (D->getPreviousDecl()) {
926     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
927                                                    D->getPreviousDecl(),
928                                                    TemplateArgs);
929     if (!Prev) return 0;
930     PrevDecl = cast<CXXRecordDecl>(Prev);
931   }
932 
933   CXXRecordDecl *Record
934     = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
935                             D->getLocStart(), D->getLocation(),
936                             D->getIdentifier(), PrevDecl);
937 
938   // Substitute the nested name specifier, if any.
939   if (SubstQualifier(D, Record))
940     return 0;
941 
942   Record->setImplicit(D->isImplicit());
943   // FIXME: Check against AS_none is an ugly hack to work around the issue that
944   // the tag decls introduced by friend class declarations don't have an access
945   // specifier. Remove once this area of the code gets sorted out.
946   if (D->getAccess() != AS_none)
947     Record->setAccess(D->getAccess());
948   if (!D->isInjectedClassName())
949     Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
950 
951   // If the original function was part of a friend declaration,
952   // inherit its namespace state.
953   if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
954     Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
955 
956   // Make sure that anonymous structs and unions are recorded.
957   if (D->isAnonymousStructOrUnion()) {
958     Record->setAnonymousStructOrUnion(true);
959     if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
960       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
961   }
962 
963   Owner->addDecl(Record);
964   return Record;
965 }
966 
967 /// Normal class members are of more specific types and therefore
968 /// don't make it here.  This function serves two purposes:
969 ///   1) instantiating function templates
970 ///   2) substituting friend declarations
971 /// FIXME: preserve function definitions in case #2
972 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
973                                        TemplateParameterList *TemplateParams) {
974   // Check whether there is already a function template specialization for
975   // this declaration.
976   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
977   void *InsertPos = 0;
978   if (FunctionTemplate && !TemplateParams) {
979     std::pair<const TemplateArgument *, unsigned> Innermost
980       = TemplateArgs.getInnermost();
981 
982     FunctionDecl *SpecFunc
983       = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
984                                              InsertPos);
985 
986     // If we already have a function template specialization, return it.
987     if (SpecFunc)
988       return SpecFunc;
989   }
990 
991   bool isFriend;
992   if (FunctionTemplate)
993     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
994   else
995     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
996 
997   bool MergeWithParentScope = (TemplateParams != 0) ||
998     Owner->isFunctionOrMethod() ||
999     !(isa<Decl>(Owner) &&
1000       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1001   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1002 
1003   SmallVector<ParmVarDecl *, 4> Params;
1004   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1005   if (!TInfo)
1006     return 0;
1007   QualType T = TInfo->getType();
1008 
1009   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1010   if (QualifierLoc) {
1011     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1012                                                        TemplateArgs);
1013     if (!QualifierLoc)
1014       return 0;
1015   }
1016 
1017   // If we're instantiating a local function declaration, put the result
1018   // in the owner;  otherwise we need to find the instantiated context.
1019   DeclContext *DC;
1020   if (D->getDeclContext()->isFunctionOrMethod())
1021     DC = Owner;
1022   else if (isFriend && QualifierLoc) {
1023     CXXScopeSpec SS;
1024     SS.Adopt(QualifierLoc);
1025     DC = SemaRef.computeDeclContext(SS);
1026     if (!DC) return 0;
1027   } else {
1028     DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1029                                          TemplateArgs);
1030   }
1031 
1032   FunctionDecl *Function =
1033       FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1034                            D->getLocation(), D->getDeclName(), T, TInfo,
1035                            D->getStorageClass(), D->getStorageClassAsWritten(),
1036                            D->isInlineSpecified(), D->hasWrittenPrototype(),
1037                            D->isConstexpr());
1038 
1039   if (QualifierLoc)
1040     Function->setQualifierInfo(QualifierLoc);
1041 
1042   DeclContext *LexicalDC = Owner;
1043   if (!isFriend && D->isOutOfLine()) {
1044     assert(D->getDeclContext()->isFileContext());
1045     LexicalDC = D->getDeclContext();
1046   }
1047 
1048   Function->setLexicalDeclContext(LexicalDC);
1049 
1050   // Attach the parameters
1051   if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
1052     // Adopt the already-instantiated parameters into our own context.
1053     for (unsigned P = 0; P < Params.size(); ++P)
1054       if (Params[P])
1055         Params[P]->setOwningFunction(Function);
1056   } else {
1057     // Since we were instantiated via a typedef of a function type, create
1058     // new parameters.
1059     const FunctionProtoType *Proto
1060       = Function->getType()->getAs<FunctionProtoType>();
1061     assert(Proto && "No function prototype in template instantiation?");
1062     for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
1063          AE = Proto->arg_type_end(); AI != AE; ++AI) {
1064       ParmVarDecl *Param
1065         = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
1066                                              *AI);
1067       Param->setScopeInfo(0, Params.size());
1068       Params.push_back(Param);
1069     }
1070   }
1071   Function->setParams(Params);
1072 
1073   SourceLocation InstantiateAtPOI;
1074   if (TemplateParams) {
1075     // Our resulting instantiation is actually a function template, since we
1076     // are substituting only the outer template parameters. For example, given
1077     //
1078     //   template<typename T>
1079     //   struct X {
1080     //     template<typename U> friend void f(T, U);
1081     //   };
1082     //
1083     //   X<int> x;
1084     //
1085     // We are instantiating the friend function template "f" within X<int>,
1086     // which means substituting int for T, but leaving "f" as a friend function
1087     // template.
1088     // Build the function template itself.
1089     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1090                                                     Function->getLocation(),
1091                                                     Function->getDeclName(),
1092                                                     TemplateParams, Function);
1093     Function->setDescribedFunctionTemplate(FunctionTemplate);
1094 
1095     FunctionTemplate->setLexicalDeclContext(LexicalDC);
1096 
1097     if (isFriend && D->isThisDeclarationADefinition()) {
1098       // TODO: should we remember this connection regardless of whether
1099       // the friend declaration provided a body?
1100       FunctionTemplate->setInstantiatedFromMemberTemplate(
1101                                            D->getDescribedFunctionTemplate());
1102     }
1103   } else if (FunctionTemplate) {
1104     // Record this function template specialization.
1105     std::pair<const TemplateArgument *, unsigned> Innermost
1106       = TemplateArgs.getInnermost();
1107     Function->setFunctionTemplateSpecialization(FunctionTemplate,
1108                             TemplateArgumentList::CreateCopy(SemaRef.Context,
1109                                                              Innermost.first,
1110                                                              Innermost.second),
1111                                                 InsertPos);
1112   } else if (isFriend) {
1113     // Note, we need this connection even if the friend doesn't have a body.
1114     // Its body may exist but not have been attached yet due to deferred
1115     // parsing.
1116     // FIXME: It might be cleaner to set this when attaching the body to the
1117     // friend function declaration, however that would require finding all the
1118     // instantiations and modifying them.
1119     Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1120   }
1121 
1122   if (InitFunctionInstantiation(Function, D))
1123     Function->setInvalidDecl();
1124 
1125   bool isExplicitSpecialization = false;
1126 
1127   LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1128                         Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1129 
1130   if (DependentFunctionTemplateSpecializationInfo *Info
1131         = D->getDependentSpecializationInfo()) {
1132     assert(isFriend && "non-friend has dependent specialization info?");
1133 
1134     // This needs to be set now for future sanity.
1135     Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1136 
1137     // Instantiate the explicit template arguments.
1138     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1139                                           Info->getRAngleLoc());
1140     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1141                       ExplicitArgs, TemplateArgs))
1142       return 0;
1143 
1144     // Map the candidate templates to their instantiations.
1145     for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1146       Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1147                                                 Info->getTemplate(I),
1148                                                 TemplateArgs);
1149       if (!Temp) return 0;
1150 
1151       Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1152     }
1153 
1154     if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1155                                                     &ExplicitArgs,
1156                                                     Previous))
1157       Function->setInvalidDecl();
1158 
1159     isExplicitSpecialization = true;
1160 
1161   } else if (TemplateParams || !FunctionTemplate) {
1162     // Look only into the namespace where the friend would be declared to
1163     // find a previous declaration. This is the innermost enclosing namespace,
1164     // as described in ActOnFriendFunctionDecl.
1165     SemaRef.LookupQualifiedName(Previous, DC);
1166 
1167     // In C++, the previous declaration we find might be a tag type
1168     // (class or enum). In this case, the new declaration will hide the
1169     // tag type. Note that this does does not apply if we're declaring a
1170     // typedef (C++ [dcl.typedef]p4).
1171     if (Previous.isSingleTagDecl())
1172       Previous.clear();
1173   }
1174 
1175   SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1176                                    isExplicitSpecialization);
1177 
1178   NamedDecl *PrincipalDecl = (TemplateParams
1179                               ? cast<NamedDecl>(FunctionTemplate)
1180                               : Function);
1181 
1182   // If the original function was part of a friend declaration,
1183   // inherit its namespace state and add it to the owner.
1184   if (isFriend) {
1185     NamedDecl *PrevDecl;
1186     if (TemplateParams)
1187       PrevDecl = FunctionTemplate->getPreviousDecl();
1188     else
1189       PrevDecl = Function->getPreviousDecl();
1190 
1191     PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1192     DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
1193 
1194     bool queuedInstantiation = false;
1195 
1196     // C++98 [temp.friend]p5: When a function is defined in a friend function
1197     //   declaration in a class template, the function is defined at each
1198     //   instantiation of the class template. The function is defined even if it
1199     //   is never used.
1200     // C++11 [temp.friend]p4: When a function is defined in a friend function
1201     //   declaration in a class template, the function is instantiated when the
1202     //   function is odr-used.
1203     //
1204     // If -Wc++98-compat is enabled, we go through the motions of checking for a
1205     // redefinition, but don't instantiate the function.
1206     if ((!SemaRef.getLangOptions().CPlusPlus0x ||
1207          SemaRef.Diags.getDiagnosticLevel(
1208              diag::warn_cxx98_compat_friend_redefinition,
1209              Function->getLocation())
1210            != DiagnosticsEngine::Ignored) &&
1211         D->isThisDeclarationADefinition()) {
1212       // Check for a function body.
1213       const FunctionDecl *Definition = 0;
1214       if (Function->isDefined(Definition) &&
1215           Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1216         SemaRef.Diag(Function->getLocation(),
1217                      SemaRef.getLangOptions().CPlusPlus0x ?
1218                        diag::warn_cxx98_compat_friend_redefinition :
1219                        diag::err_redefinition) << Function->getDeclName();
1220         SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1221         if (!SemaRef.getLangOptions().CPlusPlus0x)
1222           Function->setInvalidDecl();
1223       }
1224       // Check for redefinitions due to other instantiations of this or
1225       // a similar friend function.
1226       else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1227                                            REnd = Function->redecls_end();
1228                 R != REnd; ++R) {
1229         if (*R == Function)
1230           continue;
1231         switch (R->getFriendObjectKind()) {
1232         case Decl::FOK_None:
1233           if (!SemaRef.getLangOptions().CPlusPlus0x &&
1234               !queuedInstantiation && R->isUsed(false)) {
1235             if (MemberSpecializationInfo *MSInfo
1236                 = Function->getMemberSpecializationInfo()) {
1237               if (MSInfo->getPointOfInstantiation().isInvalid()) {
1238                 SourceLocation Loc = R->getLocation(); // FIXME
1239                 MSInfo->setPointOfInstantiation(Loc);
1240                 SemaRef.PendingLocalImplicitInstantiations.push_back(
1241                                                  std::make_pair(Function, Loc));
1242                 queuedInstantiation = true;
1243               }
1244             }
1245           }
1246           break;
1247         default:
1248           if (const FunctionDecl *RPattern
1249               = R->getTemplateInstantiationPattern())
1250             if (RPattern->isDefined(RPattern)) {
1251               SemaRef.Diag(Function->getLocation(),
1252                            SemaRef.getLangOptions().CPlusPlus0x ?
1253                              diag::warn_cxx98_compat_friend_redefinition :
1254                              diag::err_redefinition)
1255                 << Function->getDeclName();
1256               SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1257               if (!SemaRef.getLangOptions().CPlusPlus0x)
1258                 Function->setInvalidDecl();
1259               break;
1260             }
1261         }
1262       }
1263     }
1264   }
1265 
1266   if (Function->isOverloadedOperator() && !DC->isRecord() &&
1267       PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1268     PrincipalDecl->setNonMemberOperator();
1269 
1270   assert(!D->isDefaulted() && "only methods should be defaulted");
1271   return Function;
1272 }
1273 
1274 Decl *
1275 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1276                                       TemplateParameterList *TemplateParams,
1277                                       bool IsClassScopeSpecialization) {
1278   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1279   void *InsertPos = 0;
1280   if (FunctionTemplate && !TemplateParams) {
1281     // We are creating a function template specialization from a function
1282     // template. Check whether there is already a function template
1283     // specialization for this particular set of template arguments.
1284     std::pair<const TemplateArgument *, unsigned> Innermost
1285       = TemplateArgs.getInnermost();
1286 
1287     FunctionDecl *SpecFunc
1288       = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1289                                              InsertPos);
1290 
1291     // If we already have a function template specialization, return it.
1292     if (SpecFunc)
1293       return SpecFunc;
1294   }
1295 
1296   bool isFriend;
1297   if (FunctionTemplate)
1298     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1299   else
1300     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1301 
1302   bool MergeWithParentScope = (TemplateParams != 0) ||
1303     !(isa<Decl>(Owner) &&
1304       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1305   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1306 
1307   // Instantiate enclosing template arguments for friends.
1308   SmallVector<TemplateParameterList *, 4> TempParamLists;
1309   unsigned NumTempParamLists = 0;
1310   if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1311     TempParamLists.set_size(NumTempParamLists);
1312     for (unsigned I = 0; I != NumTempParamLists; ++I) {
1313       TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1314       TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1315       if (!InstParams)
1316         return NULL;
1317       TempParamLists[I] = InstParams;
1318     }
1319   }
1320 
1321   SmallVector<ParmVarDecl *, 4> Params;
1322   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1323   if (!TInfo)
1324     return 0;
1325   QualType T = TInfo->getType();
1326 
1327   // \brief If the type of this function, after ignoring parentheses,
1328   // is not *directly* a function type, then we're instantiating a function
1329   // that was declared via a typedef, e.g.,
1330   //
1331   //   typedef int functype(int, int);
1332   //   functype func;
1333   //
1334   // In this case, we'll just go instantiate the ParmVarDecls that we
1335   // synthesized in the method declaration.
1336   if (!isa<FunctionProtoType>(T.IgnoreParens())) {
1337     assert(!Params.size() && "Instantiating type could not yield parameters");
1338     SmallVector<QualType, 4> ParamTypes;
1339     if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1340                                D->getNumParams(), TemplateArgs, ParamTypes,
1341                                &Params))
1342       return 0;
1343   }
1344 
1345   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1346   if (QualifierLoc) {
1347     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1348                                                  TemplateArgs);
1349     if (!QualifierLoc)
1350       return 0;
1351   }
1352 
1353   DeclContext *DC = Owner;
1354   if (isFriend) {
1355     if (QualifierLoc) {
1356       CXXScopeSpec SS;
1357       SS.Adopt(QualifierLoc);
1358       DC = SemaRef.computeDeclContext(SS);
1359 
1360       if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1361         return 0;
1362     } else {
1363       DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1364                                            D->getDeclContext(),
1365                                            TemplateArgs);
1366     }
1367     if (!DC) return 0;
1368   }
1369 
1370   // Build the instantiated method declaration.
1371   CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1372   CXXMethodDecl *Method = 0;
1373 
1374   SourceLocation StartLoc = D->getInnerLocStart();
1375   DeclarationNameInfo NameInfo
1376     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1377   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1378     Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1379                                         StartLoc, NameInfo, T, TInfo,
1380                                         Constructor->isExplicit(),
1381                                         Constructor->isInlineSpecified(),
1382                                         false, Constructor->isConstexpr());
1383   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1384     Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1385                                        StartLoc, NameInfo, T, TInfo,
1386                                        Destructor->isInlineSpecified(),
1387                                        false);
1388   } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1389     Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1390                                        StartLoc, NameInfo, T, TInfo,
1391                                        Conversion->isInlineSpecified(),
1392                                        Conversion->isExplicit(),
1393                                        Conversion->isConstexpr(),
1394                                        Conversion->getLocEnd());
1395   } else {
1396     Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1397                                    StartLoc, NameInfo, T, TInfo,
1398                                    D->isStatic(),
1399                                    D->getStorageClassAsWritten(),
1400                                    D->isInlineSpecified(),
1401                                    D->isConstexpr(), D->getLocEnd());
1402   }
1403 
1404   if (QualifierLoc)
1405     Method->setQualifierInfo(QualifierLoc);
1406 
1407   if (TemplateParams) {
1408     // Our resulting instantiation is actually a function template, since we
1409     // are substituting only the outer template parameters. For example, given
1410     //
1411     //   template<typename T>
1412     //   struct X {
1413     //     template<typename U> void f(T, U);
1414     //   };
1415     //
1416     //   X<int> x;
1417     //
1418     // We are instantiating the member template "f" within X<int>, which means
1419     // substituting int for T, but leaving "f" as a member function template.
1420     // Build the function template itself.
1421     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1422                                                     Method->getLocation(),
1423                                                     Method->getDeclName(),
1424                                                     TemplateParams, Method);
1425     if (isFriend) {
1426       FunctionTemplate->setLexicalDeclContext(Owner);
1427       FunctionTemplate->setObjectOfFriendDecl(true);
1428     } else if (D->isOutOfLine())
1429       FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1430     Method->setDescribedFunctionTemplate(FunctionTemplate);
1431   } else if (FunctionTemplate) {
1432     // Record this function template specialization.
1433     std::pair<const TemplateArgument *, unsigned> Innermost
1434       = TemplateArgs.getInnermost();
1435     Method->setFunctionTemplateSpecialization(FunctionTemplate,
1436                          TemplateArgumentList::CreateCopy(SemaRef.Context,
1437                                                           Innermost.first,
1438                                                           Innermost.second),
1439                                               InsertPos);
1440   } else if (!isFriend) {
1441     // Record that this is an instantiation of a member function.
1442     Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1443   }
1444 
1445   // If we are instantiating a member function defined
1446   // out-of-line, the instantiation will have the same lexical
1447   // context (which will be a namespace scope) as the template.
1448   if (isFriend) {
1449     if (NumTempParamLists)
1450       Method->setTemplateParameterListsInfo(SemaRef.Context,
1451                                             NumTempParamLists,
1452                                             TempParamLists.data());
1453 
1454     Method->setLexicalDeclContext(Owner);
1455     Method->setObjectOfFriendDecl(true);
1456   } else if (D->isOutOfLine())
1457     Method->setLexicalDeclContext(D->getLexicalDeclContext());
1458 
1459   // Attach the parameters
1460   for (unsigned P = 0; P < Params.size(); ++P)
1461     Params[P]->setOwningFunction(Method);
1462   Method->setParams(Params);
1463 
1464   if (InitMethodInstantiation(Method, D))
1465     Method->setInvalidDecl();
1466 
1467   LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1468                         Sema::ForRedeclaration);
1469 
1470   if (!FunctionTemplate || TemplateParams || isFriend) {
1471     SemaRef.LookupQualifiedName(Previous, Record);
1472 
1473     // In C++, the previous declaration we find might be a tag type
1474     // (class or enum). In this case, the new declaration will hide the
1475     // tag type. Note that this does does not apply if we're declaring a
1476     // typedef (C++ [dcl.typedef]p4).
1477     if (Previous.isSingleTagDecl())
1478       Previous.clear();
1479   }
1480 
1481   if (!IsClassScopeSpecialization)
1482     SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
1483 
1484   if (D->isPure())
1485     SemaRef.CheckPureMethod(Method, SourceRange());
1486 
1487   Method->setAccess(D->getAccess());
1488 
1489   SemaRef.CheckOverrideControl(Method);
1490 
1491   // If a function is defined as defaulted or deleted, mark it as such now.
1492   if (D->isDefaulted())
1493     Method->setDefaulted();
1494   if (D->isDeletedAsWritten())
1495     Method->setDeletedAsWritten();
1496 
1497   if (FunctionTemplate) {
1498     // If there's a function template, let our caller handle it.
1499   } else if (Method->isInvalidDecl() && !Previous.empty()) {
1500     // Don't hide a (potentially) valid declaration with an invalid one.
1501   } else {
1502     NamedDecl *DeclToAdd = (TemplateParams
1503                             ? cast<NamedDecl>(FunctionTemplate)
1504                             : Method);
1505     if (isFriend)
1506       Record->makeDeclVisibleInContext(DeclToAdd);
1507     else if (!IsClassScopeSpecialization)
1508       Owner->addDecl(DeclToAdd);
1509   }
1510 
1511   if (D->isExplicitlyDefaulted()) {
1512     SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1513   } else {
1514     assert(!D->isDefaulted() &&
1515            "should not implicitly default uninstantiated function");
1516   }
1517 
1518   return Method;
1519 }
1520 
1521 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1522   return VisitCXXMethodDecl(D);
1523 }
1524 
1525 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1526   return VisitCXXMethodDecl(D);
1527 }
1528 
1529 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1530   return VisitCXXMethodDecl(D);
1531 }
1532 
1533 ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1534   return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
1535                                   llvm::Optional<unsigned>(),
1536                                   /*ExpectParameterPack=*/false);
1537 }
1538 
1539 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1540                                                     TemplateTypeParmDecl *D) {
1541   // TODO: don't always clone when decls are refcounted.
1542   assert(D->getTypeForDecl()->isTemplateTypeParmType());
1543 
1544   TemplateTypeParmDecl *Inst =
1545     TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1546                                  D->getLocStart(), D->getLocation(),
1547                                  D->getDepth() - TemplateArgs.getNumLevels(),
1548                                  D->getIndex(), D->getIdentifier(),
1549                                  D->wasDeclaredWithTypename(),
1550                                  D->isParameterPack());
1551   Inst->setAccess(AS_public);
1552 
1553   if (D->hasDefaultArgument())
1554     Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1555 
1556   // Introduce this template parameter's instantiation into the instantiation
1557   // scope.
1558   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1559 
1560   return Inst;
1561 }
1562 
1563 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1564                                                  NonTypeTemplateParmDecl *D) {
1565   // Substitute into the type of the non-type template parameter.
1566   TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1567   SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1568   SmallVector<QualType, 4> ExpandedParameterPackTypes;
1569   bool IsExpandedParameterPack = false;
1570   TypeSourceInfo *DI;
1571   QualType T;
1572   bool Invalid = false;
1573 
1574   if (D->isExpandedParameterPack()) {
1575     // The non-type template parameter pack is an already-expanded pack
1576     // expansion of types. Substitute into each of the expanded types.
1577     ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1578     ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1579     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1580       TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1581                                                TemplateArgs,
1582                                                D->getLocation(),
1583                                                D->getDeclName());
1584       if (!NewDI)
1585         return 0;
1586 
1587       ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1588       QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1589                                                               D->getLocation());
1590       if (NewT.isNull())
1591         return 0;
1592       ExpandedParameterPackTypes.push_back(NewT);
1593     }
1594 
1595     IsExpandedParameterPack = true;
1596     DI = D->getTypeSourceInfo();
1597     T = DI->getType();
1598   } else if (isa<PackExpansionTypeLoc>(TL)) {
1599     // The non-type template parameter pack's type is a pack expansion of types.
1600     // Determine whether we need to expand this parameter pack into separate
1601     // types.
1602     PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1603     TypeLoc Pattern = Expansion.getPatternLoc();
1604     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1605     SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1606 
1607     // Determine whether the set of unexpanded parameter packs can and should
1608     // be expanded.
1609     bool Expand = true;
1610     bool RetainExpansion = false;
1611     llvm::Optional<unsigned> OrigNumExpansions
1612       = Expansion.getTypePtr()->getNumExpansions();
1613     llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1614     if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1615                                                 Pattern.getSourceRange(),
1616                                                 Unexpanded,
1617                                                 TemplateArgs,
1618                                                 Expand, RetainExpansion,
1619                                                 NumExpansions))
1620       return 0;
1621 
1622     if (Expand) {
1623       for (unsigned I = 0; I != *NumExpansions; ++I) {
1624         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1625         TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1626                                                   D->getLocation(),
1627                                                   D->getDeclName());
1628         if (!NewDI)
1629           return 0;
1630 
1631         ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1632         QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1633                                                               NewDI->getType(),
1634                                                               D->getLocation());
1635         if (NewT.isNull())
1636           return 0;
1637         ExpandedParameterPackTypes.push_back(NewT);
1638       }
1639 
1640       // Note that we have an expanded parameter pack. The "type" of this
1641       // expanded parameter pack is the original expansion type, but callers
1642       // will end up using the expanded parameter pack types for type-checking.
1643       IsExpandedParameterPack = true;
1644       DI = D->getTypeSourceInfo();
1645       T = DI->getType();
1646     } else {
1647       // We cannot fully expand the pack expansion now, so substitute into the
1648       // pattern and create a new pack expansion type.
1649       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1650       TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1651                                                      D->getLocation(),
1652                                                      D->getDeclName());
1653       if (!NewPattern)
1654         return 0;
1655 
1656       DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1657                                       NumExpansions);
1658       if (!DI)
1659         return 0;
1660 
1661       T = DI->getType();
1662     }
1663   } else {
1664     // Simple case: substitution into a parameter that is not a parameter pack.
1665     DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1666                            D->getLocation(), D->getDeclName());
1667     if (!DI)
1668       return 0;
1669 
1670     // Check that this type is acceptable for a non-type template parameter.
1671     T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1672                                                   D->getLocation());
1673     if (T.isNull()) {
1674       T = SemaRef.Context.IntTy;
1675       Invalid = true;
1676     }
1677   }
1678 
1679   NonTypeTemplateParmDecl *Param;
1680   if (IsExpandedParameterPack)
1681     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1682                                             D->getInnerLocStart(),
1683                                             D->getLocation(),
1684                                     D->getDepth() - TemplateArgs.getNumLevels(),
1685                                             D->getPosition(),
1686                                             D->getIdentifier(), T,
1687                                             DI,
1688                                             ExpandedParameterPackTypes.data(),
1689                                             ExpandedParameterPackTypes.size(),
1690                                     ExpandedParameterPackTypesAsWritten.data());
1691   else
1692     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1693                                             D->getInnerLocStart(),
1694                                             D->getLocation(),
1695                                     D->getDepth() - TemplateArgs.getNumLevels(),
1696                                             D->getPosition(),
1697                                             D->getIdentifier(), T,
1698                                             D->isParameterPack(), DI);
1699 
1700   Param->setAccess(AS_public);
1701   if (Invalid)
1702     Param->setInvalidDecl();
1703 
1704   Param->setDefaultArgument(D->getDefaultArgument(), false);
1705 
1706   // Introduce this template parameter's instantiation into the instantiation
1707   // scope.
1708   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1709   return Param;
1710 }
1711 
1712 Decl *
1713 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1714                                                   TemplateTemplateParmDecl *D) {
1715   // Instantiate the template parameter list of the template template parameter.
1716   TemplateParameterList *TempParams = D->getTemplateParameters();
1717   TemplateParameterList *InstParams;
1718   {
1719     // Perform the actual substitution of template parameters within a new,
1720     // local instantiation scope.
1721     LocalInstantiationScope Scope(SemaRef);
1722     InstParams = SubstTemplateParams(TempParams);
1723     if (!InstParams)
1724       return NULL;
1725   }
1726 
1727   // Build the template template parameter.
1728   TemplateTemplateParmDecl *Param
1729     = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1730                                    D->getDepth() - TemplateArgs.getNumLevels(),
1731                                        D->getPosition(), D->isParameterPack(),
1732                                        D->getIdentifier(), InstParams);
1733   Param->setDefaultArgument(D->getDefaultArgument(), false);
1734   Param->setAccess(AS_public);
1735 
1736   // Introduce this template parameter's instantiation into the instantiation
1737   // scope.
1738   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1739 
1740   return Param;
1741 }
1742 
1743 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1744   // Using directives are never dependent (and never contain any types or
1745   // expressions), so they require no explicit instantiation work.
1746 
1747   UsingDirectiveDecl *Inst
1748     = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1749                                  D->getNamespaceKeyLocation(),
1750                                  D->getQualifierLoc(),
1751                                  D->getIdentLocation(),
1752                                  D->getNominatedNamespace(),
1753                                  D->getCommonAncestor());
1754   Owner->addDecl(Inst);
1755   return Inst;
1756 }
1757 
1758 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1759 
1760   // The nested name specifier may be dependent, for example
1761   //     template <typename T> struct t {
1762   //       struct s1 { T f1(); };
1763   //       struct s2 : s1 { using s1::f1; };
1764   //     };
1765   //     template struct t<int>;
1766   // Here, in using s1::f1, s1 refers to t<T>::s1;
1767   // we need to substitute for t<int>::s1.
1768   NestedNameSpecifierLoc QualifierLoc
1769     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1770                                           TemplateArgs);
1771   if (!QualifierLoc)
1772     return 0;
1773 
1774   // The name info is non-dependent, so no transformation
1775   // is required.
1776   DeclarationNameInfo NameInfo = D->getNameInfo();
1777 
1778   // We only need to do redeclaration lookups if we're in a class
1779   // scope (in fact, it's not really even possible in non-class
1780   // scopes).
1781   bool CheckRedeclaration = Owner->isRecord();
1782 
1783   LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1784                     Sema::ForRedeclaration);
1785 
1786   UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1787                                        D->getUsingLocation(),
1788                                        QualifierLoc,
1789                                        NameInfo,
1790                                        D->isTypeName());
1791 
1792   CXXScopeSpec SS;
1793   SS.Adopt(QualifierLoc);
1794   if (CheckRedeclaration) {
1795     Prev.setHideTags(false);
1796     SemaRef.LookupQualifiedName(Prev, Owner);
1797 
1798     // Check for invalid redeclarations.
1799     if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1800                                             D->isTypeName(), SS,
1801                                             D->getLocation(), Prev))
1802       NewUD->setInvalidDecl();
1803 
1804   }
1805 
1806   if (!NewUD->isInvalidDecl() &&
1807       SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
1808                                       D->getLocation()))
1809     NewUD->setInvalidDecl();
1810 
1811   SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1812   NewUD->setAccess(D->getAccess());
1813   Owner->addDecl(NewUD);
1814 
1815   // Don't process the shadow decls for an invalid decl.
1816   if (NewUD->isInvalidDecl())
1817     return NewUD;
1818 
1819   bool isFunctionScope = Owner->isFunctionOrMethod();
1820 
1821   // Process the shadow decls.
1822   for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1823          I != E; ++I) {
1824     UsingShadowDecl *Shadow = *I;
1825     NamedDecl *InstTarget =
1826       cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
1827                                                           Shadow->getLocation(),
1828                                                         Shadow->getTargetDecl(),
1829                                                            TemplateArgs));
1830     if (!InstTarget)
1831       return 0;
1832 
1833     if (CheckRedeclaration &&
1834         SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1835       continue;
1836 
1837     UsingShadowDecl *InstShadow
1838       = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1839     SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
1840 
1841     if (isFunctionScope)
1842       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
1843   }
1844 
1845   return NewUD;
1846 }
1847 
1848 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
1849   // Ignore these;  we handle them in bulk when processing the UsingDecl.
1850   return 0;
1851 }
1852 
1853 Decl * TemplateDeclInstantiator
1854     ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1855   NestedNameSpecifierLoc QualifierLoc
1856     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1857                                           TemplateArgs);
1858   if (!QualifierLoc)
1859     return 0;
1860 
1861   CXXScopeSpec SS;
1862   SS.Adopt(QualifierLoc);
1863 
1864   // Since NameInfo refers to a typename, it cannot be a C++ special name.
1865   // Hence, no tranformation is required for it.
1866   DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
1867   NamedDecl *UD =
1868     SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1869                                   D->getUsingLoc(), SS, NameInfo, 0,
1870                                   /*instantiation*/ true,
1871                                   /*typename*/ true, D->getTypenameLoc());
1872   if (UD)
1873     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1874 
1875   return UD;
1876 }
1877 
1878 Decl * TemplateDeclInstantiator
1879     ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1880   NestedNameSpecifierLoc QualifierLoc
1881       = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
1882   if (!QualifierLoc)
1883     return 0;
1884 
1885   CXXScopeSpec SS;
1886   SS.Adopt(QualifierLoc);
1887 
1888   DeclarationNameInfo NameInfo
1889     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1890 
1891   NamedDecl *UD =
1892     SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1893                                   D->getUsingLoc(), SS, NameInfo, 0,
1894                                   /*instantiation*/ true,
1895                                   /*typename*/ false, SourceLocation());
1896   if (UD)
1897     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1898 
1899   return UD;
1900 }
1901 
1902 
1903 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
1904                                      ClassScopeFunctionSpecializationDecl *Decl) {
1905   CXXMethodDecl *OldFD = Decl->getSpecialization();
1906   CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, 0, true));
1907 
1908   LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
1909                         Sema::ForRedeclaration);
1910 
1911   SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
1912   if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, 0, Previous)) {
1913     NewFD->setInvalidDecl();
1914     return NewFD;
1915   }
1916 
1917   // Associate the specialization with the pattern.
1918   FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
1919   assert(Specialization && "Class scope Specialization is null");
1920   SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
1921 
1922   return NewFD;
1923 }
1924 
1925 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
1926                       const MultiLevelTemplateArgumentList &TemplateArgs) {
1927   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
1928   if (D->isInvalidDecl())
1929     return 0;
1930 
1931   return Instantiator.Visit(D);
1932 }
1933 
1934 /// \brief Instantiates a nested template parameter list in the current
1935 /// instantiation context.
1936 ///
1937 /// \param L The parameter list to instantiate
1938 ///
1939 /// \returns NULL if there was an error
1940 TemplateParameterList *
1941 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
1942   // Get errors for all the parameters before bailing out.
1943   bool Invalid = false;
1944 
1945   unsigned N = L->size();
1946   typedef SmallVector<NamedDecl *, 8> ParamVector;
1947   ParamVector Params;
1948   Params.reserve(N);
1949   for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1950        PI != PE; ++PI) {
1951     NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
1952     Params.push_back(D);
1953     Invalid = Invalid || !D || D->isInvalidDecl();
1954   }
1955 
1956   // Clean up if we had an error.
1957   if (Invalid)
1958     return NULL;
1959 
1960   TemplateParameterList *InstL
1961     = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1962                                     L->getLAngleLoc(), &Params.front(), N,
1963                                     L->getRAngleLoc());
1964   return InstL;
1965 }
1966 
1967 /// \brief Instantiate the declaration of a class template partial
1968 /// specialization.
1969 ///
1970 /// \param ClassTemplate the (instantiated) class template that is partially
1971 // specialized by the instantiation of \p PartialSpec.
1972 ///
1973 /// \param PartialSpec the (uninstantiated) class template partial
1974 /// specialization that we are instantiating.
1975 ///
1976 /// \returns The instantiated partial specialization, if successful; otherwise,
1977 /// NULL to indicate an error.
1978 ClassTemplatePartialSpecializationDecl *
1979 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1980                                             ClassTemplateDecl *ClassTemplate,
1981                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
1982   // Create a local instantiation scope for this class template partial
1983   // specialization, which will contain the instantiations of the template
1984   // parameters.
1985   LocalInstantiationScope Scope(SemaRef);
1986 
1987   // Substitute into the template parameters of the class template partial
1988   // specialization.
1989   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1990   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1991   if (!InstParams)
1992     return 0;
1993 
1994   // Substitute into the template arguments of the class template partial
1995   // specialization.
1996   TemplateArgumentListInfo InstTemplateArgs; // no angle locations
1997   if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
1998                     PartialSpec->getNumTemplateArgsAsWritten(),
1999                     InstTemplateArgs, TemplateArgs))
2000     return 0;
2001 
2002   // Check that the template argument list is well-formed for this
2003   // class template.
2004   SmallVector<TemplateArgument, 4> Converted;
2005   if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2006                                         PartialSpec->getLocation(),
2007                                         InstTemplateArgs,
2008                                         false,
2009                                         Converted))
2010     return 0;
2011 
2012   // Figure out where to insert this class template partial specialization
2013   // in the member template's set of class template partial specializations.
2014   void *InsertPos = 0;
2015   ClassTemplateSpecializationDecl *PrevDecl
2016     = ClassTemplate->findPartialSpecialization(Converted.data(),
2017                                                Converted.size(), InsertPos);
2018 
2019   // Build the canonical type that describes the converted template
2020   // arguments of the class template partial specialization.
2021   QualType CanonType
2022     = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2023                                                     Converted.data(),
2024                                                     Converted.size());
2025 
2026   // Build the fully-sugared type for this class template
2027   // specialization as the user wrote in the specialization
2028   // itself. This means that we'll pretty-print the type retrieved
2029   // from the specialization's declaration the way that the user
2030   // actually wrote the specialization, rather than formatting the
2031   // name based on the "canonical" representation used to store the
2032   // template arguments in the specialization.
2033   TypeSourceInfo *WrittenTy
2034     = SemaRef.Context.getTemplateSpecializationTypeInfo(
2035                                                     TemplateName(ClassTemplate),
2036                                                     PartialSpec->getLocation(),
2037                                                     InstTemplateArgs,
2038                                                     CanonType);
2039 
2040   if (PrevDecl) {
2041     // We've already seen a partial specialization with the same template
2042     // parameters and template arguments. This can happen, for example, when
2043     // substituting the outer template arguments ends up causing two
2044     // class template partial specializations of a member class template
2045     // to have identical forms, e.g.,
2046     //
2047     //   template<typename T, typename U>
2048     //   struct Outer {
2049     //     template<typename X, typename Y> struct Inner;
2050     //     template<typename Y> struct Inner<T, Y>;
2051     //     template<typename Y> struct Inner<U, Y>;
2052     //   };
2053     //
2054     //   Outer<int, int> outer; // error: the partial specializations of Inner
2055     //                          // have the same signature.
2056     SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
2057       << WrittenTy->getType();
2058     SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2059       << SemaRef.Context.getTypeDeclType(PrevDecl);
2060     return 0;
2061   }
2062 
2063 
2064   // Create the class template partial specialization declaration.
2065   ClassTemplatePartialSpecializationDecl *InstPartialSpec
2066     = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2067                                                      PartialSpec->getTagKind(),
2068                                                      Owner,
2069                                                      PartialSpec->getLocStart(),
2070                                                      PartialSpec->getLocation(),
2071                                                      InstParams,
2072                                                      ClassTemplate,
2073                                                      Converted.data(),
2074                                                      Converted.size(),
2075                                                      InstTemplateArgs,
2076                                                      CanonType,
2077                                                      0,
2078                              ClassTemplate->getNextPartialSpecSequenceNumber());
2079   // Substitute the nested name specifier, if any.
2080   if (SubstQualifier(PartialSpec, InstPartialSpec))
2081     return 0;
2082 
2083   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2084   InstPartialSpec->setTypeAsWritten(WrittenTy);
2085 
2086   // Add this partial specialization to the set of class template partial
2087   // specializations.
2088   ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
2089   return InstPartialSpec;
2090 }
2091 
2092 TypeSourceInfo*
2093 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
2094                               SmallVectorImpl<ParmVarDecl *> &Params) {
2095   TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2096   assert(OldTInfo && "substituting function without type source info");
2097   assert(Params.empty() && "parameter vector is non-empty at start");
2098   TypeSourceInfo *NewTInfo
2099     = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2100                                     D->getTypeSpecStartLoc(),
2101                                     D->getDeclName());
2102   if (!NewTInfo)
2103     return 0;
2104 
2105   if (NewTInfo != OldTInfo) {
2106     // Get parameters from the new type info.
2107     TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2108     if (FunctionProtoTypeLoc *OldProtoLoc
2109                                   = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2110       TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
2111       FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
2112       assert(NewProtoLoc && "Missing prototype?");
2113       unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
2114       for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
2115            OldIdx != NumOldParams; ++OldIdx) {
2116         ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
2117         if (!OldParam->isParameterPack() ||
2118             (NewIdx < NumNewParams &&
2119              NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
2120           // Simple case: normal parameter, or a parameter pack that's
2121           // instantiated to a (still-dependent) parameter pack.
2122           ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2123           Params.push_back(NewParam);
2124           SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
2125                                                                NewParam);
2126           continue;
2127         }
2128 
2129         // Parameter pack: make the instantiation an argument pack.
2130         SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
2131                                                                       OldParam);
2132         unsigned NumArgumentsInExpansion
2133           = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2134                                                TemplateArgs);
2135         while (NumArgumentsInExpansion--) {
2136           ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2137           Params.push_back(NewParam);
2138           SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
2139                                                                       NewParam);
2140         }
2141       }
2142     }
2143   } else {
2144     // The function type itself was not dependent and therefore no
2145     // substitution occurred. However, we still need to instantiate
2146     // the function parameters themselves.
2147     TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2148     if (FunctionProtoTypeLoc *OldProtoLoc
2149                                     = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2150       for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2151         ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2152         if (!Parm)
2153           return 0;
2154         Params.push_back(Parm);
2155       }
2156     }
2157   }
2158   return NewTInfo;
2159 }
2160 
2161 /// \brief Initializes the common fields of an instantiation function
2162 /// declaration (New) from the corresponding fields of its template (Tmpl).
2163 ///
2164 /// \returns true if there was an error
2165 bool
2166 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
2167                                                     FunctionDecl *Tmpl) {
2168   if (Tmpl->isDeletedAsWritten())
2169     New->setDeletedAsWritten();
2170 
2171   // If we are performing substituting explicitly-specified template arguments
2172   // or deduced template arguments into a function template and we reach this
2173   // point, we are now past the point where SFINAE applies and have committed
2174   // to keeping the new function template specialization. We therefore
2175   // convert the active template instantiation for the function template
2176   // into a template instantiation for this specific function template
2177   // specialization, which is not a SFINAE context, so that we diagnose any
2178   // further errors in the declaration itself.
2179   typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2180   ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2181   if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2182       ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
2183     if (FunctionTemplateDecl *FunTmpl
2184           = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
2185       assert(FunTmpl->getTemplatedDecl() == Tmpl &&
2186              "Deduction from the wrong function template?");
2187       (void) FunTmpl;
2188       ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2189       ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
2190       --SemaRef.NonInstantiationEntries;
2191     }
2192   }
2193 
2194   const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2195   assert(Proto && "Function template without prototype?");
2196 
2197   if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
2198     // The function has an exception specification or a "noreturn"
2199     // attribute. Substitute into each of the exception types.
2200     SmallVector<QualType, 4> Exceptions;
2201     for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2202       // FIXME: Poor location information!
2203       if (const PackExpansionType *PackExpansion
2204             = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2205         // We have a pack expansion. Instantiate it.
2206         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2207         SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2208                                                 Unexpanded);
2209         assert(!Unexpanded.empty() &&
2210                "Pack expansion without parameter packs?");
2211 
2212         bool Expand = false;
2213         bool RetainExpansion = false;
2214         llvm::Optional<unsigned> NumExpansions
2215                                           = PackExpansion->getNumExpansions();
2216         if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2217                                                     SourceRange(),
2218                                                     Unexpanded,
2219                                                     TemplateArgs,
2220                                                     Expand,
2221                                                     RetainExpansion,
2222                                                     NumExpansions))
2223           break;
2224 
2225         if (!Expand) {
2226           // We can't expand this pack expansion into separate arguments yet;
2227           // just substitute into the pattern and create a new pack expansion
2228           // type.
2229           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2230           QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2231                                          TemplateArgs,
2232                                        New->getLocation(), New->getDeclName());
2233           if (T.isNull())
2234             break;
2235 
2236           T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2237           Exceptions.push_back(T);
2238           continue;
2239         }
2240 
2241         // Substitute into the pack expansion pattern for each template
2242         bool Invalid = false;
2243         for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2244           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2245 
2246           QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2247                                          TemplateArgs,
2248                                        New->getLocation(), New->getDeclName());
2249           if (T.isNull()) {
2250             Invalid = true;
2251             break;
2252           }
2253 
2254           Exceptions.push_back(T);
2255         }
2256 
2257         if (Invalid)
2258           break;
2259 
2260         continue;
2261       }
2262 
2263       QualType T
2264         = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2265                             New->getLocation(), New->getDeclName());
2266       if (T.isNull() ||
2267           SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2268         continue;
2269 
2270       Exceptions.push_back(T);
2271     }
2272     Expr *NoexceptExpr = 0;
2273     if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2274       EnterExpressionEvaluationContext Unevaluated(SemaRef,
2275                                                    Sema::ConstantEvaluated);
2276       ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2277       if (E.isUsable())
2278         E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2279 
2280       if (E.isUsable()) {
2281         NoexceptExpr = E.take();
2282         if (!NoexceptExpr->isTypeDependent() &&
2283             !NoexceptExpr->isValueDependent())
2284           NoexceptExpr = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2285             0, SemaRef.PDiag(diag::err_noexcept_needs_constant_expression),
2286             /*AllowFold*/ false).take();
2287       }
2288     }
2289 
2290     // Rebuild the function type
2291 
2292     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2293     EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2294     EPI.NumExceptions = Exceptions.size();
2295     EPI.Exceptions = Exceptions.data();
2296     EPI.NoexceptExpr = NoexceptExpr;
2297     EPI.ExtInfo = Proto->getExtInfo();
2298 
2299     const FunctionProtoType *NewProto
2300       = New->getType()->getAs<FunctionProtoType>();
2301     assert(NewProto && "Template instantiation without function prototype?");
2302     New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2303                                                  NewProto->arg_type_begin(),
2304                                                  NewProto->getNumArgs(),
2305                                                  EPI));
2306   }
2307 
2308   const FunctionDecl* Definition = Tmpl;
2309 
2310   // Get the definition. Leaves the variable unchanged if undefined.
2311   Tmpl->isDefined(Definition);
2312 
2313   SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
2314                            LateAttrs, StartingScope);
2315 
2316   return false;
2317 }
2318 
2319 /// \brief Initializes common fields of an instantiated method
2320 /// declaration (New) from the corresponding fields of its template
2321 /// (Tmpl).
2322 ///
2323 /// \returns true if there was an error
2324 bool
2325 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
2326                                                   CXXMethodDecl *Tmpl) {
2327   if (InitFunctionInstantiation(New, Tmpl))
2328     return true;
2329 
2330   New->setAccess(Tmpl->getAccess());
2331   if (Tmpl->isVirtualAsWritten())
2332     New->setVirtualAsWritten(true);
2333 
2334   // FIXME: attributes
2335   // FIXME: New needs a pointer to Tmpl
2336   return false;
2337 }
2338 
2339 /// \brief Instantiate the definition of the given function from its
2340 /// template.
2341 ///
2342 /// \param PointOfInstantiation the point at which the instantiation was
2343 /// required. Note that this is not precisely a "point of instantiation"
2344 /// for the function, but it's close.
2345 ///
2346 /// \param Function the already-instantiated declaration of a
2347 /// function template specialization or member function of a class template
2348 /// specialization.
2349 ///
2350 /// \param Recursive if true, recursively instantiates any functions that
2351 /// are required by this instantiation.
2352 ///
2353 /// \param DefinitionRequired if true, then we are performing an explicit
2354 /// instantiation where the body of the function is required. Complain if
2355 /// there is no such body.
2356 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
2357                                          FunctionDecl *Function,
2358                                          bool Recursive,
2359                                          bool DefinitionRequired) {
2360   if (Function->isInvalidDecl() || Function->isDefined())
2361     return;
2362 
2363   // Never instantiate an explicit specialization except if it is a class scope
2364   // explicit specialization.
2365   if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2366       !Function->getClassScopeSpecializationPattern())
2367     return;
2368 
2369   // Find the function body that we'll be substituting.
2370   const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
2371   assert(PatternDecl && "instantiating a non-template");
2372 
2373   Stmt *Pattern = PatternDecl->getBody(PatternDecl);
2374   assert(PatternDecl && "template definition is not a template");
2375   if (!Pattern) {
2376     // Try to find a defaulted definition
2377     PatternDecl->isDefined(PatternDecl);
2378   }
2379   assert(PatternDecl && "template definition is not a template");
2380 
2381   // Postpone late parsed template instantiations.
2382   if (PatternDecl->isLateTemplateParsed() &&
2383       !LateTemplateParser) {
2384     PendingInstantiations.push_back(
2385       std::make_pair(Function, PointOfInstantiation));
2386     return;
2387   }
2388 
2389   // Call the LateTemplateParser callback if there a need to late parse
2390   // a templated function definition.
2391   if (!Pattern && PatternDecl->isLateTemplateParsed() &&
2392       LateTemplateParser) {
2393     LateTemplateParser(OpaqueParser, PatternDecl);
2394     Pattern = PatternDecl->getBody(PatternDecl);
2395   }
2396 
2397   if (!Pattern && !PatternDecl->isDefaulted()) {
2398     if (DefinitionRequired) {
2399       if (Function->getPrimaryTemplate())
2400         Diag(PointOfInstantiation,
2401              diag::err_explicit_instantiation_undefined_func_template)
2402           << Function->getPrimaryTemplate();
2403       else
2404         Diag(PointOfInstantiation,
2405              diag::err_explicit_instantiation_undefined_member)
2406           << 1 << Function->getDeclName() << Function->getDeclContext();
2407 
2408       if (PatternDecl)
2409         Diag(PatternDecl->getLocation(),
2410              diag::note_explicit_instantiation_here);
2411       Function->setInvalidDecl();
2412     } else if (Function->getTemplateSpecializationKind()
2413                  == TSK_ExplicitInstantiationDefinition) {
2414       PendingInstantiations.push_back(
2415         std::make_pair(Function, PointOfInstantiation));
2416     }
2417 
2418     return;
2419   }
2420 
2421   // C++0x [temp.explicit]p9:
2422   //   Except for inline functions, other explicit instantiation declarations
2423   //   have the effect of suppressing the implicit instantiation of the entity
2424   //   to which they refer.
2425   if (Function->getTemplateSpecializationKind()
2426         == TSK_ExplicitInstantiationDeclaration &&
2427       !PatternDecl->isInlined())
2428     return;
2429 
2430   InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2431   if (Inst)
2432     return;
2433 
2434   // Copy the inner loc start from the pattern.
2435   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
2436 
2437   // If we're performing recursive template instantiation, create our own
2438   // queue of pending implicit instantiations that we will instantiate later,
2439   // while we're still within our own instantiation context.
2440   SmallVector<VTableUse, 16> SavedVTableUses;
2441   std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2442   if (Recursive) {
2443     VTableUses.swap(SavedVTableUses);
2444     PendingInstantiations.swap(SavedPendingInstantiations);
2445   }
2446 
2447   EnterExpressionEvaluationContext EvalContext(*this,
2448                                                Sema::PotentiallyEvaluated);
2449   ActOnStartOfFunctionDef(0, Function);
2450 
2451   // Introduce a new scope where local variable instantiations will be
2452   // recorded, unless we're actually a member function within a local
2453   // class, in which case we need to merge our results with the parent
2454   // scope (of the enclosing function).
2455   bool MergeWithParentScope = false;
2456   if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2457     MergeWithParentScope = Rec->isLocalClass();
2458 
2459   LocalInstantiationScope Scope(*this, MergeWithParentScope);
2460 
2461   // Introduce the instantiated function parameters into the local
2462   // instantiation scope, and set the parameter names to those used
2463   // in the template.
2464   unsigned FParamIdx = 0;
2465   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2466     const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2467     if (!PatternParam->isParameterPack()) {
2468       // Simple case: not a parameter pack.
2469       assert(FParamIdx < Function->getNumParams());
2470       ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2471       FunctionParam->setDeclName(PatternParam->getDeclName());
2472       Scope.InstantiatedLocal(PatternParam, FunctionParam);
2473       ++FParamIdx;
2474       continue;
2475     }
2476 
2477     // Expand the parameter pack.
2478     Scope.MakeInstantiatedLocalArgPack(PatternParam);
2479     for (unsigned NumFParams = Function->getNumParams();
2480          FParamIdx < NumFParams;
2481          ++FParamIdx) {
2482       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2483       FunctionParam->setDeclName(PatternParam->getDeclName());
2484       Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2485     }
2486   }
2487 
2488   // Enter the scope of this instantiation. We don't use
2489   // PushDeclContext because we don't have a scope.
2490   Sema::ContextRAII savedContext(*this, Function);
2491 
2492   MultiLevelTemplateArgumentList TemplateArgs =
2493     getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2494 
2495   if (PatternDecl->isDefaulted()) {
2496     ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true);
2497 
2498     SetDeclDefaulted(Function, PatternDecl->getLocation());
2499   } else {
2500     // If this is a constructor, instantiate the member initializers.
2501     if (const CXXConstructorDecl *Ctor =
2502           dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2503       InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2504                                  TemplateArgs);
2505     }
2506 
2507     // Instantiate the function body.
2508     StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2509 
2510     if (Body.isInvalid())
2511       Function->setInvalidDecl();
2512 
2513     ActOnFinishFunctionBody(Function, Body.get(),
2514                             /*IsInstantiation=*/true);
2515   }
2516 
2517   PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2518 
2519   savedContext.pop();
2520 
2521   DeclGroupRef DG(Function);
2522   Consumer.HandleTopLevelDecl(DG);
2523 
2524   // This class may have local implicit instantiations that need to be
2525   // instantiation within this scope.
2526   PerformPendingInstantiations(/*LocalOnly=*/true);
2527   Scope.Exit();
2528 
2529   if (Recursive) {
2530     // Define any pending vtables.
2531     DefineUsedVTables();
2532 
2533     // Instantiate any pending implicit instantiations found during the
2534     // instantiation of this template.
2535     PerformPendingInstantiations();
2536 
2537     // Restore the set of pending vtables.
2538     assert(VTableUses.empty() &&
2539            "VTableUses should be empty before it is discarded.");
2540     VTableUses.swap(SavedVTableUses);
2541 
2542     // Restore the set of pending implicit instantiations.
2543     assert(PendingInstantiations.empty() &&
2544            "PendingInstantiations should be empty before it is discarded.");
2545     PendingInstantiations.swap(SavedPendingInstantiations);
2546   }
2547 }
2548 
2549 /// \brief Instantiate the definition of the given variable from its
2550 /// template.
2551 ///
2552 /// \param PointOfInstantiation the point at which the instantiation was
2553 /// required. Note that this is not precisely a "point of instantiation"
2554 /// for the function, but it's close.
2555 ///
2556 /// \param Var the already-instantiated declaration of a static member
2557 /// variable of a class template specialization.
2558 ///
2559 /// \param Recursive if true, recursively instantiates any functions that
2560 /// are required by this instantiation.
2561 ///
2562 /// \param DefinitionRequired if true, then we are performing an explicit
2563 /// instantiation where an out-of-line definition of the member variable
2564 /// is required. Complain if there is no such definition.
2565 void Sema::InstantiateStaticDataMemberDefinition(
2566                                           SourceLocation PointOfInstantiation,
2567                                                  VarDecl *Var,
2568                                                  bool Recursive,
2569                                                  bool DefinitionRequired) {
2570   if (Var->isInvalidDecl())
2571     return;
2572 
2573   // Find the out-of-line definition of this static data member.
2574   VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
2575   assert(Def && "This data member was not instantiated from a template?");
2576   assert(Def->isStaticDataMember() && "Not a static data member?");
2577   Def = Def->getOutOfLineDefinition();
2578 
2579   if (!Def) {
2580     // We did not find an out-of-line definition of this static data member,
2581     // so we won't perform any instantiation. Rather, we rely on the user to
2582     // instantiate this definition (or provide a specialization for it) in
2583     // another translation unit.
2584     if (DefinitionRequired) {
2585       Def = Var->getInstantiatedFromStaticDataMember();
2586       Diag(PointOfInstantiation,
2587            diag::err_explicit_instantiation_undefined_member)
2588         << 2 << Var->getDeclName() << Var->getDeclContext();
2589       Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2590     } else if (Var->getTemplateSpecializationKind()
2591                  == TSK_ExplicitInstantiationDefinition) {
2592       PendingInstantiations.push_back(
2593         std::make_pair(Var, PointOfInstantiation));
2594     }
2595 
2596     return;
2597   }
2598 
2599   // Never instantiate an explicit specialization.
2600   if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2601     return;
2602 
2603   // C++0x [temp.explicit]p9:
2604   //   Except for inline functions, other explicit instantiation declarations
2605   //   have the effect of suppressing the implicit instantiation of the entity
2606   //   to which they refer.
2607   if (Var->getTemplateSpecializationKind()
2608         == TSK_ExplicitInstantiationDeclaration)
2609     return;
2610 
2611   // If we already have a definition, we're done.
2612   if (Var->getDefinition())
2613     return;
2614 
2615   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2616   if (Inst)
2617     return;
2618 
2619   // If we're performing recursive template instantiation, create our own
2620   // queue of pending implicit instantiations that we will instantiate later,
2621   // while we're still within our own instantiation context.
2622   SmallVector<VTableUse, 16> SavedVTableUses;
2623   std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2624   if (Recursive) {
2625     VTableUses.swap(SavedVTableUses);
2626     PendingInstantiations.swap(SavedPendingInstantiations);
2627   }
2628 
2629   // Enter the scope of this instantiation. We don't use
2630   // PushDeclContext because we don't have a scope.
2631   ContextRAII previousContext(*this, Var->getDeclContext());
2632   LocalInstantiationScope Local(*this);
2633 
2634   VarDecl *OldVar = Var;
2635   Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
2636                                         getTemplateInstantiationArgs(Var)));
2637 
2638   previousContext.pop();
2639 
2640   if (Var) {
2641     MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2642     assert(MSInfo && "Missing member specialization information?");
2643     Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2644                                        MSInfo->getPointOfInstantiation());
2645     DeclGroupRef DG(Var);
2646     Consumer.HandleTopLevelDecl(DG);
2647   }
2648   Local.Exit();
2649 
2650   if (Recursive) {
2651     // Define any newly required vtables.
2652     DefineUsedVTables();
2653 
2654     // Instantiate any pending implicit instantiations found during the
2655     // instantiation of this template.
2656     PerformPendingInstantiations();
2657 
2658     // Restore the set of pending vtables.
2659     assert(VTableUses.empty() &&
2660            "VTableUses should be empty before it is discarded, "
2661            "while instantiating static data member.");
2662     VTableUses.swap(SavedVTableUses);
2663 
2664     // Restore the set of pending implicit instantiations.
2665     assert(PendingInstantiations.empty() &&
2666            "PendingInstantiations should be empty before it is discarded, "
2667            "while instantiating static data member.");
2668     PendingInstantiations.swap(SavedPendingInstantiations);
2669   }
2670 }
2671 
2672 void
2673 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2674                                  const CXXConstructorDecl *Tmpl,
2675                            const MultiLevelTemplateArgumentList &TemplateArgs) {
2676 
2677   SmallVector<CXXCtorInitializer*, 4> NewInits;
2678   bool AnyErrors = false;
2679 
2680   // Instantiate all the initializers.
2681   for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
2682                                             InitsEnd = Tmpl->init_end();
2683        Inits != InitsEnd; ++Inits) {
2684     CXXCtorInitializer *Init = *Inits;
2685 
2686     // Only instantiate written initializers, let Sema re-construct implicit
2687     // ones.
2688     if (!Init->isWritten())
2689       continue;
2690 
2691     SourceLocation EllipsisLoc;
2692 
2693     if (Init->isPackExpansion()) {
2694       // This is a pack expansion. We should expand it now.
2695       TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
2696       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2697       collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2698       bool ShouldExpand = false;
2699       bool RetainExpansion = false;
2700       llvm::Optional<unsigned> NumExpansions;
2701       if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2702                                           BaseTL.getSourceRange(),
2703                                           Unexpanded,
2704                                           TemplateArgs, ShouldExpand,
2705                                           RetainExpansion,
2706                                           NumExpansions)) {
2707         AnyErrors = true;
2708         New->setInvalidDecl();
2709         continue;
2710       }
2711       assert(ShouldExpand && "Partial instantiation of base initializer?");
2712 
2713       // Loop over all of the arguments in the argument pack(s),
2714       for (unsigned I = 0; I != *NumExpansions; ++I) {
2715         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2716 
2717         // Instantiate the initializer.
2718         ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
2719                                                /*CXXDirectInit=*/true);
2720         if (TempInit.isInvalid()) {
2721           AnyErrors = true;
2722           break;
2723         }
2724 
2725         // Instantiate the base type.
2726         TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
2727                                               TemplateArgs,
2728                                               Init->getSourceLocation(),
2729                                               New->getDeclName());
2730         if (!BaseTInfo) {
2731           AnyErrors = true;
2732           break;
2733         }
2734 
2735         // Build the initializer.
2736         MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2737                                                      BaseTInfo, TempInit.take(),
2738                                                      New->getParent(),
2739                                                      SourceLocation());
2740         if (NewInit.isInvalid()) {
2741           AnyErrors = true;
2742           break;
2743         }
2744 
2745         NewInits.push_back(NewInit.get());
2746       }
2747 
2748       continue;
2749     }
2750 
2751     // Instantiate the initializer.
2752     ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
2753                                            /*CXXDirectInit=*/true);
2754     if (TempInit.isInvalid()) {
2755       AnyErrors = true;
2756       continue;
2757     }
2758 
2759     MemInitResult NewInit;
2760     if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
2761       TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
2762                                         TemplateArgs,
2763                                         Init->getSourceLocation(),
2764                                         New->getDeclName());
2765       if (!TInfo) {
2766         AnyErrors = true;
2767         New->setInvalidDecl();
2768         continue;
2769       }
2770 
2771       if (Init->isBaseInitializer())
2772         NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
2773                                        New->getParent(), EllipsisLoc);
2774       else
2775         NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
2776                                   cast<CXXRecordDecl>(CurContext->getParent()));
2777     } else if (Init->isMemberInitializer()) {
2778       FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
2779                                                      Init->getMemberLocation(),
2780                                                      Init->getMember(),
2781                                                      TemplateArgs));
2782       if (!Member) {
2783         AnyErrors = true;
2784         New->setInvalidDecl();
2785         continue;
2786       }
2787 
2788       NewInit = BuildMemberInitializer(Member, TempInit.take(),
2789                                        Init->getSourceLocation());
2790     } else if (Init->isIndirectMemberInitializer()) {
2791       IndirectFieldDecl *IndirectMember =
2792          cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
2793                                  Init->getMemberLocation(),
2794                                  Init->getIndirectMember(), TemplateArgs));
2795 
2796       if (!IndirectMember) {
2797         AnyErrors = true;
2798         New->setInvalidDecl();
2799         continue;
2800       }
2801 
2802       NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
2803                                        Init->getSourceLocation());
2804     }
2805 
2806     if (NewInit.isInvalid()) {
2807       AnyErrors = true;
2808       New->setInvalidDecl();
2809     } else {
2810       NewInits.push_back(NewInit.get());
2811     }
2812   }
2813 
2814   // Assign all the initializers to the new constructor.
2815   ActOnMemInitializers(New,
2816                        /*FIXME: ColonLoc */
2817                        SourceLocation(),
2818                        NewInits.data(), NewInits.size(),
2819                        AnyErrors);
2820 }
2821 
2822 ExprResult Sema::SubstInitializer(Expr *Init,
2823                           const MultiLevelTemplateArgumentList &TemplateArgs,
2824                           bool CXXDirectInit) {
2825   // Initializers are instantiated like expressions, except that various outer
2826   // layers are stripped.
2827   if (!Init)
2828     return Owned(Init);
2829 
2830   if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
2831     Init = ExprTemp->getSubExpr();
2832 
2833   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
2834     Init = Binder->getSubExpr();
2835 
2836   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
2837     Init = ICE->getSubExprAsWritten();
2838 
2839   // If this is a direct-initializer, we take apart CXXConstructExprs.
2840   // Everything else is passed through.
2841   CXXConstructExpr *Construct;
2842   if (!CXXDirectInit || !(Construct = dyn_cast<CXXConstructExpr>(Init)) ||
2843       isa<CXXTemporaryObjectExpr>(Construct))
2844     return SubstExpr(Init, TemplateArgs);
2845 
2846   ASTOwningVector<Expr*> NewArgs(*this);
2847   if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
2848                  TemplateArgs, NewArgs))
2849     return ExprError();
2850 
2851   // Treat an empty initializer like none.
2852   if (NewArgs.empty())
2853     return Owned((Expr*)0);
2854 
2855   // Build a ParenListExpr to represent anything else.
2856   // FIXME: Fake locations!
2857   SourceLocation Loc = PP.getLocForEndOfToken(Init->getLocStart());
2858   return ActOnParenListExpr(Loc, Loc, move_arg(NewArgs));
2859 }
2860 
2861 // TODO: this could be templated if the various decl types used the
2862 // same method name.
2863 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2864                               ClassTemplateDecl *Instance) {
2865   Pattern = Pattern->getCanonicalDecl();
2866 
2867   do {
2868     Instance = Instance->getCanonicalDecl();
2869     if (Pattern == Instance) return true;
2870     Instance = Instance->getInstantiatedFromMemberTemplate();
2871   } while (Instance);
2872 
2873   return false;
2874 }
2875 
2876 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2877                               FunctionTemplateDecl *Instance) {
2878   Pattern = Pattern->getCanonicalDecl();
2879 
2880   do {
2881     Instance = Instance->getCanonicalDecl();
2882     if (Pattern == Instance) return true;
2883     Instance = Instance->getInstantiatedFromMemberTemplate();
2884   } while (Instance);
2885 
2886   return false;
2887 }
2888 
2889 static bool
2890 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2891                   ClassTemplatePartialSpecializationDecl *Instance) {
2892   Pattern
2893     = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2894   do {
2895     Instance = cast<ClassTemplatePartialSpecializationDecl>(
2896                                                 Instance->getCanonicalDecl());
2897     if (Pattern == Instance)
2898       return true;
2899     Instance = Instance->getInstantiatedFromMember();
2900   } while (Instance);
2901 
2902   return false;
2903 }
2904 
2905 static bool isInstantiationOf(CXXRecordDecl *Pattern,
2906                               CXXRecordDecl *Instance) {
2907   Pattern = Pattern->getCanonicalDecl();
2908 
2909   do {
2910     Instance = Instance->getCanonicalDecl();
2911     if (Pattern == Instance) return true;
2912     Instance = Instance->getInstantiatedFromMemberClass();
2913   } while (Instance);
2914 
2915   return false;
2916 }
2917 
2918 static bool isInstantiationOf(FunctionDecl *Pattern,
2919                               FunctionDecl *Instance) {
2920   Pattern = Pattern->getCanonicalDecl();
2921 
2922   do {
2923     Instance = Instance->getCanonicalDecl();
2924     if (Pattern == Instance) return true;
2925     Instance = Instance->getInstantiatedFromMemberFunction();
2926   } while (Instance);
2927 
2928   return false;
2929 }
2930 
2931 static bool isInstantiationOf(EnumDecl *Pattern,
2932                               EnumDecl *Instance) {
2933   Pattern = Pattern->getCanonicalDecl();
2934 
2935   do {
2936     Instance = Instance->getCanonicalDecl();
2937     if (Pattern == Instance) return true;
2938     Instance = Instance->getInstantiatedFromMemberEnum();
2939   } while (Instance);
2940 
2941   return false;
2942 }
2943 
2944 static bool isInstantiationOf(UsingShadowDecl *Pattern,
2945                               UsingShadowDecl *Instance,
2946                               ASTContext &C) {
2947   return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2948 }
2949 
2950 static bool isInstantiationOf(UsingDecl *Pattern,
2951                               UsingDecl *Instance,
2952                               ASTContext &C) {
2953   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2954 }
2955 
2956 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2957                               UsingDecl *Instance,
2958                               ASTContext &C) {
2959   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2960 }
2961 
2962 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
2963                               UsingDecl *Instance,
2964                               ASTContext &C) {
2965   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2966 }
2967 
2968 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2969                                               VarDecl *Instance) {
2970   assert(Instance->isStaticDataMember());
2971 
2972   Pattern = Pattern->getCanonicalDecl();
2973 
2974   do {
2975     Instance = Instance->getCanonicalDecl();
2976     if (Pattern == Instance) return true;
2977     Instance = Instance->getInstantiatedFromStaticDataMember();
2978   } while (Instance);
2979 
2980   return false;
2981 }
2982 
2983 // Other is the prospective instantiation
2984 // D is the prospective pattern
2985 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
2986   if (D->getKind() != Other->getKind()) {
2987     if (UnresolvedUsingTypenameDecl *UUD
2988           = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2989       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2990         return isInstantiationOf(UUD, UD, Ctx);
2991       }
2992     }
2993 
2994     if (UnresolvedUsingValueDecl *UUD
2995           = dyn_cast<UnresolvedUsingValueDecl>(D)) {
2996       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2997         return isInstantiationOf(UUD, UD, Ctx);
2998       }
2999     }
3000 
3001     return false;
3002   }
3003 
3004   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3005     return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
3006 
3007   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3008     return isInstantiationOf(cast<FunctionDecl>(D), Function);
3009 
3010   if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3011     return isInstantiationOf(cast<EnumDecl>(D), Enum);
3012 
3013   if (VarDecl *Var = dyn_cast<VarDecl>(Other))
3014     if (Var->isStaticDataMember())
3015       return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3016 
3017   if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3018     return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
3019 
3020   if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3021     return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3022 
3023   if (ClassTemplatePartialSpecializationDecl *PartialSpec
3024         = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3025     return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3026                              PartialSpec);
3027 
3028   if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3029     if (!Field->getDeclName()) {
3030       // This is an unnamed field.
3031       return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
3032         cast<FieldDecl>(D);
3033     }
3034   }
3035 
3036   if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3037     return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3038 
3039   if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3040     return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3041 
3042   return D->getDeclName() && isa<NamedDecl>(Other) &&
3043     D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3044 }
3045 
3046 template<typename ForwardIterator>
3047 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
3048                                       NamedDecl *D,
3049                                       ForwardIterator first,
3050                                       ForwardIterator last) {
3051   for (; first != last; ++first)
3052     if (isInstantiationOf(Ctx, D, *first))
3053       return cast<NamedDecl>(*first);
3054 
3055   return 0;
3056 }
3057 
3058 /// \brief Finds the instantiation of the given declaration context
3059 /// within the current instantiation.
3060 ///
3061 /// \returns NULL if there was an error
3062 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
3063                           const MultiLevelTemplateArgumentList &TemplateArgs) {
3064   if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
3065     Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
3066     return cast_or_null<DeclContext>(ID);
3067   } else return DC;
3068 }
3069 
3070 /// \brief Find the instantiation of the given declaration within the
3071 /// current instantiation.
3072 ///
3073 /// This routine is intended to be used when \p D is a declaration
3074 /// referenced from within a template, that needs to mapped into the
3075 /// corresponding declaration within an instantiation. For example,
3076 /// given:
3077 ///
3078 /// \code
3079 /// template<typename T>
3080 /// struct X {
3081 ///   enum Kind {
3082 ///     KnownValue = sizeof(T)
3083 ///   };
3084 ///
3085 ///   bool getKind() const { return KnownValue; }
3086 /// };
3087 ///
3088 /// template struct X<int>;
3089 /// \endcode
3090 ///
3091 /// In the instantiation of X<int>::getKind(), we need to map the
3092 /// EnumConstantDecl for KnownValue (which refers to
3093 /// X<T>::<Kind>::KnownValue) to its instantiation
3094 /// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
3095 /// this mapping from within the instantiation of X<int>.
3096 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
3097                           const MultiLevelTemplateArgumentList &TemplateArgs) {
3098   DeclContext *ParentDC = D->getDeclContext();
3099   if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
3100       isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
3101       (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
3102       (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
3103     // D is a local of some kind. Look into the map of local
3104     // declarations to their instantiations.
3105     typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3106     llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3107       = CurrentInstantiationScope->findInstantiationOf(D);
3108 
3109     if (Found) {
3110       if (Decl *FD = Found->dyn_cast<Decl *>())
3111         return cast<NamedDecl>(FD);
3112 
3113       unsigned PackIdx = ArgumentPackSubstitutionIndex;
3114       return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3115     }
3116 
3117     // If we didn't find the decl, then we must have a label decl that hasn't
3118     // been found yet.  Lazily instantiate it and return it now.
3119     assert(isa<LabelDecl>(D));
3120 
3121     Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3122     assert(Inst && "Failed to instantiate label??");
3123 
3124     CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3125     return cast<LabelDecl>(Inst);
3126   }
3127 
3128   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3129     if (!Record->isDependentContext())
3130       return D;
3131 
3132     // Determine whether this record is the "templated" declaration describing
3133     // a class template or class template partial specialization.
3134     ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
3135     if (ClassTemplate)
3136       ClassTemplate = ClassTemplate->getCanonicalDecl();
3137     else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3138                = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
3139       ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
3140 
3141     // Walk the current context to find either the record or an instantiation of
3142     // it.
3143     DeclContext *DC = CurContext;
3144     while (!DC->isFileContext()) {
3145       // If we're performing substitution while we're inside the template
3146       // definition, we'll find our own context. We're done.
3147       if (DC->Equals(Record))
3148         return Record;
3149 
3150       if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
3151         // Check whether we're in the process of instantiating a class template
3152         // specialization of the template we're mapping.
3153         if (ClassTemplateSpecializationDecl *InstSpec
3154                       = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
3155           ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
3156           if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
3157             return InstRecord;
3158         }
3159 
3160         // Check whether we're in the process of instantiating a member class.
3161         if (isInstantiationOf(Record, InstRecord))
3162           return InstRecord;
3163       }
3164 
3165 
3166       // Move to the outer template scope.
3167       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
3168         if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
3169           DC = FD->getLexicalDeclContext();
3170           continue;
3171         }
3172       }
3173 
3174       DC = DC->getParent();
3175     }
3176 
3177     // Fall through to deal with other dependent record types (e.g.,
3178     // anonymous unions in class templates).
3179   }
3180 
3181   if (!ParentDC->isDependentContext())
3182     return D;
3183 
3184   ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
3185   if (!ParentDC)
3186     return 0;
3187 
3188   if (ParentDC != D->getDeclContext()) {
3189     // We performed some kind of instantiation in the parent context,
3190     // so now we need to look into the instantiated parent context to
3191     // find the instantiation of the declaration D.
3192 
3193     // If our context used to be dependent, we may need to instantiate
3194     // it before performing lookup into that context.
3195     bool IsBeingInstantiated = false;
3196     if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
3197       if (!Spec->isDependentContext()) {
3198         QualType T = Context.getTypeDeclType(Spec);
3199         const RecordType *Tag = T->getAs<RecordType>();
3200         assert(Tag && "type of non-dependent record is not a RecordType");
3201         if (Tag->isBeingDefined())
3202           IsBeingInstantiated = true;
3203         if (!Tag->isBeingDefined() &&
3204             RequireCompleteType(Loc, T, diag::err_incomplete_type))
3205           return 0;
3206 
3207         ParentDC = Tag->getDecl();
3208       }
3209     }
3210 
3211     NamedDecl *Result = 0;
3212     if (D->getDeclName()) {
3213       DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
3214       Result = findInstantiationOf(Context, D, Found.first, Found.second);
3215     } else {
3216       // Since we don't have a name for the entity we're looking for,
3217       // our only option is to walk through all of the declarations to
3218       // find that name. This will occur in a few cases:
3219       //
3220       //   - anonymous struct/union within a template
3221       //   - unnamed class/struct/union/enum within a template
3222       //
3223       // FIXME: Find a better way to find these instantiations!
3224       Result = findInstantiationOf(Context, D,
3225                                    ParentDC->decls_begin(),
3226                                    ParentDC->decls_end());
3227     }
3228 
3229     if (!Result) {
3230       if (isa<UsingShadowDecl>(D)) {
3231         // UsingShadowDecls can instantiate to nothing because of using hiding.
3232       } else if (Diags.hasErrorOccurred()) {
3233         // We've already complained about something, so most likely this
3234         // declaration failed to instantiate. There's no point in complaining
3235         // further, since this is normal in invalid code.
3236       } else if (IsBeingInstantiated) {
3237         // The class in which this member exists is currently being
3238         // instantiated, and we haven't gotten around to instantiating this
3239         // member yet. This can happen when the code uses forward declarations
3240         // of member classes, and introduces ordering dependencies via
3241         // template instantiation.
3242         Diag(Loc, diag::err_member_not_yet_instantiated)
3243           << D->getDeclName()
3244           << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3245         Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3246       } else {
3247         // We should have found something, but didn't.
3248         llvm_unreachable("Unable to find instantiation of declaration!");
3249       }
3250     }
3251 
3252     D = Result;
3253   }
3254 
3255   return D;
3256 }
3257 
3258 /// \brief Performs template instantiation for all implicit template
3259 /// instantiations we have seen until this point.
3260 void Sema::PerformPendingInstantiations(bool LocalOnly) {
3261   // Load pending instantiations from the external source.
3262   if (!LocalOnly && ExternalSource) {
3263     SmallVector<std::pair<ValueDecl *, SourceLocation>, 4> Pending;
3264     ExternalSource->ReadPendingInstantiations(Pending);
3265     PendingInstantiations.insert(PendingInstantiations.begin(),
3266                                  Pending.begin(), Pending.end());
3267   }
3268 
3269   while (!PendingLocalImplicitInstantiations.empty() ||
3270          (!LocalOnly && !PendingInstantiations.empty())) {
3271     PendingImplicitInstantiation Inst;
3272 
3273     if (PendingLocalImplicitInstantiations.empty()) {
3274       Inst = PendingInstantiations.front();
3275       PendingInstantiations.pop_front();
3276     } else {
3277       Inst = PendingLocalImplicitInstantiations.front();
3278       PendingLocalImplicitInstantiations.pop_front();
3279     }
3280 
3281     // Instantiate function definitions
3282     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
3283       PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3284                                           "instantiating function definition");
3285       bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3286                                 TSK_ExplicitInstantiationDefinition;
3287       InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3288                                     DefinitionRequired);
3289       continue;
3290     }
3291 
3292     // Instantiate static data member definitions.
3293     VarDecl *Var = cast<VarDecl>(Inst.first);
3294     assert(Var->isStaticDataMember() && "Not a static data member?");
3295 
3296     // Don't try to instantiate declarations if the most recent redeclaration
3297     // is invalid.
3298     if (Var->getMostRecentDecl()->isInvalidDecl())
3299       continue;
3300 
3301     // Check if the most recent declaration has changed the specialization kind
3302     // and removed the need for implicit instantiation.
3303     switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
3304     case TSK_Undeclared:
3305       llvm_unreachable("Cannot instantitiate an undeclared specialization.");
3306     case TSK_ExplicitInstantiationDeclaration:
3307     case TSK_ExplicitSpecialization:
3308       continue;  // No longer need to instantiate this type.
3309     case TSK_ExplicitInstantiationDefinition:
3310       // We only need an instantiation if the pending instantiation *is* the
3311       // explicit instantiation.
3312       if (Var != Var->getMostRecentDecl()) continue;
3313     case TSK_ImplicitInstantiation:
3314       break;
3315     }
3316 
3317     PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3318                                         "instantiating static data member "
3319                                         "definition");
3320 
3321     bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3322                               TSK_ExplicitInstantiationDefinition;
3323     InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3324                                           DefinitionRequired);
3325   }
3326 }
3327 
3328 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3329                        const MultiLevelTemplateArgumentList &TemplateArgs) {
3330   for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3331          E = Pattern->ddiag_end(); I != E; ++I) {
3332     DependentDiagnostic *DD = *I;
3333 
3334     switch (DD->getKind()) {
3335     case DependentDiagnostic::Access:
3336       HandleDependentAccessCheck(*DD, TemplateArgs);
3337       break;
3338     }
3339   }
3340 }
3341