SemaTemplateInstantiate.cpp revision c45057a4b1aae40e5b63424444cb2615a1bc4399
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/ExprCXX.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/StmtVisitor.h"
19#include "clang/Parse/DeclSpec.h"
20#include "clang/Lex/Preprocessor.h" // for the identifier table
21#include "clang/Basic/LangOptions.h"
22#include "llvm/Support/Compiler.h"
23
24using namespace clang;
25
26//===----------------------------------------------------------------------===/
27// Template Instantiation Support
28//===----------------------------------------------------------------------===/
29
30Sema::InstantiatingTemplate::
31InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
32                      ClassTemplateSpecializationDecl *Entity,
33                      SourceRange InstantiationRange)
34  :  SemaRef(SemaRef) {
35
36  Invalid = CheckInstantiationDepth(PointOfInstantiation,
37                                    InstantiationRange);
38  if (!Invalid) {
39    ActiveTemplateInstantiation Inst;
40    Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
41    Inst.PointOfInstantiation = PointOfInstantiation;
42    Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
43    Inst.TemplateArgs = 0;
44    Inst.NumTemplateArgs = 0;
45    Inst.InstantiationRange = InstantiationRange;
46    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
47    Invalid = false;
48  }
49}
50
51Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
52                                         SourceLocation PointOfInstantiation,
53                                         TemplateDecl *Template,
54                                         const TemplateArgument *TemplateArgs,
55                                         unsigned NumTemplateArgs,
56                                         SourceRange InstantiationRange)
57  : SemaRef(SemaRef) {
58
59  Invalid = CheckInstantiationDepth(PointOfInstantiation,
60                                    InstantiationRange);
61  if (!Invalid) {
62    ActiveTemplateInstantiation Inst;
63    Inst.Kind
64      = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
65    Inst.PointOfInstantiation = PointOfInstantiation;
66    Inst.Entity = reinterpret_cast<uintptr_t>(Template);
67    Inst.TemplateArgs = TemplateArgs;
68    Inst.NumTemplateArgs = NumTemplateArgs;
69    Inst.InstantiationRange = InstantiationRange;
70    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
71    Invalid = false;
72  }
73}
74
75Sema::InstantiatingTemplate::~InstantiatingTemplate() {
76  if (!Invalid)
77    SemaRef.ActiveTemplateInstantiations.pop_back();
78}
79
80bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
81                                        SourceLocation PointOfInstantiation,
82                                           SourceRange InstantiationRange) {
83  if (SemaRef.ActiveTemplateInstantiations.size()
84       <= SemaRef.getLangOptions().InstantiationDepth)
85    return false;
86
87  SemaRef.Diag(PointOfInstantiation,
88               diag::err_template_recursion_depth_exceeded)
89    << SemaRef.getLangOptions().InstantiationDepth
90    << InstantiationRange;
91  SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
92    << SemaRef.getLangOptions().InstantiationDepth;
93  return true;
94}
95
96/// \brief Post-diagnostic hook for printing the instantiation stack.
97void Sema::PrintInstantiationStackHook(unsigned, void *Cookie) {
98  Sema &SemaRef = *static_cast<Sema*>(Cookie);
99  SemaRef.PrintInstantiationStack();
100  SemaRef.LastTemplateInstantiationErrorContext
101    = SemaRef.ActiveTemplateInstantiations.back();
102}
103
104/// \brief Prints the current instantiation stack through a series of
105/// notes.
106void Sema::PrintInstantiationStack() {
107  for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
108         Active = ActiveTemplateInstantiations.rbegin(),
109         ActiveEnd = ActiveTemplateInstantiations.rend();
110       Active != ActiveEnd;
111       ++Active) {
112    switch (Active->Kind) {
113    case ActiveTemplateInstantiation::TemplateInstantiation: {
114      ClassTemplateSpecializationDecl *Spec
115        = cast<ClassTemplateSpecializationDecl>((Decl*)Active->Entity);
116      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
117                   diag::note_template_class_instantiation_here)
118        << Context.getTypeDeclType(Spec)
119        << Active->InstantiationRange;
120      break;
121    }
122
123    case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
124      TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
125      std::string TemplateArgsStr
126        = ClassTemplateSpecializationType::PrintTemplateArgumentList(
127                                                      Active->TemplateArgs,
128                                                      Active->NumTemplateArgs);
129      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
130                   diag::note_default_arg_instantiation_here)
131        << (Template->getNameAsString() + TemplateArgsStr)
132        << Active->InstantiationRange;
133      break;
134    }
135    }
136  }
137}
138
139//===----------------------------------------------------------------------===/
140// Template Instantiation for Types
141//===----------------------------------------------------------------------===/
142namespace {
143  class VISIBILITY_HIDDEN TemplateTypeInstantiator {
144    Sema &SemaRef;
145    const TemplateArgument *TemplateArgs;
146    unsigned NumTemplateArgs;
147    SourceLocation Loc;
148    DeclarationName Entity;
149
150  public:
151    TemplateTypeInstantiator(Sema &SemaRef,
152                             const TemplateArgument *TemplateArgs,
153                             unsigned NumTemplateArgs,
154                             SourceLocation Loc,
155                             DeclarationName Entity)
156      : SemaRef(SemaRef), TemplateArgs(TemplateArgs),
157        NumTemplateArgs(NumTemplateArgs), Loc(Loc), Entity(Entity) { }
158
159    QualType operator()(QualType T) const { return Instantiate(T); }
160
161    QualType Instantiate(QualType T) const;
162
163    // Declare instantiate functions for each type.
164#define TYPE(Class, Base)                                       \
165    QualType Instantiate##Class##Type(const Class##Type *T,     \
166                                      unsigned Quals) const;
167#define ABSTRACT_TYPE(Class, Base)
168#include "clang/AST/TypeNodes.def"
169  };
170}
171
172QualType
173TemplateTypeInstantiator::InstantiateExtQualType(const ExtQualType *T,
174                                                 unsigned Quals) const {
175  // FIXME: Implement this
176  assert(false && "Cannot instantiate ExtQualType yet");
177  return QualType();
178}
179
180QualType
181TemplateTypeInstantiator::InstantiateBuiltinType(const BuiltinType *T,
182                                                 unsigned Quals) const {
183  assert(false && "Builtin types are not dependent and cannot be instantiated");
184  return QualType(T, Quals);
185}
186
187QualType
188TemplateTypeInstantiator::
189InstantiateFixedWidthIntType(const FixedWidthIntType *T, unsigned Quals) const {
190  // FIXME: Implement this
191  assert(false && "Cannot instantiate FixedWidthIntType yet");
192  return QualType();
193}
194
195QualType
196TemplateTypeInstantiator::InstantiateComplexType(const ComplexType *T,
197                                                 unsigned Quals) const {
198  // FIXME: Implement this
199  assert(false && "Cannot instantiate ComplexType yet");
200  return QualType();
201}
202
203QualType
204TemplateTypeInstantiator::InstantiatePointerType(const PointerType *T,
205                                                 unsigned Quals) const {
206  QualType PointeeType = Instantiate(T->getPointeeType());
207  if (PointeeType.isNull())
208    return QualType();
209
210  return SemaRef.BuildPointerType(PointeeType, Quals, Loc, Entity);
211}
212
213QualType
214TemplateTypeInstantiator::InstantiateBlockPointerType(const BlockPointerType *T,
215                                                      unsigned Quals) const {
216  // FIXME: Implement this
217  assert(false && "Cannot instantiate BlockPointerType yet");
218  return QualType();
219}
220
221QualType
222TemplateTypeInstantiator::InstantiateReferenceType(const ReferenceType *T,
223                                                   unsigned Quals) const {
224  QualType ReferentType = Instantiate(T->getPointeeType());
225  if (ReferentType.isNull())
226    return QualType();
227
228  return SemaRef.BuildReferenceType(ReferentType, Quals, Loc, Entity);
229}
230
231QualType
232TemplateTypeInstantiator::
233InstantiateMemberPointerType(const MemberPointerType *T,
234                             unsigned Quals) const {
235  // FIXME: Implement this
236  assert(false && "Cannot instantiate MemberPointerType yet");
237  return QualType();
238}
239
240QualType
241TemplateTypeInstantiator::
242InstantiateConstantArrayType(const ConstantArrayType *T,
243                             unsigned Quals) const {
244  QualType ElementType = Instantiate(T->getElementType());
245  if (ElementType.isNull())
246    return ElementType;
247
248  // Build a temporary integer literal to specify the size for
249  // BuildArrayType. Since we have already checked the size as part of
250  // creating the dependent array type in the first place, we know
251  // there aren't any errors.
252  // FIXME: Is IntTy big enough? Maybe not, but LongLongTy causes
253  // problems that I have yet to investigate.
254  IntegerLiteral ArraySize(T->getSize(), SemaRef.Context.IntTy, Loc);
255  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
256                                &ArraySize, T->getIndexTypeQualifier(),
257                                Loc, Entity);
258}
259
260QualType
261TemplateTypeInstantiator::
262InstantiateIncompleteArrayType(const IncompleteArrayType *T,
263                               unsigned Quals) const {
264  QualType ElementType = Instantiate(T->getElementType());
265  if (ElementType.isNull())
266    return ElementType;
267
268  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
269                                0, T->getIndexTypeQualifier(),
270                                Loc, Entity);
271}
272
273QualType
274TemplateTypeInstantiator::
275InstantiateVariableArrayType(const VariableArrayType *T,
276                             unsigned Quals) const {
277  // FIXME: Implement this
278  assert(false && "Cannot instantiate VariableArrayType yet");
279  return QualType();
280}
281
282QualType
283TemplateTypeInstantiator::
284InstantiateDependentSizedArrayType(const DependentSizedArrayType *T,
285                                   unsigned Quals) const {
286  // FIXME: Implement this
287  assert(false && "Cannot instantiate DependentSizedArrayType yet");
288  return QualType();
289}
290
291QualType
292TemplateTypeInstantiator::InstantiateVectorType(const VectorType *T,
293                                             unsigned Quals) const {
294  // FIXME: Implement this
295  assert(false && "Cannot instantiate VectorType yet");
296  return QualType();
297}
298
299QualType
300TemplateTypeInstantiator::InstantiateExtVectorType(const ExtVectorType *T,
301                                                   unsigned Quals) const {
302  // FIXME: Implement this
303  assert(false && "Cannot instantiate ExtVectorType yet");
304  return QualType();
305}
306
307QualType
308TemplateTypeInstantiator::
309InstantiateFunctionProtoType(const FunctionProtoType *T,
310                             unsigned Quals) const {
311  QualType ResultType = Instantiate(T->getResultType());
312  if (ResultType.isNull())
313    return ResultType;
314
315  llvm::SmallVector<QualType, 16> ParamTypes;
316  for (FunctionProtoType::arg_type_iterator Param = T->arg_type_begin(),
317                                         ParamEnd = T->arg_type_end();
318       Param != ParamEnd; ++Param) {
319    QualType P = Instantiate(*Param);
320    if (P.isNull())
321      return P;
322
323    ParamTypes.push_back(P);
324  }
325
326  return SemaRef.BuildFunctionType(ResultType, &ParamTypes[0],
327                                   ParamTypes.size(),
328                                   T->isVariadic(), T->getTypeQuals(),
329                                   Loc, Entity);
330}
331
332QualType
333TemplateTypeInstantiator::
334InstantiateFunctionNoProtoType(const FunctionNoProtoType *T,
335                               unsigned Quals) const {
336  assert(false && "Functions without prototypes cannot be dependent.");
337  return QualType();
338}
339
340QualType
341TemplateTypeInstantiator::InstantiateTypedefType(const TypedefType *T,
342                                                 unsigned Quals) const {
343  // FIXME: Implement this
344  assert(false && "Cannot instantiate TypedefType yet");
345  return QualType();
346}
347
348QualType
349TemplateTypeInstantiator::InstantiateTypeOfExprType(const TypeOfExprType *T,
350                                                    unsigned Quals) const {
351  // FIXME: Implement this
352  assert(false && "Cannot instantiate TypeOfExprType yet");
353  return QualType();
354}
355
356QualType
357TemplateTypeInstantiator::InstantiateTypeOfType(const TypeOfType *T,
358                                                unsigned Quals) const {
359  // FIXME: Implement this
360  assert(false && "Cannot instantiate TypeOfType yet");
361  return QualType();
362}
363
364QualType
365TemplateTypeInstantiator::InstantiateRecordType(const RecordType *T,
366                                                unsigned Quals) const {
367  // FIXME: Implement this
368  assert(false && "Cannot instantiate RecordType yet");
369  return QualType();
370}
371
372QualType
373TemplateTypeInstantiator::InstantiateEnumType(const EnumType *T,
374                                              unsigned Quals) const {
375  // FIXME: Implement this
376  assert(false && "Cannot instantiate EnumType yet");
377  return QualType();
378}
379
380QualType
381TemplateTypeInstantiator::
382InstantiateTemplateTypeParmType(const TemplateTypeParmType *T,
383                                unsigned Quals) const {
384  if (T->getDepth() == 0) {
385    // Replace the template type parameter with its corresponding
386    // template argument.
387    assert(T->getIndex() < NumTemplateArgs && "Wrong # of template args");
388    assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type &&
389           "Template argument kind mismatch");
390    QualType Result = TemplateArgs[T->getIndex()].getAsType();
391    if (Result.isNull() || !Quals)
392      return Result;
393
394    // C++ [dcl.ref]p1:
395    //   [...] Cv-qualified references are ill-formed except when
396    //   the cv-qualifiers are introduced through the use of a
397    //   typedef (7.1.3) or of a template type argument (14.3), in
398    //   which case the cv-qualifiers are ignored.
399    if (Quals && Result->isReferenceType())
400      Quals = 0;
401
402    return QualType(Result.getTypePtr(), Quals | Result.getCVRQualifiers());
403  }
404
405  // The template type parameter comes from an inner template (e.g.,
406  // the template parameter list of a member template inside the
407  // template we are instantiating). Create a new template type
408  // parameter with the template "level" reduced by one.
409  return SemaRef.Context.getTemplateTypeParmType(T->getDepth() - 1,
410                                                 T->getIndex(),
411                                                 T->getName())
412    .getQualifiedType(Quals);
413}
414
415QualType
416TemplateTypeInstantiator::
417InstantiateClassTemplateSpecializationType(
418                                  const ClassTemplateSpecializationType *T,
419                                  unsigned Quals) const {
420  llvm::SmallVector<TemplateArgument, 16> InstantiatedTemplateArgs;
421  InstantiatedTemplateArgs.reserve(T->getNumArgs());
422  for (ClassTemplateSpecializationType::iterator Arg = T->begin(),
423                                              ArgEnd = T->end();
424       Arg != ArgEnd; ++Arg) {
425    switch (Arg->getKind()) {
426    case TemplateArgument::Type: {
427      QualType T = SemaRef.InstantiateType(Arg->getAsType(),
428                                           TemplateArgs, NumTemplateArgs,
429                                           Arg->getLocation(),
430                                           DeclarationName());
431      if (T.isNull())
432        return QualType();
433
434      InstantiatedTemplateArgs.push_back(
435                                TemplateArgument(Arg->getLocation(), T));
436      break;
437    }
438
439    case TemplateArgument::Declaration:
440    case TemplateArgument::Integral:
441      InstantiatedTemplateArgs.push_back(*Arg);
442      break;
443
444    case TemplateArgument::Expression:
445      Sema::OwningExprResult E
446        = SemaRef.InstantiateExpr(Arg->getAsExpr(), TemplateArgs,
447                                  NumTemplateArgs);
448      if (E.isInvalid())
449        return QualType();
450      InstantiatedTemplateArgs.push_back((Expr *)E.release());
451      break;
452    }
453  }
454
455  // FIXME: We're missing the locations of the template name, '<', and
456  // '>'.
457  return SemaRef.CheckClassTemplateId(cast<ClassTemplateDecl>(T->getTemplate()),
458                                      Loc,
459                                      SourceLocation(),
460                                      &InstantiatedTemplateArgs[0],
461                                      InstantiatedTemplateArgs.size(),
462                                      SourceLocation());
463}
464
465QualType
466TemplateTypeInstantiator::
467InstantiateObjCInterfaceType(const ObjCInterfaceType *T,
468                             unsigned Quals) const {
469  assert(false && "Objective-C types cannot be dependent");
470  return QualType();
471}
472
473QualType
474TemplateTypeInstantiator::
475InstantiateObjCQualifiedInterfaceType(const ObjCQualifiedInterfaceType *T,
476                                      unsigned Quals) const {
477  assert(false && "Objective-C types cannot be dependent");
478  return QualType();
479}
480
481QualType
482TemplateTypeInstantiator::
483InstantiateObjCQualifiedIdType(const ObjCQualifiedIdType *T,
484                               unsigned Quals) const {
485  assert(false && "Objective-C types cannot be dependent");
486  return QualType();
487}
488
489QualType
490TemplateTypeInstantiator::
491InstantiateObjCQualifiedClassType(const ObjCQualifiedClassType *T,
492                                  unsigned Quals) const {
493  assert(false && "Objective-C types cannot be dependent");
494  return QualType();
495}
496
497/// \brief The actual implementation of Sema::InstantiateType().
498QualType TemplateTypeInstantiator::Instantiate(QualType T) const {
499  // If T is not a dependent type, there is nothing to do.
500  if (!T->isDependentType())
501    return T;
502
503  switch (T->getTypeClass()) {
504#define TYPE(Class, Base)                                               \
505  case Type::Class:                                                     \
506    return Instantiate##Class##Type(cast<Class##Type>(T.getTypePtr()),  \
507                                    T.getCVRQualifiers());
508#define ABSTRACT_TYPE(Class, Base)
509#include "clang/AST/TypeNodes.def"
510  }
511
512  assert(false && "Not all types have been decoded for instantiation");
513  return QualType();
514}
515
516/// \brief Instantiate the type T with a given set of template arguments.
517///
518/// This routine substitutes the given template arguments into the
519/// type T and produces the instantiated type.
520///
521/// \param T the type into which the template arguments will be
522/// substituted. If this type is not dependent, it will be returned
523/// immediately.
524///
525/// \param TemplateArgs the template arguments that will be
526/// substituted for the top-level template parameters within T.
527///
528/// \param NumTemplateArgs the number of template arguments provided
529/// by TemplateArgs.
530///
531/// \param Loc the location in the source code where this substitution
532/// is being performed. It will typically be the location of the
533/// declarator (if we're instantiating the type of some declaration)
534/// or the location of the type in the source code (if, e.g., we're
535/// instantiating the type of a cast expression).
536///
537/// \param Entity the name of the entity associated with a declaration
538/// being instantiated (if any). May be empty to indicate that there
539/// is no such entity (if, e.g., this is a type that occurs as part of
540/// a cast expression) or that the entity has no name (e.g., an
541/// unnamed function parameter).
542///
543/// \returns If the instantiation succeeds, the instantiated
544/// type. Otherwise, produces diagnostics and returns a NULL type.
545QualType Sema::InstantiateType(QualType T,
546                               const TemplateArgument *TemplateArgs,
547                               unsigned NumTemplateArgs,
548                               SourceLocation Loc, DeclarationName Entity) {
549  assert(!ActiveTemplateInstantiations.empty() &&
550         "Cannot perform an instantiation without some context on the "
551         "instantiation stack");
552
553  // If T is not a dependent type, there is nothing to do.
554  if (!T->isDependentType())
555    return T;
556
557  TemplateTypeInstantiator Instantiator(*this, TemplateArgs, NumTemplateArgs,
558                                        Loc, Entity);
559  return Instantiator(T);
560}
561
562//===----------------------------------------------------------------------===/
563// Template Instantiation for Expressions
564//===----------------------------------------------------------------------===/
565namespace {
566  class VISIBILITY_HIDDEN TemplateExprInstantiator
567    : public StmtVisitor<TemplateExprInstantiator, Sema::OwningExprResult> {
568    Sema &SemaRef;
569    const TemplateArgument *TemplateArgs;
570    unsigned NumTemplateArgs;
571
572  public:
573    typedef Sema::OwningExprResult OwningExprResult;
574
575    TemplateExprInstantiator(Sema &SemaRef,
576                             const TemplateArgument *TemplateArgs,
577                             unsigned NumTemplateArgs)
578      : SemaRef(SemaRef), TemplateArgs(TemplateArgs),
579        NumTemplateArgs(NumTemplateArgs) { }
580
581    // FIXME: Once we get closer to completion, replace these
582    // manually-written declarations with automatically-generated ones
583    // from clang/AST/StmtNodes.def.
584    OwningExprResult VisitIntegerLiteral(IntegerLiteral *E);
585    OwningExprResult VisitDeclRefExpr(DeclRefExpr *E);
586    OwningExprResult VisitParenExpr(ParenExpr *E);
587    OwningExprResult VisitUnaryOperator(UnaryOperator *E);
588    OwningExprResult VisitBinaryOperator(BinaryOperator *E);
589    OwningExprResult VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
590    OwningExprResult VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
591    OwningExprResult VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
592
593    // Base case. I'm supposed to ignore this.
594    Sema::OwningExprResult VisitStmt(Stmt *S) {
595      S->dump();
596      assert(false && "Cannot instantiate this kind of expression");
597      return SemaRef.ExprError();
598    }
599  };
600}
601
602Sema::OwningExprResult
603TemplateExprInstantiator::VisitIntegerLiteral(IntegerLiteral *E) {
604  return SemaRef.Clone(E);
605}
606
607Sema::OwningExprResult
608TemplateExprInstantiator::VisitDeclRefExpr(DeclRefExpr *E) {
609  Decl *D = E->getDecl();
610  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
611    assert(NTTP->getDepth() == 0 && "No nested templates yet");
612    const TemplateArgument &Arg = TemplateArgs[NTTP->getPosition()];
613    return SemaRef.Owned(new (SemaRef.Context) IntegerLiteral(
614                                                 *Arg.getAsIntegral(),
615                                                 Arg.getIntegralType(),
616                                       E->getSourceRange().getBegin()));
617  } else
618    assert(false && "Can't handle arbitrary declaration references");
619
620  return SemaRef.ExprError();
621}
622
623Sema::OwningExprResult
624TemplateExprInstantiator::VisitParenExpr(ParenExpr *E) {
625  Sema::OwningExprResult SubExpr
626    = SemaRef.InstantiateExpr(E->getSubExpr(), TemplateArgs, NumTemplateArgs);
627  if (SubExpr.isInvalid())
628    return SemaRef.ExprError();
629
630  return SemaRef.Owned(new (SemaRef.Context) ParenExpr(
631                                               E->getLParen(), E->getRParen(),
632                                               (Expr *)SubExpr.release()));
633}
634
635Sema::OwningExprResult
636TemplateExprInstantiator::VisitUnaryOperator(UnaryOperator *E) {
637  Sema::OwningExprResult Arg = Visit(E->getSubExpr());
638  if (Arg.isInvalid())
639    return SemaRef.ExprError();
640
641  return SemaRef.CreateBuiltinUnaryOp(E->getOperatorLoc(),
642                                      E->getOpcode(),
643                                      move(Arg));
644}
645
646Sema::OwningExprResult
647TemplateExprInstantiator::VisitBinaryOperator(BinaryOperator *E) {
648  Sema::OwningExprResult LHS = Visit(E->getLHS());
649  if (LHS.isInvalid())
650    return SemaRef.ExprError();
651
652  Sema::OwningExprResult RHS = Visit(E->getRHS());
653  if (RHS.isInvalid())
654    return SemaRef.ExprError();
655
656  Sema::OwningExprResult Result
657    = SemaRef.CreateBuiltinBinOp(E->getOperatorLoc(),
658                                 E->getOpcode(),
659                                 (Expr *)LHS.get(),
660                                 (Expr *)RHS.get());
661  if (Result.isInvalid())
662    return SemaRef.ExprError();
663
664  LHS.release();
665  RHS.release();
666  return move(Result);
667}
668
669Sema::OwningExprResult
670TemplateExprInstantiator::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
671  Sema::OwningExprResult First = Visit(E->getArg(0));
672  if (First.isInvalid())
673    return SemaRef.ExprError();
674
675  Expr *Args[2] = { (Expr *)First.get(), 0 };
676
677  Sema::OwningExprResult Second(SemaRef);
678  if (E->getNumArgs() == 2) {
679    Second = Visit(E->getArg(1));
680
681    if (Second.isInvalid())
682      return SemaRef.ExprError();
683
684    Args[1] = (Expr *)Second.get();
685  }
686
687  if (!E->isTypeDependent()) {
688    // Since our original expression was not type-dependent, we do not
689    // perform lookup again at instantiation time (C++ [temp.dep]p1).
690    // Instead, we just build the new overloaded operator call
691    // expression.
692    First.release();
693    Second.release();
694    return SemaRef.Owned(new (SemaRef.Context) CXXOperatorCallExpr(
695                                                       SemaRef.Context,
696                                                       E->getOperator(),
697                                                       E->getCallee(),
698                                                       Args, E->getNumArgs(),
699                                                       E->getType(),
700                                                       E->getOperatorLoc()));
701  }
702
703  bool isPostIncDec = E->getNumArgs() == 2 &&
704    (E->getOperator() == OO_PlusPlus || E->getOperator() == OO_MinusMinus);
705  if (E->getNumArgs() == 1 || isPostIncDec) {
706    if (!Args[0]->getType()->isOverloadableType()) {
707      // The argument is not of overloadable type, so try to create a
708      // built-in unary operation.
709      UnaryOperator::Opcode Opc
710        = UnaryOperator::getOverloadedOpcode(E->getOperator(), isPostIncDec);
711
712      return SemaRef.CreateBuiltinUnaryOp(E->getOperatorLoc(), Opc,
713                                          move(First));
714    }
715
716    // Fall through to perform overload resolution
717  } else {
718    assert(E->getNumArgs() == 2 && "Expected binary operation");
719
720    Sema::OwningExprResult Result(SemaRef);
721    if (!Args[0]->getType()->isOverloadableType() &&
722        !Args[1]->getType()->isOverloadableType()) {
723      // Neither of the arguments is an overloadable type, so try to
724      // create a built-in binary operation.
725      BinaryOperator::Opcode Opc =
726        BinaryOperator::getOverloadedOpcode(E->getOperator());
727      Result = SemaRef.CreateBuiltinBinOp(E->getOperatorLoc(), Opc,
728                                          Args[0], Args[1]);
729      if (Result.isInvalid())
730        return SemaRef.ExprError();
731
732      First.release();
733      Second.release();
734      return move(Result);
735    }
736
737    // Fall through to perform overload resolution.
738  }
739
740  // Compute the set of functions that were found at template
741  // definition time.
742  Sema::FunctionSet Functions;
743  DeclRefExpr *DRE = cast<DeclRefExpr>(E->getCallee());
744  OverloadedFunctionDecl *Overloads
745    = cast<OverloadedFunctionDecl>(DRE->getDecl());
746
747  // FIXME: Do we have to check
748  // IsAcceptableNonMemberOperatorCandidate for each of these?
749  for (OverloadedFunctionDecl::function_iterator
750         F = Overloads->function_begin(),
751         FEnd = Overloads->function_end();
752       F != FEnd; ++F)
753    Functions.insert(*F);
754
755  // Add any functions found via argument-dependent lookup.
756  DeclarationName OpName
757    = SemaRef.Context.DeclarationNames.getCXXOperatorName(E->getOperator());
758  SemaRef.ArgumentDependentLookup(OpName, Args, E->getNumArgs(), Functions);
759
760  // Create the overloaded operator invocation.
761  if (E->getNumArgs() == 1 || isPostIncDec) {
762    UnaryOperator::Opcode Opc
763      = UnaryOperator::getOverloadedOpcode(E->getOperator(), isPostIncDec);
764    return SemaRef.CreateOverloadedUnaryOp(E->getOperatorLoc(), Opc,
765                                           Functions, move(First));
766  }
767
768  // FIXME: This would be far less ugly if CreateOverloadedBinOp took
769  // in ExprArg arguments!
770  BinaryOperator::Opcode Opc =
771    BinaryOperator::getOverloadedOpcode(E->getOperator());
772  OwningExprResult Result
773    = SemaRef.CreateOverloadedBinOp(E->getOperatorLoc(), Opc,
774                                    Functions, Args[0], Args[1]);
775
776  if (Result.isInvalid())
777    return SemaRef.ExprError();
778
779  First.release();
780  Second.release();
781  return move(Result);
782}
783
784Sema::OwningExprResult
785TemplateExprInstantiator::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
786  bool isSizeOf = E->isSizeOf();
787
788  if (E->isArgumentType()) {
789    QualType T = E->getArgumentType();
790    if (T->isDependentType()) {
791      T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs,
792                                  /*FIXME*/E->getOperatorLoc(),
793                                  &SemaRef.PP.getIdentifierTable().get("sizeof"));
794      if (T.isNull())
795        return SemaRef.ExprError();
796    }
797
798    return SemaRef.CreateSizeOfAlignOfExpr(T, E->getOperatorLoc(), isSizeOf,
799                                           E->getSourceRange());
800  }
801
802  Sema::OwningExprResult Arg = Visit(E->getArgumentExpr());
803  if (Arg.isInvalid())
804    return SemaRef.ExprError();
805
806  Sema::OwningExprResult Result
807    = SemaRef.CreateSizeOfAlignOfExpr((Expr *)Arg.get(), E->getOperatorLoc(),
808                                      isSizeOf, E->getSourceRange());
809  if (Result.isInvalid())
810    return SemaRef.ExprError();
811
812  Arg.release();
813  return move(Result);
814}
815
816Sema::OwningExprResult
817TemplateExprInstantiator::VisitCXXTemporaryObjectExpr(
818                                                  CXXTemporaryObjectExpr *E) {
819  QualType T = E->getType();
820  if (T->isDependentType()) {
821    T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs,
822                                E->getTypeBeginLoc(), DeclarationName());
823    if (T.isNull())
824      return SemaRef.ExprError();
825  }
826
827  llvm::SmallVector<Expr *, 16> Args;
828  Args.reserve(E->getNumArgs());
829  bool Invalid = false;
830  for (CXXTemporaryObjectExpr::arg_iterator Arg = E->arg_begin(),
831                                         ArgEnd = E->arg_end();
832       Arg != ArgEnd; ++Arg) {
833    OwningExprResult InstantiatedArg = Visit(*Arg);
834    if (InstantiatedArg.isInvalid()) {
835      Invalid = true;
836      break;
837    }
838
839    Args.push_back((Expr *)InstantiatedArg.release());
840  }
841
842  if (!Invalid) {
843    SourceLocation CommaLoc;
844    // FIXME: HACK!
845    if (Args.size() > 1)
846      CommaLoc
847        = SemaRef.PP.getLocForEndOfToken(Args[0]->getSourceRange().getEnd());
848    Sema::OwningExprResult Result(
849      SemaRef.ActOnCXXTypeConstructExpr(SourceRange(E->getTypeBeginLoc()
850                                                    /*, FIXME*/),
851                                        T.getAsOpaquePtr(),
852                                        /*FIXME*/E->getTypeBeginLoc(),
853                                        Sema::MultiExprArg(SemaRef,
854                                                           (void**)&Args[0],
855                                                           Args.size()),
856                                        /*HACK*/&CommaLoc,
857                                        E->getSourceRange().getEnd()));
858    // At this point, Args no longer owns the arguments, no matter what.
859    return move(Result);
860  }
861
862  // Clean up the instantiated arguments.
863  // FIXME: Would rather do this with RAII.
864  for (unsigned Idx = 0; Idx < Args.size(); ++Idx)
865    SemaRef.DeleteExpr(Args[Idx]);
866
867  return SemaRef.ExprError();
868}
869
870Sema::OwningExprResult
871Sema::InstantiateExpr(Expr *E, const TemplateArgument *TemplateArgs,
872                      unsigned NumTemplateArgs) {
873  TemplateExprInstantiator Instantiator(*this, TemplateArgs, NumTemplateArgs);
874  return Instantiator.Visit(E);
875}
876
877/// \brief Instantiate the base class specifiers of the given class
878/// template specialization.
879///
880/// Produces a diagnostic and returns true on error, returns false and
881/// attaches the instantiated base classes to the class template
882/// specialization if successful.
883bool
884Sema::InstantiateBaseSpecifiers(
885                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
886                           ClassTemplateDecl *ClassTemplate) {
887  bool Invalid = false;
888  llvm::SmallVector<CXXBaseSpecifier*, 8> InstantiatedBases;
889  for (ClassTemplateSpecializationDecl::base_class_iterator
890         Base = ClassTemplate->getTemplatedDecl()->bases_begin(),
891         BaseEnd = ClassTemplate->getTemplatedDecl()->bases_end();
892       Base != BaseEnd; ++Base) {
893    if (!Base->getType()->isDependentType()) {
894      // FIXME: Allocate via ASTContext
895      InstantiatedBases.push_back(new CXXBaseSpecifier(*Base));
896      continue;
897    }
898
899    QualType BaseType = InstantiateType(Base->getType(),
900                                        ClassTemplateSpec->getTemplateArgs(),
901                                        ClassTemplateSpec->getNumTemplateArgs(),
902                                        Base->getSourceRange().getBegin(),
903                                        DeclarationName());
904    if (BaseType.isNull()) {
905      Invalid = true;
906      continue;
907    }
908
909    if (CXXBaseSpecifier *InstantiatedBase
910          = CheckBaseSpecifier(ClassTemplateSpec,
911                               Base->getSourceRange(),
912                               Base->isVirtual(),
913                               Base->getAccessSpecifierAsWritten(),
914                               BaseType,
915                               /*FIXME: Not totally accurate */
916                               Base->getSourceRange().getBegin()))
917      InstantiatedBases.push_back(InstantiatedBase);
918    else
919      Invalid = true;
920  }
921
922  if (!Invalid &&
923      AttachBaseSpecifiers(ClassTemplateSpec, &InstantiatedBases[0],
924                           InstantiatedBases.size()))
925    Invalid = true;
926
927  return Invalid;
928}
929
930bool
931Sema::InstantiateClassTemplateSpecialization(
932                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
933                           bool ExplicitInstantiation) {
934  // Perform the actual instantiation on the canonical declaration.
935  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
936                               Context.getCanonicalDecl(ClassTemplateSpec));
937
938  // We can only instantiate something that hasn't already been
939  // instantiated or specialized. Fail without any diagnostics: our
940  // caller will provide an error message.
941  if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared)
942    return true;
943
944  // FIXME: Push this class template instantiation onto the
945  // instantiation stack, checking for recursion that exceeds a
946  // certain depth.
947
948  // FIXME: Perform class template partial specialization to select
949  // the best template.
950  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
951
952  if (!Template->getTemplatedDecl()->getDefinition(Context)) {
953    Diag(ClassTemplateSpec->getLocation(),
954         diag::err_template_implicit_instantiate_undefined)
955      << Context.getTypeDeclType(ClassTemplateSpec);
956    Diag(Template->getTemplatedDecl()->getLocation(),
957         diag::note_template_decl_here);
958    return true;
959  }
960
961  // Note that this is an instantiation.
962  ClassTemplateSpec->setSpecializationKind(
963                        ExplicitInstantiation? TSK_ExplicitInstantiation
964                                             : TSK_ImplicitInstantiation);
965
966
967  bool Invalid = false;
968
969  InstantiatingTemplate Inst(*this, ClassTemplateSpec->getLocation(),
970                             ClassTemplateSpec);
971  if (Inst)
972    return true;
973
974  // Enter the scope of this instantiation. We don't use
975  // PushDeclContext because we don't have a scope.
976  DeclContext *PreviousContext = CurContext;
977  CurContext = ClassTemplateSpec;
978
979  // Start the definition of this instantiation.
980  ClassTemplateSpec->startDefinition();
981
982
983  // Instantiate the base class specifiers.
984  if (InstantiateBaseSpecifiers(ClassTemplateSpec, Template))
985    Invalid = true;
986
987  // FIXME: Create the injected-class-name for the
988  // instantiation. Should this be a typedef or something like it?
989
990  RecordDecl *Pattern = Template->getTemplatedDecl();
991  llvm::SmallVector<DeclTy *, 32> Fields;
992  for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
993                              MemberEnd = Pattern->decls_end();
994       Member != MemberEnd; ++Member) {
995    if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(*Member)) {
996      // FIXME: Simplified instantiation of typedefs needs to be made
997      // "real".
998      QualType T = Typedef->getUnderlyingType();
999      if (T->isDependentType()) {
1000        T = InstantiateType(T, ClassTemplateSpec->getTemplateArgs(),
1001                            ClassTemplateSpec->getNumTemplateArgs(),
1002                            Typedef->getLocation(),
1003                            Typedef->getDeclName());
1004        if (T.isNull()) {
1005          Invalid = true;
1006          T = Context.IntTy;
1007        }
1008      }
1009
1010      // Create the new typedef
1011      TypedefDecl *New
1012        = TypedefDecl::Create(Context, ClassTemplateSpec,
1013                              Typedef->getLocation(),
1014                              Typedef->getIdentifier(),
1015                              T);
1016      ClassTemplateSpec->addDecl(New);
1017    }
1018    else if (FieldDecl *Field = dyn_cast<FieldDecl>(*Member)) {
1019      // FIXME: Simplified instantiation of fields needs to be made
1020      // "real".
1021      bool InvalidDecl = false;
1022      QualType T = Field->getType();
1023      if (T->isDependentType())  {
1024        T = InstantiateType(T, ClassTemplateSpec->getTemplateArgs(),
1025                            ClassTemplateSpec->getNumTemplateArgs(),
1026                            Field->getLocation(),
1027                            Field->getDeclName());
1028        if (!T.isNull() && T->isFunctionType()) {
1029          // C++ [temp.arg.type]p3:
1030          //   If a declaration acquires a function type through a type
1031          //   dependent on a template-parameter and this causes a
1032          //   declaration that does not use the syntactic form of a
1033          //   function declarator to have function type, the program is
1034          //   ill-formed.
1035          Diag(Field->getLocation(), diag::err_field_instantiates_to_function)
1036            << T;
1037          T = QualType();
1038          InvalidDecl = true;
1039        }
1040      }
1041
1042      Expr *BitWidth = Field->getBitWidth();
1043      if (InvalidDecl)
1044        BitWidth = 0;
1045      else if (BitWidth) {
1046        OwningExprResult InstantiatedBitWidth
1047          = InstantiateExpr(BitWidth,
1048                            ClassTemplateSpec->getTemplateArgs(),
1049                            ClassTemplateSpec->getNumTemplateArgs());
1050        if (InstantiatedBitWidth.isInvalid()) {
1051          Invalid = InvalidDecl = true;
1052          BitWidth = 0;
1053        } else
1054          BitWidth = (Expr *)InstantiatedBitWidth.release();
1055      }
1056
1057      FieldDecl *New = CheckFieldDecl(Field->getDeclName(), T,
1058                                      ClassTemplateSpec,
1059                                      Field->getLocation(),
1060                                      Field->isMutable(),
1061                                      BitWidth,
1062                                      Field->getAccess(),
1063                                      0);
1064      if (New) {
1065        ClassTemplateSpec->addDecl(New);
1066        Fields.push_back(New);
1067
1068        if (InvalidDecl)
1069          New->setInvalidDecl();
1070
1071        if (New->isInvalidDecl())
1072          Invalid = true;
1073      }
1074    } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(*Member)) {
1075      Expr *AssertExpr = SA->getAssertExpr();
1076
1077      OwningExprResult InstantiatedAssertExpr
1078        = InstantiateExpr(AssertExpr,
1079                          ClassTemplateSpec->getTemplateArgs(),
1080                          ClassTemplateSpec->getNumTemplateArgs());
1081      if (!InstantiatedAssertExpr.isInvalid()) {
1082        OwningExprResult Message = Clone(SA->getMessage());
1083
1084        Decl *New =
1085          (Decl *)ActOnStaticAssertDeclaration(SA->getLocation(),
1086                                               move(InstantiatedAssertExpr),
1087                                               move(Message));
1088        if (New->isInvalidDecl())
1089          Invalid = true;
1090
1091      } else
1092        Invalid = true;
1093    }
1094  }
1095
1096  // Finish checking fields.
1097  ActOnFields(0, ClassTemplateSpec->getLocation(), ClassTemplateSpec,
1098              &Fields[0], Fields.size(), SourceLocation(), SourceLocation(),
1099              0);
1100
1101  // Add any implicitly-declared members that we might need.
1102  AddImplicitlyDeclaredMembersToClass(ClassTemplateSpec);
1103
1104  // Exit the scope of this instantiation.
1105  CurContext = PreviousContext;
1106
1107  return Invalid;
1108}
1109