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