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