SemaTemplateInstantiate.cpp revision 9e6bef4fb5efb19c7286fa24d8aedab9c3d625fc
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 "clang/AST/ASTContext.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/Parse/DeclSpec.h"
18#include "clang/Basic/LangOptions.h"
19#include "llvm/Support/Compiler.h"
20
21using namespace clang;
22
23//===----------------------------------------------------------------------===/
24// Template Instantiation Support
25//===----------------------------------------------------------------------===/
26
27/// \brief Retrieve the template argument list that should be used to
28/// instantiate the given declaration.
29const TemplateArgumentList &
30Sema::getTemplateInstantiationArgs(NamedDecl *D) {
31  if (ClassTemplateSpecializationDecl *Spec
32        = dyn_cast<ClassTemplateSpecializationDecl>(D))
33    return Spec->getTemplateArgs();
34
35  DeclContext *EnclosingTemplateCtx = D->getDeclContext();
36  while (!isa<ClassTemplateSpecializationDecl>(EnclosingTemplateCtx)) {
37    assert(!EnclosingTemplateCtx->isFileContext() &&
38           "Tried to get the instantiation arguments of a non-template");
39    EnclosingTemplateCtx = EnclosingTemplateCtx->getParent();
40  }
41
42  ClassTemplateSpecializationDecl *EnclosingTemplate
43    = cast<ClassTemplateSpecializationDecl>(EnclosingTemplateCtx);
44  return EnclosingTemplate->getTemplateArgs();
45}
46
47Sema::InstantiatingTemplate::
48InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
49                      Decl *Entity,
50                      SourceRange InstantiationRange)
51  :  SemaRef(SemaRef) {
52
53  Invalid = CheckInstantiationDepth(PointOfInstantiation,
54                                    InstantiationRange);
55  if (!Invalid) {
56    ActiveTemplateInstantiation Inst;
57    Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
58    Inst.PointOfInstantiation = PointOfInstantiation;
59    Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
60    Inst.TemplateArgs = 0;
61    Inst.NumTemplateArgs = 0;
62    Inst.InstantiationRange = InstantiationRange;
63    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
64    Invalid = false;
65  }
66}
67
68Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
69                                         SourceLocation PointOfInstantiation,
70                                         TemplateDecl *Template,
71                                         const TemplateArgument *TemplateArgs,
72                                         unsigned NumTemplateArgs,
73                                         SourceRange InstantiationRange)
74  : SemaRef(SemaRef) {
75
76  Invalid = CheckInstantiationDepth(PointOfInstantiation,
77                                    InstantiationRange);
78  if (!Invalid) {
79    ActiveTemplateInstantiation Inst;
80    Inst.Kind
81      = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
82    Inst.PointOfInstantiation = PointOfInstantiation;
83    Inst.Entity = reinterpret_cast<uintptr_t>(Template);
84    Inst.TemplateArgs = TemplateArgs;
85    Inst.NumTemplateArgs = NumTemplateArgs;
86    Inst.InstantiationRange = InstantiationRange;
87    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
88    Invalid = false;
89  }
90}
91
92void Sema::InstantiatingTemplate::Clear() {
93  if (!Invalid) {
94    SemaRef.ActiveTemplateInstantiations.pop_back();
95    Invalid = true;
96  }
97}
98
99bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
100                                        SourceLocation PointOfInstantiation,
101                                           SourceRange InstantiationRange) {
102  if (SemaRef.ActiveTemplateInstantiations.size()
103       <= SemaRef.getLangOptions().InstantiationDepth)
104    return false;
105
106  SemaRef.Diag(PointOfInstantiation,
107               diag::err_template_recursion_depth_exceeded)
108    << SemaRef.getLangOptions().InstantiationDepth
109    << InstantiationRange;
110  SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
111    << SemaRef.getLangOptions().InstantiationDepth;
112  return true;
113}
114
115/// \brief Prints the current instantiation stack through a series of
116/// notes.
117void Sema::PrintInstantiationStack() {
118  for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
119         Active = ActiveTemplateInstantiations.rbegin(),
120         ActiveEnd = ActiveTemplateInstantiations.rend();
121       Active != ActiveEnd;
122       ++Active) {
123    switch (Active->Kind) {
124    case ActiveTemplateInstantiation::TemplateInstantiation: {
125      Decl *D = reinterpret_cast<Decl *>(Active->Entity);
126      if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
127        unsigned DiagID = diag::note_template_member_class_here;
128        if (isa<ClassTemplateSpecializationDecl>(Record))
129          DiagID = diag::note_template_class_instantiation_here;
130        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
131                     DiagID)
132          << Context.getTypeDeclType(Record)
133          << Active->InstantiationRange;
134      } else {
135        FunctionDecl *Function = cast<FunctionDecl>(D);
136        unsigned DiagID = diag::note_template_member_function_here;
137        // FIXME: check for a function template
138        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
139                     DiagID)
140          << Function
141          << Active->InstantiationRange;
142      }
143      break;
144    }
145
146    case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
147      TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
148      std::string TemplateArgsStr
149        = TemplateSpecializationType::PrintTemplateArgumentList(
150                                                      Active->TemplateArgs,
151                                                      Active->NumTemplateArgs);
152      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
153                   diag::note_default_arg_instantiation_here)
154        << (Template->getNameAsString() + TemplateArgsStr)
155        << Active->InstantiationRange;
156      break;
157    }
158    }
159  }
160}
161
162//===----------------------------------------------------------------------===/
163// Template Instantiation for Types
164//===----------------------------------------------------------------------===/
165namespace {
166  class VISIBILITY_HIDDEN TemplateTypeInstantiator {
167    Sema &SemaRef;
168    const TemplateArgumentList &TemplateArgs;
169    SourceLocation Loc;
170    DeclarationName Entity;
171
172  public:
173    TemplateTypeInstantiator(Sema &SemaRef,
174                             const TemplateArgumentList &TemplateArgs,
175                             SourceLocation Loc,
176                             DeclarationName Entity)
177      : SemaRef(SemaRef), TemplateArgs(TemplateArgs),
178        Loc(Loc), Entity(Entity) { }
179
180    QualType operator()(QualType T) const { return Instantiate(T); }
181
182    QualType Instantiate(QualType T) const;
183
184    // Declare instantiate functions for each type.
185#define TYPE(Class, Base)                                       \
186    QualType Instantiate##Class##Type(const Class##Type *T,     \
187                                      unsigned Quals) const;
188#define ABSTRACT_TYPE(Class, Base)
189#include "clang/AST/TypeNodes.def"
190  };
191}
192
193QualType
194TemplateTypeInstantiator::InstantiateExtQualType(const ExtQualType *T,
195                                                 unsigned Quals) const {
196  // FIXME: Implement this
197  assert(false && "Cannot instantiate ExtQualType yet");
198  return QualType();
199}
200
201QualType
202TemplateTypeInstantiator::InstantiateBuiltinType(const BuiltinType *T,
203                                                 unsigned Quals) const {
204  assert(false && "Builtin types are not dependent and cannot be instantiated");
205  return QualType(T, Quals);
206}
207
208QualType
209TemplateTypeInstantiator::
210InstantiateFixedWidthIntType(const FixedWidthIntType *T, unsigned Quals) const {
211  // FIXME: Implement this
212  assert(false && "Cannot instantiate FixedWidthIntType yet");
213  return QualType();
214}
215
216QualType
217TemplateTypeInstantiator::InstantiateComplexType(const ComplexType *T,
218                                                 unsigned Quals) const {
219  // FIXME: Implement this
220  assert(false && "Cannot instantiate ComplexType yet");
221  return QualType();
222}
223
224QualType
225TemplateTypeInstantiator::InstantiatePointerType(const PointerType *T,
226                                                 unsigned Quals) const {
227  QualType PointeeType = Instantiate(T->getPointeeType());
228  if (PointeeType.isNull())
229    return QualType();
230
231  return SemaRef.BuildPointerType(PointeeType, Quals, Loc, Entity);
232}
233
234QualType
235TemplateTypeInstantiator::InstantiateBlockPointerType(const BlockPointerType *T,
236                                                      unsigned Quals) const {
237  // FIXME: Implement this
238  assert(false && "Cannot instantiate BlockPointerType yet");
239  return QualType();
240}
241
242QualType
243TemplateTypeInstantiator::InstantiateLValueReferenceType(
244    const LValueReferenceType *T, unsigned Quals) const {
245  QualType ReferentType = Instantiate(T->getPointeeType());
246  if (ReferentType.isNull())
247    return QualType();
248
249  return SemaRef.BuildReferenceType(ReferentType, true, Quals, Loc, Entity);
250}
251
252QualType
253TemplateTypeInstantiator::InstantiateRValueReferenceType(
254    const RValueReferenceType *T, unsigned Quals) const {
255  QualType ReferentType = Instantiate(T->getPointeeType());
256  if (ReferentType.isNull())
257    return QualType();
258
259  return SemaRef.BuildReferenceType(ReferentType, false, Quals, Loc, Entity);
260}
261
262QualType
263TemplateTypeInstantiator::
264InstantiateMemberPointerType(const MemberPointerType *T,
265                             unsigned Quals) const {
266  // FIXME: Implement this
267  assert(false && "Cannot instantiate MemberPointerType yet");
268  return QualType();
269}
270
271QualType
272TemplateTypeInstantiator::
273InstantiateConstantArrayType(const ConstantArrayType *T,
274                             unsigned Quals) const {
275  QualType ElementType = Instantiate(T->getElementType());
276  if (ElementType.isNull())
277    return ElementType;
278
279  // Build a temporary integer literal to specify the size for
280  // BuildArrayType. Since we have already checked the size as part of
281  // creating the dependent array type in the first place, we know
282  // there aren't any errors. However, we do need to determine what
283  // C++ type to give the size expression.
284  llvm::APInt Size = T->getSize();
285  QualType Types[] = {
286    SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
287    SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
288    SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
289  };
290  const unsigned NumTypes = sizeof(Types) / sizeof(QualType);
291  QualType SizeType;
292  for (unsigned I = 0; I != NumTypes; ++I)
293    if (Size.getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
294      SizeType = Types[I];
295      break;
296    }
297
298  if (SizeType.isNull())
299    SizeType = SemaRef.Context.getFixedWidthIntType(Size.getBitWidth(), false);
300
301  IntegerLiteral ArraySize(Size, SizeType, Loc);
302  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
303                                &ArraySize, T->getIndexTypeQualifier(),
304                                Loc, Entity);
305}
306
307QualType
308TemplateTypeInstantiator::
309InstantiateIncompleteArrayType(const IncompleteArrayType *T,
310                               unsigned Quals) const {
311  QualType ElementType = Instantiate(T->getElementType());
312  if (ElementType.isNull())
313    return ElementType;
314
315  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
316                                0, T->getIndexTypeQualifier(),
317                                Loc, Entity);
318}
319
320QualType
321TemplateTypeInstantiator::
322InstantiateVariableArrayType(const VariableArrayType *T,
323                             unsigned Quals) const {
324  // FIXME: Implement this
325  assert(false && "Cannot instantiate VariableArrayType yet");
326  return QualType();
327}
328
329QualType
330TemplateTypeInstantiator::
331InstantiateDependentSizedArrayType(const DependentSizedArrayType *T,
332                                   unsigned Quals) const {
333  Expr *ArraySize = T->getSizeExpr();
334  assert(ArraySize->isValueDependent() &&
335         "dependent sized array types must have value dependent size expr");
336
337  // Instantiate the element type if needed
338  QualType ElementType = T->getElementType();
339  if (ElementType->isDependentType()) {
340    ElementType = Instantiate(ElementType);
341    if (ElementType.isNull())
342      return QualType();
343  }
344
345  // Instantiate the size expression
346  Sema::OwningExprResult InstantiatedArraySize =
347    SemaRef.InstantiateExpr(ArraySize, TemplateArgs);
348  if (InstantiatedArraySize.isInvalid())
349    return QualType();
350
351  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
352                                InstantiatedArraySize.takeAs<Expr>(),
353                                T->getIndexTypeQualifier(), Loc, Entity);
354}
355
356QualType
357TemplateTypeInstantiator::InstantiateVectorType(const VectorType *T,
358                                             unsigned Quals) const {
359  // FIXME: Implement this
360  assert(false && "Cannot instantiate VectorType yet");
361  return QualType();
362}
363
364QualType
365TemplateTypeInstantiator::InstantiateExtVectorType(const ExtVectorType *T,
366                                                   unsigned Quals) const {
367  // FIXME: Implement this
368  assert(false && "Cannot instantiate ExtVectorType yet");
369  return QualType();
370}
371
372QualType
373TemplateTypeInstantiator::
374InstantiateFunctionProtoType(const FunctionProtoType *T,
375                             unsigned Quals) const {
376  QualType ResultType = Instantiate(T->getResultType());
377  if (ResultType.isNull())
378    return ResultType;
379
380  llvm::SmallVector<QualType, 16> ParamTypes;
381  for (FunctionProtoType::arg_type_iterator Param = T->arg_type_begin(),
382                                         ParamEnd = T->arg_type_end();
383       Param != ParamEnd; ++Param) {
384    QualType P = Instantiate(*Param);
385    if (P.isNull())
386      return P;
387
388    ParamTypes.push_back(P);
389  }
390
391  return SemaRef.BuildFunctionType(ResultType, &ParamTypes[0],
392                                   ParamTypes.size(),
393                                   T->isVariadic(), T->getTypeQuals(),
394                                   Loc, Entity);
395}
396
397QualType
398TemplateTypeInstantiator::
399InstantiateFunctionNoProtoType(const FunctionNoProtoType *T,
400                               unsigned Quals) const {
401  assert(false && "Functions without prototypes cannot be dependent.");
402  return QualType();
403}
404
405QualType
406TemplateTypeInstantiator::InstantiateTypedefType(const TypedefType *T,
407                                                 unsigned Quals) const {
408  // FIXME: Implement this
409  assert(false && "Cannot instantiate TypedefType yet");
410  return QualType();
411}
412
413QualType
414TemplateTypeInstantiator::InstantiateTypeOfExprType(const TypeOfExprType *T,
415                                                    unsigned Quals) const {
416  // FIXME: Implement this
417  assert(false && "Cannot instantiate TypeOfExprType yet");
418  return QualType();
419}
420
421QualType
422TemplateTypeInstantiator::InstantiateTypeOfType(const TypeOfType *T,
423                                                unsigned Quals) const {
424  // FIXME: Implement this
425  assert(false && "Cannot instantiate TypeOfType yet");
426  return QualType();
427}
428
429QualType
430TemplateTypeInstantiator::InstantiateRecordType(const RecordType *T,
431                                                unsigned Quals) const {
432  // FIXME: Implement this
433  assert(false && "Cannot instantiate RecordType yet");
434  return QualType();
435}
436
437QualType
438TemplateTypeInstantiator::InstantiateEnumType(const EnumType *T,
439                                              unsigned Quals) const {
440  // FIXME: Implement this
441  assert(false && "Cannot instantiate EnumType yet");
442  return QualType();
443}
444
445QualType
446TemplateTypeInstantiator::
447InstantiateTemplateTypeParmType(const TemplateTypeParmType *T,
448                                unsigned Quals) const {
449  if (T->getDepth() == 0) {
450    // Replace the template type parameter with its corresponding
451    // template argument.
452    assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type &&
453           "Template argument kind mismatch");
454    QualType Result = TemplateArgs[T->getIndex()].getAsType();
455    if (Result.isNull() || !Quals)
456      return Result;
457
458    // C++ [dcl.ref]p1:
459    //   [...] Cv-qualified references are ill-formed except when
460    //   the cv-qualifiers are introduced through the use of a
461    //   typedef (7.1.3) or of a template type argument (14.3), in
462    //   which case the cv-qualifiers are ignored.
463    if (Quals && Result->isReferenceType())
464      Quals = 0;
465
466    return QualType(Result.getTypePtr(), Quals | Result.getCVRQualifiers());
467  }
468
469  // The template type parameter comes from an inner template (e.g.,
470  // the template parameter list of a member template inside the
471  // template we are instantiating). Create a new template type
472  // parameter with the template "level" reduced by one.
473  return SemaRef.Context.getTemplateTypeParmType(T->getDepth() - 1,
474                                                 T->getIndex(),
475                                                 T->getName())
476    .getQualifiedType(Quals);
477}
478
479QualType
480TemplateTypeInstantiator::
481InstantiateTemplateSpecializationType(
482                                  const TemplateSpecializationType *T,
483                                  unsigned Quals) const {
484  llvm::SmallVector<TemplateArgument, 16> InstantiatedTemplateArgs;
485  InstantiatedTemplateArgs.reserve(T->getNumArgs());
486  for (TemplateSpecializationType::iterator Arg = T->begin(), ArgEnd = T->end();
487       Arg != ArgEnd; ++Arg) {
488    switch (Arg->getKind()) {
489    case TemplateArgument::Type: {
490      QualType T = SemaRef.InstantiateType(Arg->getAsType(),
491                                           TemplateArgs,
492                                           Arg->getLocation(),
493                                           DeclarationName());
494      if (T.isNull())
495        return QualType();
496
497      InstantiatedTemplateArgs.push_back(
498                                TemplateArgument(Arg->getLocation(), T));
499      break;
500    }
501
502    case TemplateArgument::Declaration:
503    case TemplateArgument::Integral:
504      InstantiatedTemplateArgs.push_back(*Arg);
505      break;
506
507    case TemplateArgument::Expression:
508      Sema::OwningExprResult E
509        = SemaRef.InstantiateExpr(Arg->getAsExpr(), TemplateArgs);
510      if (E.isInvalid())
511        return QualType();
512      InstantiatedTemplateArgs.push_back(E.takeAs<Expr>());
513      break;
514    }
515  }
516
517  // FIXME: We're missing the locations of the template name, '<', and '>'.
518
519  TemplateName Name = SemaRef.InstantiateTemplateName(T->getTemplateName(),
520                                                      Loc,
521                                                      TemplateArgs);
522
523  return SemaRef.CheckTemplateIdType(Name, Loc, SourceLocation(),
524                                     &InstantiatedTemplateArgs[0],
525                                     InstantiatedTemplateArgs.size(),
526                                     SourceLocation());
527}
528
529QualType
530TemplateTypeInstantiator::
531InstantiateQualifiedNameType(const QualifiedNameType *T,
532                             unsigned Quals) const {
533  // When we instantiated a qualified name type, there's no point in
534  // keeping the qualification around in the instantiated result. So,
535  // just instantiate the named type.
536  return (*this)(T->getNamedType());
537}
538
539QualType
540TemplateTypeInstantiator::
541InstantiateTypenameType(const TypenameType *T, unsigned Quals) const {
542  if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
543    // When the typename type refers to a template-id, the template-id
544    // is dependent and has enough information to instantiate the
545    // result of the typename type. Since we don't care about keeping
546    // the spelling of the typename type in template instantiations,
547    // we just instantiate the template-id.
548    return InstantiateTemplateSpecializationType(TemplateId, Quals);
549  }
550
551  NestedNameSpecifier *NNS
552    = SemaRef.InstantiateNestedNameSpecifier(T->getQualifier(),
553                                             SourceRange(Loc),
554                                             TemplateArgs);
555  if (!NNS)
556    return QualType();
557
558  return SemaRef.CheckTypenameType(NNS, *T->getIdentifier(), SourceRange(Loc));
559}
560
561QualType
562TemplateTypeInstantiator::
563InstantiateObjCInterfaceType(const ObjCInterfaceType *T,
564                             unsigned Quals) const {
565  assert(false && "Objective-C types cannot be dependent");
566  return QualType();
567}
568
569QualType
570TemplateTypeInstantiator::
571InstantiateObjCQualifiedInterfaceType(const ObjCQualifiedInterfaceType *T,
572                                      unsigned Quals) const {
573  assert(false && "Objective-C types cannot be dependent");
574  return QualType();
575}
576
577QualType
578TemplateTypeInstantiator::
579InstantiateObjCQualifiedIdType(const ObjCQualifiedIdType *T,
580                               unsigned Quals) const {
581  assert(false && "Objective-C types cannot be dependent");
582  return QualType();
583}
584
585/// \brief The actual implementation of Sema::InstantiateType().
586QualType TemplateTypeInstantiator::Instantiate(QualType T) const {
587  // If T is not a dependent type, there is nothing to do.
588  if (!T->isDependentType())
589    return T;
590
591  switch (T->getTypeClass()) {
592#define TYPE(Class, Base)                                               \
593  case Type::Class:                                                     \
594    return Instantiate##Class##Type(cast<Class##Type>(T.getTypePtr()),  \
595                                    T.getCVRQualifiers());
596#define ABSTRACT_TYPE(Class, Base)
597#include "clang/AST/TypeNodes.def"
598  }
599
600  assert(false && "Not all types have been decoded for instantiation");
601  return QualType();
602}
603
604/// \brief Instantiate the type T with a given set of template arguments.
605///
606/// This routine substitutes the given template arguments into the
607/// type T and produces the instantiated type.
608///
609/// \param T the type into which the template arguments will be
610/// substituted. If this type is not dependent, it will be returned
611/// immediately.
612///
613/// \param TemplateArgs the template arguments that will be
614/// substituted for the top-level template parameters within T.
615///
616/// \param Loc the location in the source code where this substitution
617/// is being performed. It will typically be the location of the
618/// declarator (if we're instantiating the type of some declaration)
619/// or the location of the type in the source code (if, e.g., we're
620/// instantiating the type of a cast expression).
621///
622/// \param Entity the name of the entity associated with a declaration
623/// being instantiated (if any). May be empty to indicate that there
624/// is no such entity (if, e.g., this is a type that occurs as part of
625/// a cast expression) or that the entity has no name (e.g., an
626/// unnamed function parameter).
627///
628/// \returns If the instantiation succeeds, the instantiated
629/// type. Otherwise, produces diagnostics and returns a NULL type.
630QualType Sema::InstantiateType(QualType T,
631                               const TemplateArgumentList &TemplateArgs,
632                               SourceLocation Loc, DeclarationName Entity) {
633  assert(!ActiveTemplateInstantiations.empty() &&
634         "Cannot perform an instantiation without some context on the "
635         "instantiation stack");
636
637  // If T is not a dependent type, there is nothing to do.
638  if (!T->isDependentType())
639    return T;
640
641  TemplateTypeInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
642  return Instantiator(T);
643}
644
645/// \brief Instantiate the base class specifiers of the given class
646/// template specialization.
647///
648/// Produces a diagnostic and returns true on error, returns false and
649/// attaches the instantiated base classes to the class template
650/// specialization if successful.
651bool
652Sema::InstantiateBaseSpecifiers(CXXRecordDecl *Instantiation,
653                                CXXRecordDecl *Pattern,
654                                const TemplateArgumentList &TemplateArgs) {
655  bool Invalid = false;
656  llvm::SmallVector<CXXBaseSpecifier*, 8> InstantiatedBases;
657  for (ClassTemplateSpecializationDecl::base_class_iterator
658         Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
659       Base != BaseEnd; ++Base) {
660    if (!Base->getType()->isDependentType()) {
661      // FIXME: Allocate via ASTContext
662      InstantiatedBases.push_back(new CXXBaseSpecifier(*Base));
663      continue;
664    }
665
666    QualType BaseType = InstantiateType(Base->getType(),
667                                        TemplateArgs,
668                                        Base->getSourceRange().getBegin(),
669                                        DeclarationName());
670    if (BaseType.isNull()) {
671      Invalid = true;
672      continue;
673    }
674
675    if (CXXBaseSpecifier *InstantiatedBase
676          = CheckBaseSpecifier(Instantiation,
677                               Base->getSourceRange(),
678                               Base->isVirtual(),
679                               Base->getAccessSpecifierAsWritten(),
680                               BaseType,
681                               /*FIXME: Not totally accurate */
682                               Base->getSourceRange().getBegin()))
683      InstantiatedBases.push_back(InstantiatedBase);
684    else
685      Invalid = true;
686  }
687
688  if (!Invalid &&
689      AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
690                           InstantiatedBases.size()))
691    Invalid = true;
692
693  return Invalid;
694}
695
696/// \brief Instantiate the definition of a class from a given pattern.
697///
698/// \param PointOfInstantiation The point of instantiation within the
699/// source code.
700///
701/// \param Instantiation is the declaration whose definition is being
702/// instantiated. This will be either a class template specialization
703/// or a member class of a class template specialization.
704///
705/// \param Pattern is the pattern from which the instantiation
706/// occurs. This will be either the declaration of a class template or
707/// the declaration of a member class of a class template.
708///
709/// \param TemplateArgs The template arguments to be substituted into
710/// the pattern.
711///
712/// \returns true if an error occurred, false otherwise.
713bool
714Sema::InstantiateClass(SourceLocation PointOfInstantiation,
715                       CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
716                       const TemplateArgumentList &TemplateArgs,
717                       bool ExplicitInstantiation) {
718  bool Invalid = false;
719
720  CXXRecordDecl *PatternDef
721    = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
722  if (!PatternDef) {
723    if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
724      Diag(PointOfInstantiation,
725           diag::err_implicit_instantiate_member_undefined)
726        << Context.getTypeDeclType(Instantiation);
727      Diag(Pattern->getLocation(), diag::note_member_of_template_here);
728    } else {
729      Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
730        << ExplicitInstantiation
731        << Context.getTypeDeclType(Instantiation);
732      Diag(Pattern->getLocation(), diag::note_template_decl_here);
733    }
734    return true;
735  }
736  Pattern = PatternDef;
737
738  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
739  if (Inst)
740    return true;
741
742  // Enter the scope of this instantiation. We don't use
743  // PushDeclContext because we don't have a scope.
744  DeclContext *PreviousContext = CurContext;
745  CurContext = Instantiation;
746
747  // Start the definition of this instantiation.
748  Instantiation->startDefinition();
749
750  // Instantiate the base class specifiers.
751  if (InstantiateBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
752    Invalid = true;
753
754  llvm::SmallVector<DeclPtrTy, 32> Fields;
755  for (RecordDecl::decl_iterator Member = Pattern->decls_begin(Context),
756         MemberEnd = Pattern->decls_end(Context);
757       Member != MemberEnd; ++Member) {
758    Decl *NewMember = InstantiateDecl(*Member, Instantiation, TemplateArgs);
759    if (NewMember) {
760      if (NewMember->isInvalidDecl())
761        Invalid = true;
762      else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
763        Fields.push_back(DeclPtrTy::make(Field));
764    } else {
765      // FIXME: Eventually, a NULL return will mean that one of the
766      // instantiations was a semantic disaster, and we'll want to set Invalid =
767      // true. For now, we expect to skip some members that we can't yet handle.
768    }
769  }
770
771  // Finish checking fields.
772  ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation),
773              Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
774              0);
775
776  // Add any implicitly-declared members that we might need.
777  AddImplicitlyDeclaredMembersToClass(Instantiation);
778
779  // Exit the scope of this instantiation.
780  CurContext = PreviousContext;
781
782  // If this is an explicit instantiation, instantiate our members, too.
783  if (!Invalid && ExplicitInstantiation) {
784    Inst.Clear();
785    InstantiateClassMembers(PointOfInstantiation, Instantiation, TemplateArgs);
786  }
787
788  return Invalid;
789}
790
791bool
792Sema::InstantiateClassTemplateSpecialization(
793                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
794                           bool ExplicitInstantiation) {
795  // Perform the actual instantiation on the canonical declaration.
796  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
797                               Context.getCanonicalDecl(ClassTemplateSpec));
798
799  // We can only instantiate something that hasn't already been
800  // instantiated or specialized. Fail without any diagnostics: our
801  // caller will provide an error message.
802  if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared)
803    return true;
804
805  // FIXME: Push this class template instantiation onto the instantiation stack,
806  // checking for recursion that exceeds a certain depth.
807
808  // FIXME: Perform class template partial specialization to select the best
809  // template.
810  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
811
812  CXXRecordDecl *Pattern = Template->getTemplatedDecl();
813
814  // Note that this is an instantiation.
815  ClassTemplateSpec->setSpecializationKind(
816                        ExplicitInstantiation? TSK_ExplicitInstantiation
817                                             : TSK_ImplicitInstantiation);
818
819  return InstantiateClass(ClassTemplateSpec->getLocation(),
820                          ClassTemplateSpec, Pattern,
821                          ClassTemplateSpec->getTemplateArgs(),
822                          ExplicitInstantiation);
823}
824
825/// \brief Instantiate the definitions of all of the member of the
826/// given class, which is an instantiation of a class template or a
827/// member class of a template.
828void
829Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
830                              CXXRecordDecl *Instantiation,
831                              const TemplateArgumentList &TemplateArgs) {
832  for (DeclContext::decl_iterator D = Instantiation->decls_begin(Context),
833                               DEnd = Instantiation->decls_end(Context);
834       D != DEnd; ++D) {
835    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
836      if (!Function->getBody(Context))
837        InstantiateFunctionDefinition(PointOfInstantiation, Function);
838    } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
839      const VarDecl *Def = 0;
840      if (!Var->getDefinition(Def))
841        InstantiateVariableDefinition(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                          ClassTemplateSpec->getTemplateArgs());
870}
871
872/// \brief Instantiate a nested-name-specifier.
873NestedNameSpecifier *
874Sema::InstantiateNestedNameSpecifier(NestedNameSpecifier *NNS,
875                                     SourceRange Range,
876                                     const TemplateArgumentList &TemplateArgs) {
877  // Instantiate the prefix of this nested name specifier.
878  NestedNameSpecifier *Prefix = NNS->getPrefix();
879  if (Prefix) {
880    Prefix = InstantiateNestedNameSpecifier(Prefix, Range, TemplateArgs);
881    if (!Prefix)
882      return 0;
883  }
884
885  switch (NNS->getKind()) {
886  case NestedNameSpecifier::Identifier: {
887    assert(Prefix &&
888           "Can't have an identifier nested-name-specifier with no prefix");
889    CXXScopeSpec SS;
890    // FIXME: The source location information is all wrong.
891    SS.setRange(Range);
892    SS.setScopeRep(Prefix);
893    return static_cast<NestedNameSpecifier *>(
894                                 ActOnCXXNestedNameSpecifier(0, SS,
895                                                             Range.getEnd(),
896                                                             Range.getEnd(),
897                                                    *NNS->getAsIdentifier()));
898    break;
899  }
900
901  case NestedNameSpecifier::Namespace:
902  case NestedNameSpecifier::Global:
903    return NNS;
904
905  case NestedNameSpecifier::TypeSpecWithTemplate:
906  case NestedNameSpecifier::TypeSpec: {
907    QualType T = QualType(NNS->getAsType(), 0);
908    if (!T->isDependentType())
909      return NNS;
910
911    T = InstantiateType(T, TemplateArgs, Range.getBegin(), DeclarationName());
912    if (T.isNull())
913      return 0;
914
915    if (T->isRecordType() ||
916        (getLangOptions().CPlusPlus0x && T->isEnumeralType())) {
917      assert(T.getCVRQualifiers() == 0 && "Can't get cv-qualifiers here");
918      return NestedNameSpecifier::Create(Context, Prefix,
919                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
920                                         T.getTypePtr());
921    }
922
923    Diag(Range.getBegin(), diag::err_nested_name_spec_non_tag) << T;
924    return 0;
925  }
926  }
927
928  // Required to silence a GCC warning
929  return 0;
930}
931
932TemplateName
933Sema::InstantiateTemplateName(TemplateName Name, SourceLocation Loc,
934                              const TemplateArgumentList &TemplateArgs) {
935  if (TemplateTemplateParmDecl *TTP
936        = dyn_cast_or_null<TemplateTemplateParmDecl>(
937                                                 Name.getAsTemplateDecl())) {
938    assert(TTP->getDepth() == 0 &&
939           "Cannot reduce depth of a template template parameter");
940    assert(TemplateArgs[TTP->getPosition()].getAsDecl() &&
941           "Wrong kind of template template argument");
942    ClassTemplateDecl *ClassTemplate
943      = dyn_cast<ClassTemplateDecl>(
944                               TemplateArgs[TTP->getPosition()].getAsDecl());
945    assert(ClassTemplate && "Expected a class template");
946    if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
947      NestedNameSpecifier *NNS
948        = InstantiateNestedNameSpecifier(QTN->getQualifier(),
949                                         /*FIXME=*/SourceRange(Loc),
950                                         TemplateArgs);
951      if (NNS)
952        return Context.getQualifiedTemplateName(NNS,
953                                                QTN->hasTemplateKeyword(),
954                                                ClassTemplate);
955    }
956
957    return TemplateName(ClassTemplate);
958  } else if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
959    NestedNameSpecifier *NNS
960      = InstantiateNestedNameSpecifier(DTN->getQualifier(),
961                                       /*FIXME=*/SourceRange(Loc),
962                                       TemplateArgs);
963
964    if (!NNS) // FIXME: Not the best recovery strategy.
965      return Name;
966
967    if (NNS->isDependent())
968      return Context.getDependentTemplateName(NNS, DTN->getName());
969
970    // Somewhat redundant with ActOnDependentTemplateName.
971    CXXScopeSpec SS;
972    SS.setRange(SourceRange(Loc));
973    SS.setScopeRep(NNS);
974    TemplateTy Template;
975    TemplateNameKind TNK = isTemplateName(*DTN->getName(), 0, Template, &SS);
976    if (TNK == TNK_Non_template) {
977      Diag(Loc, diag::err_template_kw_refers_to_non_template)
978        << DTN->getName();
979      return Name;
980    } else if (TNK == TNK_Function_template) {
981      Diag(Loc, diag::err_template_kw_refers_to_non_template)
982        << DTN->getName();
983      return Name;
984    }
985
986    return Template.getAsVal<TemplateName>();
987  }
988
989
990
991  // FIXME: Even if we're referring to a Decl that isn't a template template
992  // parameter, we may need to instantiate the outer contexts of that
993  // Decl. However, this won't be needed until we implement member templates.
994  return Name;
995}
996