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