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