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