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