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