SemaTemplateInstantiate.cpp revision b964c1d84bdbad2ebdfce7081a619fbfe276b5f4
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/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
20#include "llvm/Support/Compiler.h"
21
22using namespace clang;
23
24//===----------------------------------------------------------------------===/
25// Template Instantiation for Types
26//===----------------------------------------------------------------------===/
27namespace {
28  class VISIBILITY_HIDDEN TemplateTypeInstantiator {
29    Sema &SemaRef;
30    const TemplateArgument *TemplateArgs;
31    unsigned NumTemplateArgs;
32    SourceLocation Loc;
33    DeclarationName Entity;
34
35  public:
36    TemplateTypeInstantiator(Sema &SemaRef,
37                             const TemplateArgument *TemplateArgs,
38                             unsigned NumTemplateArgs,
39                             SourceLocation Loc,
40                             DeclarationName Entity)
41      : SemaRef(SemaRef), TemplateArgs(TemplateArgs),
42        NumTemplateArgs(NumTemplateArgs), Loc(Loc), Entity(Entity) { }
43
44    QualType operator()(QualType T) const { return Instantiate(T); }
45
46    QualType Instantiate(QualType T) const;
47
48    // Declare instantiate functions for each type.
49#define TYPE(Class, Base)                                       \
50    QualType Instantiate##Class##Type(const Class##Type *T,     \
51                                      unsigned Quals) const;
52#define ABSTRACT_TYPE(Class, Base)
53#include "clang/AST/TypeNodes.def"
54  };
55}
56
57QualType
58TemplateTypeInstantiator::InstantiateExtQualType(const ExtQualType *T,
59                                                 unsigned Quals) const {
60  // FIXME: Implement this
61  assert(false && "Cannot instantiate ExtQualType yet");
62  return QualType();
63}
64
65QualType
66TemplateTypeInstantiator::InstantiateBuiltinType(const BuiltinType *T,
67                                                 unsigned Quals) const {
68  assert(false && "Builtin types are not dependent and cannot be instantiated");
69  return QualType(T, Quals);
70}
71
72QualType
73TemplateTypeInstantiator::
74InstantiateFixedWidthIntType(const FixedWidthIntType *T, unsigned Quals) const {
75  // FIXME: Implement this
76  assert(false && "Cannot instantiate FixedWidthIntType yet");
77  return QualType();
78}
79
80QualType
81TemplateTypeInstantiator::InstantiateComplexType(const ComplexType *T,
82                                                 unsigned Quals) const {
83  // FIXME: Implement this
84  assert(false && "Cannot instantiate ComplexType yet");
85  return QualType();
86}
87
88QualType
89TemplateTypeInstantiator::InstantiatePointerType(const PointerType *T,
90                                                 unsigned Quals) const {
91  QualType PointeeType = Instantiate(T->getPointeeType());
92  if (PointeeType.isNull())
93    return QualType();
94
95  return SemaRef.BuildPointerType(PointeeType, Quals, Loc, Entity);
96}
97
98QualType
99TemplateTypeInstantiator::InstantiateBlockPointerType(const BlockPointerType *T,
100                                                      unsigned Quals) const {
101  // FIXME: Implement this
102  assert(false && "Cannot instantiate BlockPointerType yet");
103  return QualType();
104}
105
106QualType
107TemplateTypeInstantiator::InstantiateReferenceType(const ReferenceType *T,
108                                                   unsigned Quals) const {
109  QualType ReferentType = Instantiate(T->getPointeeType());
110  if (ReferentType.isNull())
111    return QualType();
112
113  return SemaRef.BuildReferenceType(ReferentType, Quals, Loc, Entity);
114}
115
116QualType
117TemplateTypeInstantiator::
118InstantiateMemberPointerType(const MemberPointerType *T,
119                             unsigned Quals) const {
120  // FIXME: Implement this
121  assert(false && "Cannot instantiate MemberPointerType yet");
122  return QualType();
123}
124
125QualType
126TemplateTypeInstantiator::
127InstantiateConstantArrayType(const ConstantArrayType *T,
128                             unsigned Quals) const {
129  QualType ElementType = Instantiate(T->getElementType());
130  if (ElementType.isNull())
131    return ElementType;
132
133  // Build a temporary integer literal to specify the size for
134  // BuildArrayType. Since we have already checked the size as part of
135  // creating the dependent array type in the first place, we know
136  // there aren't any errors.
137  IntegerLiteral ArraySize(T->getSize(), SemaRef.Context.getSizeType(), Loc);
138  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
139                                &ArraySize, T->getIndexTypeQualifier(),
140                                Loc, Entity);
141}
142
143QualType
144TemplateTypeInstantiator::
145InstantiateIncompleteArrayType(const IncompleteArrayType *T,
146                               unsigned Quals) const {
147  QualType ElementType = Instantiate(T->getElementType());
148  if (ElementType.isNull())
149    return ElementType;
150
151  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
152                                0, T->getIndexTypeQualifier(),
153                                Loc, Entity);
154}
155
156QualType
157TemplateTypeInstantiator::
158InstantiateVariableArrayType(const VariableArrayType *T,
159                             unsigned Quals) const {
160  // FIXME: Implement this
161  assert(false && "Cannot instantiate VariableArrayType yet");
162  return QualType();
163}
164
165QualType
166TemplateTypeInstantiator::
167InstantiateDependentSizedArrayType(const DependentSizedArrayType *T,
168                                   unsigned Quals) const {
169  // FIXME: Implement this
170  assert(false && "Cannot instantiate DependentSizedArrayType yet");
171  return QualType();
172}
173
174QualType
175TemplateTypeInstantiator::InstantiateVectorType(const VectorType *T,
176                                             unsigned Quals) const {
177  // FIXME: Implement this
178  assert(false && "Cannot instantiate VectorType yet");
179  return QualType();
180}
181
182QualType
183TemplateTypeInstantiator::InstantiateExtVectorType(const ExtVectorType *T,
184                                                   unsigned Quals) const {
185  // FIXME: Implement this
186  assert(false && "Cannot instantiate ExtVectorType yet");
187  return QualType();
188}
189
190QualType
191TemplateTypeInstantiator::
192InstantiateFunctionProtoType(const FunctionProtoType *T,
193                             unsigned Quals) const {
194  QualType ResultType = Instantiate(T->getResultType());
195  if (ResultType.isNull())
196    return ResultType;
197
198  llvm::SmallVector<QualType, 16> ParamTypes;
199  for (FunctionProtoType::arg_type_iterator Param = T->arg_type_begin(),
200                                         ParamEnd = T->arg_type_end();
201       Param != ParamEnd; ++Param) {
202    QualType P = Instantiate(*Param);
203    if (P.isNull())
204      return P;
205
206    ParamTypes.push_back(P);
207  }
208
209  return SemaRef.BuildFunctionType(ResultType, &ParamTypes[0],
210                                   ParamTypes.size(),
211                                   T->isVariadic(), T->getTypeQuals(),
212                                   Loc, Entity);
213}
214
215QualType
216TemplateTypeInstantiator::
217InstantiateFunctionNoProtoType(const FunctionNoProtoType *T,
218                               unsigned Quals) const {
219  assert(false && "Functions without prototypes cannot be dependent.");
220  return QualType();
221}
222
223QualType
224TemplateTypeInstantiator::InstantiateTypedefType(const TypedefType *T,
225                                                 unsigned Quals) const {
226  // FIXME: Implement this
227  assert(false && "Cannot instantiate TypedefType yet");
228  return QualType();
229}
230
231QualType
232TemplateTypeInstantiator::InstantiateTypeOfExprType(const TypeOfExprType *T,
233                                                    unsigned Quals) const {
234  // FIXME: Implement this
235  assert(false && "Cannot instantiate TypeOfExprType yet");
236  return QualType();
237}
238
239QualType
240TemplateTypeInstantiator::InstantiateTypeOfType(const TypeOfType *T,
241                                                unsigned Quals) const {
242  // FIXME: Implement this
243  assert(false && "Cannot instantiate TypeOfType yet");
244  return QualType();
245}
246
247QualType
248TemplateTypeInstantiator::InstantiateRecordType(const RecordType *T,
249                                                unsigned Quals) const {
250  // FIXME: Implement this
251  assert(false && "Cannot instantiate RecordType yet");
252  return QualType();
253}
254
255QualType
256TemplateTypeInstantiator::InstantiateEnumType(const EnumType *T,
257                                              unsigned Quals) const {
258  // FIXME: Implement this
259  assert(false && "Cannot instantiate EnumType yet");
260  return QualType();
261}
262
263QualType
264TemplateTypeInstantiator::
265InstantiateTemplateTypeParmType(const TemplateTypeParmType *T,
266                                unsigned Quals) const {
267  if (T->getDepth() == 0) {
268    // Replace the template type parameter with its corresponding
269    // template argument.
270    assert(T->getIndex() < NumTemplateArgs && "Wrong # of template args");
271    assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type &&
272           "Template argument kind mismatch");
273    QualType Result = TemplateArgs[T->getIndex()].getAsType();
274    if (Result.isNull() || !Quals)
275      return Result;
276
277    // C++ [dcl.ref]p1:
278    //   [...] Cv-qualified references are ill-formed except when
279    //   the cv-qualifiers are introduced through the use of a
280    //   typedef (7.1.3) or of a template type argument (14.3), in
281    //   which case the cv-qualifiers are ignored.
282    if (Quals && Result->isReferenceType())
283      Quals = 0;
284
285    return QualType(Result.getTypePtr(), Quals | Result.getCVRQualifiers());
286  }
287
288  // The template type parameter comes from an inner template (e.g.,
289  // the template parameter list of a member template inside the
290  // template we are instantiating). Create a new template type
291  // parameter with the template "level" reduced by one.
292  return SemaRef.Context.getTemplateTypeParmType(T->getDepth() - 1,
293                                                 T->getIndex(),
294                                                 T->getName())
295    .getQualifiedType(Quals);
296}
297
298QualType
299TemplateTypeInstantiator::
300InstantiateClassTemplateSpecializationType(
301                                  const ClassTemplateSpecializationType *T,
302                                  unsigned Quals) const {
303  // FIXME: Implement this
304  assert(false && "Cannot instantiate ClassTemplateSpecializationType yet");
305  return QualType();
306}
307
308QualType
309TemplateTypeInstantiator::
310InstantiateObjCInterfaceType(const ObjCInterfaceType *T,
311                             unsigned Quals) const {
312  assert(false && "Objective-C types cannot be dependent");
313  return QualType();
314}
315
316QualType
317TemplateTypeInstantiator::
318InstantiateObjCQualifiedInterfaceType(const ObjCQualifiedInterfaceType *T,
319                                      unsigned Quals) const {
320  assert(false && "Objective-C types cannot be dependent");
321  return QualType();
322}
323
324QualType
325TemplateTypeInstantiator::
326InstantiateObjCQualifiedIdType(const ObjCQualifiedIdType *T,
327                               unsigned Quals) const {
328  assert(false && "Objective-C types cannot be dependent");
329  return QualType();
330}
331
332QualType
333TemplateTypeInstantiator::
334InstantiateObjCQualifiedClassType(const ObjCQualifiedClassType *T,
335                                  unsigned Quals) const {
336  assert(false && "Objective-C types cannot be dependent");
337  return QualType();
338}
339
340/// \brief The actual implementation of Sema::InstantiateType().
341QualType TemplateTypeInstantiator::Instantiate(QualType T) const {
342  // If T is not a dependent type, there is nothing to do.
343  if (!T->isDependentType())
344    return T;
345
346  switch (T->getTypeClass()) {
347#define TYPE(Class, Base)                                               \
348  case Type::Class:                                                     \
349    return Instantiate##Class##Type(cast<Class##Type>(T.getTypePtr()),  \
350                                    T.getCVRQualifiers());
351#define ABSTRACT_TYPE(Class, Base)
352#include "clang/AST/TypeNodes.def"
353  }
354
355  assert(false && "Not all types have been decoded for instantiation");
356  return QualType();
357}
358
359/// \brief Instantiate the type T with a given set of template arguments.
360///
361/// This routine substitutes the given template arguments into the
362/// type T and produces the instantiated type.
363///
364/// \param T the type into which the template arguments will be
365/// substituted. If this type is not dependent, it will be returned
366/// immediately.
367///
368/// \param TemplateArgs the template arguments that will be
369/// substituted for the top-level template parameters within T.
370///
371/// \param NumTemplateArgs the number of template arguments provided
372/// by TemplateArgs.
373///
374/// \param Loc the location in the source code where this substitution
375/// is being performed. It will typically be the location of the
376/// declarator (if we're instantiating the type of some declaration)
377/// or the location of the type in the source code (if, e.g., we're
378/// instantiating the type of a cast expression).
379///
380/// \param Entity the name of the entity associated with a declaration
381/// being instantiated (if any). May be empty to indicate that there
382/// is no such entity (if, e.g., this is a type that occurs as part of
383/// a cast expression) or that the entity has no name (e.g., an
384/// unnamed function parameter).
385///
386/// \returns If the instantiation succeeds, the instantiated
387/// type. Otherwise, produces diagnostics and returns a NULL type.
388QualType Sema::InstantiateType(QualType T,
389                               const TemplateArgument *TemplateArgs,
390                               unsigned NumTemplateArgs,
391                               SourceLocation Loc, DeclarationName Entity) {
392  // If T is not a dependent type, there is nothing to do.
393  if (!T->isDependentType())
394    return T;
395
396  TemplateTypeInstantiator Instantiator(*this, TemplateArgs, NumTemplateArgs,
397                                        Loc, Entity);
398  return Instantiator(T);
399}
400
401/// \brief Instantiate the base class specifiers of the given class
402/// template specialization.
403///
404/// Produces a diagnostic and returns true on error, returns false and
405/// attaches the instantiated base classes to the class template
406/// specialization if successful.
407bool
408Sema::InstantiateBaseSpecifiers(
409                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
410                           ClassTemplateDecl *ClassTemplate) {
411  bool Invalid = false;
412  llvm::SmallVector<CXXBaseSpecifier*, 8> InstantiatedBases;
413  for (ClassTemplateSpecializationDecl::base_class_iterator
414         Base = ClassTemplate->getTemplatedDecl()->bases_begin(),
415         BaseEnd = ClassTemplate->getTemplatedDecl()->bases_end();
416       Base != BaseEnd && !Invalid; ++Base) {
417    if (!Base->getType()->isDependentType()) {
418      // FIXME: Allocate via ASTContext
419      InstantiatedBases.push_back(new CXXBaseSpecifier(*Base));
420      continue;
421    }
422
423    QualType BaseType = InstantiateType(Base->getType(),
424                                        ClassTemplateSpec->getTemplateArgs(),
425                                        ClassTemplateSpec->getNumTemplateArgs(),
426                                        Base->getSourceRange().getBegin(),
427                                        DeclarationName());
428    if (BaseType.isNull()) {
429      Invalid = true;
430      continue;
431    }
432
433    if (CXXBaseSpecifier *InstantiatedBase
434          = CheckBaseSpecifier(ClassTemplateSpec,
435                               Base->getSourceRange(),
436                               Base->isVirtual(),
437                               Base->getAccessSpecifierAsWritten(),
438                               BaseType,
439                               /*FIXME: Not totally accurate */
440                               Base->getSourceRange().getBegin()))
441      InstantiatedBases.push_back(InstantiatedBase);
442    else
443      Invalid = true;
444  }
445
446  if (AttachBaseSpecifiers(ClassTemplateSpec, &InstantiatedBases[0],
447                           InstantiatedBases.size()))
448    Invalid = true;
449
450  return Invalid;
451}
452
453bool
454Sema::InstantiateClassTemplateSpecialization(
455                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
456                           bool ExplicitInstantiation) {
457  // Perform the actual instantiation on the canonical declaration.
458  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
459                               Context.getCanonicalDecl(ClassTemplateSpec));
460
461  // We can only instantiate something that hasn't already been
462  // instantiated or specialized. Fail without any diagnostics: our
463  // caller will provide an error message.
464  if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared)
465    return true;
466
467  // FIXME: Push this class template instantiation onto the
468  // instantiation stack, checking for recursion that exceeds a
469  // certain depth.
470
471  // FIXME: Perform class template partial specialization to select
472  // the best template.
473  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
474
475  if (!Template->getTemplatedDecl()->getDefinition(Context)) {
476    Diag(ClassTemplateSpec->getLocation(),
477         diag::err_template_implicit_instantiate_undefined)
478      << Context.getTypeDeclType(ClassTemplateSpec);
479    Diag(Template->getTemplatedDecl()->getLocation(),
480         diag::note_template_decl_here);
481    return true;
482  }
483
484  // Note that this is an instantiation.
485  ClassTemplateSpec->setSpecializationKind(
486                        ExplicitInstantiation? TSK_ExplicitInstantiation
487                                             : TSK_ImplicitInstantiation);
488
489
490  bool Invalid = false;
491
492  // Enter the scope of this instantiation. We don't use
493  // PushDeclContext because we don't have a scope.
494  DeclContext *PreviousContext = CurContext;
495  CurContext = ClassTemplateSpec;
496
497  // Start the definition of this instantiation.
498  ClassTemplateSpec->startDefinition();
499
500  // FIXME: Create the injected-class-name for the
501  // instantiation. Should this be a typedef or something like it?
502
503  // Instantiate the base class specifiers.
504  if (InstantiateBaseSpecifiers(ClassTemplateSpec, Template))
505    Invalid = true;
506
507  // FIXME: Instantiate all of the members.
508
509  // Add any implicitly-declared members that we might need.
510  AddImplicitlyDeclaredMembersToClass(ClassTemplateSpec);
511
512  // Finish the definition of this instantiation.
513  // FIXME: ActOnFields does more checking, which we'll eventually need.
514  ClassTemplateSpec->completeDefinition(Context);
515
516  // Exit the scope of this instantiation.
517  CurContext = PreviousContext;
518
519  return Invalid;
520}
521