blob: 10f9926b3e7b652ea06650071fd86652ef61c24d [file] [log] [blame]
Douglas Gregor74296542009-02-27 19:31:52 +00001//===------- 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"
Douglas Gregor95ba1282009-03-12 18:36:18 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor74296542009-02-27 19:31:52 +000019#include "clang/Parse/DeclSpec.h"
Douglas Gregor396f1142009-03-13 21:01:28 +000020#include "clang/Lex/Preprocessor.h" // for the identifier table
Douglas Gregor74296542009-02-27 19:31:52 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregorf57dcd02009-02-28 00:25:32 +000022#include "llvm/Support/Compiler.h"
Douglas Gregor74296542009-02-27 19:31:52 +000023
24using namespace clang;
25
Douglas Gregorfee85d62009-03-10 18:03:33 +000026//===----------------------------------------------------------------------===/
27// Template Instantiation Support
28//===----------------------------------------------------------------------===/
29
Douglas Gregor375733c2009-03-10 00:06:19 +000030Sema::InstantiatingTemplate::
31InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
32 ClassTemplateSpecializationDecl *Entity,
33 SourceRange InstantiationRange)
34 : SemaRef(SemaRef) {
Douglas Gregor56d25a72009-03-10 20:44:00 +000035
36 Invalid = CheckInstantiationDepth(PointOfInstantiation,
37 InstantiationRange);
38 if (!Invalid) {
Douglas Gregor375733c2009-03-10 00:06:19 +000039 ActiveTemplateInstantiation Inst;
Douglas Gregor56d25a72009-03-10 20:44:00 +000040 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregor375733c2009-03-10 00:06:19 +000041 Inst.PointOfInstantiation = PointOfInstantiation;
Douglas Gregor56d25a72009-03-10 20:44:00 +000042 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
Douglas Gregor95ba1282009-03-12 18:36:18 +000043 Inst.TemplateArgs = 0;
44 Inst.NumTemplateArgs = 0;
Douglas Gregor56d25a72009-03-10 20:44:00 +000045 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;
Douglas Gregor375733c2009-03-10 00:06:19 +000069 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
Douglas Gregor56d25a72009-03-10 20:44:00 +000080bool 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
Douglas Gregorfee85d62009-03-10 18:03:33 +000096/// \brief Post-diagnostic hook for printing the instantiation stack.
97void Sema::PrintInstantiationStackHook(unsigned, void *Cookie) {
Douglas Gregord9572a12009-03-10 18:52:44 +000098 Sema &SemaRef = *static_cast<Sema*>(Cookie);
99 SemaRef.PrintInstantiationStack();
100 SemaRef.LastTemplateInstantiationErrorContext
Douglas Gregor56d25a72009-03-10 20:44:00 +0000101 = SemaRef.ActiveTemplateInstantiations.back();
Douglas Gregorfee85d62009-03-10 18:03:33 +0000102}
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) {
Douglas Gregor56d25a72009-03-10 20:44:00 +0000112 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 }
Douglas Gregorfee85d62009-03-10 18:03:33 +0000136 }
137}
138
Douglas Gregor74296542009-02-27 19:31:52 +0000139//===----------------------------------------------------------------------===/
140// Template Instantiation for Types
141//===----------------------------------------------------------------------===/
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000142namespace {
143 class VISIBILITY_HIDDEN TemplateTypeInstantiator {
144 Sema &SemaRef;
145 const TemplateArgument *TemplateArgs;
146 unsigned NumTemplateArgs;
147 SourceLocation Loc;
148 DeclarationName Entity;
Douglas Gregor74296542009-02-27 19:31:52 +0000149
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000150 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 {
Douglas Gregor74296542009-02-27 19:31:52 +0000175 // FIXME: Implement this
176 assert(false && "Cannot instantiate ExtQualType yet");
177 return QualType();
178}
179
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000180QualType
181TemplateTypeInstantiator::InstantiateBuiltinType(const BuiltinType *T,
182 unsigned Quals) const {
Douglas Gregorc0139ca2009-02-28 01:04:19 +0000183 assert(false && "Builtin types are not dependent and cannot be instantiated");
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000184 return QualType(T, Quals);
Douglas Gregor74296542009-02-27 19:31:52 +0000185}
186
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000187QualType
188TemplateTypeInstantiator::
189InstantiateFixedWidthIntType(const FixedWidthIntType *T, unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000190 // FIXME: Implement this
191 assert(false && "Cannot instantiate FixedWidthIntType yet");
192 return QualType();
193}
194
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000195QualType
196TemplateTypeInstantiator::InstantiateComplexType(const ComplexType *T,
197 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000198 // FIXME: Implement this
199 assert(false && "Cannot instantiate ComplexType yet");
200 return QualType();
201}
202
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000203QualType
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);
Douglas Gregor74296542009-02-27 19:31:52 +0000211}
212
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000213QualType
214TemplateTypeInstantiator::InstantiateBlockPointerType(const BlockPointerType *T,
215 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000216 // FIXME: Implement this
217 assert(false && "Cannot instantiate BlockPointerType yet");
218 return QualType();
219}
220
Sebastian Redlce6fff02009-03-16 23:22:08 +0000221QualType
222TemplateTypeInstantiator::InstantiateLValueReferenceType(
223 const LValueReferenceType *T, unsigned Quals) const {
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000224 QualType ReferentType = Instantiate(T->getPointeeType());
225 if (ReferentType.isNull())
226 return QualType();
227
Sebastian Redlce6fff02009-03-16 23:22:08 +0000228 return SemaRef.BuildReferenceType(ReferentType, true, Quals, Loc, Entity);
229}
230
231QualType
232TemplateTypeInstantiator::InstantiateRValueReferenceType(
233 const RValueReferenceType *T, unsigned Quals) const {
234 QualType ReferentType = Instantiate(T->getPointeeType());
235 if (ReferentType.isNull())
236 return QualType();
237
238 return SemaRef.BuildReferenceType(ReferentType, false, Quals, Loc, Entity);
Douglas Gregor74296542009-02-27 19:31:52 +0000239}
240
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000241QualType
242TemplateTypeInstantiator::
243InstantiateMemberPointerType(const MemberPointerType *T,
244 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000245 // FIXME: Implement this
246 assert(false && "Cannot instantiate MemberPointerType yet");
247 return QualType();
248}
249
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000250QualType
251TemplateTypeInstantiator::
252InstantiateConstantArrayType(const ConstantArrayType *T,
253 unsigned Quals) const {
254 QualType ElementType = Instantiate(T->getElementType());
255 if (ElementType.isNull())
256 return ElementType;
257
258 // Build a temporary integer literal to specify the size for
259 // BuildArrayType. Since we have already checked the size as part of
260 // creating the dependent array type in the first place, we know
261 // there aren't any errors.
Douglas Gregor448fcd32009-03-09 20:07:22 +0000262 // FIXME: Is IntTy big enough? Maybe not, but LongLongTy causes
263 // problems that I have yet to investigate.
264 IntegerLiteral ArraySize(T->getSize(), SemaRef.Context.IntTy, Loc);
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000265 return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
266 &ArraySize, T->getIndexTypeQualifier(),
267 Loc, Entity);
Douglas Gregor74296542009-02-27 19:31:52 +0000268}
269
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000270QualType
271TemplateTypeInstantiator::
272InstantiateIncompleteArrayType(const IncompleteArrayType *T,
273 unsigned Quals) const {
274 QualType ElementType = Instantiate(T->getElementType());
275 if (ElementType.isNull())
276 return ElementType;
277
278 return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
279 0, T->getIndexTypeQualifier(),
280 Loc, Entity);
Douglas Gregor74296542009-02-27 19:31:52 +0000281}
282
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000283QualType
284TemplateTypeInstantiator::
285InstantiateVariableArrayType(const VariableArrayType *T,
286 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000287 // FIXME: Implement this
288 assert(false && "Cannot instantiate VariableArrayType yet");
289 return QualType();
290}
291
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000292QualType
293TemplateTypeInstantiator::
294InstantiateDependentSizedArrayType(const DependentSizedArrayType *T,
295 unsigned Quals) const {
Anders Carlsson149f2782009-03-15 20:12:13 +0000296 Expr *ArraySize = T->getSizeExpr();
297 assert(ArraySize->isValueDependent() &&
298 "dependent sized array types must have value dependent size expr");
299
300 // Instantiate the element type if needed
301 QualType ElementType = T->getElementType();
302 if (ElementType->isDependentType()) {
303 ElementType = Instantiate(ElementType);
304 if (ElementType.isNull())
305 return QualType();
306 }
307
308 // Instantiate the size expression
309 Sema::OwningExprResult InstantiatedArraySize =
310 SemaRef.InstantiateExpr(ArraySize, TemplateArgs, NumTemplateArgs);
311 if (InstantiatedArraySize.isInvalid())
312 return QualType();
313
314 return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
315 (Expr *)InstantiatedArraySize.release(),
316 T->getIndexTypeQualifier(), Loc, Entity);
Douglas Gregor74296542009-02-27 19:31:52 +0000317}
318
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000319QualType
320TemplateTypeInstantiator::InstantiateVectorType(const VectorType *T,
321 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000322 // FIXME: Implement this
323 assert(false && "Cannot instantiate VectorType yet");
324 return QualType();
325}
326
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000327QualType
328TemplateTypeInstantiator::InstantiateExtVectorType(const ExtVectorType *T,
329 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000330 // FIXME: Implement this
331 assert(false && "Cannot instantiate ExtVectorType yet");
332 return QualType();
333}
334
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000335QualType
336TemplateTypeInstantiator::
337InstantiateFunctionProtoType(const FunctionProtoType *T,
338 unsigned Quals) const {
Douglas Gregorc0139ca2009-02-28 01:04:19 +0000339 QualType ResultType = Instantiate(T->getResultType());
340 if (ResultType.isNull())
341 return ResultType;
342
343 llvm::SmallVector<QualType, 16> ParamTypes;
344 for (FunctionProtoType::arg_type_iterator Param = T->arg_type_begin(),
345 ParamEnd = T->arg_type_end();
346 Param != ParamEnd; ++Param) {
347 QualType P = Instantiate(*Param);
348 if (P.isNull())
349 return P;
350
351 ParamTypes.push_back(P);
352 }
353
354 return SemaRef.BuildFunctionType(ResultType, &ParamTypes[0],
355 ParamTypes.size(),
356 T->isVariadic(), T->getTypeQuals(),
357 Loc, Entity);
Douglas Gregor74296542009-02-27 19:31:52 +0000358}
359
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000360QualType
361TemplateTypeInstantiator::
362InstantiateFunctionNoProtoType(const FunctionNoProtoType *T,
363 unsigned Quals) const {
Douglas Gregorc0139ca2009-02-28 01:04:19 +0000364 assert(false && "Functions without prototypes cannot be dependent.");
Douglas Gregor74296542009-02-27 19:31:52 +0000365 return QualType();
366}
367
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000368QualType
369TemplateTypeInstantiator::InstantiateTypedefType(const TypedefType *T,
370 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000371 // FIXME: Implement this
372 assert(false && "Cannot instantiate TypedefType yet");
373 return QualType();
374}
375
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000376QualType
377TemplateTypeInstantiator::InstantiateTypeOfExprType(const TypeOfExprType *T,
378 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000379 // FIXME: Implement this
380 assert(false && "Cannot instantiate TypeOfExprType yet");
381 return QualType();
382}
383
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000384QualType
385TemplateTypeInstantiator::InstantiateTypeOfType(const TypeOfType *T,
386 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000387 // FIXME: Implement this
388 assert(false && "Cannot instantiate TypeOfType yet");
389 return QualType();
390}
391
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000392QualType
393TemplateTypeInstantiator::InstantiateRecordType(const RecordType *T,
394 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000395 // FIXME: Implement this
396 assert(false && "Cannot instantiate RecordType yet");
397 return QualType();
398}
399
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000400QualType
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000401TemplateTypeInstantiator::InstantiateEnumType(const EnumType *T,
402 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000403 // FIXME: Implement this
404 assert(false && "Cannot instantiate EnumType yet");
405 return QualType();
406}
407
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000408QualType
409TemplateTypeInstantiator::
410InstantiateTemplateTypeParmType(const TemplateTypeParmType *T,
411 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000412 if (T->getDepth() == 0) {
413 // Replace the template type parameter with its corresponding
414 // template argument.
415 assert(T->getIndex() < NumTemplateArgs && "Wrong # of template args");
416 assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type &&
417 "Template argument kind mismatch");
418 QualType Result = TemplateArgs[T->getIndex()].getAsType();
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000419 if (Result.isNull() || !Quals)
Douglas Gregor74296542009-02-27 19:31:52 +0000420 return Result;
421
422 // C++ [dcl.ref]p1:
423 // [...] Cv-qualified references are ill-formed except when
424 // the cv-qualifiers are introduced through the use of a
425 // typedef (7.1.3) or of a template type argument (14.3), in
426 // which case the cv-qualifiers are ignored.
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000427 if (Quals && Result->isReferenceType())
428 Quals = 0;
Douglas Gregor74296542009-02-27 19:31:52 +0000429
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000430 return QualType(Result.getTypePtr(), Quals | Result.getCVRQualifiers());
Douglas Gregor74296542009-02-27 19:31:52 +0000431 }
432
433 // The template type parameter comes from an inner template (e.g.,
434 // the template parameter list of a member template inside the
435 // template we are instantiating). Create a new template type
436 // parameter with the template "level" reduced by one.
437 return SemaRef.Context.getTemplateTypeParmType(T->getDepth() - 1,
438 T->getIndex(),
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000439 T->getName())
440 .getQualifiedType(Quals);
Douglas Gregor74296542009-02-27 19:31:52 +0000441}
442
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000443QualType
444TemplateTypeInstantiator::
445InstantiateClassTemplateSpecializationType(
446 const ClassTemplateSpecializationType *T,
447 unsigned Quals) const {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000448 llvm::SmallVector<TemplateArgument, 16> InstantiatedTemplateArgs;
449 InstantiatedTemplateArgs.reserve(T->getNumArgs());
450 for (ClassTemplateSpecializationType::iterator Arg = T->begin(),
451 ArgEnd = T->end();
452 Arg != ArgEnd; ++Arg) {
453 switch (Arg->getKind()) {
454 case TemplateArgument::Type: {
455 QualType T = SemaRef.InstantiateType(Arg->getAsType(),
456 TemplateArgs, NumTemplateArgs,
457 Arg->getLocation(),
458 DeclarationName());
459 if (T.isNull())
460 return QualType();
461
462 InstantiatedTemplateArgs.push_back(
463 TemplateArgument(Arg->getLocation(), T));
464 break;
465 }
466
467 case TemplateArgument::Declaration:
468 case TemplateArgument::Integral:
469 InstantiatedTemplateArgs.push_back(*Arg);
470 break;
471
472 case TemplateArgument::Expression:
Douglas Gregor396f1142009-03-13 21:01:28 +0000473 Sema::OwningExprResult E
474 = SemaRef.InstantiateExpr(Arg->getAsExpr(), TemplateArgs,
475 NumTemplateArgs);
476 if (E.isInvalid())
477 return QualType();
478 InstantiatedTemplateArgs.push_back((Expr *)E.release());
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000479 break;
480 }
481 }
482
483 // FIXME: We're missing the locations of the template name, '<', and
484 // '>'.
485 return SemaRef.CheckClassTemplateId(cast<ClassTemplateDecl>(T->getTemplate()),
486 Loc,
487 SourceLocation(),
488 &InstantiatedTemplateArgs[0],
489 InstantiatedTemplateArgs.size(),
490 SourceLocation());
Douglas Gregor74296542009-02-27 19:31:52 +0000491}
492
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000493QualType
494TemplateTypeInstantiator::
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000495InstantiateQualifiedNameType(const QualifiedNameType *T,
496 unsigned Quals) const {
497 assert(false && "Cannot have dependent qualified name types (yet)");
498 return QualType();
499}
500
501QualType
502TemplateTypeInstantiator::
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000503InstantiateObjCInterfaceType(const ObjCInterfaceType *T,
504 unsigned Quals) const {
505 assert(false && "Objective-C types cannot be dependent");
Douglas Gregor74296542009-02-27 19:31:52 +0000506 return QualType();
507}
508
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000509QualType
510TemplateTypeInstantiator::
511InstantiateObjCQualifiedInterfaceType(const ObjCQualifiedInterfaceType *T,
512 unsigned Quals) const {
513 assert(false && "Objective-C types cannot be dependent");
Douglas Gregor74296542009-02-27 19:31:52 +0000514 return QualType();
515}
516
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000517QualType
518TemplateTypeInstantiator::
519InstantiateObjCQualifiedIdType(const ObjCQualifiedIdType *T,
520 unsigned Quals) const {
521 assert(false && "Objective-C types cannot be dependent");
Douglas Gregor74296542009-02-27 19:31:52 +0000522 return QualType();
523}
524
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000525QualType
526TemplateTypeInstantiator::
527InstantiateObjCQualifiedClassType(const ObjCQualifiedClassType *T,
528 unsigned Quals) const {
529 assert(false && "Objective-C types cannot be dependent");
Douglas Gregor74296542009-02-27 19:31:52 +0000530 return QualType();
531}
532
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000533/// \brief The actual implementation of Sema::InstantiateType().
534QualType TemplateTypeInstantiator::Instantiate(QualType T) const {
535 // If T is not a dependent type, there is nothing to do.
536 if (!T->isDependentType())
537 return T;
538
539 switch (T->getTypeClass()) {
540#define TYPE(Class, Base) \
541 case Type::Class: \
542 return Instantiate##Class##Type(cast<Class##Type>(T.getTypePtr()), \
543 T.getCVRQualifiers());
544#define ABSTRACT_TYPE(Class, Base)
545#include "clang/AST/TypeNodes.def"
546 }
547
548 assert(false && "Not all types have been decoded for instantiation");
549 return QualType();
550}
Douglas Gregor74296542009-02-27 19:31:52 +0000551
552/// \brief Instantiate the type T with a given set of template arguments.
553///
554/// This routine substitutes the given template arguments into the
555/// type T and produces the instantiated type.
556///
557/// \param T the type into which the template arguments will be
558/// substituted. If this type is not dependent, it will be returned
559/// immediately.
560///
561/// \param TemplateArgs the template arguments that will be
562/// substituted for the top-level template parameters within T.
563///
564/// \param NumTemplateArgs the number of template arguments provided
565/// by TemplateArgs.
566///
567/// \param Loc the location in the source code where this substitution
568/// is being performed. It will typically be the location of the
569/// declarator (if we're instantiating the type of some declaration)
570/// or the location of the type in the source code (if, e.g., we're
571/// instantiating the type of a cast expression).
572///
573/// \param Entity the name of the entity associated with a declaration
574/// being instantiated (if any). May be empty to indicate that there
575/// is no such entity (if, e.g., this is a type that occurs as part of
576/// a cast expression) or that the entity has no name (e.g., an
577/// unnamed function parameter).
578///
579/// \returns If the instantiation succeeds, the instantiated
580/// type. Otherwise, produces diagnostics and returns a NULL type.
581QualType Sema::InstantiateType(QualType T,
582 const TemplateArgument *TemplateArgs,
583 unsigned NumTemplateArgs,
584 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor56d25a72009-03-10 20:44:00 +0000585 assert(!ActiveTemplateInstantiations.empty() &&
586 "Cannot perform an instantiation without some context on the "
587 "instantiation stack");
588
Douglas Gregor74296542009-02-27 19:31:52 +0000589 // If T is not a dependent type, there is nothing to do.
590 if (!T->isDependentType())
591 return T;
592
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000593 TemplateTypeInstantiator Instantiator(*this, TemplateArgs, NumTemplateArgs,
594 Loc, Entity);
595 return Instantiator(T);
Douglas Gregor74296542009-02-27 19:31:52 +0000596}
Douglas Gregored3a3982009-03-03 04:44:36 +0000597
Douglas Gregorbd300312009-03-12 16:53:44 +0000598//===----------------------------------------------------------------------===/
599// Template Instantiation for Expressions
600//===----------------------------------------------------------------------===/
Douglas Gregor95ba1282009-03-12 18:36:18 +0000601namespace {
602 class VISIBILITY_HIDDEN TemplateExprInstantiator
603 : public StmtVisitor<TemplateExprInstantiator, Sema::OwningExprResult> {
604 Sema &SemaRef;
605 const TemplateArgument *TemplateArgs;
606 unsigned NumTemplateArgs;
607
608 public:
Douglas Gregor396f1142009-03-13 21:01:28 +0000609 typedef Sema::OwningExprResult OwningExprResult;
610
Douglas Gregor95ba1282009-03-12 18:36:18 +0000611 TemplateExprInstantiator(Sema &SemaRef,
612 const TemplateArgument *TemplateArgs,
613 unsigned NumTemplateArgs)
614 : SemaRef(SemaRef), TemplateArgs(TemplateArgs),
615 NumTemplateArgs(NumTemplateArgs) { }
616
617 // FIXME: Once we get closer to completion, replace these
618 // manually-written declarations with automatically-generated ones
619 // from clang/AST/StmtNodes.def.
Douglas Gregor396f1142009-03-13 21:01:28 +0000620 OwningExprResult VisitIntegerLiteral(IntegerLiteral *E);
621 OwningExprResult VisitDeclRefExpr(DeclRefExpr *E);
622 OwningExprResult VisitParenExpr(ParenExpr *E);
Douglas Gregorc78182d2009-03-13 23:49:33 +0000623 OwningExprResult VisitUnaryOperator(UnaryOperator *E);
Douglas Gregor396f1142009-03-13 21:01:28 +0000624 OwningExprResult VisitBinaryOperator(BinaryOperator *E);
625 OwningExprResult VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Gabor Greif8a0659c2009-03-18 00:55:04 +0000626 OwningExprResult VisitConditionalOperator(ConditionalOperator *E);
Douglas Gregor396f1142009-03-13 21:01:28 +0000627 OwningExprResult VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000628 OwningExprResult VisitUnresolvedDeclRefExpr(UnresolvedDeclRefExpr *E);
Douglas Gregor396f1142009-03-13 21:01:28 +0000629 OwningExprResult VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Anders Carlsson121bcad2009-03-17 00:28:02 +0000630 OwningExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
631
Douglas Gregor95ba1282009-03-12 18:36:18 +0000632 // Base case. I'm supposed to ignore this.
Anders Carlsson7f2e7442009-03-15 18:34:13 +0000633 Sema::OwningExprResult VisitStmt(Stmt *S) {
634 S->dump();
Douglas Gregor5b5b6692009-03-12 22:46:12 +0000635 assert(false && "Cannot instantiate this kind of expression");
636 return SemaRef.ExprError();
637 }
Douglas Gregor95ba1282009-03-12 18:36:18 +0000638 };
639}
640
641Sema::OwningExprResult
642TemplateExprInstantiator::VisitIntegerLiteral(IntegerLiteral *E) {
Anders Carlsson7f2e7442009-03-15 18:34:13 +0000643 return SemaRef.Clone(E);
Douglas Gregor95ba1282009-03-12 18:36:18 +0000644}
645
646Sema::OwningExprResult
647TemplateExprInstantiator::VisitDeclRefExpr(DeclRefExpr *E) {
648 Decl *D = E->getDecl();
649 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
650 assert(NTTP->getDepth() == 0 && "No nested templates yet");
Douglas Gregor63f5d602009-03-12 22:20:26 +0000651 const TemplateArgument &Arg = TemplateArgs[NTTP->getPosition()];
Douglas Gregor3b27cc72009-03-16 23:35:25 +0000652 QualType T = Arg.getIntegralType();
653 if (T->isCharType() || T->isWideCharType())
654 return SemaRef.Owned(new (SemaRef.Context) CharacterLiteral(
655 Arg.getAsIntegral()->getZExtValue(),
656 T->isWideCharType(),
657 T,
658 E->getSourceRange().getBegin()));
659 else if (T->isBooleanType())
660 return SemaRef.Owned(new (SemaRef.Context) CXXBoolLiteralExpr(
661 Arg.getAsIntegral()->getBoolValue(),
662 T,
663 E->getSourceRange().getBegin()));
664
Douglas Gregor95ba1282009-03-12 18:36:18 +0000665 return SemaRef.Owned(new (SemaRef.Context) IntegerLiteral(
Douglas Gregor63f5d602009-03-12 22:20:26 +0000666 *Arg.getAsIntegral(),
Douglas Gregor3b27cc72009-03-16 23:35:25 +0000667 T,
Douglas Gregor63f5d602009-03-12 22:20:26 +0000668 E->getSourceRange().getBegin()));
Douglas Gregor95ba1282009-03-12 18:36:18 +0000669 } else
670 assert(false && "Can't handle arbitrary declaration references");
671
672 return SemaRef.ExprError();
673}
674
675Sema::OwningExprResult
676TemplateExprInstantiator::VisitParenExpr(ParenExpr *E) {
Douglas Gregor3ae974b2009-03-17 19:05:46 +0000677 Sema::OwningExprResult SubExpr = Visit(E->getSubExpr());
Douglas Gregor95ba1282009-03-12 18:36:18 +0000678 if (SubExpr.isInvalid())
679 return SemaRef.ExprError();
680
681 return SemaRef.Owned(new (SemaRef.Context) ParenExpr(
682 E->getLParen(), E->getRParen(),
683 (Expr *)SubExpr.release()));
684}
685
Douglas Gregorbd300312009-03-12 16:53:44 +0000686Sema::OwningExprResult
Douglas Gregorc78182d2009-03-13 23:49:33 +0000687TemplateExprInstantiator::VisitUnaryOperator(UnaryOperator *E) {
688 Sema::OwningExprResult Arg = Visit(E->getSubExpr());
689 if (Arg.isInvalid())
690 return SemaRef.ExprError();
691
692 return SemaRef.CreateBuiltinUnaryOp(E->getOperatorLoc(),
693 E->getOpcode(),
694 move(Arg));
695}
696
697Sema::OwningExprResult
Douglas Gregor5b5b6692009-03-12 22:46:12 +0000698TemplateExprInstantiator::VisitBinaryOperator(BinaryOperator *E) {
699 Sema::OwningExprResult LHS = Visit(E->getLHS());
700 if (LHS.isInvalid())
701 return SemaRef.ExprError();
702
703 Sema::OwningExprResult RHS = Visit(E->getRHS());
704 if (RHS.isInvalid())
705 return SemaRef.ExprError();
706
707 Sema::OwningExprResult Result
708 = SemaRef.CreateBuiltinBinOp(E->getOperatorLoc(),
709 E->getOpcode(),
710 (Expr *)LHS.get(),
711 (Expr *)RHS.get());
712 if (Result.isInvalid())
713 return SemaRef.ExprError();
714
715 LHS.release();
716 RHS.release();
717 return move(Result);
718}
719
720Sema::OwningExprResult
Douglas Gregor3fc092f2009-03-13 00:33:25 +0000721TemplateExprInstantiator::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
Douglas Gregorc78182d2009-03-13 23:49:33 +0000722 Sema::OwningExprResult First = Visit(E->getArg(0));
723 if (First.isInvalid())
Douglas Gregor3fc092f2009-03-13 00:33:25 +0000724 return SemaRef.ExprError();
725
Douglas Gregorc78182d2009-03-13 23:49:33 +0000726 Expr *Args[2] = { (Expr *)First.get(), 0 };
Douglas Gregor3fc092f2009-03-13 00:33:25 +0000727
Douglas Gregorc78182d2009-03-13 23:49:33 +0000728 Sema::OwningExprResult Second(SemaRef);
729 if (E->getNumArgs() == 2) {
730 Second = Visit(E->getArg(1));
731
732 if (Second.isInvalid())
733 return SemaRef.ExprError();
734
735 Args[1] = (Expr *)Second.get();
736 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000737
738 if (!E->isTypeDependent()) {
739 // Since our original expression was not type-dependent, we do not
740 // perform lookup again at instantiation time (C++ [temp.dep]p1).
741 // Instead, we just build the new overloaded operator call
742 // expression.
Douglas Gregorc78182d2009-03-13 23:49:33 +0000743 First.release();
744 Second.release();
Douglas Gregor3ae974b2009-03-17 19:05:46 +0000745 // FIXME: Don't reuse the callee here. We need to instantiate it.
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000746 return SemaRef.Owned(new (SemaRef.Context) CXXOperatorCallExpr(
747 SemaRef.Context,
748 E->getOperator(),
749 E->getCallee(),
Douglas Gregorc78182d2009-03-13 23:49:33 +0000750 Args, E->getNumArgs(),
751 E->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000752 E->getOperatorLoc()));
753 }
754
Douglas Gregorc78182d2009-03-13 23:49:33 +0000755 bool isPostIncDec = E->getNumArgs() == 2 &&
756 (E->getOperator() == OO_PlusPlus || E->getOperator() == OO_MinusMinus);
757 if (E->getNumArgs() == 1 || isPostIncDec) {
758 if (!Args[0]->getType()->isOverloadableType()) {
759 // The argument is not of overloadable type, so try to create a
760 // built-in unary operation.
761 UnaryOperator::Opcode Opc
762 = UnaryOperator::getOverloadedOpcode(E->getOperator(), isPostIncDec);
763
764 return SemaRef.CreateBuiltinUnaryOp(E->getOperatorLoc(), Opc,
765 move(First));
766 }
767
768 // Fall through to perform overload resolution
769 } else {
770 assert(E->getNumArgs() == 2 && "Expected binary operation");
771
772 Sema::OwningExprResult Result(SemaRef);
773 if (!Args[0]->getType()->isOverloadableType() &&
774 !Args[1]->getType()->isOverloadableType()) {
775 // Neither of the arguments is an overloadable type, so try to
776 // create a built-in binary operation.
777 BinaryOperator::Opcode Opc =
778 BinaryOperator::getOverloadedOpcode(E->getOperator());
779 Result = SemaRef.CreateBuiltinBinOp(E->getOperatorLoc(), Opc,
780 Args[0], Args[1]);
781 if (Result.isInvalid())
782 return SemaRef.ExprError();
783
784 First.release();
785 Second.release();
786 return move(Result);
787 }
788
789 // Fall through to perform overload resolution.
790 }
791
792 // Compute the set of functions that were found at template
793 // definition time.
794 Sema::FunctionSet Functions;
795 DeclRefExpr *DRE = cast<DeclRefExpr>(E->getCallee());
796 OverloadedFunctionDecl *Overloads
797 = cast<OverloadedFunctionDecl>(DRE->getDecl());
798
799 // FIXME: Do we have to check
800 // IsAcceptableNonMemberOperatorCandidate for each of these?
801 for (OverloadedFunctionDecl::function_iterator
802 F = Overloads->function_begin(),
803 FEnd = Overloads->function_end();
804 F != FEnd; ++F)
805 Functions.insert(*F);
806
807 // Add any functions found via argument-dependent lookup.
808 DeclarationName OpName
809 = SemaRef.Context.DeclarationNames.getCXXOperatorName(E->getOperator());
810 SemaRef.ArgumentDependentLookup(OpName, Args, E->getNumArgs(), Functions);
811
812 // Create the overloaded operator invocation.
813 if (E->getNumArgs() == 1 || isPostIncDec) {
814 UnaryOperator::Opcode Opc
815 = UnaryOperator::getOverloadedOpcode(E->getOperator(), isPostIncDec);
816 return SemaRef.CreateOverloadedUnaryOp(E->getOperatorLoc(), Opc,
817 Functions, move(First));
818 }
819
820 // FIXME: This would be far less ugly if CreateOverloadedBinOp took
821 // in ExprArg arguments!
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000822 BinaryOperator::Opcode Opc =
823 BinaryOperator::getOverloadedOpcode(E->getOperator());
Douglas Gregorc78182d2009-03-13 23:49:33 +0000824 OwningExprResult Result
825 = SemaRef.CreateOverloadedBinOp(E->getOperatorLoc(), Opc,
826 Functions, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000827
Douglas Gregor3fc092f2009-03-13 00:33:25 +0000828 if (Result.isInvalid())
829 return SemaRef.ExprError();
830
Douglas Gregorc78182d2009-03-13 23:49:33 +0000831 First.release();
832 Second.release();
Douglas Gregor3fc092f2009-03-13 00:33:25 +0000833 return move(Result);
834}
835
Gabor Greif8a0659c2009-03-18 00:55:04 +0000836Sema::OwningExprResult
837TemplateExprInstantiator::VisitConditionalOperator(ConditionalOperator *E) {
838 Sema::OwningExprResult Cond = Visit(E->getCond());
839 if (Cond.isInvalid())
840 return SemaRef.ExprError();
841
842 // FIXME: use getLHS() and cope with NULLness
843 Sema::OwningExprResult True = Visit(E->getTrueExpr());
844 if (True.isInvalid())
845 return SemaRef.ExprError();
846
847 Sema::OwningExprResult False = Visit(E->getFalseExpr());
848 if (False.isInvalid())
849 return SemaRef.ExprError();
850
Gabor Greiff85b8ea2009-03-18 20:12:58 +0000851 if (!E->isTypeDependent()) {
852 // Since our original expression was not type-dependent, we do not
853 // perform lookup again at instantiation time (C++ [temp.dep]p1).
854 // Instead, we just build the new conditional operator call expression.
Gabor Greiff85b8ea2009-03-18 20:12:58 +0000855 return SemaRef.Owned(new (SemaRef.Context) ConditionalOperator(
Gabor Greiff4df7da2009-03-18 23:47:39 +0000856 Cond.takeAs<Expr>(),
857 True.takeAs<Expr>(),
858 False.takeAs<Expr>(),
859 E->getType()));
Gabor Greiff85b8ea2009-03-18 20:12:58 +0000860 }
861
862
863 return SemaRef.ActOnConditionalOp(/*FIXME*/E->getCond()->getLocEnd(),
864 /*FIXME*/E->getFalseExpr()->getLocStart(),
Gabor Greif6c24c7f2009-03-18 17:53:25 +0000865 move(Cond), move(True), move(False));
Gabor Greif8a0659c2009-03-18 00:55:04 +0000866}
867
Douglas Gregor3fc092f2009-03-13 00:33:25 +0000868Sema::OwningExprResult
Douglas Gregor396f1142009-03-13 21:01:28 +0000869TemplateExprInstantiator::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
870 bool isSizeOf = E->isSizeOf();
871
872 if (E->isArgumentType()) {
873 QualType T = E->getArgumentType();
874 if (T->isDependentType()) {
875 T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs,
876 /*FIXME*/E->getOperatorLoc(),
Gabor Greif8a0659c2009-03-18 00:55:04 +0000877 &SemaRef.PP.getIdentifierTable().get("sizeof"));
Douglas Gregor396f1142009-03-13 21:01:28 +0000878 if (T.isNull())
879 return SemaRef.ExprError();
880 }
881
882 return SemaRef.CreateSizeOfAlignOfExpr(T, E->getOperatorLoc(), isSizeOf,
883 E->getSourceRange());
884 }
885
886 Sema::OwningExprResult Arg = Visit(E->getArgumentExpr());
887 if (Arg.isInvalid())
888 return SemaRef.ExprError();
889
890 Sema::OwningExprResult Result
891 = SemaRef.CreateSizeOfAlignOfExpr((Expr *)Arg.get(), E->getOperatorLoc(),
892 isSizeOf, E->getSourceRange());
893 if (Result.isInvalid())
894 return SemaRef.ExprError();
895
896 Arg.release();
897 return move(Result);
898}
899
900Sema::OwningExprResult
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000901TemplateExprInstantiator::VisitUnresolvedDeclRefExpr(UnresolvedDeclRefExpr *E) {
902 CXXScopeSpec SS = SemaRef.InstantiateScopeSpecifier(E->begin(), E->size(),
903 E->getQualifierRange(),
904 TemplateArgs,
905 NumTemplateArgs);
906 if (SS.isInvalid() || SS.isEmpty())
907 return SemaRef.ExprError();
908
909 // FIXME: We're passing in a NULL scope, because
910 // ActOnDeclarationNameExpr doesn't actually use the scope when we
911 // give it a non-empty scope specifier. Investigate whether it would
912 // be better to refactor ActOnDeclarationNameExpr.
913 return SemaRef.ActOnDeclarationNameExpr(/*Scope=*/0, E->getLocation(),
914 E->getDeclName(),
915 /*HasTrailingLParen=*/false,
916 &SS,
917 /*FIXME:isAddressOfOperand=*/false);
918}
919
920Sema::OwningExprResult
Douglas Gregor396f1142009-03-13 21:01:28 +0000921TemplateExprInstantiator::VisitCXXTemporaryObjectExpr(
922 CXXTemporaryObjectExpr *E) {
923 QualType T = E->getType();
924 if (T->isDependentType()) {
925 T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs,
926 E->getTypeBeginLoc(), DeclarationName());
927 if (T.isNull())
928 return SemaRef.ExprError();
929 }
930
931 llvm::SmallVector<Expr *, 16> Args;
932 Args.reserve(E->getNumArgs());
933 bool Invalid = false;
934 for (CXXTemporaryObjectExpr::arg_iterator Arg = E->arg_begin(),
935 ArgEnd = E->arg_end();
936 Arg != ArgEnd; ++Arg) {
937 OwningExprResult InstantiatedArg = Visit(*Arg);
938 if (InstantiatedArg.isInvalid()) {
939 Invalid = true;
940 break;
941 }
942
943 Args.push_back((Expr *)InstantiatedArg.release());
944 }
945
946 if (!Invalid) {
947 SourceLocation CommaLoc;
948 // FIXME: HACK!
949 if (Args.size() > 1)
950 CommaLoc
951 = SemaRef.PP.getLocForEndOfToken(Args[0]->getSourceRange().getEnd());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000952 Sema::OwningExprResult Result(
953 SemaRef.ActOnCXXTypeConstructExpr(SourceRange(E->getTypeBeginLoc()
954 /*, FIXME*/),
955 T.getAsOpaquePtr(),
956 /*FIXME*/E->getTypeBeginLoc(),
957 Sema::MultiExprArg(SemaRef,
958 (void**)&Args[0],
959 Args.size()),
960 /*HACK*/&CommaLoc,
961 E->getSourceRange().getEnd()));
962 // At this point, Args no longer owns the arguments, no matter what.
963 return move(Result);
Douglas Gregor396f1142009-03-13 21:01:28 +0000964 }
965
966 // Clean up the instantiated arguments.
967 // FIXME: Would rather do this with RAII.
968 for (unsigned Idx = 0; Idx < Args.size(); ++Idx)
969 SemaRef.DeleteExpr(Args[Idx]);
970
971 return SemaRef.ExprError();
972}
973
Anders Carlsson121bcad2009-03-17 00:28:02 +0000974Sema::OwningExprResult TemplateExprInstantiator::VisitImplicitCastExpr(
975 ImplicitCastExpr *E) {
976 assert(!E->isTypeDependent() && "Implicit casts must have known types");
977
978 Sema::OwningExprResult SubExpr = Visit(E->getSubExpr());
979 if (SubExpr.isInvalid())
980 return SemaRef.ExprError();
981
982 ImplicitCastExpr *ICE =
983 new (SemaRef.Context) ImplicitCastExpr(E->getType(),
984 (Expr *)SubExpr.release(),
985 E->isLvalueCast());
986 return SemaRef.Owned(ICE);
987}
988
Douglas Gregor396f1142009-03-13 21:01:28 +0000989Sema::OwningExprResult
Douglas Gregorbd300312009-03-12 16:53:44 +0000990Sema::InstantiateExpr(Expr *E, const TemplateArgument *TemplateArgs,
991 unsigned NumTemplateArgs) {
Douglas Gregor95ba1282009-03-12 18:36:18 +0000992 TemplateExprInstantiator Instantiator(*this, TemplateArgs, NumTemplateArgs);
993 return Instantiator.Visit(E);
Douglas Gregorbd300312009-03-12 16:53:44 +0000994}
995
Douglas Gregored3a3982009-03-03 04:44:36 +0000996/// \brief Instantiate the base class specifiers of the given class
997/// template specialization.
998///
999/// Produces a diagnostic and returns true on error, returns false and
1000/// attaches the instantiated base classes to the class template
1001/// specialization if successful.
1002bool
1003Sema::InstantiateBaseSpecifiers(
1004 ClassTemplateSpecializationDecl *ClassTemplateSpec,
1005 ClassTemplateDecl *ClassTemplate) {
1006 bool Invalid = false;
1007 llvm::SmallVector<CXXBaseSpecifier*, 8> InstantiatedBases;
1008 for (ClassTemplateSpecializationDecl::base_class_iterator
1009 Base = ClassTemplate->getTemplatedDecl()->bases_begin(),
1010 BaseEnd = ClassTemplate->getTemplatedDecl()->bases_end();
Douglas Gregord9572a12009-03-10 18:52:44 +00001011 Base != BaseEnd; ++Base) {
Douglas Gregored3a3982009-03-03 04:44:36 +00001012 if (!Base->getType()->isDependentType()) {
1013 // FIXME: Allocate via ASTContext
1014 InstantiatedBases.push_back(new CXXBaseSpecifier(*Base));
1015 continue;
1016 }
1017
1018 QualType BaseType = InstantiateType(Base->getType(),
1019 ClassTemplateSpec->getTemplateArgs(),
1020 ClassTemplateSpec->getNumTemplateArgs(),
1021 Base->getSourceRange().getBegin(),
1022 DeclarationName());
1023 if (BaseType.isNull()) {
1024 Invalid = true;
1025 continue;
1026 }
1027
1028 if (CXXBaseSpecifier *InstantiatedBase
1029 = CheckBaseSpecifier(ClassTemplateSpec,
1030 Base->getSourceRange(),
1031 Base->isVirtual(),
1032 Base->getAccessSpecifierAsWritten(),
1033 BaseType,
1034 /*FIXME: Not totally accurate */
1035 Base->getSourceRange().getBegin()))
1036 InstantiatedBases.push_back(InstantiatedBase);
1037 else
1038 Invalid = true;
1039 }
1040
Douglas Gregord9572a12009-03-10 18:52:44 +00001041 if (!Invalid &&
1042 AttachBaseSpecifiers(ClassTemplateSpec, &InstantiatedBases[0],
Douglas Gregored3a3982009-03-03 04:44:36 +00001043 InstantiatedBases.size()))
1044 Invalid = true;
1045
1046 return Invalid;
1047}
1048
1049bool
1050Sema::InstantiateClassTemplateSpecialization(
1051 ClassTemplateSpecializationDecl *ClassTemplateSpec,
1052 bool ExplicitInstantiation) {
1053 // Perform the actual instantiation on the canonical declaration.
1054 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
1055 Context.getCanonicalDecl(ClassTemplateSpec));
1056
1057 // We can only instantiate something that hasn't already been
1058 // instantiated or specialized. Fail without any diagnostics: our
1059 // caller will provide an error message.
1060 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared)
1061 return true;
1062
1063 // FIXME: Push this class template instantiation onto the
1064 // instantiation stack, checking for recursion that exceeds a
1065 // certain depth.
1066
1067 // FIXME: Perform class template partial specialization to select
1068 // the best template.
1069 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
1070
Douglas Gregor47bde7c2009-03-19 17:26:29 +00001071 RecordDecl *Pattern = cast_or_null<RecordDecl>(
1072 Template->getTemplatedDecl()->getDefinition(Context));
1073 if (!Pattern) {
Douglas Gregored3a3982009-03-03 04:44:36 +00001074 Diag(ClassTemplateSpec->getLocation(),
1075 diag::err_template_implicit_instantiate_undefined)
1076 << Context.getTypeDeclType(ClassTemplateSpec);
1077 Diag(Template->getTemplatedDecl()->getLocation(),
1078 diag::note_template_decl_here);
1079 return true;
1080 }
1081
1082 // Note that this is an instantiation.
1083 ClassTemplateSpec->setSpecializationKind(
1084 ExplicitInstantiation? TSK_ExplicitInstantiation
1085 : TSK_ImplicitInstantiation);
1086
1087
1088 bool Invalid = false;
1089
Douglas Gregor375733c2009-03-10 00:06:19 +00001090 InstantiatingTemplate Inst(*this, ClassTemplateSpec->getLocation(),
1091 ClassTemplateSpec);
1092 if (Inst)
1093 return true;
1094
Douglas Gregored3a3982009-03-03 04:44:36 +00001095 // Enter the scope of this instantiation. We don't use
1096 // PushDeclContext because we don't have a scope.
1097 DeclContext *PreviousContext = CurContext;
1098 CurContext = ClassTemplateSpec;
1099
1100 // Start the definition of this instantiation.
1101 ClassTemplateSpec->startDefinition();
1102
Douglas Gregored3a3982009-03-03 04:44:36 +00001103 // Instantiate the base class specifiers.
1104 if (InstantiateBaseSpecifiers(ClassTemplateSpec, Template))
1105 Invalid = true;
1106
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00001107 // FIXME: Create the injected-class-name for the
1108 // instantiation. Should this be a typedef or something like it?
1109
Douglas Gregor0e518af2009-03-11 18:59:21 +00001110 llvm::SmallVector<DeclTy *, 32> Fields;
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00001111 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
1112 MemberEnd = Pattern->decls_end();
1113 Member != MemberEnd; ++Member) {
Douglas Gregor1b39ef42009-03-17 21:15:40 +00001114 Decl *NewMember = InstantiateDecl(*Member, ClassTemplateSpec,
1115 ClassTemplateSpec->getTemplateArgs(),
1116 ClassTemplateSpec->getNumTemplateArgs());
1117 if (NewMember) {
1118 if (NewMember->isInvalidDecl())
Anders Carlssonc45057a2009-03-15 18:44:04 +00001119 Invalid = true;
Douglas Gregor1b39ef42009-03-17 21:15:40 +00001120 else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
1121 Fields.push_back(Field);
1122 } else {
1123 // FIXME: Eventually, a NULL return will mean that one of the
1124 // instantiations was a semantic disaster, and we'll want to set
1125 // Invalid = true. For now, we expect to skip some members that
1126 // we can't yet handle.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00001127 }
1128 }
1129
Douglas Gregor0e518af2009-03-11 18:59:21 +00001130 // Finish checking fields.
1131 ActOnFields(0, ClassTemplateSpec->getLocation(), ClassTemplateSpec,
1132 &Fields[0], Fields.size(), SourceLocation(), SourceLocation(),
1133 0);
1134
Douglas Gregored3a3982009-03-03 04:44:36 +00001135 // Add any implicitly-declared members that we might need.
1136 AddImplicitlyDeclaredMembersToClass(ClassTemplateSpec);
1137
Douglas Gregored3a3982009-03-03 04:44:36 +00001138 // Exit the scope of this instantiation.
1139 CurContext = PreviousContext;
1140
1141 return Invalid;
1142}
Douglas Gregor47bde7c2009-03-19 17:26:29 +00001143
1144/// \brief Instantiate a sequence of nested-name-specifiers into a
1145/// scope specifier.
1146CXXScopeSpec
1147Sema::InstantiateScopeSpecifier(const NestedNameSpecifier *Components,
1148 unsigned NumComponents,
1149 SourceRange Range,
1150 const TemplateArgument *TemplateArgs,
1151 unsigned NumTemplateArgs) {
1152 CXXScopeSpec SS;
1153 for (unsigned Comp = 0; Comp < NumComponents; ++Comp) {
1154 if (Type *T = Components[Comp].getAsType()) {
1155 QualType NewT = InstantiateType(QualType(T, 0), TemplateArgs,
1156 NumTemplateArgs, Range.getBegin(),
1157 DeclarationName());
1158 if (NewT.isNull())
1159 return SS;
1160 NestedNameSpecifier NNS(NewT.getTypePtr());
1161 SS.addScopeRep(NNS.getAsOpaquePtr());
1162 } else {
1163 DeclContext *DC = Components[Comp].getAsDeclContext();
1164 // FIXME: injected-class-name might be dependent, and therefore
1165 // would need instantiation.
1166 NestedNameSpecifier NNS(DC);
1167 SS.addScopeRep(NNS.getAsOpaquePtr());
1168 }
1169 }
1170
1171 SS.setRange(Range);
1172 return SS;
1173}