SemaTemplateInstantiate.cpp revision 0d8df780aef1acda5962347a32591efc629b6748
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
51    // Add template arguments from a function template specialization.
52    else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
53      // FIXME: Check whether this is an explicit specialization.
54      if (const TemplateArgumentList *TemplateArgs
55            = Function->getTemplateSpecializationArgs())
56        Result.addOuterTemplateArguments(TemplateArgs);
57
58      // If this is a friend declaration and it declares an entity at
59      // namespace scope, take arguments from its lexical parent
60      // instead of its semantic parent.
61      if (Function->getFriendObjectKind() &&
62          Function->getDeclContext()->isFileContext()) {
63        Ctx = Function->getLexicalDeclContext();
64        continue;
65      }
66    }
67
68    Ctx = Ctx->getParent();
69  }
70
71  return Result;
72}
73
74Sema::InstantiatingTemplate::
75InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
76                      Decl *Entity,
77                      SourceRange InstantiationRange)
78  :  SemaRef(SemaRef) {
79
80  Invalid = CheckInstantiationDepth(PointOfInstantiation,
81                                    InstantiationRange);
82  if (!Invalid) {
83    ActiveTemplateInstantiation Inst;
84    Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
85    Inst.PointOfInstantiation = PointOfInstantiation;
86    Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
87    Inst.TemplateArgs = 0;
88    Inst.NumTemplateArgs = 0;
89    Inst.InstantiationRange = InstantiationRange;
90    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
91    Invalid = false;
92  }
93}
94
95Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
96                                         SourceLocation PointOfInstantiation,
97                                         TemplateDecl *Template,
98                                         const TemplateArgument *TemplateArgs,
99                                         unsigned NumTemplateArgs,
100                                         SourceRange InstantiationRange)
101  : SemaRef(SemaRef) {
102
103  Invalid = CheckInstantiationDepth(PointOfInstantiation,
104                                    InstantiationRange);
105  if (!Invalid) {
106    ActiveTemplateInstantiation Inst;
107    Inst.Kind
108      = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
109    Inst.PointOfInstantiation = PointOfInstantiation;
110    Inst.Entity = reinterpret_cast<uintptr_t>(Template);
111    Inst.TemplateArgs = TemplateArgs;
112    Inst.NumTemplateArgs = NumTemplateArgs;
113    Inst.InstantiationRange = InstantiationRange;
114    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
115    Invalid = false;
116  }
117}
118
119Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
120                                         SourceLocation PointOfInstantiation,
121                                      FunctionTemplateDecl *FunctionTemplate,
122                                        const TemplateArgument *TemplateArgs,
123                                                   unsigned NumTemplateArgs,
124                         ActiveTemplateInstantiation::InstantiationKind Kind,
125                                              SourceRange InstantiationRange)
126: SemaRef(SemaRef) {
127
128  Invalid = CheckInstantiationDepth(PointOfInstantiation,
129                                    InstantiationRange);
130  if (!Invalid) {
131    ActiveTemplateInstantiation Inst;
132    Inst.Kind = Kind;
133    Inst.PointOfInstantiation = PointOfInstantiation;
134    Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
135    Inst.TemplateArgs = TemplateArgs;
136    Inst.NumTemplateArgs = NumTemplateArgs;
137    Inst.InstantiationRange = InstantiationRange;
138    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
139    Invalid = false;
140  }
141}
142
143Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
144                                         SourceLocation PointOfInstantiation,
145                          ClassTemplatePartialSpecializationDecl *PartialSpec,
146                                         const TemplateArgument *TemplateArgs,
147                                         unsigned NumTemplateArgs,
148                                         SourceRange InstantiationRange)
149  : SemaRef(SemaRef) {
150
151  Invalid = CheckInstantiationDepth(PointOfInstantiation,
152                                    InstantiationRange);
153  if (!Invalid) {
154    ActiveTemplateInstantiation Inst;
155    Inst.Kind
156      = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
157    Inst.PointOfInstantiation = PointOfInstantiation;
158    Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
159    Inst.TemplateArgs = TemplateArgs;
160    Inst.NumTemplateArgs = NumTemplateArgs;
161    Inst.InstantiationRange = InstantiationRange;
162    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
163    Invalid = false;
164  }
165}
166
167void Sema::InstantiatingTemplate::Clear() {
168  if (!Invalid) {
169    SemaRef.ActiveTemplateInstantiations.pop_back();
170    Invalid = true;
171  }
172}
173
174bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
175                                        SourceLocation PointOfInstantiation,
176                                           SourceRange InstantiationRange) {
177  if (SemaRef.ActiveTemplateInstantiations.size()
178       <= SemaRef.getLangOptions().InstantiationDepth)
179    return false;
180
181  SemaRef.Diag(PointOfInstantiation,
182               diag::err_template_recursion_depth_exceeded)
183    << SemaRef.getLangOptions().InstantiationDepth
184    << InstantiationRange;
185  SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
186    << SemaRef.getLangOptions().InstantiationDepth;
187  return true;
188}
189
190/// \brief Prints the current instantiation stack through a series of
191/// notes.
192void Sema::PrintInstantiationStack() {
193  // FIXME: In all of these cases, we need to show the template arguments
194  for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
195         Active = ActiveTemplateInstantiations.rbegin(),
196         ActiveEnd = ActiveTemplateInstantiations.rend();
197       Active != ActiveEnd;
198       ++Active) {
199    switch (Active->Kind) {
200    case ActiveTemplateInstantiation::TemplateInstantiation: {
201      Decl *D = reinterpret_cast<Decl *>(Active->Entity);
202      if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
203        unsigned DiagID = diag::note_template_member_class_here;
204        if (isa<ClassTemplateSpecializationDecl>(Record))
205          DiagID = diag::note_template_class_instantiation_here;
206        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
207                     DiagID)
208          << Context.getTypeDeclType(Record)
209          << Active->InstantiationRange;
210      } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
211        unsigned DiagID;
212        if (Function->getPrimaryTemplate())
213          DiagID = diag::note_function_template_spec_here;
214        else
215          DiagID = diag::note_template_member_function_here;
216        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
217                     DiagID)
218          << Function
219          << Active->InstantiationRange;
220      } else {
221        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
222                     diag::note_template_static_data_member_def_here)
223          << cast<VarDecl>(D)
224          << Active->InstantiationRange;
225      }
226      break;
227    }
228
229    case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
230      TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
231      std::string TemplateArgsStr
232        = TemplateSpecializationType::PrintTemplateArgumentList(
233                                                         Active->TemplateArgs,
234                                                      Active->NumTemplateArgs,
235                                                      Context.PrintingPolicy);
236      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
237                   diag::note_default_arg_instantiation_here)
238        << (Template->getNameAsString() + TemplateArgsStr)
239        << Active->InstantiationRange;
240      break;
241    }
242
243    case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
244      FunctionTemplateDecl *FnTmpl
245        = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
246      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
247                   diag::note_explicit_template_arg_substitution_here)
248        << FnTmpl << Active->InstantiationRange;
249      break;
250    }
251
252    case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
253      if (ClassTemplatePartialSpecializationDecl *PartialSpec
254            = dyn_cast<ClassTemplatePartialSpecializationDecl>(
255                                                    (Decl *)Active->Entity)) {
256        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
257                     diag::note_partial_spec_deduct_instantiation_here)
258          << Context.getTypeDeclType(PartialSpec)
259          << Active->InstantiationRange;
260      } else {
261        FunctionTemplateDecl *FnTmpl
262          = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
263        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
264                     diag::note_function_template_deduction_instantiation_here)
265          << FnTmpl << Active->InstantiationRange;
266      }
267      break;
268
269    }
270  }
271}
272
273bool Sema::isSFINAEContext() const {
274  using llvm::SmallVector;
275  for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
276         Active = ActiveTemplateInstantiations.rbegin(),
277         ActiveEnd = ActiveTemplateInstantiations.rend();
278       Active != ActiveEnd;
279       ++Active) {
280
281    switch(Active->Kind) {
282    case ActiveTemplateInstantiation::TemplateInstantiation:
283      // This is a template instantiation, so there is no SFINAE.
284      return false;
285
286    case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
287      // A default template argument instantiation may or may not be a
288      // SFINAE context; look further up the stack.
289      break;
290
291    case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
292    case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
293      // We're either substitution explicitly-specified template arguments
294      // or deduced template arguments, so SFINAE applies.
295      return true;
296    }
297  }
298
299  return false;
300}
301
302//===----------------------------------------------------------------------===/
303// Template Instantiation for Types
304//===----------------------------------------------------------------------===/
305namespace {
306  class VISIBILITY_HIDDEN TemplateInstantiator
307    : public TreeTransform<TemplateInstantiator>
308  {
309    const MultiLevelTemplateArgumentList &TemplateArgs;
310    SourceLocation Loc;
311    DeclarationName Entity;
312
313  public:
314    typedef TreeTransform<TemplateInstantiator> inherited;
315
316    TemplateInstantiator(Sema &SemaRef,
317                         const MultiLevelTemplateArgumentList &TemplateArgs,
318                         SourceLocation Loc,
319                         DeclarationName Entity)
320      : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
321        Entity(Entity) { }
322
323    /// \brief Determine whether the given type \p T has already been
324    /// transformed.
325    ///
326    /// For the purposes of template instantiation, a type has already been
327    /// transformed if it is NULL or if it is not dependent.
328    bool AlreadyTransformed(QualType T) {
329      return T.isNull() || !T->isDependentType();
330    }
331
332    /// \brief Returns the location of the entity being instantiated, if known.
333    SourceLocation getBaseLocation() { return Loc; }
334
335    /// \brief Returns the name of the entity being instantiated, if any.
336    DeclarationName getBaseEntity() { return Entity; }
337
338    /// \brief Transform the given declaration by instantiating a reference to
339    /// this declaration.
340    Decl *TransformDecl(Decl *D);
341
342    /// \brief Transform the definition of the given declaration by
343    /// instantiating it.
344    Decl *TransformDefinition(Decl *D);
345
346    /// \brief Rebuild the exception declaration and register the declaration
347    /// as an instantiated local.
348    VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, QualType T,
349                                  DeclaratorInfo *Declarator,
350                                  IdentifierInfo *Name,
351                                  SourceLocation Loc, SourceRange TypeRange);
352
353    Sema::OwningExprResult TransformDeclRefExpr(DeclRefExpr *E);
354
355    /// \brief Transforms a template type parameter type by performing
356    /// substitution of the corresponding template type argument.
357    QualType TransformTemplateTypeParmType(const TemplateTypeParmType *T);
358  };
359}
360
361Decl *TemplateInstantiator::TransformDecl(Decl *D) {
362  if (TemplateTemplateParmDecl *TTP
363        = dyn_cast_or_null<TemplateTemplateParmDecl>(D)) {
364    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
365      assert(TemplateArgs(TTP->getDepth(), TTP->getPosition()).getAsDecl() &&
366             "Wrong kind of template template argument");
367      return cast<TemplateDecl>(TemplateArgs(TTP->getDepth(),
368                                             TTP->getPosition()).getAsDecl());
369    }
370
371    // If the corresponding template argument is NULL or non-existent, it's
372    // because we are performing instantiation from explicitly-specified
373    // template arguments in a function template, but there were some
374    // arguments left unspecified.
375    if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
376                                          TTP->getPosition()))
377      return D;
378
379    // FIXME: Implement depth reduction of template template parameters
380    assert(false &&
381      "Reducing depth of template template parameters is not yet implemented");
382  }
383
384  return SemaRef.FindInstantiatedDecl(cast_or_null<NamedDecl>(D));
385}
386
387Decl *TemplateInstantiator::TransformDefinition(Decl *D) {
388  Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
389  if (!Inst)
390    return 0;
391
392  getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
393  return Inst;
394}
395
396VarDecl *
397TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
398                                           QualType T,
399                                           DeclaratorInfo *Declarator,
400                                           IdentifierInfo *Name,
401                                           SourceLocation Loc,
402                                           SourceRange TypeRange) {
403  VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, T, Declarator,
404                                                 Name, Loc, TypeRange);
405  if (Var && !Var->isInvalidDecl())
406    getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
407  return Var;
408}
409
410Sema::OwningExprResult
411TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
412  // FIXME: Clean this up a bit
413  NamedDecl *D = E->getDecl();
414  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
415    if (NTTP->getDepth() >= TemplateArgs.getNumLevels()) {
416      assert(false && "Cannot reduce non-type template parameter depth yet");
417      return getSema().ExprError();
418    }
419
420    // If the corresponding template argument is NULL or non-existent, it's
421    // because we are performing instantiation from explicitly-specified
422    // template arguments in a function template, but there were some
423    // arguments left unspecified.
424    if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
425                                          NTTP->getPosition()))
426      return SemaRef.Owned(E->Retain());
427
428    const TemplateArgument &Arg = TemplateArgs(NTTP->getDepth(),
429                                               NTTP->getPosition());
430
431    // The template argument itself might be an expression, in which
432    // case we just return that expression.
433    if (Arg.getKind() == TemplateArgument::Expression)
434      return SemaRef.Owned(Arg.getAsExpr()->Retain());
435
436    if (Arg.getKind() == TemplateArgument::Declaration) {
437      ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
438
439      VD = cast_or_null<ValueDecl>(getSema().FindInstantiatedDecl(VD));
440      if (!VD)
441        return SemaRef.ExprError();
442
443      return SemaRef.BuildDeclRefExpr(VD, VD->getType(), E->getLocation(),
444                                      /*FIXME:*/false, /*FIXME:*/false);
445    }
446
447    assert(Arg.getKind() == TemplateArgument::Integral);
448    QualType T = Arg.getIntegralType();
449    if (T->isCharType() || T->isWideCharType())
450      return SemaRef.Owned(new (SemaRef.Context) CharacterLiteral(
451                                            Arg.getAsIntegral()->getZExtValue(),
452                                            T->isWideCharType(),
453                                            T,
454                                            E->getSourceRange().getBegin()));
455    if (T->isBooleanType())
456      return SemaRef.Owned(new (SemaRef.Context) CXXBoolLiteralExpr(
457                                          Arg.getAsIntegral()->getBoolValue(),
458                                          T,
459                                          E->getSourceRange().getBegin()));
460
461    assert(Arg.getAsIntegral()->getBitWidth() == SemaRef.Context.getIntWidth(T));
462    return SemaRef.Owned(new (SemaRef.Context) IntegerLiteral(
463                                              *Arg.getAsIntegral(),
464                                              T,
465                                              E->getSourceRange().getBegin()));
466  }
467
468  if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) {
469    // FIXME: instantiate each decl in the overload set
470    return SemaRef.Owned(new (SemaRef.Context) DeclRefExpr(Ovl,
471                                                     SemaRef.Context.OverloadTy,
472                                                     E->getLocation(),
473                                                     false, false));
474  }
475
476  NamedDecl *InstD = SemaRef.FindInstantiatedDecl(D);
477  if (!InstD)
478    return SemaRef.ExprError();
479
480  // If we instantiated an UnresolvedUsingDecl and got back an UsingDecl,
481  // we need to get the underlying decl.
482  // FIXME: Is this correct? Maybe FindInstantiatedDecl should do this?
483  InstD = InstD->getUnderlyingDecl();
484
485  // FIXME: nested-name-specifier for QualifiedDeclRefExpr
486  return SemaRef.BuildDeclarationNameExpr(E->getLocation(), InstD,
487                                          /*FIXME:*/false,
488                                          /*FIXME:*/0,
489                                          /*FIXME:*/false);
490}
491
492QualType
493TemplateInstantiator::TransformTemplateTypeParmType(
494                                              const TemplateTypeParmType *T) {
495  if (T->getDepth() < TemplateArgs.getNumLevels()) {
496    // Replace the template type parameter with its corresponding
497    // template argument.
498
499    // If the corresponding template argument is NULL or doesn't exist, it's
500    // because we are performing instantiation from explicitly-specified
501    // template arguments in a function template class, but there were some
502    // arguments left unspecified.
503    if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex()))
504      return QualType(T, 0);
505
506    assert(TemplateArgs(T->getDepth(), T->getIndex()).getKind()
507             == TemplateArgument::Type &&
508           "Template argument kind mismatch");
509
510    return TemplateArgs(T->getDepth(), T->getIndex()).getAsType();
511  }
512
513  // The template type parameter comes from an inner template (e.g.,
514  // the template parameter list of a member template inside the
515  // template we are instantiating). Create a new template type
516  // parameter with the template "level" reduced by one.
517  return getSema().Context.getTemplateTypeParmType(
518                                  T->getDepth() - TemplateArgs.getNumLevels(),
519                                                   T->getIndex(),
520                                                   T->isParameterPack(),
521                                                   T->getName());
522}
523
524/// \brief Perform substitution on the type T with a given set of template
525/// arguments.
526///
527/// This routine substitutes the given template arguments into the
528/// type T and produces the instantiated type.
529///
530/// \param T the type into which the template arguments will be
531/// substituted. If this type is not dependent, it will be returned
532/// immediately.
533///
534/// \param TemplateArgs the template arguments that will be
535/// substituted for the top-level template parameters within T.
536///
537/// \param Loc the location in the source code where this substitution
538/// is being performed. It will typically be the location of the
539/// declarator (if we're instantiating the type of some declaration)
540/// or the location of the type in the source code (if, e.g., we're
541/// instantiating the type of a cast expression).
542///
543/// \param Entity the name of the entity associated with a declaration
544/// being instantiated (if any). May be empty to indicate that there
545/// is no such entity (if, e.g., this is a type that occurs as part of
546/// a cast expression) or that the entity has no name (e.g., an
547/// unnamed function parameter).
548///
549/// \returns If the instantiation succeeds, the instantiated
550/// type. Otherwise, produces diagnostics and returns a NULL type.
551QualType Sema::SubstType(QualType T,
552                         const MultiLevelTemplateArgumentList &TemplateArgs,
553                         SourceLocation Loc, DeclarationName Entity) {
554  assert(!ActiveTemplateInstantiations.empty() &&
555         "Cannot perform an instantiation without some context on the "
556         "instantiation stack");
557
558  // If T is not a dependent type, there is nothing to do.
559  if (!T->isDependentType())
560    return T;
561
562  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
563  return Instantiator.TransformType(T);
564}
565
566/// \brief Perform substitution on the base class specifiers of the
567/// given class template specialization.
568///
569/// Produces a diagnostic and returns true on error, returns false and
570/// attaches the instantiated base classes to the class template
571/// specialization if successful.
572bool
573Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
574                          CXXRecordDecl *Pattern,
575                          const MultiLevelTemplateArgumentList &TemplateArgs) {
576  bool Invalid = false;
577  llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
578  for (ClassTemplateSpecializationDecl::base_class_iterator
579         Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
580       Base != BaseEnd; ++Base) {
581    if (!Base->getType()->isDependentType()) {
582      InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
583      continue;
584    }
585
586    QualType BaseType = SubstType(Base->getType(),
587                                  TemplateArgs,
588                                  Base->getSourceRange().getBegin(),
589                                  DeclarationName());
590    if (BaseType.isNull()) {
591      Invalid = true;
592      continue;
593    }
594
595    if (CXXBaseSpecifier *InstantiatedBase
596          = CheckBaseSpecifier(Instantiation,
597                               Base->getSourceRange(),
598                               Base->isVirtual(),
599                               Base->getAccessSpecifierAsWritten(),
600                               BaseType,
601                               /*FIXME: Not totally accurate */
602                               Base->getSourceRange().getBegin()))
603      InstantiatedBases.push_back(InstantiatedBase);
604    else
605      Invalid = true;
606  }
607
608  if (!Invalid &&
609      AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
610                           InstantiatedBases.size()))
611    Invalid = true;
612
613  return Invalid;
614}
615
616/// \brief Instantiate the definition of a class from a given pattern.
617///
618/// \param PointOfInstantiation The point of instantiation within the
619/// source code.
620///
621/// \param Instantiation is the declaration whose definition is being
622/// instantiated. This will be either a class template specialization
623/// or a member class of a class template specialization.
624///
625/// \param Pattern is the pattern from which the instantiation
626/// occurs. This will be either the declaration of a class template or
627/// the declaration of a member class of a class template.
628///
629/// \param TemplateArgs The template arguments to be substituted into
630/// the pattern.
631///
632/// \param ExplicitInstantiation whether this is an explicit instantiation
633/// (otherwise, it is an implicit instantiation).
634///
635/// \param Complain whether to complain if the class cannot be instantiated due
636/// to the lack of a definition.
637///
638/// \returns true if an error occurred, false otherwise.
639bool
640Sema::InstantiateClass(SourceLocation PointOfInstantiation,
641                       CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
642                       const MultiLevelTemplateArgumentList &TemplateArgs,
643                       bool ExplicitInstantiation,
644                       bool Complain) {
645  bool Invalid = false;
646
647  CXXRecordDecl *PatternDef
648    = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
649  if (!PatternDef) {
650    if (!Complain) {
651      // Say nothing
652    } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
653      Diag(PointOfInstantiation,
654           diag::err_implicit_instantiate_member_undefined)
655        << Context.getTypeDeclType(Instantiation);
656      Diag(Pattern->getLocation(), diag::note_member_of_template_here);
657    } else {
658      Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
659        << ExplicitInstantiation
660        << Context.getTypeDeclType(Instantiation);
661      Diag(Pattern->getLocation(), diag::note_template_decl_here);
662    }
663    return true;
664  }
665  Pattern = PatternDef;
666
667  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
668  if (Inst)
669    return true;
670
671  // Enter the scope of this instantiation. We don't use
672  // PushDeclContext because we don't have a scope.
673  DeclContext *PreviousContext = CurContext;
674  CurContext = Instantiation;
675
676  // Start the definition of this instantiation.
677  Instantiation->startDefinition();
678
679  // Do substitution on the base class specifiers.
680  if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
681    Invalid = true;
682
683  llvm::SmallVector<DeclPtrTy, 4> Fields;
684  for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
685         MemberEnd = Pattern->decls_end();
686       Member != MemberEnd; ++Member) {
687    Decl *NewMember = SubstDecl(*Member, Instantiation, TemplateArgs);
688    if (NewMember) {
689      if (NewMember->isInvalidDecl())
690        Invalid = true;
691      else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
692        Fields.push_back(DeclPtrTy::make(Field));
693      else if (UsingDecl *UD = dyn_cast<UsingDecl>(NewMember))
694        Instantiation->addDecl(UD);
695    } else {
696      // FIXME: Eventually, a NULL return will mean that one of the
697      // instantiations was a semantic disaster, and we'll want to set Invalid =
698      // true. For now, we expect to skip some members that we can't yet handle.
699    }
700  }
701
702  // Finish checking fields.
703  ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation),
704              Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
705              0);
706
707  // Add any implicitly-declared members that we might need.
708  AddImplicitlyDeclaredMembersToClass(Instantiation);
709
710  // Exit the scope of this instantiation.
711  CurContext = PreviousContext;
712
713  if (!Invalid)
714    Consumer.HandleTagDeclDefinition(Instantiation);
715
716  // If this is an explicit instantiation, instantiate our members, too.
717  if (!Invalid && ExplicitInstantiation) {
718    Inst.Clear();
719    InstantiateClassMembers(PointOfInstantiation, Instantiation, TemplateArgs);
720  }
721
722  return Invalid;
723}
724
725bool
726Sema::InstantiateClassTemplateSpecialization(
727                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
728                           bool ExplicitInstantiation,
729                           bool Complain) {
730  // Perform the actual instantiation on the canonical declaration.
731  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
732                                         ClassTemplateSpec->getCanonicalDecl());
733
734  // We can only instantiate something that hasn't already been
735  // instantiated or specialized. Fail without any diagnostics: our
736  // caller will provide an error message.
737  if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared)
738    return true;
739
740  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
741  CXXRecordDecl *Pattern = 0;
742
743  // C++ [temp.class.spec.match]p1:
744  //   When a class template is used in a context that requires an
745  //   instantiation of the class, it is necessary to determine
746  //   whether the instantiation is to be generated using the primary
747  //   template or one of the partial specializations. This is done by
748  //   matching the template arguments of the class template
749  //   specialization with the template argument lists of the partial
750  //   specializations.
751  typedef std::pair<ClassTemplatePartialSpecializationDecl *,
752                    TemplateArgumentList *> MatchResult;
753  llvm::SmallVector<MatchResult, 4> Matched;
754  for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
755         Partial = Template->getPartialSpecializations().begin(),
756         PartialEnd = Template->getPartialSpecializations().end();
757       Partial != PartialEnd;
758       ++Partial) {
759    TemplateDeductionInfo Info(Context);
760    if (TemplateDeductionResult Result
761          = DeduceTemplateArguments(&*Partial,
762                                    ClassTemplateSpec->getTemplateArgs(),
763                                    Info)) {
764      // FIXME: Store the failed-deduction information for use in
765      // diagnostics, later.
766      (void)Result;
767    } else {
768      Matched.push_back(std::make_pair(&*Partial, Info.take()));
769    }
770  }
771
772  if (Matched.size() == 1) {
773    //   -- If exactly one matching specialization is found, the
774    //      instantiation is generated from that specialization.
775    Pattern = Matched[0].first;
776    ClassTemplateSpec->setInstantiationOf(Matched[0].first, Matched[0].second);
777  } else if (Matched.size() > 1) {
778    //   -- If more than one matching specialization is found, the
779    //      partial order rules (14.5.4.2) are used to determine
780    //      whether one of the specializations is more specialized
781    //      than the others. If none of the specializations is more
782    //      specialized than all of the other matching
783    //      specializations, then the use of the class template is
784    //      ambiguous and the program is ill-formed.
785    // FIXME: Implement partial ordering of class template partial
786    // specializations.
787    Diag(ClassTemplateSpec->getLocation(),
788         diag::unsup_template_partial_spec_ordering);
789
790    // FIXME: Temporary hack to fall back to the primary template
791    ClassTemplateDecl *OrigTemplate = Template;
792    while (OrigTemplate->getInstantiatedFromMemberTemplate())
793      OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
794
795    Pattern = OrigTemplate->getTemplatedDecl();
796  } else {
797    //   -- If no matches are found, the instantiation is generated
798    //      from the primary template.
799    ClassTemplateDecl *OrigTemplate = Template;
800    while (OrigTemplate->getInstantiatedFromMemberTemplate())
801      OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
802
803    Pattern = OrigTemplate->getTemplatedDecl();
804  }
805
806  // Note that this is an instantiation.
807  ClassTemplateSpec->setSpecializationKind(
808                        ExplicitInstantiation? TSK_ExplicitInstantiation
809                                             : TSK_ImplicitInstantiation);
810
811  bool Result = InstantiateClass(ClassTemplateSpec->getLocation(),
812                                 ClassTemplateSpec, Pattern,
813                              getTemplateInstantiationArgs(ClassTemplateSpec),
814                                 ExplicitInstantiation,
815                                 Complain);
816
817  for (unsigned I = 0, N = Matched.size(); I != N; ++I) {
818    // FIXME: Implement TemplateArgumentList::Destroy!
819    //    if (Matched[I].first != Pattern)
820    //      Matched[I].second->Destroy(Context);
821  }
822
823  return Result;
824}
825
826/// \brief Instantiates the definitions of all of the member
827/// of the given class, which is an instantiation of a class template
828/// or a member class of a template.
829void
830Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
831                        CXXRecordDecl *Instantiation,
832                        const MultiLevelTemplateArgumentList &TemplateArgs) {
833  for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
834                               DEnd = Instantiation->decls_end();
835       D != DEnd; ++D) {
836    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
837      if (!Function->getBody())
838        InstantiateFunctionDefinition(PointOfInstantiation, Function);
839    } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
840      if (Var->isStaticDataMember())
841        InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
842    } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
843      if (!Record->isInjectedClassName() && !Record->getDefinition(Context)) {
844        assert(Record->getInstantiatedFromMemberClass() &&
845               "Missing instantiated-from-template information");
846        InstantiateClass(PointOfInstantiation, Record,
847                         Record->getInstantiatedFromMemberClass(),
848                         TemplateArgs, true);
849      }
850    }
851  }
852}
853
854/// \brief Instantiate the definitions of all of the members of the
855/// given class template specialization, which was named as part of an
856/// explicit instantiation.
857void Sema::InstantiateClassTemplateSpecializationMembers(
858                                           SourceLocation PointOfInstantiation,
859                          ClassTemplateSpecializationDecl *ClassTemplateSpec) {
860  // C++0x [temp.explicit]p7:
861  //   An explicit instantiation that names a class template
862  //   specialization is an explicit instantion of the same kind
863  //   (declaration or definition) of each of its members (not
864  //   including members inherited from base classes) that has not
865  //   been previously explicitly specialized in the translation unit
866  //   containing the explicit instantiation, except as described
867  //   below.
868  InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
869                          getTemplateInstantiationArgs(ClassTemplateSpec));
870}
871
872Sema::OwningStmtResult
873Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
874  if (!S)
875    return Owned(S);
876
877  TemplateInstantiator Instantiator(*this, TemplateArgs,
878                                    SourceLocation(),
879                                    DeclarationName());
880  return Instantiator.TransformStmt(S);
881}
882
883Sema::OwningExprResult
884Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
885  if (!E)
886    return Owned(E);
887
888  TemplateInstantiator Instantiator(*this, TemplateArgs,
889                                    SourceLocation(),
890                                    DeclarationName());
891  return Instantiator.TransformExpr(E);
892}
893
894/// \brief Do template substitution on a nested-name-specifier.
895NestedNameSpecifier *
896Sema::SubstNestedNameSpecifier(NestedNameSpecifier *NNS,
897                               SourceRange Range,
898                         const MultiLevelTemplateArgumentList &TemplateArgs) {
899  TemplateInstantiator Instantiator(*this, TemplateArgs, Range.getBegin(),
900                                    DeclarationName());
901  return Instantiator.TransformNestedNameSpecifier(NNS, Range);
902}
903
904TemplateName
905Sema::SubstTemplateName(TemplateName Name, SourceLocation Loc,
906                        const MultiLevelTemplateArgumentList &TemplateArgs) {
907  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
908                                    DeclarationName());
909  return Instantiator.TransformTemplateName(Name);
910}
911
912TemplateArgument Sema::Subst(TemplateArgument Arg,
913                         const MultiLevelTemplateArgumentList &TemplateArgs) {
914  TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
915                                    DeclarationName());
916  return Instantiator.TransformTemplateArgument(Arg);
917}
918