SemaTemplateInstantiateDecl.cpp revision 5764f613e61cb3183f3d7ceeafd23396de96ed16
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  if (TemplateParams) {
1013    // Our resulting instantiation is actually a function template, since we
1014    // are substituting only the outer template parameters. For example, given
1015    //
1016    //   template<typename T>
1017    //   struct X {
1018    //     template<typename U> friend void f(T, U);
1019    //   };
1020    //
1021    //   X<int> x;
1022    //
1023    // We are instantiating the friend function template "f" within X<int>,
1024    // which means substituting int for T, but leaving "f" as a friend function
1025    // template.
1026    // Build the function template itself.
1027    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1028                                                    Function->getLocation(),
1029                                                    Function->getDeclName(),
1030                                                    TemplateParams, Function);
1031    Function->setDescribedFunctionTemplate(FunctionTemplate);
1032
1033    FunctionTemplate->setLexicalDeclContext(LexicalDC);
1034
1035    if (isFriend && D->isThisDeclarationADefinition()) {
1036      // TODO: should we remember this connection regardless of whether
1037      // the friend declaration provided a body?
1038      FunctionTemplate->setInstantiatedFromMemberTemplate(
1039                                           D->getDescribedFunctionTemplate());
1040    }
1041  } else if (FunctionTemplate) {
1042    // Record this function template specialization.
1043    Function->setFunctionTemplateSpecialization(FunctionTemplate,
1044                                                &TemplateArgs.getInnermost(),
1045                                                InsertPos);
1046  } else if (isFriend && D->isThisDeclarationADefinition()) {
1047    // TODO: should we remember this connection regardless of whether
1048    // the friend declaration provided a body?
1049    Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1050  }
1051
1052  if (InitFunctionInstantiation(Function, D))
1053    Function->setInvalidDecl();
1054
1055  bool Redeclaration = false;
1056  bool OverloadableAttrRequired = false;
1057  bool isExplicitSpecialization = false;
1058
1059  LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1060                        Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1061
1062  if (DependentFunctionTemplateSpecializationInfo *Info
1063        = D->getDependentSpecializationInfo()) {
1064    assert(isFriend && "non-friend has dependent specialization info?");
1065
1066    // This needs to be set now for future sanity.
1067    Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1068
1069    // Instantiate the explicit template arguments.
1070    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1071                                          Info->getRAngleLoc());
1072    for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1073      TemplateArgumentLoc Loc;
1074      if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1075        return 0;
1076
1077      ExplicitArgs.addArgument(Loc);
1078    }
1079
1080    // Map the candidate templates to their instantiations.
1081    for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1082      Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1083                                                Info->getTemplate(I),
1084                                                TemplateArgs);
1085      if (!Temp) return 0;
1086
1087      Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1088    }
1089
1090    if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1091                                                    &ExplicitArgs,
1092                                                    Previous))
1093      Function->setInvalidDecl();
1094
1095    isExplicitSpecialization = true;
1096
1097  } else if (TemplateParams || !FunctionTemplate) {
1098    // Look only into the namespace where the friend would be declared to
1099    // find a previous declaration. This is the innermost enclosing namespace,
1100    // as described in ActOnFriendFunctionDecl.
1101    SemaRef.LookupQualifiedName(Previous, DC);
1102
1103    // In C++, the previous declaration we find might be a tag type
1104    // (class or enum). In this case, the new declaration will hide the
1105    // tag type. Note that this does does not apply if we're declaring a
1106    // typedef (C++ [dcl.typedef]p4).
1107    if (Previous.isSingleTagDecl())
1108      Previous.clear();
1109  }
1110
1111  SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1112                                   isExplicitSpecialization, Redeclaration,
1113                                   /*FIXME:*/OverloadableAttrRequired);
1114
1115  NamedDecl *PrincipalDecl = (TemplateParams
1116                              ? cast<NamedDecl>(FunctionTemplate)
1117                              : Function);
1118
1119  // If the original function was part of a friend declaration,
1120  // inherit its namespace state and add it to the owner.
1121  if (isFriend) {
1122    NamedDecl *PrevDecl;
1123    if (TemplateParams)
1124      PrevDecl = FunctionTemplate->getPreviousDeclaration();
1125    else
1126      PrevDecl = Function->getPreviousDeclaration();
1127
1128    PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1129    DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
1130  }
1131
1132  if (Function->isOverloadedOperator() && !DC->isRecord() &&
1133      PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1134    PrincipalDecl->setNonMemberOperator();
1135
1136  return Function;
1137}
1138
1139Decl *
1140TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1141                                      TemplateParameterList *TemplateParams) {
1142  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1143  void *InsertPos = 0;
1144  if (FunctionTemplate && !TemplateParams) {
1145    // We are creating a function template specialization from a function
1146    // template. Check whether there is already a function template
1147    // specialization for this particular set of template arguments.
1148    llvm::FoldingSetNodeID ID;
1149    FunctionTemplateSpecializationInfo::Profile(ID,
1150                            TemplateArgs.getInnermost().getFlatArgumentList(),
1151                                      TemplateArgs.getInnermost().flat_size(),
1152                                                SemaRef.Context);
1153
1154    FunctionTemplateSpecializationInfo *Info
1155      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
1156                                                                   InsertPos);
1157
1158    // If we already have a function template specialization, return it.
1159    if (Info)
1160      return Info->Function;
1161  }
1162
1163  bool isFriend;
1164  if (FunctionTemplate)
1165    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1166  else
1167    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1168
1169  bool MergeWithParentScope = (TemplateParams != 0) ||
1170    !(isa<Decl>(Owner) &&
1171      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1172  Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1173
1174  llvm::SmallVector<ParmVarDecl *, 4> Params;
1175  TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1176  TInfo = SubstFunctionType(D, Params);
1177  if (!TInfo)
1178    return 0;
1179  QualType T = TInfo->getType();
1180
1181  // \brief If the type of this function is not *directly* a function
1182  // type, then we're instantiating the a function that was declared
1183  // via a typedef, e.g.,
1184  //
1185  //   typedef int functype(int, int);
1186  //   functype func;
1187  //
1188  // In this case, we'll just go instantiate the ParmVarDecls that we
1189  // synthesized in the method declaration.
1190  if (!isa<FunctionProtoType>(T)) {
1191    assert(!Params.size() && "Instantiating type could not yield parameters");
1192    for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) {
1193      ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I),
1194                                                TemplateArgs);
1195      if (!P)
1196        return 0;
1197
1198      Params.push_back(P);
1199    }
1200  }
1201
1202  NestedNameSpecifier *Qualifier = D->getQualifier();
1203  if (Qualifier) {
1204    Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1205                                                 D->getQualifierRange(),
1206                                                 TemplateArgs);
1207    if (!Qualifier) return 0;
1208  }
1209
1210  DeclContext *DC = Owner;
1211  if (isFriend) {
1212    if (Qualifier) {
1213      CXXScopeSpec SS;
1214      SS.setScopeRep(Qualifier);
1215      SS.setRange(D->getQualifierRange());
1216      DC = SemaRef.computeDeclContext(SS);
1217    } else {
1218      DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1219                                           D->getDeclContext(),
1220                                           TemplateArgs);
1221    }
1222    if (!DC) return 0;
1223  }
1224
1225  // Build the instantiated method declaration.
1226  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1227  CXXMethodDecl *Method = 0;
1228
1229  DeclarationName Name = D->getDeclName();
1230  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1231    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1232    Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1233                                    SemaRef.Context.getCanonicalType(ClassTy));
1234    Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1235                                        Constructor->getLocation(),
1236                                        Name, T, TInfo,
1237                                        Constructor->isExplicit(),
1238                                        Constructor->isInlineSpecified(),
1239                                        false);
1240  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1241    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1242    Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1243                                   SemaRef.Context.getCanonicalType(ClassTy));
1244    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1245                                       Destructor->getLocation(), Name,
1246                                       T, Destructor->isInlineSpecified(),
1247                                       false);
1248  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1249    CanQualType ConvTy
1250      = SemaRef.Context.getCanonicalType(
1251                                      T->getAs<FunctionType>()->getResultType());
1252    Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1253                                                                      ConvTy);
1254    Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1255                                       Conversion->getLocation(), Name,
1256                                       T, TInfo,
1257                                       Conversion->isInlineSpecified(),
1258                                       Conversion->isExplicit());
1259  } else {
1260    Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
1261                                   D->getDeclName(), T, TInfo,
1262                                   D->isStatic(),
1263                                   D->getStorageClassAsWritten(),
1264                                   D->isInlineSpecified());
1265  }
1266
1267  if (Qualifier)
1268    Method->setQualifierInfo(Qualifier, D->getQualifierRange());
1269
1270  if (TemplateParams) {
1271    // Our resulting instantiation is actually a function template, since we
1272    // are substituting only the outer template parameters. For example, given
1273    //
1274    //   template<typename T>
1275    //   struct X {
1276    //     template<typename U> void f(T, U);
1277    //   };
1278    //
1279    //   X<int> x;
1280    //
1281    // We are instantiating the member template "f" within X<int>, which means
1282    // substituting int for T, but leaving "f" as a member function template.
1283    // Build the function template itself.
1284    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1285                                                    Method->getLocation(),
1286                                                    Method->getDeclName(),
1287                                                    TemplateParams, Method);
1288    if (isFriend) {
1289      FunctionTemplate->setLexicalDeclContext(Owner);
1290      FunctionTemplate->setObjectOfFriendDecl(true);
1291    } else if (D->isOutOfLine())
1292      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1293    Method->setDescribedFunctionTemplate(FunctionTemplate);
1294  } else if (FunctionTemplate) {
1295    // Record this function template specialization.
1296    Method->setFunctionTemplateSpecialization(FunctionTemplate,
1297                                              &TemplateArgs.getInnermost(),
1298                                              InsertPos);
1299  } else if (!isFriend) {
1300    // Record that this is an instantiation of a member function.
1301    Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1302  }
1303
1304  // If we are instantiating a member function defined
1305  // out-of-line, the instantiation will have the same lexical
1306  // context (which will be a namespace scope) as the template.
1307  if (isFriend) {
1308    Method->setLexicalDeclContext(Owner);
1309    Method->setObjectOfFriendDecl(true);
1310  } else if (D->isOutOfLine())
1311    Method->setLexicalDeclContext(D->getLexicalDeclContext());
1312
1313  // Attach the parameters
1314  for (unsigned P = 0; P < Params.size(); ++P)
1315    Params[P]->setOwningFunction(Method);
1316  Method->setParams(Params.data(), Params.size());
1317
1318  if (InitMethodInstantiation(Method, D))
1319    Method->setInvalidDecl();
1320
1321  LookupResult Previous(SemaRef, Name, SourceLocation(),
1322                        Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1323
1324  if (!FunctionTemplate || TemplateParams || isFriend) {
1325    SemaRef.LookupQualifiedName(Previous, Record);
1326
1327    // In C++, the previous declaration we find might be a tag type
1328    // (class or enum). In this case, the new declaration will hide the
1329    // tag type. Note that this does does not apply if we're declaring a
1330    // typedef (C++ [dcl.typedef]p4).
1331    if (Previous.isSingleTagDecl())
1332      Previous.clear();
1333  }
1334
1335  bool Redeclaration = false;
1336  bool OverloadableAttrRequired = false;
1337  SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
1338                                   /*FIXME:*/OverloadableAttrRequired);
1339
1340  if (D->isPure())
1341    SemaRef.CheckPureMethod(Method, SourceRange());
1342
1343  Method->setAccess(D->getAccess());
1344
1345  if (FunctionTemplate) {
1346    // If there's a function template, let our caller handle it.
1347  } else if (Method->isInvalidDecl() && !Previous.empty()) {
1348    // Don't hide a (potentially) valid declaration with an invalid one.
1349  } else {
1350    NamedDecl *DeclToAdd = (TemplateParams
1351                            ? cast<NamedDecl>(FunctionTemplate)
1352                            : Method);
1353    if (isFriend)
1354      Record->makeDeclVisibleInContext(DeclToAdd);
1355    else
1356      Owner->addDecl(DeclToAdd);
1357  }
1358
1359  return Method;
1360}
1361
1362Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1363  return VisitCXXMethodDecl(D);
1364}
1365
1366Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1367  return VisitCXXMethodDecl(D);
1368}
1369
1370Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1371  return VisitCXXMethodDecl(D);
1372}
1373
1374ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1375  return SemaRef.SubstParmVarDecl(D, TemplateArgs);
1376}
1377
1378Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1379                                                    TemplateTypeParmDecl *D) {
1380  // TODO: don't always clone when decls are refcounted.
1381  const Type* T = D->getTypeForDecl();
1382  assert(T->isTemplateTypeParmType());
1383  const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
1384
1385  TemplateTypeParmDecl *Inst =
1386    TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1387                                 TTPT->getDepth() - 1, TTPT->getIndex(),
1388                                 TTPT->getName(),
1389                                 D->wasDeclaredWithTypename(),
1390                                 D->isParameterPack());
1391
1392  if (D->hasDefaultArgument())
1393    Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1394
1395  // Introduce this template parameter's instantiation into the instantiation
1396  // scope.
1397  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1398
1399  return Inst;
1400}
1401
1402Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1403                                                 NonTypeTemplateParmDecl *D) {
1404  // Substitute into the type of the non-type template parameter.
1405  QualType T;
1406  TypeSourceInfo *DI = D->getTypeSourceInfo();
1407  if (DI) {
1408    DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1409                           D->getDeclName());
1410    if (DI) T = DI->getType();
1411  } else {
1412    T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1413                          D->getDeclName());
1414    DI = 0;
1415  }
1416  if (T.isNull())
1417    return 0;
1418
1419  // Check that this type is acceptable for a non-type template parameter.
1420  bool Invalid = false;
1421  T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1422  if (T.isNull()) {
1423    T = SemaRef.Context.IntTy;
1424    Invalid = true;
1425  }
1426
1427  NonTypeTemplateParmDecl *Param
1428    = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1429                                      D->getDepth() - 1, D->getPosition(),
1430                                      D->getIdentifier(), T, DI);
1431  if (Invalid)
1432    Param->setInvalidDecl();
1433
1434  Param->setDefaultArgument(D->getDefaultArgument());
1435
1436  // Introduce this template parameter's instantiation into the instantiation
1437  // scope.
1438  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1439  return Param;
1440}
1441
1442Decl *
1443TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1444                                                  TemplateTemplateParmDecl *D) {
1445  // Instantiate the template parameter list of the template template parameter.
1446  TemplateParameterList *TempParams = D->getTemplateParameters();
1447  TemplateParameterList *InstParams;
1448  {
1449    // Perform the actual substitution of template parameters within a new,
1450    // local instantiation scope.
1451    Sema::LocalInstantiationScope Scope(SemaRef);
1452    InstParams = SubstTemplateParams(TempParams);
1453    if (!InstParams)
1454      return NULL;
1455  }
1456
1457  // Build the template template parameter.
1458  TemplateTemplateParmDecl *Param
1459    = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1460                                       D->getDepth() - 1, D->getPosition(),
1461                                       D->getIdentifier(), InstParams);
1462  Param->setDefaultArgument(D->getDefaultArgument());
1463
1464  // Introduce this template parameter's instantiation into the instantiation
1465  // scope.
1466  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1467
1468  return Param;
1469}
1470
1471Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1472  // Using directives are never dependent, so they require no explicit
1473
1474  UsingDirectiveDecl *Inst
1475    = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1476                                 D->getNamespaceKeyLocation(),
1477                                 D->getQualifierRange(), D->getQualifier(),
1478                                 D->getIdentLocation(),
1479                                 D->getNominatedNamespace(),
1480                                 D->getCommonAncestor());
1481  Owner->addDecl(Inst);
1482  return Inst;
1483}
1484
1485Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1486  // The nested name specifier is non-dependent, so no transformation
1487  // is required.
1488
1489  // We only need to do redeclaration lookups if we're in a class
1490  // scope (in fact, it's not really even possible in non-class
1491  // scopes).
1492  bool CheckRedeclaration = Owner->isRecord();
1493
1494  LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1495                    Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1496
1497  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1498                                       D->getLocation(),
1499                                       D->getNestedNameRange(),
1500                                       D->getUsingLocation(),
1501                                       D->getTargetNestedNameDecl(),
1502                                       D->getDeclName(),
1503                                       D->isTypeName());
1504
1505  CXXScopeSpec SS;
1506  SS.setScopeRep(D->getTargetNestedNameDecl());
1507  SS.setRange(D->getNestedNameRange());
1508
1509  if (CheckRedeclaration) {
1510    Prev.setHideTags(false);
1511    SemaRef.LookupQualifiedName(Prev, Owner);
1512
1513    // Check for invalid redeclarations.
1514    if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1515                                            D->isTypeName(), SS,
1516                                            D->getLocation(), Prev))
1517      NewUD->setInvalidDecl();
1518
1519  }
1520
1521  if (!NewUD->isInvalidDecl() &&
1522      SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
1523                                      D->getLocation()))
1524    NewUD->setInvalidDecl();
1525
1526  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1527  NewUD->setAccess(D->getAccess());
1528  Owner->addDecl(NewUD);
1529
1530  // Don't process the shadow decls for an invalid decl.
1531  if (NewUD->isInvalidDecl())
1532    return NewUD;
1533
1534  bool isFunctionScope = Owner->isFunctionOrMethod();
1535
1536  // Process the shadow decls.
1537  for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1538         I != E; ++I) {
1539    UsingShadowDecl *Shadow = *I;
1540    NamedDecl *InstTarget =
1541      cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1542                                                   Shadow->getTargetDecl(),
1543                                                   TemplateArgs));
1544
1545    if (CheckRedeclaration &&
1546        SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1547      continue;
1548
1549    UsingShadowDecl *InstShadow
1550      = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1551    SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
1552
1553    if (isFunctionScope)
1554      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
1555  }
1556
1557  return NewUD;
1558}
1559
1560Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
1561  // Ignore these;  we handle them in bulk when processing the UsingDecl.
1562  return 0;
1563}
1564
1565Decl * TemplateDeclInstantiator
1566    ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1567  NestedNameSpecifier *NNS =
1568    SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1569                                     D->getTargetNestedNameRange(),
1570                                     TemplateArgs);
1571  if (!NNS)
1572    return 0;
1573
1574  CXXScopeSpec SS;
1575  SS.setRange(D->getTargetNestedNameRange());
1576  SS.setScopeRep(NNS);
1577
1578  NamedDecl *UD =
1579    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1580                                  D->getUsingLoc(), SS, D->getLocation(),
1581                                  D->getDeclName(), 0,
1582                                  /*instantiation*/ true,
1583                                  /*typename*/ true, D->getTypenameLoc());
1584  if (UD)
1585    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1586
1587  return UD;
1588}
1589
1590Decl * TemplateDeclInstantiator
1591    ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1592  NestedNameSpecifier *NNS =
1593    SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1594                                     D->getTargetNestedNameRange(),
1595                                     TemplateArgs);
1596  if (!NNS)
1597    return 0;
1598
1599  CXXScopeSpec SS;
1600  SS.setRange(D->getTargetNestedNameRange());
1601  SS.setScopeRep(NNS);
1602
1603  NamedDecl *UD =
1604    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1605                                  D->getUsingLoc(), SS, D->getLocation(),
1606                                  D->getDeclName(), 0,
1607                                  /*instantiation*/ true,
1608                                  /*typename*/ false, SourceLocation());
1609  if (UD)
1610    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1611
1612  return UD;
1613}
1614
1615Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
1616                      const MultiLevelTemplateArgumentList &TemplateArgs) {
1617  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
1618  if (D->isInvalidDecl())
1619    return 0;
1620
1621  return Instantiator.Visit(D);
1622}
1623
1624/// \brief Instantiates a nested template parameter list in the current
1625/// instantiation context.
1626///
1627/// \param L The parameter list to instantiate
1628///
1629/// \returns NULL if there was an error
1630TemplateParameterList *
1631TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
1632  // Get errors for all the parameters before bailing out.
1633  bool Invalid = false;
1634
1635  unsigned N = L->size();
1636  typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
1637  ParamVector Params;
1638  Params.reserve(N);
1639  for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1640       PI != PE; ++PI) {
1641    NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
1642    Params.push_back(D);
1643    Invalid = Invalid || !D || D->isInvalidDecl();
1644  }
1645
1646  // Clean up if we had an error.
1647  if (Invalid) {
1648    for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1649         PI != PE; ++PI)
1650      if (*PI)
1651        (*PI)->Destroy(SemaRef.Context);
1652    return NULL;
1653  }
1654
1655  TemplateParameterList *InstL
1656    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1657                                    L->getLAngleLoc(), &Params.front(), N,
1658                                    L->getRAngleLoc());
1659  return InstL;
1660}
1661
1662/// \brief Instantiate the declaration of a class template partial
1663/// specialization.
1664///
1665/// \param ClassTemplate the (instantiated) class template that is partially
1666// specialized by the instantiation of \p PartialSpec.
1667///
1668/// \param PartialSpec the (uninstantiated) class template partial
1669/// specialization that we are instantiating.
1670///
1671/// \returns true if there was an error, false otherwise.
1672bool
1673TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1674                                            ClassTemplateDecl *ClassTemplate,
1675                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
1676  // Create a local instantiation scope for this class template partial
1677  // specialization, which will contain the instantiations of the template
1678  // parameters.
1679  Sema::LocalInstantiationScope Scope(SemaRef);
1680
1681  // Substitute into the template parameters of the class template partial
1682  // specialization.
1683  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1684  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1685  if (!InstParams)
1686    return true;
1687
1688  // Substitute into the template arguments of the class template partial
1689  // specialization.
1690  const TemplateArgumentLoc *PartialSpecTemplateArgs
1691    = PartialSpec->getTemplateArgsAsWritten();
1692  unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1693
1694  TemplateArgumentListInfo InstTemplateArgs; // no angle locations
1695  for (unsigned I = 0; I != N; ++I) {
1696    TemplateArgumentLoc Loc;
1697    if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
1698      return true;
1699    InstTemplateArgs.addArgument(Loc);
1700  }
1701
1702
1703  // Check that the template argument list is well-formed for this
1704  // class template.
1705  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1706                                        InstTemplateArgs.size());
1707  if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1708                                        PartialSpec->getLocation(),
1709                                        InstTemplateArgs,
1710                                        false,
1711                                        Converted))
1712    return true;
1713
1714  // Figure out where to insert this class template partial specialization
1715  // in the member template's set of class template partial specializations.
1716  llvm::FoldingSetNodeID ID;
1717  ClassTemplatePartialSpecializationDecl::Profile(ID,
1718                                                  Converted.getFlatArguments(),
1719                                                  Converted.flatSize(),
1720                                                  SemaRef.Context);
1721  void *InsertPos = 0;
1722  ClassTemplateSpecializationDecl *PrevDecl
1723    = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1724                                                                     InsertPos);
1725
1726  // Build the canonical type that describes the converted template
1727  // arguments of the class template partial specialization.
1728  QualType CanonType
1729    = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1730                                                  Converted.getFlatArguments(),
1731                                                    Converted.flatSize());
1732
1733  // Build the fully-sugared type for this class template
1734  // specialization as the user wrote in the specialization
1735  // itself. This means that we'll pretty-print the type retrieved
1736  // from the specialization's declaration the way that the user
1737  // actually wrote the specialization, rather than formatting the
1738  // name based on the "canonical" representation used to store the
1739  // template arguments in the specialization.
1740  TypeSourceInfo *WrittenTy
1741    = SemaRef.Context.getTemplateSpecializationTypeInfo(
1742                                                    TemplateName(ClassTemplate),
1743                                                    PartialSpec->getLocation(),
1744                                                    InstTemplateArgs,
1745                                                    CanonType);
1746
1747  if (PrevDecl) {
1748    // We've already seen a partial specialization with the same template
1749    // parameters and template arguments. This can happen, for example, when
1750    // substituting the outer template arguments ends up causing two
1751    // class template partial specializations of a member class template
1752    // to have identical forms, e.g.,
1753    //
1754    //   template<typename T, typename U>
1755    //   struct Outer {
1756    //     template<typename X, typename Y> struct Inner;
1757    //     template<typename Y> struct Inner<T, Y>;
1758    //     template<typename Y> struct Inner<U, Y>;
1759    //   };
1760    //
1761    //   Outer<int, int> outer; // error: the partial specializations of Inner
1762    //                          // have the same signature.
1763    SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1764      << WrittenTy;
1765    SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1766      << SemaRef.Context.getTypeDeclType(PrevDecl);
1767    return true;
1768  }
1769
1770
1771  // Create the class template partial specialization declaration.
1772  ClassTemplatePartialSpecializationDecl *InstPartialSpec
1773    = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1774                                                     PartialSpec->getTagKind(),
1775                                                     Owner,
1776                                                     PartialSpec->getLocation(),
1777                                                     InstParams,
1778                                                     ClassTemplate,
1779                                                     Converted,
1780                                                     InstTemplateArgs,
1781                                                     CanonType,
1782                                                     0,
1783                             ClassTemplate->getPartialSpecializations().size());
1784  // Substitute the nested name specifier, if any.
1785  if (SubstQualifier(PartialSpec, InstPartialSpec))
1786    return 0;
1787
1788  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1789  InstPartialSpec->setTypeAsWritten(WrittenTy);
1790
1791  // Add this partial specialization to the set of class template partial
1792  // specializations.
1793  ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1794                                                        InsertPos);
1795  return false;
1796}
1797
1798TypeSourceInfo*
1799TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
1800                              llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1801  TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1802  assert(OldTInfo && "substituting function without type source info");
1803  assert(Params.empty() && "parameter vector is non-empty at start");
1804  TypeSourceInfo *NewTInfo
1805    = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1806                                    D->getTypeSpecStartLoc(),
1807                                    D->getDeclName());
1808  if (!NewTInfo)
1809    return 0;
1810
1811  if (NewTInfo != OldTInfo) {
1812    // Get parameters from the new type info.
1813    TypeLoc OldTL = OldTInfo->getTypeLoc();
1814    if (FunctionProtoTypeLoc *OldProtoLoc
1815                                  = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1816      TypeLoc NewTL = NewTInfo->getTypeLoc();
1817      FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1818      assert(NewProtoLoc && "Missing prototype?");
1819      for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1820        // FIXME: Variadic templates will break this.
1821        Params.push_back(NewProtoLoc->getArg(i));
1822        SemaRef.CurrentInstantiationScope->InstantiatedLocal(
1823                                                        OldProtoLoc->getArg(i),
1824                                                        NewProtoLoc->getArg(i));
1825      }
1826    }
1827  } else {
1828    // The function type itself was not dependent and therefore no
1829    // substitution occurred. However, we still need to instantiate
1830    // the function parameters themselves.
1831    TypeLoc OldTL = OldTInfo->getTypeLoc();
1832    if (FunctionProtoTypeLoc *OldProtoLoc
1833                                    = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1834      for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1835        ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1836        if (!Parm)
1837          return 0;
1838        Params.push_back(Parm);
1839      }
1840    }
1841  }
1842  return NewTInfo;
1843}
1844
1845/// \brief Initializes the common fields of an instantiation function
1846/// declaration (New) from the corresponding fields of its template (Tmpl).
1847///
1848/// \returns true if there was an error
1849bool
1850TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
1851                                                    FunctionDecl *Tmpl) {
1852  if (Tmpl->isDeleted())
1853    New->setDeleted();
1854
1855  // If we are performing substituting explicitly-specified template arguments
1856  // or deduced template arguments into a function template and we reach this
1857  // point, we are now past the point where SFINAE applies and have committed
1858  // to keeping the new function template specialization. We therefore
1859  // convert the active template instantiation for the function template
1860  // into a template instantiation for this specific function template
1861  // specialization, which is not a SFINAE context, so that we diagnose any
1862  // further errors in the declaration itself.
1863  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1864  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1865  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1866      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
1867    if (FunctionTemplateDecl *FunTmpl
1868          = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
1869      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
1870             "Deduction from the wrong function template?");
1871      (void) FunTmpl;
1872      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1873      ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
1874      --SemaRef.NonInstantiationEntries;
1875    }
1876  }
1877
1878  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1879  assert(Proto && "Function template without prototype?");
1880
1881  if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1882      Proto->getNoReturnAttr()) {
1883    // The function has an exception specification or a "noreturn"
1884    // attribute. Substitute into each of the exception types.
1885    llvm::SmallVector<QualType, 4> Exceptions;
1886    for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1887      // FIXME: Poor location information!
1888      QualType T
1889        = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1890                            New->getLocation(), New->getDeclName());
1891      if (T.isNull() ||
1892          SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1893        continue;
1894
1895      Exceptions.push_back(T);
1896    }
1897
1898    // Rebuild the function type
1899
1900    const FunctionProtoType *NewProto
1901      = New->getType()->getAs<FunctionProtoType>();
1902    assert(NewProto && "Template instantiation without function prototype?");
1903    New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1904                                                 NewProto->arg_type_begin(),
1905                                                 NewProto->getNumArgs(),
1906                                                 NewProto->isVariadic(),
1907                                                 NewProto->getTypeQuals(),
1908                                                 Proto->hasExceptionSpec(),
1909                                                 Proto->hasAnyExceptionSpec(),
1910                                                 Exceptions.size(),
1911                                                 Exceptions.data(),
1912                                                 Proto->getExtInfo()));
1913  }
1914
1915  return false;
1916}
1917
1918/// \brief Initializes common fields of an instantiated method
1919/// declaration (New) from the corresponding fields of its template
1920/// (Tmpl).
1921///
1922/// \returns true if there was an error
1923bool
1924TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
1925                                                  CXXMethodDecl *Tmpl) {
1926  if (InitFunctionInstantiation(New, Tmpl))
1927    return true;
1928
1929  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1930  New->setAccess(Tmpl->getAccess());
1931  if (Tmpl->isVirtualAsWritten())
1932    Record->setMethodAsVirtual(New);
1933
1934  // FIXME: attributes
1935  // FIXME: New needs a pointer to Tmpl
1936  return false;
1937}
1938
1939/// \brief Instantiate the definition of the given function from its
1940/// template.
1941///
1942/// \param PointOfInstantiation the point at which the instantiation was
1943/// required. Note that this is not precisely a "point of instantiation"
1944/// for the function, but it's close.
1945///
1946/// \param Function the already-instantiated declaration of a
1947/// function template specialization or member function of a class template
1948/// specialization.
1949///
1950/// \param Recursive if true, recursively instantiates any functions that
1951/// are required by this instantiation.
1952///
1953/// \param DefinitionRequired if true, then we are performing an explicit
1954/// instantiation where the body of the function is required. Complain if
1955/// there is no such body.
1956void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
1957                                         FunctionDecl *Function,
1958                                         bool Recursive,
1959                                         bool DefinitionRequired) {
1960  if (Function->isInvalidDecl())
1961    return;
1962
1963  assert(!Function->getBody() && "Already instantiated!");
1964
1965  // Never instantiate an explicit specialization.
1966  if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1967    return;
1968
1969  // Find the function body that we'll be substituting.
1970  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
1971  Stmt *Pattern = 0;
1972  if (PatternDecl)
1973    Pattern = PatternDecl->getBody(PatternDecl);
1974
1975  if (!Pattern) {
1976    if (DefinitionRequired) {
1977      if (Function->getPrimaryTemplate())
1978        Diag(PointOfInstantiation,
1979             diag::err_explicit_instantiation_undefined_func_template)
1980          << Function->getPrimaryTemplate();
1981      else
1982        Diag(PointOfInstantiation,
1983             diag::err_explicit_instantiation_undefined_member)
1984          << 1 << Function->getDeclName() << Function->getDeclContext();
1985
1986      if (PatternDecl)
1987        Diag(PatternDecl->getLocation(),
1988             diag::note_explicit_instantiation_here);
1989    }
1990
1991    return;
1992  }
1993
1994  // C++0x [temp.explicit]p9:
1995  //   Except for inline functions, other explicit instantiation declarations
1996  //   have the effect of suppressing the implicit instantiation of the entity
1997  //   to which they refer.
1998  if (Function->getTemplateSpecializationKind()
1999        == TSK_ExplicitInstantiationDeclaration &&
2000      !PatternDecl->isInlined())
2001    return;
2002
2003  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2004  if (Inst)
2005    return;
2006
2007  // If we're performing recursive template instantiation, create our own
2008  // queue of pending implicit instantiations that we will instantiate later,
2009  // while we're still within our own instantiation context.
2010  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2011  if (Recursive)
2012    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2013
2014  ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
2015
2016  // Introduce a new scope where local variable instantiations will be
2017  // recorded, unless we're actually a member function within a local
2018  // class, in which case we need to merge our results with the parent
2019  // scope (of the enclosing function).
2020  bool MergeWithParentScope = false;
2021  if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2022    MergeWithParentScope = Rec->isLocalClass();
2023
2024  LocalInstantiationScope Scope(*this, MergeWithParentScope);
2025
2026  // Introduce the instantiated function parameters into the local
2027  // instantiation scope.
2028  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
2029    Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
2030                            Function->getParamDecl(I));
2031
2032  // Enter the scope of this instantiation. We don't use
2033  // PushDeclContext because we don't have a scope.
2034  DeclContext *PreviousContext = CurContext;
2035  CurContext = Function;
2036
2037  MultiLevelTemplateArgumentList TemplateArgs =
2038    getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2039
2040  // If this is a constructor, instantiate the member initializers.
2041  if (const CXXConstructorDecl *Ctor =
2042        dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2043    InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2044                               TemplateArgs);
2045  }
2046
2047  // Instantiate the function body.
2048  OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
2049
2050  if (Body.isInvalid())
2051    Function->setInvalidDecl();
2052
2053  ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
2054                          /*IsInstantiation=*/true);
2055
2056  PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2057
2058  CurContext = PreviousContext;
2059
2060  DeclGroupRef DG(Function);
2061  Consumer.HandleTopLevelDecl(DG);
2062
2063  // This class may have local implicit instantiations that need to be
2064  // instantiation within this scope.
2065  PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2066  Scope.Exit();
2067
2068  if (Recursive) {
2069    // Instantiate any pending implicit instantiations found during the
2070    // instantiation of this template.
2071    PerformPendingImplicitInstantiations();
2072
2073    // Restore the set of pending implicit instantiations.
2074    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2075  }
2076}
2077
2078/// \brief Instantiate the definition of the given variable from its
2079/// template.
2080///
2081/// \param PointOfInstantiation the point at which the instantiation was
2082/// required. Note that this is not precisely a "point of instantiation"
2083/// for the function, but it's close.
2084///
2085/// \param Var the already-instantiated declaration of a static member
2086/// variable of a class template specialization.
2087///
2088/// \param Recursive if true, recursively instantiates any functions that
2089/// are required by this instantiation.
2090///
2091/// \param DefinitionRequired if true, then we are performing an explicit
2092/// instantiation where an out-of-line definition of the member variable
2093/// is required. Complain if there is no such definition.
2094void Sema::InstantiateStaticDataMemberDefinition(
2095                                          SourceLocation PointOfInstantiation,
2096                                                 VarDecl *Var,
2097                                                 bool Recursive,
2098                                                 bool DefinitionRequired) {
2099  if (Var->isInvalidDecl())
2100    return;
2101
2102  // Find the out-of-line definition of this static data member.
2103  VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
2104  assert(Def && "This data member was not instantiated from a template?");
2105  assert(Def->isStaticDataMember() && "Not a static data member?");
2106  Def = Def->getOutOfLineDefinition();
2107
2108  if (!Def) {
2109    // We did not find an out-of-line definition of this static data member,
2110    // so we won't perform any instantiation. Rather, we rely on the user to
2111    // instantiate this definition (or provide a specialization for it) in
2112    // another translation unit.
2113    if (DefinitionRequired) {
2114      Def = Var->getInstantiatedFromStaticDataMember();
2115      Diag(PointOfInstantiation,
2116           diag::err_explicit_instantiation_undefined_member)
2117        << 2 << Var->getDeclName() << Var->getDeclContext();
2118      Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2119    }
2120
2121    return;
2122  }
2123
2124  // Never instantiate an explicit specialization.
2125  if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2126    return;
2127
2128  // C++0x [temp.explicit]p9:
2129  //   Except for inline functions, other explicit instantiation declarations
2130  //   have the effect of suppressing the implicit instantiation of the entity
2131  //   to which they refer.
2132  if (Var->getTemplateSpecializationKind()
2133        == TSK_ExplicitInstantiationDeclaration)
2134    return;
2135
2136  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2137  if (Inst)
2138    return;
2139
2140  // If we're performing recursive template instantiation, create our own
2141  // queue of pending implicit instantiations that we will instantiate later,
2142  // while we're still within our own instantiation context.
2143  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2144  if (Recursive)
2145    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2146
2147  // Enter the scope of this instantiation. We don't use
2148  // PushDeclContext because we don't have a scope.
2149  DeclContext *PreviousContext = CurContext;
2150  CurContext = Var->getDeclContext();
2151
2152  VarDecl *OldVar = Var;
2153  Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
2154                                          getTemplateInstantiationArgs(Var)));
2155  CurContext = PreviousContext;
2156
2157  if (Var) {
2158    MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2159    assert(MSInfo && "Missing member specialization information?");
2160    Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2161                                       MSInfo->getPointOfInstantiation());
2162    DeclGroupRef DG(Var);
2163    Consumer.HandleTopLevelDecl(DG);
2164  }
2165
2166  if (Recursive) {
2167    // Instantiate any pending implicit instantiations found during the
2168    // instantiation of this template.
2169    PerformPendingImplicitInstantiations();
2170
2171    // Restore the set of pending implicit instantiations.
2172    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2173  }
2174}
2175
2176void
2177Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2178                                 const CXXConstructorDecl *Tmpl,
2179                           const MultiLevelTemplateArgumentList &TemplateArgs) {
2180
2181  llvm::SmallVector<MemInitTy*, 4> NewInits;
2182  bool AnyErrors = false;
2183
2184  // Instantiate all the initializers.
2185  for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
2186                                            InitsEnd = Tmpl->init_end();
2187       Inits != InitsEnd; ++Inits) {
2188    CXXBaseOrMemberInitializer *Init = *Inits;
2189
2190    SourceLocation LParenLoc, RParenLoc;
2191    ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
2192    llvm::SmallVector<SourceLocation, 4> CommaLocs;
2193
2194    // Instantiate the initializer.
2195    if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2196                               LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2197      AnyErrors = true;
2198      continue;
2199    }
2200
2201    MemInitResult NewInit;
2202    if (Init->isBaseInitializer()) {
2203      TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
2204                                            TemplateArgs,
2205                                            Init->getSourceLocation(),
2206                                            New->getDeclName());
2207      if (!BaseTInfo) {
2208        AnyErrors = true;
2209        New->setInvalidDecl();
2210        continue;
2211      }
2212
2213      NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
2214                                     (Expr **)NewArgs.data(),
2215                                     NewArgs.size(),
2216                                     Init->getLParenLoc(),
2217                                     Init->getRParenLoc(),
2218                                     New->getParent());
2219    } else if (Init->isMemberInitializer()) {
2220      FieldDecl *Member;
2221
2222      // Is this an anonymous union?
2223      if (FieldDecl *UnionInit = Init->getAnonUnionMember())
2224        Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2225                                                      UnionInit, TemplateArgs));
2226      else
2227        Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2228                                                      Init->getMember(),
2229                                                      TemplateArgs));
2230
2231      NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
2232                                       NewArgs.size(),
2233                                       Init->getSourceLocation(),
2234                                       Init->getLParenLoc(),
2235                                       Init->getRParenLoc());
2236    }
2237
2238    if (NewInit.isInvalid()) {
2239      AnyErrors = true;
2240      New->setInvalidDecl();
2241    } else {
2242      // FIXME: It would be nice if ASTOwningVector had a release function.
2243      NewArgs.take();
2244
2245      NewInits.push_back((MemInitTy *)NewInit.get());
2246    }
2247  }
2248
2249  // Assign all the initializers to the new constructor.
2250  ActOnMemInitializers(DeclPtrTy::make(New),
2251                       /*FIXME: ColonLoc */
2252                       SourceLocation(),
2253                       NewInits.data(), NewInits.size(),
2254                       AnyErrors);
2255}
2256
2257// TODO: this could be templated if the various decl types used the
2258// same method name.
2259static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2260                              ClassTemplateDecl *Instance) {
2261  Pattern = Pattern->getCanonicalDecl();
2262
2263  do {
2264    Instance = Instance->getCanonicalDecl();
2265    if (Pattern == Instance) return true;
2266    Instance = Instance->getInstantiatedFromMemberTemplate();
2267  } while (Instance);
2268
2269  return false;
2270}
2271
2272static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2273                              FunctionTemplateDecl *Instance) {
2274  Pattern = Pattern->getCanonicalDecl();
2275
2276  do {
2277    Instance = Instance->getCanonicalDecl();
2278    if (Pattern == Instance) return true;
2279    Instance = Instance->getInstantiatedFromMemberTemplate();
2280  } while (Instance);
2281
2282  return false;
2283}
2284
2285static bool
2286isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2287                  ClassTemplatePartialSpecializationDecl *Instance) {
2288  Pattern
2289    = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2290  do {
2291    Instance = cast<ClassTemplatePartialSpecializationDecl>(
2292                                                Instance->getCanonicalDecl());
2293    if (Pattern == Instance)
2294      return true;
2295    Instance = Instance->getInstantiatedFromMember();
2296  } while (Instance);
2297
2298  return false;
2299}
2300
2301static bool isInstantiationOf(CXXRecordDecl *Pattern,
2302                              CXXRecordDecl *Instance) {
2303  Pattern = Pattern->getCanonicalDecl();
2304
2305  do {
2306    Instance = Instance->getCanonicalDecl();
2307    if (Pattern == Instance) return true;
2308    Instance = Instance->getInstantiatedFromMemberClass();
2309  } while (Instance);
2310
2311  return false;
2312}
2313
2314static bool isInstantiationOf(FunctionDecl *Pattern,
2315                              FunctionDecl *Instance) {
2316  Pattern = Pattern->getCanonicalDecl();
2317
2318  do {
2319    Instance = Instance->getCanonicalDecl();
2320    if (Pattern == Instance) return true;
2321    Instance = Instance->getInstantiatedFromMemberFunction();
2322  } while (Instance);
2323
2324  return false;
2325}
2326
2327static bool isInstantiationOf(EnumDecl *Pattern,
2328                              EnumDecl *Instance) {
2329  Pattern = Pattern->getCanonicalDecl();
2330
2331  do {
2332    Instance = Instance->getCanonicalDecl();
2333    if (Pattern == Instance) return true;
2334    Instance = Instance->getInstantiatedFromMemberEnum();
2335  } while (Instance);
2336
2337  return false;
2338}
2339
2340static bool isInstantiationOf(UsingShadowDecl *Pattern,
2341                              UsingShadowDecl *Instance,
2342                              ASTContext &C) {
2343  return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2344}
2345
2346static bool isInstantiationOf(UsingDecl *Pattern,
2347                              UsingDecl *Instance,
2348                              ASTContext &C) {
2349  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2350}
2351
2352static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2353                              UsingDecl *Instance,
2354                              ASTContext &C) {
2355  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2356}
2357
2358static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
2359                              UsingDecl *Instance,
2360                              ASTContext &C) {
2361  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2362}
2363
2364static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2365                                              VarDecl *Instance) {
2366  assert(Instance->isStaticDataMember());
2367
2368  Pattern = Pattern->getCanonicalDecl();
2369
2370  do {
2371    Instance = Instance->getCanonicalDecl();
2372    if (Pattern == Instance) return true;
2373    Instance = Instance->getInstantiatedFromStaticDataMember();
2374  } while (Instance);
2375
2376  return false;
2377}
2378
2379// Other is the prospective instantiation
2380// D is the prospective pattern
2381static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
2382  if (D->getKind() != Other->getKind()) {
2383    if (UnresolvedUsingTypenameDecl *UUD
2384          = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2385      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2386        return isInstantiationOf(UUD, UD, Ctx);
2387      }
2388    }
2389
2390    if (UnresolvedUsingValueDecl *UUD
2391          = dyn_cast<UnresolvedUsingValueDecl>(D)) {
2392      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2393        return isInstantiationOf(UUD, UD, Ctx);
2394      }
2395    }
2396
2397    return false;
2398  }
2399
2400  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2401    return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
2402
2403  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2404    return isInstantiationOf(cast<FunctionDecl>(D), Function);
2405
2406  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2407    return isInstantiationOf(cast<EnumDecl>(D), Enum);
2408
2409  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
2410    if (Var->isStaticDataMember())
2411      return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2412
2413  if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2414    return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
2415
2416  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2417    return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2418
2419  if (ClassTemplatePartialSpecializationDecl *PartialSpec
2420        = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2421    return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2422                             PartialSpec);
2423
2424  if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2425    if (!Field->getDeclName()) {
2426      // This is an unnamed field.
2427      return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
2428        cast<FieldDecl>(D);
2429    }
2430  }
2431
2432  if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2433    return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2434
2435  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2436    return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2437
2438  return D->getDeclName() && isa<NamedDecl>(Other) &&
2439    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2440}
2441
2442template<typename ForwardIterator>
2443static NamedDecl *findInstantiationOf(ASTContext &Ctx,
2444                                      NamedDecl *D,
2445                                      ForwardIterator first,
2446                                      ForwardIterator last) {
2447  for (; first != last; ++first)
2448    if (isInstantiationOf(Ctx, D, *first))
2449      return cast<NamedDecl>(*first);
2450
2451  return 0;
2452}
2453
2454/// \brief Finds the instantiation of the given declaration context
2455/// within the current instantiation.
2456///
2457/// \returns NULL if there was an error
2458DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
2459                          const MultiLevelTemplateArgumentList &TemplateArgs) {
2460  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
2461    Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
2462    return cast_or_null<DeclContext>(ID);
2463  } else return DC;
2464}
2465
2466/// \brief Find the instantiation of the given declaration within the
2467/// current instantiation.
2468///
2469/// This routine is intended to be used when \p D is a declaration
2470/// referenced from within a template, that needs to mapped into the
2471/// corresponding declaration within an instantiation. For example,
2472/// given:
2473///
2474/// \code
2475/// template<typename T>
2476/// struct X {
2477///   enum Kind {
2478///     KnownValue = sizeof(T)
2479///   };
2480///
2481///   bool getKind() const { return KnownValue; }
2482/// };
2483///
2484/// template struct X<int>;
2485/// \endcode
2486///
2487/// In the instantiation of X<int>::getKind(), we need to map the
2488/// EnumConstantDecl for KnownValue (which refers to
2489/// X<T>::<Kind>::KnownValue) to its instantiation
2490/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2491/// this mapping from within the instantiation of X<int>.
2492NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
2493                          const MultiLevelTemplateArgumentList &TemplateArgs) {
2494  DeclContext *ParentDC = D->getDeclContext();
2495  if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
2496      isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
2497      ParentDC->isFunctionOrMethod()) {
2498    // D is a local of some kind. Look into the map of local
2499    // declarations to their instantiations.
2500    return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2501  }
2502
2503  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2504    if (!Record->isDependentContext())
2505      return D;
2506
2507    // If the RecordDecl is actually the injected-class-name or a
2508    // "templated" declaration for a class template, class template
2509    // partial specialization, or a member class of a class template,
2510    // substitute into the injected-class-name of the class template
2511    // or partial specialization to find the new DeclContext.
2512    QualType T;
2513    ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2514
2515    if (ClassTemplate) {
2516      T = ClassTemplate->getInjectedClassNameSpecialization(Context);
2517    } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2518                 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2519      ClassTemplate = PartialSpec->getSpecializedTemplate();
2520
2521      // If we call SubstType with an InjectedClassNameType here we
2522      // can end up in an infinite loop.
2523      T = Context.getTypeDeclType(Record);
2524      assert(isa<InjectedClassNameType>(T) &&
2525             "type of partial specialization is not an InjectedClassNameType");
2526      T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
2527    }
2528
2529    if (!T.isNull()) {
2530      // Substitute into the injected-class-name to get the type
2531      // corresponding to the instantiation we want, which may also be
2532      // the current instantiation (if we're in a template
2533      // definition). This substitution should never fail, since we
2534      // know we can instantiate the injected-class-name or we
2535      // wouldn't have gotten to the injected-class-name!
2536
2537      // FIXME: Can we use the CurrentInstantiationScope to avoid this
2538      // extra instantiation in the common case?
2539      T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2540      assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2541
2542      if (!T->isDependentType()) {
2543        assert(T->isRecordType() && "Instantiation must produce a record type");
2544        return T->getAs<RecordType>()->getDecl();
2545      }
2546
2547      // We are performing "partial" template instantiation to create
2548      // the member declarations for the members of a class template
2549      // specialization. Therefore, D is actually referring to something
2550      // in the current instantiation. Look through the current
2551      // context, which contains actual instantiations, to find the
2552      // instantiation of the "current instantiation" that D refers
2553      // to.
2554      bool SawNonDependentContext = false;
2555      for (DeclContext *DC = CurContext; !DC->isFileContext();
2556           DC = DC->getParent()) {
2557        if (ClassTemplateSpecializationDecl *Spec
2558                          = dyn_cast<ClassTemplateSpecializationDecl>(DC))
2559          if (isInstantiationOf(ClassTemplate,
2560                                Spec->getSpecializedTemplate()))
2561            return Spec;
2562
2563        if (!DC->isDependentContext())
2564          SawNonDependentContext = true;
2565      }
2566
2567      // We're performing "instantiation" of a member of the current
2568      // instantiation while we are type-checking the
2569      // definition. Compute the declaration context and return that.
2570      assert(!SawNonDependentContext &&
2571             "No dependent context while instantiating record");
2572      DeclContext *DC = computeDeclContext(T);
2573      assert(DC &&
2574             "Unable to find declaration for the current instantiation");
2575      return cast<CXXRecordDecl>(DC);
2576    }
2577
2578    // Fall through to deal with other dependent record types (e.g.,
2579    // anonymous unions in class templates).
2580  }
2581
2582  if (!ParentDC->isDependentContext())
2583    return D;
2584
2585  ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
2586  if (!ParentDC)
2587    return 0;
2588
2589  if (ParentDC != D->getDeclContext()) {
2590    // We performed some kind of instantiation in the parent context,
2591    // so now we need to look into the instantiated parent context to
2592    // find the instantiation of the declaration D.
2593
2594    // If our context used to be dependent, we may need to instantiate
2595    // it before performing lookup into that context.
2596    if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
2597      if (!Spec->isDependentContext()) {
2598        QualType T = Context.getTypeDeclType(Spec);
2599        const RecordType *Tag = T->getAs<RecordType>();
2600        assert(Tag && "type of non-dependent record is not a RecordType");
2601        if (!Tag->isBeingDefined() &&
2602            RequireCompleteType(Loc, T, diag::err_incomplete_type))
2603          return 0;
2604      }
2605    }
2606
2607    NamedDecl *Result = 0;
2608    if (D->getDeclName()) {
2609      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
2610      Result = findInstantiationOf(Context, D, Found.first, Found.second);
2611    } else {
2612      // Since we don't have a name for the entity we're looking for,
2613      // our only option is to walk through all of the declarations to
2614      // find that name. This will occur in a few cases:
2615      //
2616      //   - anonymous struct/union within a template
2617      //   - unnamed class/struct/union/enum within a template
2618      //
2619      // FIXME: Find a better way to find these instantiations!
2620      Result = findInstantiationOf(Context, D,
2621                                   ParentDC->decls_begin(),
2622                                   ParentDC->decls_end());
2623    }
2624
2625    // UsingShadowDecls can instantiate to nothing because of using hiding.
2626    assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2627            cast<Decl>(ParentDC)->isInvalidDecl())
2628           && "Unable to find instantiation of declaration!");
2629
2630    D = Result;
2631  }
2632
2633  return D;
2634}
2635
2636/// \brief Performs template instantiation for all implicit template
2637/// instantiations we have seen until this point.
2638void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2639  while (!PendingLocalImplicitInstantiations.empty() ||
2640         (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2641    PendingImplicitInstantiation Inst;
2642
2643    if (PendingLocalImplicitInstantiations.empty()) {
2644      Inst = PendingImplicitInstantiations.front();
2645      PendingImplicitInstantiations.pop_front();
2646    } else {
2647      Inst = PendingLocalImplicitInstantiations.front();
2648      PendingLocalImplicitInstantiations.pop_front();
2649    }
2650
2651    // Instantiate function definitions
2652    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
2653      PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
2654                                            Function->getLocation(), *this,
2655                                            Context.getSourceManager(),
2656                                           "instantiating function definition");
2657
2658      if (!Function->getBody())
2659        InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
2660      continue;
2661    }
2662
2663    // Instantiate static data member definitions.
2664    VarDecl *Var = cast<VarDecl>(Inst.first);
2665    assert(Var->isStaticDataMember() && "Not a static data member?");
2666
2667    // Don't try to instantiate declarations if the most recent redeclaration
2668    // is invalid.
2669    if (Var->getMostRecentDeclaration()->isInvalidDecl())
2670      continue;
2671
2672    // Check if the most recent declaration has changed the specialization kind
2673    // and removed the need for implicit instantiation.
2674    switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2675    case TSK_Undeclared:
2676      assert(false && "Cannot instantitiate an undeclared specialization.");
2677    case TSK_ExplicitInstantiationDeclaration:
2678    case TSK_ExplicitInstantiationDefinition:
2679    case TSK_ExplicitSpecialization:
2680      continue;  // No longer need implicit instantiation.
2681    case TSK_ImplicitInstantiation:
2682      break;
2683    }
2684
2685    PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
2686                                          Var->getLocation(), *this,
2687                                          Context.getSourceManager(),
2688                                          "instantiating static data member "
2689                                          "definition");
2690
2691    InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
2692  }
2693}
2694
2695void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2696                       const MultiLevelTemplateArgumentList &TemplateArgs) {
2697  for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2698         E = Pattern->ddiag_end(); I != E; ++I) {
2699    DependentDiagnostic *DD = *I;
2700
2701    switch (DD->getKind()) {
2702    case DependentDiagnostic::Access:
2703      HandleDependentAccessCheck(*DD, TemplateArgs);
2704      break;
2705    }
2706  }
2707}
2708