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