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