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