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