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