SemaTemplateInstantiate.cpp revision 63c8e75e3df30caab2d7251514a0d7ddc9cb39a2
1//===------- SemaTemplateInstantiate.cpp - C++ Template 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.
10//
11//===----------------------------------------------------------------------===/
12
13#include "Sema.h"
14#include "TreeTransform.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21#include "llvm/Support/Compiler.h"
22
23using namespace clang;
24
25//===----------------------------------------------------------------------===/
26// Template Instantiation Support
27//===----------------------------------------------------------------------===/
28
29/// \brief Retrieve the template argument list(s) that should be used to
30/// instantiate the definition of the given declaration.
31///
32/// \param D the declaration for which we are computing template instantiation
33/// arguments.
34///
35/// \param Innermost if non-NULL, the innermost template argument list.
36MultiLevelTemplateArgumentList
37Sema::getTemplateInstantiationArgs(NamedDecl *D,
38                                   const TemplateArgumentList *Innermost) {
39  // Accumulate the set of template argument lists in this structure.
40  MultiLevelTemplateArgumentList Result;
41
42  if (Innermost)
43    Result.addOuterTemplateArguments(Innermost);
44
45  DeclContext *Ctx = dyn_cast<DeclContext>(D);
46  if (!Ctx)
47    Ctx = D->getDeclContext();
48
49  while (!Ctx->isFileContext()) {
50    // Add template arguments from a class template instantiation.
51    if (ClassTemplateSpecializationDecl *Spec
52          = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
53      // We're done when we hit an explicit specialization.
54      if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization)
55        break;
56
57      Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
58
59      // If this class template specialization was instantiated from a
60      // specialized member that is a class template, we're done.
61      assert(Spec->getSpecializedTemplate() && "No class template?");
62      if (Spec->getSpecializedTemplate()->isMemberSpecialization())
63        break;
64    }
65    // Add template arguments from a function template specialization.
66    else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
67      if (Function->getTemplateSpecializationKind()
68            == TSK_ExplicitSpecialization)
69        break;
70
71      if (const TemplateArgumentList *TemplateArgs
72            = Function->getTemplateSpecializationArgs()) {
73        // Add the template arguments for this specialization.
74        Result.addOuterTemplateArguments(TemplateArgs);
75
76        // If this function was instantiated from a specialized member that is
77        // a function template, we're done.
78        assert(Function->getPrimaryTemplate() && "No function template?");
79        if (Function->getPrimaryTemplate()->isMemberSpecialization())
80          break;
81      }
82
83      // If this is a friend declaration and it declares an entity at
84      // namespace scope, take arguments from its lexical parent
85      // instead of its semantic parent.
86      if (Function->getFriendObjectKind() &&
87          Function->getDeclContext()->isFileContext()) {
88        Ctx = Function->getLexicalDeclContext();
89        continue;
90      }
91    }
92
93    Ctx = Ctx->getParent();
94  }
95
96  return Result;
97}
98
99Sema::InstantiatingTemplate::
100InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
101                      Decl *Entity,
102                      SourceRange InstantiationRange)
103  :  SemaRef(SemaRef) {
104
105  Invalid = CheckInstantiationDepth(PointOfInstantiation,
106                                    InstantiationRange);
107  if (!Invalid) {
108    ActiveTemplateInstantiation Inst;
109    Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
110    Inst.PointOfInstantiation = PointOfInstantiation;
111    Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
112    Inst.TemplateArgs = 0;
113    Inst.NumTemplateArgs = 0;
114    Inst.InstantiationRange = InstantiationRange;
115    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
116    Invalid = false;
117  }
118}
119
120Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
121                                         SourceLocation PointOfInstantiation,
122                                         TemplateDecl *Template,
123                                         const TemplateArgument *TemplateArgs,
124                                         unsigned NumTemplateArgs,
125                                         SourceRange InstantiationRange)
126  : SemaRef(SemaRef) {
127
128  Invalid = CheckInstantiationDepth(PointOfInstantiation,
129                                    InstantiationRange);
130  if (!Invalid) {
131    ActiveTemplateInstantiation Inst;
132    Inst.Kind
133      = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
134    Inst.PointOfInstantiation = PointOfInstantiation;
135    Inst.Entity = reinterpret_cast<uintptr_t>(Template);
136    Inst.TemplateArgs = TemplateArgs;
137    Inst.NumTemplateArgs = NumTemplateArgs;
138    Inst.InstantiationRange = InstantiationRange;
139    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
140    Invalid = false;
141  }
142}
143
144Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
145                                         SourceLocation PointOfInstantiation,
146                                      FunctionTemplateDecl *FunctionTemplate,
147                                        const TemplateArgument *TemplateArgs,
148                                                   unsigned NumTemplateArgs,
149                         ActiveTemplateInstantiation::InstantiationKind Kind,
150                                              SourceRange InstantiationRange)
151: SemaRef(SemaRef) {
152
153  Invalid = CheckInstantiationDepth(PointOfInstantiation,
154                                    InstantiationRange);
155  if (!Invalid) {
156    ActiveTemplateInstantiation Inst;
157    Inst.Kind = Kind;
158    Inst.PointOfInstantiation = PointOfInstantiation;
159    Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
160    Inst.TemplateArgs = TemplateArgs;
161    Inst.NumTemplateArgs = NumTemplateArgs;
162    Inst.InstantiationRange = InstantiationRange;
163    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
164    Invalid = false;
165  }
166}
167
168Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
169                                         SourceLocation PointOfInstantiation,
170                          ClassTemplatePartialSpecializationDecl *PartialSpec,
171                                         const TemplateArgument *TemplateArgs,
172                                         unsigned NumTemplateArgs,
173                                         SourceRange InstantiationRange)
174  : SemaRef(SemaRef) {
175
176  Invalid = CheckInstantiationDepth(PointOfInstantiation,
177                                    InstantiationRange);
178  if (!Invalid) {
179    ActiveTemplateInstantiation Inst;
180    Inst.Kind
181      = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
182    Inst.PointOfInstantiation = PointOfInstantiation;
183    Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
184    Inst.TemplateArgs = TemplateArgs;
185    Inst.NumTemplateArgs = NumTemplateArgs;
186    Inst.InstantiationRange = InstantiationRange;
187    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
188    Invalid = false;
189  }
190}
191
192Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
193                                          SourceLocation PointOfInstantation,
194                                          ParmVarDecl *Param,
195                                          const TemplateArgument *TemplateArgs,
196                                          unsigned NumTemplateArgs,
197                                          SourceRange InstantiationRange)
198  : SemaRef(SemaRef) {
199
200  Invalid = CheckInstantiationDepth(PointOfInstantation, InstantiationRange);
201
202  if (!Invalid) {
203    ActiveTemplateInstantiation Inst;
204    Inst.Kind
205      = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
206    Inst.PointOfInstantiation = PointOfInstantation;
207    Inst.Entity = reinterpret_cast<uintptr_t>(Param);
208    Inst.TemplateArgs = TemplateArgs;
209    Inst.NumTemplateArgs = NumTemplateArgs;
210    Inst.InstantiationRange = InstantiationRange;
211    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
212    Invalid = false;
213  }
214}
215
216void Sema::InstantiatingTemplate::Clear() {
217  if (!Invalid) {
218    SemaRef.ActiveTemplateInstantiations.pop_back();
219    Invalid = true;
220  }
221}
222
223bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
224                                        SourceLocation PointOfInstantiation,
225                                           SourceRange InstantiationRange) {
226  if (SemaRef.ActiveTemplateInstantiations.size()
227       <= SemaRef.getLangOptions().InstantiationDepth)
228    return false;
229
230  SemaRef.Diag(PointOfInstantiation,
231               diag::err_template_recursion_depth_exceeded)
232    << SemaRef.getLangOptions().InstantiationDepth
233    << InstantiationRange;
234  SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
235    << SemaRef.getLangOptions().InstantiationDepth;
236  return true;
237}
238
239/// \brief Prints the current instantiation stack through a series of
240/// notes.
241void Sema::PrintInstantiationStack() {
242  // FIXME: In all of these cases, we need to show the template arguments
243  for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
244         Active = ActiveTemplateInstantiations.rbegin(),
245         ActiveEnd = ActiveTemplateInstantiations.rend();
246       Active != ActiveEnd;
247       ++Active) {
248    switch (Active->Kind) {
249    case ActiveTemplateInstantiation::TemplateInstantiation: {
250      Decl *D = reinterpret_cast<Decl *>(Active->Entity);
251      if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
252        unsigned DiagID = diag::note_template_member_class_here;
253        if (isa<ClassTemplateSpecializationDecl>(Record))
254          DiagID = diag::note_template_class_instantiation_here;
255        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
256                     DiagID)
257          << Context.getTypeDeclType(Record)
258          << Active->InstantiationRange;
259      } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
260        unsigned DiagID;
261        if (Function->getPrimaryTemplate())
262          DiagID = diag::note_function_template_spec_here;
263        else
264          DiagID = diag::note_template_member_function_here;
265        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
266                     DiagID)
267          << Function
268          << Active->InstantiationRange;
269      } else {
270        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
271                     diag::note_template_static_data_member_def_here)
272          << cast<VarDecl>(D)
273          << Active->InstantiationRange;
274      }
275      break;
276    }
277
278    case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
279      TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
280      std::string TemplateArgsStr
281        = TemplateSpecializationType::PrintTemplateArgumentList(
282                                                         Active->TemplateArgs,
283                                                      Active->NumTemplateArgs,
284                                                      Context.PrintingPolicy);
285      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
286                   diag::note_default_arg_instantiation_here)
287        << (Template->getNameAsString() + TemplateArgsStr)
288        << Active->InstantiationRange;
289      break;
290    }
291
292    case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
293      FunctionTemplateDecl *FnTmpl
294        = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
295      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
296                   diag::note_explicit_template_arg_substitution_here)
297        << FnTmpl << Active->InstantiationRange;
298      break;
299    }
300
301    case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
302      if (ClassTemplatePartialSpecializationDecl *PartialSpec
303            = dyn_cast<ClassTemplatePartialSpecializationDecl>(
304                                                    (Decl *)Active->Entity)) {
305        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
306                     diag::note_partial_spec_deduct_instantiation_here)
307          << Context.getTypeDeclType(PartialSpec)
308          << Active->InstantiationRange;
309      } else {
310        FunctionTemplateDecl *FnTmpl
311          = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
312        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
313                     diag::note_function_template_deduction_instantiation_here)
314          << FnTmpl << Active->InstantiationRange;
315      }
316      break;
317
318    case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
319      ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
320      FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
321
322      std::string TemplateArgsStr
323        = TemplateSpecializationType::PrintTemplateArgumentList(
324                                                         Active->TemplateArgs,
325                                                      Active->NumTemplateArgs,
326                                                      Context.PrintingPolicy);
327      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
328                   diag::note_default_function_arg_instantiation_here)
329        << (FD->getNameAsString() + TemplateArgsStr)
330        << Active->InstantiationRange;
331      break;
332    }
333
334    }
335  }
336}
337
338bool Sema::isSFINAEContext() const {
339  using llvm::SmallVector;
340  for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
341         Active = ActiveTemplateInstantiations.rbegin(),
342         ActiveEnd = ActiveTemplateInstantiations.rend();
343       Active != ActiveEnd;
344       ++Active) {
345
346    switch(Active->Kind) {
347    case ActiveTemplateInstantiation::TemplateInstantiation:
348    case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
349
350      // This is a template instantiation, so there is no SFINAE.
351      return false;
352
353    case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
354      // A default template argument instantiation may or may not be a
355      // SFINAE context; look further up the stack.
356      break;
357
358    case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
359    case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
360      // We're either substitution explicitly-specified template arguments
361      // or deduced template arguments, so SFINAE applies.
362      return true;
363    }
364  }
365
366  return false;
367}
368
369//===----------------------------------------------------------------------===/
370// Template Instantiation for Types
371//===----------------------------------------------------------------------===/
372namespace {
373  class VISIBILITY_HIDDEN TemplateInstantiator
374    : public TreeTransform<TemplateInstantiator> {
375    const MultiLevelTemplateArgumentList &TemplateArgs;
376    SourceLocation Loc;
377    DeclarationName Entity;
378
379  public:
380    typedef TreeTransform<TemplateInstantiator> inherited;
381
382    TemplateInstantiator(Sema &SemaRef,
383                         const MultiLevelTemplateArgumentList &TemplateArgs,
384                         SourceLocation Loc,
385                         DeclarationName Entity)
386      : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
387        Entity(Entity) { }
388
389    /// \brief Determine whether the given type \p T has already been
390    /// transformed.
391    ///
392    /// For the purposes of template instantiation, a type has already been
393    /// transformed if it is NULL or if it is not dependent.
394    bool AlreadyTransformed(QualType T) {
395      return T.isNull() || !T->isDependentType();
396    }
397
398    /// \brief Returns the location of the entity being instantiated, if known.
399    SourceLocation getBaseLocation() { return Loc; }
400
401    /// \brief Returns the name of the entity being instantiated, if any.
402    DeclarationName getBaseEntity() { return Entity; }
403
404    /// \brief Sets the "base" location and entity when that
405    /// information is known based on another transformation.
406    void setBase(SourceLocation Loc, DeclarationName Entity) {
407      this->Loc = Loc;
408      this->Entity = Entity;
409    }
410
411    /// \brief Transform the given declaration by instantiating a reference to
412    /// this declaration.
413    Decl *TransformDecl(Decl *D);
414
415    /// \brief Transform the definition of the given declaration by
416    /// instantiating it.
417    Decl *TransformDefinition(Decl *D);
418
419    /// \bried Transform the first qualifier within a scope by instantiating the
420    /// declaration.
421    NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
422
423    /// \brief Rebuild the exception declaration and register the declaration
424    /// as an instantiated local.
425    VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, QualType T,
426                                  DeclaratorInfo *Declarator,
427                                  IdentifierInfo *Name,
428                                  SourceLocation Loc, SourceRange TypeRange);
429
430    /// \brief Check for tag mismatches when instantiating an
431    /// elaborated type.
432    QualType RebuildElaboratedType(QualType T, ElaboratedType::TagKind Tag);
433
434    Sema::OwningExprResult TransformPredefinedExpr(PredefinedExpr *E,
435                                                   bool isAddressOfOperand);
436    Sema::OwningExprResult TransformDeclRefExpr(DeclRefExpr *E,
437                                                bool isAddressOfOperand);
438
439    Sema::OwningExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E,
440                                                      bool isAddressOfOperand);
441
442    /// \brief Transforms a template type parameter type by performing
443    /// substitution of the corresponding template type argument.
444    QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
445                                           TemplateTypeParmTypeLoc TL);
446  };
447}
448
449Decl *TemplateInstantiator::TransformDecl(Decl *D) {
450  if (!D)
451    return 0;
452
453  if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
454    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
455      TemplateName Template
456        = TemplateArgs(TTP->getDepth(), TTP->getPosition()).getAsTemplate();
457      assert(!Template.isNull() && Template.getAsTemplateDecl() &&
458             "Wrong kind of template template argument");
459      return Template.getAsTemplateDecl();
460    }
461
462    // If the corresponding template argument is NULL or non-existent, it's
463    // because we are performing instantiation from explicitly-specified
464    // template arguments in a function template, but there were some
465    // arguments left unspecified.
466    if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
467                                          TTP->getPosition()))
468      return D;
469
470    // Fall through to find the instantiated declaration for this template
471    // template parameter.
472  }
473
474  return SemaRef.FindInstantiatedDecl(cast<NamedDecl>(D), TemplateArgs);
475}
476
477Decl *TemplateInstantiator::TransformDefinition(Decl *D) {
478  Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
479  if (!Inst)
480    return 0;
481
482  getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
483  return Inst;
484}
485
486NamedDecl *
487TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
488                                                     SourceLocation Loc) {
489  // If the first part of the nested-name-specifier was a template type
490  // parameter, instantiate that type parameter down to a tag type.
491  if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
492    const TemplateTypeParmType *TTP
493      = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
494    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
495      QualType T = TemplateArgs(TTP->getDepth(), TTP->getIndex()).getAsType();
496      if (T.isNull())
497        return cast_or_null<NamedDecl>(TransformDecl(D));
498
499      if (const TagType *Tag = T->getAs<TagType>())
500        return Tag->getDecl();
501
502      // The resulting type is not a tag; complain.
503      getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
504      return 0;
505    }
506  }
507
508  return cast_or_null<NamedDecl>(TransformDecl(D));
509}
510
511VarDecl *
512TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
513                                           QualType T,
514                                           DeclaratorInfo *Declarator,
515                                           IdentifierInfo *Name,
516                                           SourceLocation Loc,
517                                           SourceRange TypeRange) {
518  VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, T, Declarator,
519                                                 Name, Loc, TypeRange);
520  if (Var && !Var->isInvalidDecl())
521    getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
522  return Var;
523}
524
525QualType
526TemplateInstantiator::RebuildElaboratedType(QualType T,
527                                            ElaboratedType::TagKind Tag) {
528  if (const TagType *TT = T->getAs<TagType>()) {
529    TagDecl* TD = TT->getDecl();
530
531    // FIXME: this location is very wrong;  we really need typelocs.
532    SourceLocation TagLocation = TD->getTagKeywordLoc();
533
534    // FIXME: type might be anonymous.
535    IdentifierInfo *Id = TD->getIdentifier();
536
537    // TODO: should we even warn on struct/class mismatches for this?  Seems
538    // like it's likely to produce a lot of spurious errors.
539    if (!SemaRef.isAcceptableTagRedeclaration(TD, Tag, TagLocation, *Id)) {
540      SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
541        << Id
542        << CodeModificationHint::CreateReplacement(SourceRange(TagLocation),
543                                                   TD->getKindName());
544      SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
545    }
546  }
547
548  return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(T, Tag);
549}
550
551Sema::OwningExprResult
552TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E,
553                                              bool isAddressOfOperand) {
554  if (!E->isTypeDependent())
555    return SemaRef.Owned(E->Retain());
556
557  FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
558  assert(currentDecl && "Must have current function declaration when "
559                        "instantiating.");
560
561  PredefinedExpr::IdentType IT = E->getIdentType();
562
563  unsigned Length =
564    PredefinedExpr::ComputeName(getSema().Context, IT, currentDecl).length();
565
566  llvm::APInt LengthI(32, Length + 1);
567  QualType ResTy = getSema().Context.CharTy.withConst();
568  ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
569                                                 ArrayType::Normal, 0);
570  PredefinedExpr *PE =
571    new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
572  return getSema().Owned(PE);
573}
574
575Sema::OwningExprResult
576TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E,
577                                           bool isAddressOfOperand) {
578  // FIXME: Clean this up a bit
579  NamedDecl *D = E->getDecl();
580  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
581    if (NTTP->getDepth() < TemplateArgs.getNumLevels()) {
582
583      // If the corresponding template argument is NULL or non-existent, it's
584      // because we are performing instantiation from explicitly-specified
585      // template arguments in a function template, but there were some
586      // arguments left unspecified.
587      if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
588                                            NTTP->getPosition()))
589        return SemaRef.Owned(E->Retain());
590
591      const TemplateArgument &Arg = TemplateArgs(NTTP->getDepth(),
592                                                 NTTP->getPosition());
593
594      // The template argument itself might be an expression, in which
595      // case we just return that expression.
596      if (Arg.getKind() == TemplateArgument::Expression)
597        return SemaRef.Owned(Arg.getAsExpr()->Retain());
598
599      if (Arg.getKind() == TemplateArgument::Declaration) {
600        ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
601
602        VD = cast_or_null<ValueDecl>(
603                              getSema().FindInstantiatedDecl(VD, TemplateArgs));
604        if (!VD)
605          return SemaRef.ExprError();
606
607        return SemaRef.BuildDeclRefExpr(VD, VD->getType(), E->getLocation(),
608                                        /*FIXME:*/false, /*FIXME:*/false);
609      }
610
611      assert(Arg.getKind() == TemplateArgument::Integral);
612      QualType T = Arg.getIntegralType();
613      if (T->isCharType() || T->isWideCharType())
614        return SemaRef.Owned(new (SemaRef.Context) CharacterLiteral(
615                                              Arg.getAsIntegral()->getZExtValue(),
616                                              T->isWideCharType(),
617                                              T,
618                                              E->getSourceRange().getBegin()));
619      if (T->isBooleanType())
620        return SemaRef.Owned(new (SemaRef.Context) CXXBoolLiteralExpr(
621                                            Arg.getAsIntegral()->getBoolValue(),
622                                            T,
623                                            E->getSourceRange().getBegin()));
624
625      assert(Arg.getAsIntegral()->getBitWidth() == SemaRef.Context.getIntWidth(T));
626      return SemaRef.Owned(new (SemaRef.Context) IntegerLiteral(
627                                                *Arg.getAsIntegral(),
628                                                T,
629                                                E->getSourceRange().getBegin()));
630    }
631
632    // We have a non-type template parameter that isn't fully substituted;
633    // FindInstantiatedDecl will find it in the local instantiation scope.
634  }
635
636  NamedDecl *InstD = SemaRef.FindInstantiatedDecl(D, TemplateArgs);
637  if (!InstD)
638    return SemaRef.ExprError();
639
640  // If we instantiated an UnresolvedUsingDecl and got back an UsingDecl,
641  // we need to get the underlying decl.
642  // FIXME: Is this correct? Maybe FindInstantiatedDecl should do this?
643  InstD = InstD->getUnderlyingDecl();
644
645  CXXScopeSpec SS;
646  NestedNameSpecifier *Qualifier = 0;
647  if (E->getQualifier()) {
648    Qualifier = TransformNestedNameSpecifier(E->getQualifier(),
649                                             E->getQualifierRange());
650    if (!Qualifier)
651      return SemaRef.ExprError();
652
653    SS.setScopeRep(Qualifier);
654    SS.setRange(E->getQualifierRange());
655  }
656
657  return SemaRef.BuildDeclarationNameExpr(E->getLocation(), InstD,
658                                          /*FIXME:*/false,
659                                          &SS,
660                                          isAddressOfOperand);
661}
662
663Sema::OwningExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
664    CXXDefaultArgExpr *E, bool isAddressOfOperand) {
665  assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
666             getDescribedFunctionTemplate() &&
667         "Default arg expressions are never formed in dependent cases.");
668  return SemaRef.Owned(E->Retain());
669}
670
671
672QualType
673TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
674                                                TemplateTypeParmTypeLoc TL) {
675  TemplateTypeParmType *T = TL.getTypePtr();
676  if (T->getDepth() < TemplateArgs.getNumLevels()) {
677    // Replace the template type parameter with its corresponding
678    // template argument.
679
680    // If the corresponding template argument is NULL or doesn't exist, it's
681    // because we are performing instantiation from explicitly-specified
682    // template arguments in a function template class, but there were some
683    // arguments left unspecified.
684    if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
685      TemplateTypeParmTypeLoc NewTL
686        = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
687      NewTL.setNameLoc(TL.getNameLoc());
688      return TL.getType();
689    }
690
691    assert(TemplateArgs(T->getDepth(), T->getIndex()).getKind()
692             == TemplateArgument::Type &&
693           "Template argument kind mismatch");
694
695    QualType Replacement
696      = TemplateArgs(T->getDepth(), T->getIndex()).getAsType();
697
698    // TODO: only do this uniquing once, at the start of instantiation.
699    QualType Result
700      = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
701    SubstTemplateTypeParmTypeLoc NewTL
702      = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
703    NewTL.setNameLoc(TL.getNameLoc());
704    return Result;
705  }
706
707  // The template type parameter comes from an inner template (e.g.,
708  // the template parameter list of a member template inside the
709  // template we are instantiating). Create a new template type
710  // parameter with the template "level" reduced by one.
711  QualType Result
712    = getSema().Context.getTemplateTypeParmType(T->getDepth()
713                                                 - TemplateArgs.getNumLevels(),
714                                                T->getIndex(),
715                                                T->isParameterPack(),
716                                                T->getName());
717  TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
718  NewTL.setNameLoc(TL.getNameLoc());
719  return Result;
720}
721
722/// \brief Perform substitution on the type T with a given set of template
723/// arguments.
724///
725/// This routine substitutes the given template arguments into the
726/// type T and produces the instantiated type.
727///
728/// \param T the type into which the template arguments will be
729/// substituted. If this type is not dependent, it will be returned
730/// immediately.
731///
732/// \param TemplateArgs the template arguments that will be
733/// substituted for the top-level template parameters within T.
734///
735/// \param Loc the location in the source code where this substitution
736/// is being performed. It will typically be the location of the
737/// declarator (if we're instantiating the type of some declaration)
738/// or the location of the type in the source code (if, e.g., we're
739/// instantiating the type of a cast expression).
740///
741/// \param Entity the name of the entity associated with a declaration
742/// being instantiated (if any). May be empty to indicate that there
743/// is no such entity (if, e.g., this is a type that occurs as part of
744/// a cast expression) or that the entity has no name (e.g., an
745/// unnamed function parameter).
746///
747/// \returns If the instantiation succeeds, the instantiated
748/// type. Otherwise, produces diagnostics and returns a NULL type.
749DeclaratorInfo *Sema::SubstType(DeclaratorInfo *T,
750                                const MultiLevelTemplateArgumentList &Args,
751                                SourceLocation Loc,
752                                DeclarationName Entity) {
753  assert(!ActiveTemplateInstantiations.empty() &&
754         "Cannot perform an instantiation without some context on the "
755         "instantiation stack");
756
757  if (!T->getType()->isDependentType())
758    return T;
759
760  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
761  return Instantiator.TransformType(T);
762}
763
764/// Deprecated form of the above.
765QualType Sema::SubstType(QualType T,
766                         const MultiLevelTemplateArgumentList &TemplateArgs,
767                         SourceLocation Loc, DeclarationName Entity) {
768  assert(!ActiveTemplateInstantiations.empty() &&
769         "Cannot perform an instantiation without some context on the "
770         "instantiation stack");
771
772  // If T is not a dependent type, there is nothing to do.
773  if (!T->isDependentType())
774    return T;
775
776  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
777  return Instantiator.TransformType(T);
778}
779
780/// \brief Perform substitution on the base class specifiers of the
781/// given class template specialization.
782///
783/// Produces a diagnostic and returns true on error, returns false and
784/// attaches the instantiated base classes to the class template
785/// specialization if successful.
786bool
787Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
788                          CXXRecordDecl *Pattern,
789                          const MultiLevelTemplateArgumentList &TemplateArgs) {
790  bool Invalid = false;
791  llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
792  for (ClassTemplateSpecializationDecl::base_class_iterator
793         Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
794       Base != BaseEnd; ++Base) {
795    if (!Base->getType()->isDependentType()) {
796      InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
797      continue;
798    }
799
800    QualType BaseType = SubstType(Base->getType(),
801                                  TemplateArgs,
802                                  Base->getSourceRange().getBegin(),
803                                  DeclarationName());
804    if (BaseType.isNull()) {
805      Invalid = true;
806      continue;
807    }
808
809    if (CXXBaseSpecifier *InstantiatedBase
810          = CheckBaseSpecifier(Instantiation,
811                               Base->getSourceRange(),
812                               Base->isVirtual(),
813                               Base->getAccessSpecifierAsWritten(),
814                               BaseType,
815                               /*FIXME: Not totally accurate */
816                               Base->getSourceRange().getBegin()))
817      InstantiatedBases.push_back(InstantiatedBase);
818    else
819      Invalid = true;
820  }
821
822  if (!Invalid &&
823      AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
824                           InstantiatedBases.size()))
825    Invalid = true;
826
827  return Invalid;
828}
829
830/// \brief Instantiate the definition of a class from a given pattern.
831///
832/// \param PointOfInstantiation The point of instantiation within the
833/// source code.
834///
835/// \param Instantiation is the declaration whose definition is being
836/// instantiated. This will be either a class template specialization
837/// or a member class of a class template specialization.
838///
839/// \param Pattern is the pattern from which the instantiation
840/// occurs. This will be either the declaration of a class template or
841/// the declaration of a member class of a class template.
842///
843/// \param TemplateArgs The template arguments to be substituted into
844/// the pattern.
845///
846/// \param TSK the kind of implicit or explicit instantiation to perform.
847///
848/// \param Complain whether to complain if the class cannot be instantiated due
849/// to the lack of a definition.
850///
851/// \returns true if an error occurred, false otherwise.
852bool
853Sema::InstantiateClass(SourceLocation PointOfInstantiation,
854                       CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
855                       const MultiLevelTemplateArgumentList &TemplateArgs,
856                       TemplateSpecializationKind TSK,
857                       bool Complain) {
858  bool Invalid = false;
859
860  CXXRecordDecl *PatternDef
861    = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
862  if (!PatternDef) {
863    if (!Complain) {
864      // Say nothing
865    } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
866      Diag(PointOfInstantiation,
867           diag::err_implicit_instantiate_member_undefined)
868        << Context.getTypeDeclType(Instantiation);
869      Diag(Pattern->getLocation(), diag::note_member_of_template_here);
870    } else {
871      Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
872        << (TSK != TSK_ImplicitInstantiation)
873        << Context.getTypeDeclType(Instantiation);
874      Diag(Pattern->getLocation(), diag::note_template_decl_here);
875    }
876    return true;
877  }
878  Pattern = PatternDef;
879
880  // \brief Record the point of instantiation.
881  if (MemberSpecializationInfo *MSInfo
882        = Instantiation->getMemberSpecializationInfo()) {
883    MSInfo->setTemplateSpecializationKind(TSK);
884    MSInfo->setPointOfInstantiation(PointOfInstantiation);
885  } else if (ClassTemplateSpecializationDecl *Spec
886               = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
887    Spec->setTemplateSpecializationKind(TSK);
888    Spec->setPointOfInstantiation(PointOfInstantiation);
889  }
890
891  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
892  if (Inst)
893    return true;
894
895  // Enter the scope of this instantiation. We don't use
896  // PushDeclContext because we don't have a scope.
897  DeclContext *PreviousContext = CurContext;
898  CurContext = Instantiation;
899
900  // Start the definition of this instantiation.
901  Instantiation->startDefinition();
902
903  // Do substitution on the base class specifiers.
904  if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
905    Invalid = true;
906
907  llvm::SmallVector<DeclPtrTy, 4> Fields;
908  for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
909         MemberEnd = Pattern->decls_end();
910       Member != MemberEnd; ++Member) {
911    Decl *NewMember = SubstDecl(*Member, Instantiation, TemplateArgs);
912    if (NewMember) {
913      if (NewMember->isInvalidDecl())
914        Invalid = true;
915      else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
916        Fields.push_back(DeclPtrTy::make(Field));
917      else if (UsingDecl *UD = dyn_cast<UsingDecl>(NewMember))
918        Instantiation->addDecl(UD);
919    } else {
920      // FIXME: Eventually, a NULL return will mean that one of the
921      // instantiations was a semantic disaster, and we'll want to set Invalid =
922      // true. For now, we expect to skip some members that we can't yet handle.
923    }
924  }
925
926  // Finish checking fields.
927  ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation),
928              Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
929              0);
930  if (Instantiation->isInvalidDecl())
931    Invalid = true;
932
933  // Add any implicitly-declared members that we might need.
934  if (!Invalid)
935    AddImplicitlyDeclaredMembersToClass(Instantiation);
936
937  // Exit the scope of this instantiation.
938  CurContext = PreviousContext;
939
940  if (!Invalid)
941    Consumer.HandleTagDeclDefinition(Instantiation);
942
943  return Invalid;
944}
945
946bool
947Sema::InstantiateClassTemplateSpecialization(
948                           SourceLocation PointOfInstantiation,
949                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
950                           TemplateSpecializationKind TSK,
951                           bool Complain) {
952  // Perform the actual instantiation on the canonical declaration.
953  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
954                                         ClassTemplateSpec->getCanonicalDecl());
955
956  // Check whether we have already instantiated or specialized this class
957  // template specialization.
958  if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
959    if (ClassTemplateSpec->getSpecializationKind() ==
960          TSK_ExplicitInstantiationDeclaration &&
961        TSK == TSK_ExplicitInstantiationDefinition) {
962      // An explicit instantiation definition follows an explicit instantiation
963      // declaration (C++0x [temp.explicit]p10); go ahead and perform the
964      // explicit instantiation.
965      ClassTemplateSpec->setSpecializationKind(TSK);
966      return false;
967    }
968
969    // We can only instantiate something that hasn't already been
970    // instantiated or specialized. Fail without any diagnostics: our
971    // caller will provide an error message.
972    return true;
973  }
974
975  if (ClassTemplateSpec->isInvalidDecl())
976    return true;
977
978  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
979  CXXRecordDecl *Pattern = 0;
980
981  // C++ [temp.class.spec.match]p1:
982  //   When a class template is used in a context that requires an
983  //   instantiation of the class, it is necessary to determine
984  //   whether the instantiation is to be generated using the primary
985  //   template or one of the partial specializations. This is done by
986  //   matching the template arguments of the class template
987  //   specialization with the template argument lists of the partial
988  //   specializations.
989  typedef std::pair<ClassTemplatePartialSpecializationDecl *,
990                    TemplateArgumentList *> MatchResult;
991  llvm::SmallVector<MatchResult, 4> Matched;
992  for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
993         Partial = Template->getPartialSpecializations().begin(),
994         PartialEnd = Template->getPartialSpecializations().end();
995       Partial != PartialEnd;
996       ++Partial) {
997    TemplateDeductionInfo Info(Context);
998    if (TemplateDeductionResult Result
999          = DeduceTemplateArguments(&*Partial,
1000                                    ClassTemplateSpec->getTemplateArgs(),
1001                                    Info)) {
1002      // FIXME: Store the failed-deduction information for use in
1003      // diagnostics, later.
1004      (void)Result;
1005    } else {
1006      Matched.push_back(std::make_pair(&*Partial, Info.take()));
1007    }
1008  }
1009
1010  if (Matched.size() >= 1) {
1011    llvm::SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
1012    if (Matched.size() == 1) {
1013      //   -- If exactly one matching specialization is found, the
1014      //      instantiation is generated from that specialization.
1015      // We don't need to do anything for this.
1016    } else {
1017      //   -- If more than one matching specialization is found, the
1018      //      partial order rules (14.5.4.2) are used to determine
1019      //      whether one of the specializations is more specialized
1020      //      than the others. If none of the specializations is more
1021      //      specialized than all of the other matching
1022      //      specializations, then the use of the class template is
1023      //      ambiguous and the program is ill-formed.
1024      for (llvm::SmallVector<MatchResult, 4>::iterator P = Best + 1,
1025                                                    PEnd = Matched.end();
1026           P != PEnd; ++P) {
1027        if (getMoreSpecializedPartialSpecialization(P->first, Best->first)
1028              == P->first)
1029          Best = P;
1030      }
1031
1032      // Determine if the best partial specialization is more specialized than
1033      // the others.
1034      bool Ambiguous = false;
1035      for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1036                                                    PEnd = Matched.end();
1037           P != PEnd; ++P) {
1038        if (P != Best &&
1039            getMoreSpecializedPartialSpecialization(P->first, Best->first)
1040              != Best->first) {
1041          Ambiguous = true;
1042          break;
1043        }
1044      }
1045
1046      if (Ambiguous) {
1047        // Partial ordering did not produce a clear winner. Complain.
1048        ClassTemplateSpec->setInvalidDecl();
1049        Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
1050          << ClassTemplateSpec;
1051
1052        // Print the matching partial specializations.
1053        for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1054                                                      PEnd = Matched.end();
1055             P != PEnd; ++P)
1056          Diag(P->first->getLocation(), diag::note_partial_spec_match)
1057            << getTemplateArgumentBindingsText(P->first->getTemplateParameters(),
1058                                               *P->second);
1059
1060        return true;
1061      }
1062    }
1063
1064    // Instantiate using the best class template partial specialization.
1065    ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->first;
1066    while (OrigPartialSpec->getInstantiatedFromMember()) {
1067      // If we've found an explicit specialization of this class template,
1068      // stop here and use that as the pattern.
1069      if (OrigPartialSpec->isMemberSpecialization())
1070        break;
1071
1072      OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
1073    }
1074
1075    Pattern = OrigPartialSpec;
1076    ClassTemplateSpec->setInstantiationOf(Best->first, Best->second);
1077  } else {
1078    //   -- If no matches are found, the instantiation is generated
1079    //      from the primary template.
1080    ClassTemplateDecl *OrigTemplate = Template;
1081    while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
1082      // If we've found an explicit specialization of this class template,
1083      // stop here and use that as the pattern.
1084      if (OrigTemplate->isMemberSpecialization())
1085        break;
1086
1087      OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
1088    }
1089
1090    Pattern = OrigTemplate->getTemplatedDecl();
1091  }
1092
1093  bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
1094                                 Pattern,
1095                                getTemplateInstantiationArgs(ClassTemplateSpec),
1096                                 TSK,
1097                                 Complain);
1098
1099  for (unsigned I = 0, N = Matched.size(); I != N; ++I) {
1100    // FIXME: Implement TemplateArgumentList::Destroy!
1101    //    if (Matched[I].first != Pattern)
1102    //      Matched[I].second->Destroy(Context);
1103  }
1104
1105  return Result;
1106}
1107
1108/// \brief Instantiates the definitions of all of the member
1109/// of the given class, which is an instantiation of a class template
1110/// or a member class of a template.
1111void
1112Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
1113                              CXXRecordDecl *Instantiation,
1114                        const MultiLevelTemplateArgumentList &TemplateArgs,
1115                              TemplateSpecializationKind TSK) {
1116  for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
1117                               DEnd = Instantiation->decls_end();
1118       D != DEnd; ++D) {
1119    bool SuppressNew = false;
1120    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
1121      if (FunctionDecl *Pattern
1122            = Function->getInstantiatedFromMemberFunction()) {
1123        MemberSpecializationInfo *MSInfo
1124          = Function->getMemberSpecializationInfo();
1125        assert(MSInfo && "No member specialization information?");
1126        if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
1127                                                   Function,
1128                                        MSInfo->getTemplateSpecializationKind(),
1129                                              MSInfo->getPointOfInstantiation(),
1130                                                   SuppressNew) ||
1131            SuppressNew)
1132          continue;
1133
1134        if (Function->getBody())
1135          continue;
1136
1137        if (TSK == TSK_ExplicitInstantiationDefinition) {
1138          // C++0x [temp.explicit]p8:
1139          //   An explicit instantiation definition that names a class template
1140          //   specialization explicitly instantiates the class template
1141          //   specialization and is only an explicit instantiation definition
1142          //   of members whose definition is visible at the point of
1143          //   instantiation.
1144          if (!Pattern->getBody())
1145            continue;
1146
1147          Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1148
1149          InstantiateFunctionDefinition(PointOfInstantiation, Function);
1150        } else {
1151          Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1152        }
1153      }
1154    } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
1155      if (Var->isStaticDataMember()) {
1156        MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
1157        assert(MSInfo && "No member specialization information?");
1158        if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
1159                                                   Var,
1160                                        MSInfo->getTemplateSpecializationKind(),
1161                                              MSInfo->getPointOfInstantiation(),
1162                                                   SuppressNew) ||
1163            SuppressNew)
1164          continue;
1165
1166        if (TSK == TSK_ExplicitInstantiationDefinition) {
1167          // C++0x [temp.explicit]p8:
1168          //   An explicit instantiation definition that names a class template
1169          //   specialization explicitly instantiates the class template
1170          //   specialization and is only an explicit instantiation definition
1171          //   of members whose definition is visible at the point of
1172          //   instantiation.
1173          if (!Var->getInstantiatedFromStaticDataMember()
1174                                                     ->getOutOfLineDefinition())
1175            continue;
1176
1177          Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1178          InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
1179        } else {
1180          Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1181        }
1182      }
1183    } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
1184      if (Record->isInjectedClassName())
1185        continue;
1186
1187      MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
1188      assert(MSInfo && "No member specialization information?");
1189      if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
1190                                                 Record,
1191                                        MSInfo->getTemplateSpecializationKind(),
1192                                              MSInfo->getPointOfInstantiation(),
1193                                                 SuppressNew) ||
1194          SuppressNew)
1195        continue;
1196
1197      CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
1198      assert(Pattern && "Missing instantiated-from-template information");
1199
1200      if (!Record->getDefinition(Context)) {
1201        if (!Pattern->getDefinition(Context)) {
1202          // C++0x [temp.explicit]p8:
1203          //   An explicit instantiation definition that names a class template
1204          //   specialization explicitly instantiates the class template
1205          //   specialization and is only an explicit instantiation definition
1206          //   of members whose definition is visible at the point of
1207          //   instantiation.
1208          if (TSK == TSK_ExplicitInstantiationDeclaration) {
1209            MSInfo->setTemplateSpecializationKind(TSK);
1210            MSInfo->setPointOfInstantiation(PointOfInstantiation);
1211          }
1212
1213          continue;
1214        }
1215
1216        InstantiateClass(PointOfInstantiation, Record, Pattern,
1217                         TemplateArgs,
1218                         TSK);
1219      }
1220
1221      Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
1222      if (Pattern)
1223        InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
1224                                TSK);
1225    }
1226  }
1227}
1228
1229/// \brief Instantiate the definitions of all of the members of the
1230/// given class template specialization, which was named as part of an
1231/// explicit instantiation.
1232void
1233Sema::InstantiateClassTemplateSpecializationMembers(
1234                                           SourceLocation PointOfInstantiation,
1235                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
1236                                               TemplateSpecializationKind TSK) {
1237  // C++0x [temp.explicit]p7:
1238  //   An explicit instantiation that names a class template
1239  //   specialization is an explicit instantion of the same kind
1240  //   (declaration or definition) of each of its members (not
1241  //   including members inherited from base classes) that has not
1242  //   been previously explicitly specialized in the translation unit
1243  //   containing the explicit instantiation, except as described
1244  //   below.
1245  InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
1246                          getTemplateInstantiationArgs(ClassTemplateSpec),
1247                          TSK);
1248}
1249
1250Sema::OwningStmtResult
1251Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
1252  if (!S)
1253    return Owned(S);
1254
1255  TemplateInstantiator Instantiator(*this, TemplateArgs,
1256                                    SourceLocation(),
1257                                    DeclarationName());
1258  return Instantiator.TransformStmt(S);
1259}
1260
1261Sema::OwningExprResult
1262Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
1263  if (!E)
1264    return Owned(E);
1265
1266  TemplateInstantiator Instantiator(*this, TemplateArgs,
1267                                    SourceLocation(),
1268                                    DeclarationName());
1269  return Instantiator.TransformExpr(E);
1270}
1271
1272/// \brief Do template substitution on a nested-name-specifier.
1273NestedNameSpecifier *
1274Sema::SubstNestedNameSpecifier(NestedNameSpecifier *NNS,
1275                               SourceRange Range,
1276                         const MultiLevelTemplateArgumentList &TemplateArgs) {
1277  TemplateInstantiator Instantiator(*this, TemplateArgs, Range.getBegin(),
1278                                    DeclarationName());
1279  return Instantiator.TransformNestedNameSpecifier(NNS, Range);
1280}
1281
1282TemplateName
1283Sema::SubstTemplateName(TemplateName Name, SourceLocation Loc,
1284                        const MultiLevelTemplateArgumentList &TemplateArgs) {
1285  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1286                                    DeclarationName());
1287  return Instantiator.TransformTemplateName(Name);
1288}
1289
1290bool Sema::Subst(const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output,
1291                 const MultiLevelTemplateArgumentList &TemplateArgs) {
1292  TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
1293                                    DeclarationName());
1294
1295  return Instantiator.TransformTemplateArgument(Input, Output);
1296}
1297