blob: e856e91ffccdb0168a8bf35ab6f69d5a7980a5d7 [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 Prints the current instantiation stack through a series of
97/// notes.
98void Sema::PrintInstantiationStack() {
99 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
100 Active = ActiveTemplateInstantiations.rbegin(),
101 ActiveEnd = ActiveTemplateInstantiations.rend();
102 Active != ActiveEnd;
103 ++Active) {
Douglas Gregor56d25a72009-03-10 20:44:00 +0000104 switch (Active->Kind) {
105 case ActiveTemplateInstantiation::TemplateInstantiation: {
106 ClassTemplateSpecializationDecl *Spec
107 = cast<ClassTemplateSpecializationDecl>((Decl*)Active->Entity);
108 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
109 diag::note_template_class_instantiation_here)
110 << Context.getTypeDeclType(Spec)
111 << Active->InstantiationRange;
112 break;
113 }
114
115 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
116 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
117 std::string TemplateArgsStr
118 = ClassTemplateSpecializationType::PrintTemplateArgumentList(
119 Active->TemplateArgs,
120 Active->NumTemplateArgs);
121 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
122 diag::note_default_arg_instantiation_here)
123 << (Template->getNameAsString() + TemplateArgsStr)
124 << Active->InstantiationRange;
125 break;
126 }
127 }
Douglas Gregorfee85d62009-03-10 18:03:33 +0000128 }
129}
130
Douglas Gregor74296542009-02-27 19:31:52 +0000131//===----------------------------------------------------------------------===/
132// Template Instantiation for Types
133//===----------------------------------------------------------------------===/
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000134namespace {
135 class VISIBILITY_HIDDEN TemplateTypeInstantiator {
136 Sema &SemaRef;
137 const TemplateArgument *TemplateArgs;
138 unsigned NumTemplateArgs;
139 SourceLocation Loc;
140 DeclarationName Entity;
Douglas Gregor74296542009-02-27 19:31:52 +0000141
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000142 public:
143 TemplateTypeInstantiator(Sema &SemaRef,
144 const TemplateArgument *TemplateArgs,
145 unsigned NumTemplateArgs,
146 SourceLocation Loc,
147 DeclarationName Entity)
148 : SemaRef(SemaRef), TemplateArgs(TemplateArgs),
149 NumTemplateArgs(NumTemplateArgs), Loc(Loc), Entity(Entity) { }
150
151 QualType operator()(QualType T) const { return Instantiate(T); }
152
153 QualType Instantiate(QualType T) const;
154
155 // Declare instantiate functions for each type.
156#define TYPE(Class, Base) \
157 QualType Instantiate##Class##Type(const Class##Type *T, \
158 unsigned Quals) const;
159#define ABSTRACT_TYPE(Class, Base)
160#include "clang/AST/TypeNodes.def"
161 };
162}
163
164QualType
165TemplateTypeInstantiator::InstantiateExtQualType(const ExtQualType *T,
166 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000167 // FIXME: Implement this
168 assert(false && "Cannot instantiate ExtQualType yet");
169 return QualType();
170}
171
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000172QualType
173TemplateTypeInstantiator::InstantiateBuiltinType(const BuiltinType *T,
174 unsigned Quals) const {
Douglas Gregorc0139ca2009-02-28 01:04:19 +0000175 assert(false && "Builtin types are not dependent and cannot be instantiated");
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000176 return QualType(T, Quals);
Douglas Gregor74296542009-02-27 19:31:52 +0000177}
178
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000179QualType
180TemplateTypeInstantiator::
181InstantiateFixedWidthIntType(const FixedWidthIntType *T, unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000182 // FIXME: Implement this
183 assert(false && "Cannot instantiate FixedWidthIntType yet");
184 return QualType();
185}
186
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000187QualType
188TemplateTypeInstantiator::InstantiateComplexType(const ComplexType *T,
189 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000190 // FIXME: Implement this
191 assert(false && "Cannot instantiate ComplexType yet");
192 return QualType();
193}
194
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000195QualType
196TemplateTypeInstantiator::InstantiatePointerType(const PointerType *T,
197 unsigned Quals) const {
198 QualType PointeeType = Instantiate(T->getPointeeType());
199 if (PointeeType.isNull())
200 return QualType();
201
202 return SemaRef.BuildPointerType(PointeeType, Quals, Loc, Entity);
Douglas Gregor74296542009-02-27 19:31:52 +0000203}
204
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000205QualType
206TemplateTypeInstantiator::InstantiateBlockPointerType(const BlockPointerType *T,
207 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000208 // FIXME: Implement this
209 assert(false && "Cannot instantiate BlockPointerType yet");
210 return QualType();
211}
212
Sebastian Redlce6fff02009-03-16 23:22:08 +0000213QualType
214TemplateTypeInstantiator::InstantiateLValueReferenceType(
215 const LValueReferenceType *T, unsigned Quals) const {
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000216 QualType ReferentType = Instantiate(T->getPointeeType());
217 if (ReferentType.isNull())
218 return QualType();
219
Sebastian Redlce6fff02009-03-16 23:22:08 +0000220 return SemaRef.BuildReferenceType(ReferentType, true, Quals, Loc, Entity);
221}
222
223QualType
224TemplateTypeInstantiator::InstantiateRValueReferenceType(
225 const RValueReferenceType *T, unsigned Quals) const {
226 QualType ReferentType = Instantiate(T->getPointeeType());
227 if (ReferentType.isNull())
228 return QualType();
229
230 return SemaRef.BuildReferenceType(ReferentType, false, Quals, Loc, Entity);
Douglas Gregor74296542009-02-27 19:31:52 +0000231}
232
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000233QualType
234TemplateTypeInstantiator::
235InstantiateMemberPointerType(const MemberPointerType *T,
236 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000237 // FIXME: Implement this
238 assert(false && "Cannot instantiate MemberPointerType yet");
239 return QualType();
240}
241
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000242QualType
243TemplateTypeInstantiator::
244InstantiateConstantArrayType(const ConstantArrayType *T,
245 unsigned Quals) const {
246 QualType ElementType = Instantiate(T->getElementType());
247 if (ElementType.isNull())
248 return ElementType;
249
250 // Build a temporary integer literal to specify the size for
251 // BuildArrayType. Since we have already checked the size as part of
252 // creating the dependent array type in the first place, we know
253 // there aren't any errors.
Douglas Gregor448fcd32009-03-09 20:07:22 +0000254 // FIXME: Is IntTy big enough? Maybe not, but LongLongTy causes
255 // problems that I have yet to investigate.
256 IntegerLiteral ArraySize(T->getSize(), SemaRef.Context.IntTy, Loc);
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000257 return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
258 &ArraySize, T->getIndexTypeQualifier(),
259 Loc, Entity);
Douglas Gregor74296542009-02-27 19:31:52 +0000260}
261
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000262QualType
263TemplateTypeInstantiator::
264InstantiateIncompleteArrayType(const IncompleteArrayType *T,
265 unsigned Quals) const {
266 QualType ElementType = Instantiate(T->getElementType());
267 if (ElementType.isNull())
268 return ElementType;
269
270 return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
271 0, T->getIndexTypeQualifier(),
272 Loc, Entity);
Douglas Gregor74296542009-02-27 19:31:52 +0000273}
274
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000275QualType
276TemplateTypeInstantiator::
277InstantiateVariableArrayType(const VariableArrayType *T,
278 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000279 // FIXME: Implement this
280 assert(false && "Cannot instantiate VariableArrayType yet");
281 return QualType();
282}
283
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000284QualType
285TemplateTypeInstantiator::
286InstantiateDependentSizedArrayType(const DependentSizedArrayType *T,
287 unsigned Quals) const {
Anders Carlsson149f2782009-03-15 20:12:13 +0000288 Expr *ArraySize = T->getSizeExpr();
289 assert(ArraySize->isValueDependent() &&
290 "dependent sized array types must have value dependent size expr");
291
292 // Instantiate the element type if needed
293 QualType ElementType = T->getElementType();
294 if (ElementType->isDependentType()) {
295 ElementType = Instantiate(ElementType);
296 if (ElementType.isNull())
297 return QualType();
298 }
299
300 // Instantiate the size expression
301 Sema::OwningExprResult InstantiatedArraySize =
302 SemaRef.InstantiateExpr(ArraySize, TemplateArgs, NumTemplateArgs);
303 if (InstantiatedArraySize.isInvalid())
304 return QualType();
305
306 return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
307 (Expr *)InstantiatedArraySize.release(),
308 T->getIndexTypeQualifier(), Loc, Entity);
Douglas Gregor74296542009-02-27 19:31:52 +0000309}
310
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000311QualType
312TemplateTypeInstantiator::InstantiateVectorType(const VectorType *T,
313 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000314 // FIXME: Implement this
315 assert(false && "Cannot instantiate VectorType yet");
316 return QualType();
317}
318
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000319QualType
320TemplateTypeInstantiator::InstantiateExtVectorType(const ExtVectorType *T,
321 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000322 // FIXME: Implement this
323 assert(false && "Cannot instantiate ExtVectorType yet");
324 return QualType();
325}
326
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000327QualType
328TemplateTypeInstantiator::
329InstantiateFunctionProtoType(const FunctionProtoType *T,
330 unsigned Quals) const {
Douglas Gregorc0139ca2009-02-28 01:04:19 +0000331 QualType ResultType = Instantiate(T->getResultType());
332 if (ResultType.isNull())
333 return ResultType;
334
335 llvm::SmallVector<QualType, 16> ParamTypes;
336 for (FunctionProtoType::arg_type_iterator Param = T->arg_type_begin(),
337 ParamEnd = T->arg_type_end();
338 Param != ParamEnd; ++Param) {
339 QualType P = Instantiate(*Param);
340 if (P.isNull())
341 return P;
342
343 ParamTypes.push_back(P);
344 }
345
346 return SemaRef.BuildFunctionType(ResultType, &ParamTypes[0],
347 ParamTypes.size(),
348 T->isVariadic(), T->getTypeQuals(),
349 Loc, Entity);
Douglas Gregor74296542009-02-27 19:31:52 +0000350}
351
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000352QualType
353TemplateTypeInstantiator::
354InstantiateFunctionNoProtoType(const FunctionNoProtoType *T,
355 unsigned Quals) const {
Douglas Gregorc0139ca2009-02-28 01:04:19 +0000356 assert(false && "Functions without prototypes cannot be dependent.");
Douglas Gregor74296542009-02-27 19:31:52 +0000357 return QualType();
358}
359
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000360QualType
361TemplateTypeInstantiator::InstantiateTypedefType(const TypedefType *T,
362 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000363 // FIXME: Implement this
364 assert(false && "Cannot instantiate TypedefType yet");
365 return QualType();
366}
367
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000368QualType
369TemplateTypeInstantiator::InstantiateTypeOfExprType(const TypeOfExprType *T,
370 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000371 // FIXME: Implement this
372 assert(false && "Cannot instantiate TypeOfExprType yet");
373 return QualType();
374}
375
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000376QualType
377TemplateTypeInstantiator::InstantiateTypeOfType(const TypeOfType *T,
378 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000379 // FIXME: Implement this
380 assert(false && "Cannot instantiate TypeOfType yet");
381 return QualType();
382}
383
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000384QualType
385TemplateTypeInstantiator::InstantiateRecordType(const RecordType *T,
386 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000387 // FIXME: Implement this
388 assert(false && "Cannot instantiate RecordType yet");
389 return QualType();
390}
391
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000392QualType
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000393TemplateTypeInstantiator::InstantiateEnumType(const EnumType *T,
394 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000395 // FIXME: Implement this
396 assert(false && "Cannot instantiate EnumType yet");
397 return QualType();
398}
399
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000400QualType
401TemplateTypeInstantiator::
402InstantiateTemplateTypeParmType(const TemplateTypeParmType *T,
403 unsigned Quals) const {
Douglas Gregor74296542009-02-27 19:31:52 +0000404 if (T->getDepth() == 0) {
405 // Replace the template type parameter with its corresponding
406 // template argument.
407 assert(T->getIndex() < NumTemplateArgs && "Wrong # of template args");
408 assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type &&
409 "Template argument kind mismatch");
410 QualType Result = TemplateArgs[T->getIndex()].getAsType();
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000411 if (Result.isNull() || !Quals)
Douglas Gregor74296542009-02-27 19:31:52 +0000412 return Result;
413
414 // C++ [dcl.ref]p1:
415 // [...] Cv-qualified references are ill-formed except when
416 // the cv-qualifiers are introduced through the use of a
417 // typedef (7.1.3) or of a template type argument (14.3), in
418 // which case the cv-qualifiers are ignored.
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000419 if (Quals && Result->isReferenceType())
420 Quals = 0;
Douglas Gregor74296542009-02-27 19:31:52 +0000421
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000422 return QualType(Result.getTypePtr(), Quals | Result.getCVRQualifiers());
Douglas Gregor74296542009-02-27 19:31:52 +0000423 }
424
425 // The template type parameter comes from an inner template (e.g.,
426 // the template parameter list of a member template inside the
427 // template we are instantiating). Create a new template type
428 // parameter with the template "level" reduced by one.
429 return SemaRef.Context.getTemplateTypeParmType(T->getDepth() - 1,
430 T->getIndex(),
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000431 T->getName())
432 .getQualifiedType(Quals);
Douglas Gregor74296542009-02-27 19:31:52 +0000433}
434
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000435QualType
436TemplateTypeInstantiator::
437InstantiateClassTemplateSpecializationType(
438 const ClassTemplateSpecializationType *T,
439 unsigned Quals) const {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000440 llvm::SmallVector<TemplateArgument, 16> InstantiatedTemplateArgs;
441 InstantiatedTemplateArgs.reserve(T->getNumArgs());
442 for (ClassTemplateSpecializationType::iterator Arg = T->begin(),
443 ArgEnd = T->end();
444 Arg != ArgEnd; ++Arg) {
445 switch (Arg->getKind()) {
446 case TemplateArgument::Type: {
447 QualType T = SemaRef.InstantiateType(Arg->getAsType(),
448 TemplateArgs, NumTemplateArgs,
449 Arg->getLocation(),
450 DeclarationName());
451 if (T.isNull())
452 return QualType();
453
454 InstantiatedTemplateArgs.push_back(
455 TemplateArgument(Arg->getLocation(), T));
456 break;
457 }
458
459 case TemplateArgument::Declaration:
460 case TemplateArgument::Integral:
461 InstantiatedTemplateArgs.push_back(*Arg);
462 break;
463
464 case TemplateArgument::Expression:
Douglas Gregor396f1142009-03-13 21:01:28 +0000465 Sema::OwningExprResult E
466 = SemaRef.InstantiateExpr(Arg->getAsExpr(), TemplateArgs,
467 NumTemplateArgs);
468 if (E.isInvalid())
469 return QualType();
470 InstantiatedTemplateArgs.push_back((Expr *)E.release());
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000471 break;
472 }
473 }
474
475 // FIXME: We're missing the locations of the template name, '<', and
476 // '>'.
477 return SemaRef.CheckClassTemplateId(cast<ClassTemplateDecl>(T->getTemplate()),
478 Loc,
479 SourceLocation(),
480 &InstantiatedTemplateArgs[0],
481 InstantiatedTemplateArgs.size(),
482 SourceLocation());
Douglas Gregor74296542009-02-27 19:31:52 +0000483}
484
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000485QualType
486TemplateTypeInstantiator::
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000487InstantiateQualifiedNameType(const QualifiedNameType *T,
488 unsigned Quals) const {
489 assert(false && "Cannot have dependent qualified name types (yet)");
490 return QualType();
491}
492
493QualType
494TemplateTypeInstantiator::
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000495InstantiateObjCInterfaceType(const ObjCInterfaceType *T,
496 unsigned Quals) const {
497 assert(false && "Objective-C types cannot be dependent");
Douglas Gregor74296542009-02-27 19:31:52 +0000498 return QualType();
499}
500
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000501QualType
502TemplateTypeInstantiator::
503InstantiateObjCQualifiedInterfaceType(const ObjCQualifiedInterfaceType *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::
511InstantiateObjCQualifiedIdType(const ObjCQualifiedIdType *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::
519InstantiateObjCQualifiedClassType(const ObjCQualifiedClassType *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 +0000525/// \brief The actual implementation of Sema::InstantiateType().
526QualType TemplateTypeInstantiator::Instantiate(QualType T) const {
527 // If T is not a dependent type, there is nothing to do.
528 if (!T->isDependentType())
529 return T;
530
531 switch (T->getTypeClass()) {
532#define TYPE(Class, Base) \
533 case Type::Class: \
534 return Instantiate##Class##Type(cast<Class##Type>(T.getTypePtr()), \
535 T.getCVRQualifiers());
536#define ABSTRACT_TYPE(Class, Base)
537#include "clang/AST/TypeNodes.def"
538 }
539
540 assert(false && "Not all types have been decoded for instantiation");
541 return QualType();
542}
Douglas Gregor74296542009-02-27 19:31:52 +0000543
544/// \brief Instantiate the type T with a given set of template arguments.
545///
546/// This routine substitutes the given template arguments into the
547/// type T and produces the instantiated type.
548///
549/// \param T the type into which the template arguments will be
550/// substituted. If this type is not dependent, it will be returned
551/// immediately.
552///
553/// \param TemplateArgs the template arguments that will be
554/// substituted for the top-level template parameters within T.
555///
556/// \param NumTemplateArgs the number of template arguments provided
557/// by TemplateArgs.
558///
559/// \param Loc the location in the source code where this substitution
560/// is being performed. It will typically be the location of the
561/// declarator (if we're instantiating the type of some declaration)
562/// or the location of the type in the source code (if, e.g., we're
563/// instantiating the type of a cast expression).
564///
565/// \param Entity the name of the entity associated with a declaration
566/// being instantiated (if any). May be empty to indicate that there
567/// is no such entity (if, e.g., this is a type that occurs as part of
568/// a cast expression) or that the entity has no name (e.g., an
569/// unnamed function parameter).
570///
571/// \returns If the instantiation succeeds, the instantiated
572/// type. Otherwise, produces diagnostics and returns a NULL type.
573QualType Sema::InstantiateType(QualType T,
574 const TemplateArgument *TemplateArgs,
575 unsigned NumTemplateArgs,
576 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor56d25a72009-03-10 20:44:00 +0000577 assert(!ActiveTemplateInstantiations.empty() &&
578 "Cannot perform an instantiation without some context on the "
579 "instantiation stack");
580
Douglas Gregor74296542009-02-27 19:31:52 +0000581 // If T is not a dependent type, there is nothing to do.
582 if (!T->isDependentType())
583 return T;
584
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000585 TemplateTypeInstantiator Instantiator(*this, TemplateArgs, NumTemplateArgs,
586 Loc, Entity);
587 return Instantiator(T);
Douglas Gregor74296542009-02-27 19:31:52 +0000588}
Douglas Gregored3a3982009-03-03 04:44:36 +0000589
Douglas Gregorbd300312009-03-12 16:53:44 +0000590//===----------------------------------------------------------------------===/
591// Template Instantiation for Expressions
592//===----------------------------------------------------------------------===/
Douglas Gregor95ba1282009-03-12 18:36:18 +0000593namespace {
594 class VISIBILITY_HIDDEN TemplateExprInstantiator
595 : public StmtVisitor<TemplateExprInstantiator, Sema::OwningExprResult> {
596 Sema &SemaRef;
597 const TemplateArgument *TemplateArgs;
598 unsigned NumTemplateArgs;
599
600 public:
Douglas Gregor396f1142009-03-13 21:01:28 +0000601 typedef Sema::OwningExprResult OwningExprResult;
602
Douglas Gregor95ba1282009-03-12 18:36:18 +0000603 TemplateExprInstantiator(Sema &SemaRef,
604 const TemplateArgument *TemplateArgs,
605 unsigned NumTemplateArgs)
606 : SemaRef(SemaRef), TemplateArgs(TemplateArgs),
607 NumTemplateArgs(NumTemplateArgs) { }
608
609 // FIXME: Once we get closer to completion, replace these
610 // manually-written declarations with automatically-generated ones
611 // from clang/AST/StmtNodes.def.
Douglas Gregor396f1142009-03-13 21:01:28 +0000612 OwningExprResult VisitIntegerLiteral(IntegerLiteral *E);
613 OwningExprResult VisitDeclRefExpr(DeclRefExpr *E);
614 OwningExprResult VisitParenExpr(ParenExpr *E);
Douglas Gregorc78182d2009-03-13 23:49:33 +0000615 OwningExprResult VisitUnaryOperator(UnaryOperator *E);
Douglas Gregor396f1142009-03-13 21:01:28 +0000616 OwningExprResult VisitBinaryOperator(BinaryOperator *E);
617 OwningExprResult VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Gabor Greif8a0659c2009-03-18 00:55:04 +0000618 OwningExprResult VisitConditionalOperator(ConditionalOperator *E);
Douglas Gregor396f1142009-03-13 21:01:28 +0000619 OwningExprResult VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000620 OwningExprResult VisitUnresolvedDeclRefExpr(UnresolvedDeclRefExpr *E);
Douglas Gregor396f1142009-03-13 21:01:28 +0000621 OwningExprResult VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
Anders Carlsson121bcad2009-03-17 00:28:02 +0000622 OwningExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
623
Douglas Gregor95ba1282009-03-12 18:36:18 +0000624 // Base case. I'm supposed to ignore this.
Anders Carlsson7f2e7442009-03-15 18:34:13 +0000625 Sema::OwningExprResult VisitStmt(Stmt *S) {
626 S->dump();
Douglas Gregor5b5b6692009-03-12 22:46:12 +0000627 assert(false && "Cannot instantiate this kind of expression");
628 return SemaRef.ExprError();
629 }
Douglas Gregor95ba1282009-03-12 18:36:18 +0000630 };
631}
632
633Sema::OwningExprResult
634TemplateExprInstantiator::VisitIntegerLiteral(IntegerLiteral *E) {
Anders Carlsson7f2e7442009-03-15 18:34:13 +0000635 return SemaRef.Clone(E);
Douglas Gregor95ba1282009-03-12 18:36:18 +0000636}
637
638Sema::OwningExprResult
639TemplateExprInstantiator::VisitDeclRefExpr(DeclRefExpr *E) {
640 Decl *D = E->getDecl();
641 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
642 assert(NTTP->getDepth() == 0 && "No nested templates yet");
Douglas Gregor63f5d602009-03-12 22:20:26 +0000643 const TemplateArgument &Arg = TemplateArgs[NTTP->getPosition()];
Douglas Gregor3b27cc72009-03-16 23:35:25 +0000644 QualType T = Arg.getIntegralType();
645 if (T->isCharType() || T->isWideCharType())
646 return SemaRef.Owned(new (SemaRef.Context) CharacterLiteral(
647 Arg.getAsIntegral()->getZExtValue(),
648 T->isWideCharType(),
649 T,
650 E->getSourceRange().getBegin()));
651 else if (T->isBooleanType())
652 return SemaRef.Owned(new (SemaRef.Context) CXXBoolLiteralExpr(
653 Arg.getAsIntegral()->getBoolValue(),
654 T,
655 E->getSourceRange().getBegin()));
656
Douglas Gregor95ba1282009-03-12 18:36:18 +0000657 return SemaRef.Owned(new (SemaRef.Context) IntegerLiteral(
Douglas Gregor63f5d602009-03-12 22:20:26 +0000658 *Arg.getAsIntegral(),
Douglas Gregor3b27cc72009-03-16 23:35:25 +0000659 T,
Douglas Gregor63f5d602009-03-12 22:20:26 +0000660 E->getSourceRange().getBegin()));
Douglas Gregor95ba1282009-03-12 18:36:18 +0000661 } else
662 assert(false && "Can't handle arbitrary declaration references");
663
664 return SemaRef.ExprError();
665}
666
667Sema::OwningExprResult
668TemplateExprInstantiator::VisitParenExpr(ParenExpr *E) {
Douglas Gregor3ae974b2009-03-17 19:05:46 +0000669 Sema::OwningExprResult SubExpr = Visit(E->getSubExpr());
Douglas Gregor95ba1282009-03-12 18:36:18 +0000670 if (SubExpr.isInvalid())
671 return SemaRef.ExprError();
672
673 return SemaRef.Owned(new (SemaRef.Context) ParenExpr(
674 E->getLParen(), E->getRParen(),
675 (Expr *)SubExpr.release()));
676}
677
Douglas Gregorbd300312009-03-12 16:53:44 +0000678Sema::OwningExprResult
Douglas Gregorc78182d2009-03-13 23:49:33 +0000679TemplateExprInstantiator::VisitUnaryOperator(UnaryOperator *E) {
680 Sema::OwningExprResult Arg = Visit(E->getSubExpr());
681 if (Arg.isInvalid())
682 return SemaRef.ExprError();
683
684 return SemaRef.CreateBuiltinUnaryOp(E->getOperatorLoc(),
685 E->getOpcode(),
686 move(Arg));
687}
688
689Sema::OwningExprResult
Douglas Gregor5b5b6692009-03-12 22:46:12 +0000690TemplateExprInstantiator::VisitBinaryOperator(BinaryOperator *E) {
691 Sema::OwningExprResult LHS = Visit(E->getLHS());
692 if (LHS.isInvalid())
693 return SemaRef.ExprError();
694
695 Sema::OwningExprResult RHS = Visit(E->getRHS());
696 if (RHS.isInvalid())
697 return SemaRef.ExprError();
698
699 Sema::OwningExprResult Result
700 = SemaRef.CreateBuiltinBinOp(E->getOperatorLoc(),
701 E->getOpcode(),
702 (Expr *)LHS.get(),
703 (Expr *)RHS.get());
704 if (Result.isInvalid())
705 return SemaRef.ExprError();
706
707 LHS.release();
708 RHS.release();
709 return move(Result);
710}
711
712Sema::OwningExprResult
Douglas Gregor3fc092f2009-03-13 00:33:25 +0000713TemplateExprInstantiator::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
Douglas Gregorc78182d2009-03-13 23:49:33 +0000714 Sema::OwningExprResult First = Visit(E->getArg(0));
715 if (First.isInvalid())
Douglas Gregor3fc092f2009-03-13 00:33:25 +0000716 return SemaRef.ExprError();
717
Douglas Gregorc78182d2009-03-13 23:49:33 +0000718 Expr *Args[2] = { (Expr *)First.get(), 0 };
Douglas Gregor3fc092f2009-03-13 00:33:25 +0000719
Douglas Gregorc78182d2009-03-13 23:49:33 +0000720 Sema::OwningExprResult Second(SemaRef);
721 if (E->getNumArgs() == 2) {
722 Second = Visit(E->getArg(1));
723
724 if (Second.isInvalid())
725 return SemaRef.ExprError();
726
727 Args[1] = (Expr *)Second.get();
728 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000729
730 if (!E->isTypeDependent()) {
731 // Since our original expression was not type-dependent, we do not
732 // perform lookup again at instantiation time (C++ [temp.dep]p1).
733 // Instead, we just build the new overloaded operator call
734 // expression.
Douglas Gregorc78182d2009-03-13 23:49:33 +0000735 First.release();
736 Second.release();
Douglas Gregor3ae974b2009-03-17 19:05:46 +0000737 // FIXME: Don't reuse the callee here. We need to instantiate it.
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000738 return SemaRef.Owned(new (SemaRef.Context) CXXOperatorCallExpr(
739 SemaRef.Context,
740 E->getOperator(),
741 E->getCallee(),
Douglas Gregorc78182d2009-03-13 23:49:33 +0000742 Args, E->getNumArgs(),
743 E->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000744 E->getOperatorLoc()));
745 }
746
Douglas Gregorc78182d2009-03-13 23:49:33 +0000747 bool isPostIncDec = E->getNumArgs() == 2 &&
748 (E->getOperator() == OO_PlusPlus || E->getOperator() == OO_MinusMinus);
749 if (E->getNumArgs() == 1 || isPostIncDec) {
750 if (!Args[0]->getType()->isOverloadableType()) {
751 // The argument is not of overloadable type, so try to create a
752 // built-in unary operation.
753 UnaryOperator::Opcode Opc
754 = UnaryOperator::getOverloadedOpcode(E->getOperator(), isPostIncDec);
755
756 return SemaRef.CreateBuiltinUnaryOp(E->getOperatorLoc(), Opc,
757 move(First));
758 }
759
760 // Fall through to perform overload resolution
761 } else {
762 assert(E->getNumArgs() == 2 && "Expected binary operation");
763
764 Sema::OwningExprResult Result(SemaRef);
765 if (!Args[0]->getType()->isOverloadableType() &&
766 !Args[1]->getType()->isOverloadableType()) {
767 // Neither of the arguments is an overloadable type, so try to
768 // create a built-in binary operation.
769 BinaryOperator::Opcode Opc =
770 BinaryOperator::getOverloadedOpcode(E->getOperator());
771 Result = SemaRef.CreateBuiltinBinOp(E->getOperatorLoc(), Opc,
772 Args[0], Args[1]);
773 if (Result.isInvalid())
774 return SemaRef.ExprError();
775
776 First.release();
777 Second.release();
778 return move(Result);
779 }
780
781 // Fall through to perform overload resolution.
782 }
783
784 // Compute the set of functions that were found at template
785 // definition time.
786 Sema::FunctionSet Functions;
787 DeclRefExpr *DRE = cast<DeclRefExpr>(E->getCallee());
788 OverloadedFunctionDecl *Overloads
789 = cast<OverloadedFunctionDecl>(DRE->getDecl());
790
791 // FIXME: Do we have to check
792 // IsAcceptableNonMemberOperatorCandidate for each of these?
793 for (OverloadedFunctionDecl::function_iterator
794 F = Overloads->function_begin(),
795 FEnd = Overloads->function_end();
796 F != FEnd; ++F)
797 Functions.insert(*F);
798
799 // Add any functions found via argument-dependent lookup.
800 DeclarationName OpName
801 = SemaRef.Context.DeclarationNames.getCXXOperatorName(E->getOperator());
802 SemaRef.ArgumentDependentLookup(OpName, Args, E->getNumArgs(), Functions);
803
804 // Create the overloaded operator invocation.
805 if (E->getNumArgs() == 1 || isPostIncDec) {
806 UnaryOperator::Opcode Opc
807 = UnaryOperator::getOverloadedOpcode(E->getOperator(), isPostIncDec);
808 return SemaRef.CreateOverloadedUnaryOp(E->getOperatorLoc(), Opc,
809 Functions, move(First));
810 }
811
812 // FIXME: This would be far less ugly if CreateOverloadedBinOp took
813 // in ExprArg arguments!
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000814 BinaryOperator::Opcode Opc =
815 BinaryOperator::getOverloadedOpcode(E->getOperator());
Douglas Gregorc78182d2009-03-13 23:49:33 +0000816 OwningExprResult Result
817 = SemaRef.CreateOverloadedBinOp(E->getOperatorLoc(), Opc,
818 Functions, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000819
Douglas Gregor3fc092f2009-03-13 00:33:25 +0000820 if (Result.isInvalid())
821 return SemaRef.ExprError();
822
Douglas Gregorc78182d2009-03-13 23:49:33 +0000823 First.release();
824 Second.release();
Douglas Gregor3fc092f2009-03-13 00:33:25 +0000825 return move(Result);
826}
827
Gabor Greif8a0659c2009-03-18 00:55:04 +0000828Sema::OwningExprResult
829TemplateExprInstantiator::VisitConditionalOperator(ConditionalOperator *E) {
830 Sema::OwningExprResult Cond = Visit(E->getCond());
831 if (Cond.isInvalid())
832 return SemaRef.ExprError();
833
834 // FIXME: use getLHS() and cope with NULLness
835 Sema::OwningExprResult True = Visit(E->getTrueExpr());
836 if (True.isInvalid())
837 return SemaRef.ExprError();
838
839 Sema::OwningExprResult False = Visit(E->getFalseExpr());
840 if (False.isInvalid())
841 return SemaRef.ExprError();
842
Gabor Greiff85b8ea2009-03-18 20:12:58 +0000843 if (!E->isTypeDependent()) {
844 // Since our original expression was not type-dependent, we do not
845 // perform lookup again at instantiation time (C++ [temp.dep]p1).
846 // Instead, we just build the new conditional operator call expression.
Gabor Greiff85b8ea2009-03-18 20:12:58 +0000847 return SemaRef.Owned(new (SemaRef.Context) ConditionalOperator(
Gabor Greiff4df7da2009-03-18 23:47:39 +0000848 Cond.takeAs<Expr>(),
849 True.takeAs<Expr>(),
850 False.takeAs<Expr>(),
851 E->getType()));
Gabor Greiff85b8ea2009-03-18 20:12:58 +0000852 }
853
854
855 return SemaRef.ActOnConditionalOp(/*FIXME*/E->getCond()->getLocEnd(),
856 /*FIXME*/E->getFalseExpr()->getLocStart(),
Gabor Greif6c24c7f2009-03-18 17:53:25 +0000857 move(Cond), move(True), move(False));
Gabor Greif8a0659c2009-03-18 00:55:04 +0000858}
859
Douglas Gregor3fc092f2009-03-13 00:33:25 +0000860Sema::OwningExprResult
Douglas Gregor396f1142009-03-13 21:01:28 +0000861TemplateExprInstantiator::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
862 bool isSizeOf = E->isSizeOf();
863
864 if (E->isArgumentType()) {
865 QualType T = E->getArgumentType();
866 if (T->isDependentType()) {
867 T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs,
868 /*FIXME*/E->getOperatorLoc(),
Gabor Greif8a0659c2009-03-18 00:55:04 +0000869 &SemaRef.PP.getIdentifierTable().get("sizeof"));
Douglas Gregor396f1142009-03-13 21:01:28 +0000870 if (T.isNull())
871 return SemaRef.ExprError();
872 }
873
874 return SemaRef.CreateSizeOfAlignOfExpr(T, E->getOperatorLoc(), isSizeOf,
875 E->getSourceRange());
876 }
877
878 Sema::OwningExprResult Arg = Visit(E->getArgumentExpr());
879 if (Arg.isInvalid())
880 return SemaRef.ExprError();
881
882 Sema::OwningExprResult Result
883 = SemaRef.CreateSizeOfAlignOfExpr((Expr *)Arg.get(), E->getOperatorLoc(),
884 isSizeOf, E->getSourceRange());
885 if (Result.isInvalid())
886 return SemaRef.ExprError();
887
888 Arg.release();
889 return move(Result);
890}
891
892Sema::OwningExprResult
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000893TemplateExprInstantiator::VisitUnresolvedDeclRefExpr(UnresolvedDeclRefExpr *E) {
894 CXXScopeSpec SS = SemaRef.InstantiateScopeSpecifier(E->begin(), E->size(),
895 E->getQualifierRange(),
896 TemplateArgs,
897 NumTemplateArgs);
898 if (SS.isInvalid() || SS.isEmpty())
899 return SemaRef.ExprError();
900
901 // FIXME: We're passing in a NULL scope, because
902 // ActOnDeclarationNameExpr doesn't actually use the scope when we
903 // give it a non-empty scope specifier. Investigate whether it would
904 // be better to refactor ActOnDeclarationNameExpr.
905 return SemaRef.ActOnDeclarationNameExpr(/*Scope=*/0, E->getLocation(),
906 E->getDeclName(),
907 /*HasTrailingLParen=*/false,
908 &SS,
909 /*FIXME:isAddressOfOperand=*/false);
910}
911
912Sema::OwningExprResult
Douglas Gregor396f1142009-03-13 21:01:28 +0000913TemplateExprInstantiator::VisitCXXTemporaryObjectExpr(
914 CXXTemporaryObjectExpr *E) {
915 QualType T = E->getType();
916 if (T->isDependentType()) {
917 T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs,
918 E->getTypeBeginLoc(), DeclarationName());
919 if (T.isNull())
920 return SemaRef.ExprError();
921 }
922
923 llvm::SmallVector<Expr *, 16> Args;
924 Args.reserve(E->getNumArgs());
925 bool Invalid = false;
926 for (CXXTemporaryObjectExpr::arg_iterator Arg = E->arg_begin(),
927 ArgEnd = E->arg_end();
928 Arg != ArgEnd; ++Arg) {
929 OwningExprResult InstantiatedArg = Visit(*Arg);
930 if (InstantiatedArg.isInvalid()) {
931 Invalid = true;
932 break;
933 }
934
935 Args.push_back((Expr *)InstantiatedArg.release());
936 }
937
938 if (!Invalid) {
939 SourceLocation CommaLoc;
940 // FIXME: HACK!
941 if (Args.size() > 1)
942 CommaLoc
943 = SemaRef.PP.getLocForEndOfToken(Args[0]->getSourceRange().getEnd());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000944 Sema::OwningExprResult Result(
945 SemaRef.ActOnCXXTypeConstructExpr(SourceRange(E->getTypeBeginLoc()
946 /*, FIXME*/),
947 T.getAsOpaquePtr(),
948 /*FIXME*/E->getTypeBeginLoc(),
949 Sema::MultiExprArg(SemaRef,
950 (void**)&Args[0],
951 Args.size()),
952 /*HACK*/&CommaLoc,
953 E->getSourceRange().getEnd()));
954 // At this point, Args no longer owns the arguments, no matter what.
955 return move(Result);
Douglas Gregor396f1142009-03-13 21:01:28 +0000956 }
957
958 // Clean up the instantiated arguments.
959 // FIXME: Would rather do this with RAII.
960 for (unsigned Idx = 0; Idx < Args.size(); ++Idx)
961 SemaRef.DeleteExpr(Args[Idx]);
962
963 return SemaRef.ExprError();
964}
965
Anders Carlsson121bcad2009-03-17 00:28:02 +0000966Sema::OwningExprResult TemplateExprInstantiator::VisitImplicitCastExpr(
967 ImplicitCastExpr *E) {
968 assert(!E->isTypeDependent() && "Implicit casts must have known types");
969
970 Sema::OwningExprResult SubExpr = Visit(E->getSubExpr());
971 if (SubExpr.isInvalid())
972 return SemaRef.ExprError();
973
974 ImplicitCastExpr *ICE =
975 new (SemaRef.Context) ImplicitCastExpr(E->getType(),
976 (Expr *)SubExpr.release(),
977 E->isLvalueCast());
978 return SemaRef.Owned(ICE);
979}
980
Douglas Gregor396f1142009-03-13 21:01:28 +0000981Sema::OwningExprResult
Douglas Gregorbd300312009-03-12 16:53:44 +0000982Sema::InstantiateExpr(Expr *E, const TemplateArgument *TemplateArgs,
983 unsigned NumTemplateArgs) {
Douglas Gregor95ba1282009-03-12 18:36:18 +0000984 TemplateExprInstantiator Instantiator(*this, TemplateArgs, NumTemplateArgs);
985 return Instantiator.Visit(E);
Douglas Gregorbd300312009-03-12 16:53:44 +0000986}
987
Douglas Gregored3a3982009-03-03 04:44:36 +0000988/// \brief Instantiate the base class specifiers of the given class
989/// template specialization.
990///
991/// Produces a diagnostic and returns true on error, returns false and
992/// attaches the instantiated base classes to the class template
993/// specialization if successful.
994bool
995Sema::InstantiateBaseSpecifiers(
996 ClassTemplateSpecializationDecl *ClassTemplateSpec,
997 ClassTemplateDecl *ClassTemplate) {
998 bool Invalid = false;
999 llvm::SmallVector<CXXBaseSpecifier*, 8> InstantiatedBases;
1000 for (ClassTemplateSpecializationDecl::base_class_iterator
1001 Base = ClassTemplate->getTemplatedDecl()->bases_begin(),
1002 BaseEnd = ClassTemplate->getTemplatedDecl()->bases_end();
Douglas Gregord9572a12009-03-10 18:52:44 +00001003 Base != BaseEnd; ++Base) {
Douglas Gregored3a3982009-03-03 04:44:36 +00001004 if (!Base->getType()->isDependentType()) {
1005 // FIXME: Allocate via ASTContext
1006 InstantiatedBases.push_back(new CXXBaseSpecifier(*Base));
1007 continue;
1008 }
1009
1010 QualType BaseType = InstantiateType(Base->getType(),
1011 ClassTemplateSpec->getTemplateArgs(),
1012 ClassTemplateSpec->getNumTemplateArgs(),
1013 Base->getSourceRange().getBegin(),
1014 DeclarationName());
1015 if (BaseType.isNull()) {
1016 Invalid = true;
1017 continue;
1018 }
1019
1020 if (CXXBaseSpecifier *InstantiatedBase
1021 = CheckBaseSpecifier(ClassTemplateSpec,
1022 Base->getSourceRange(),
1023 Base->isVirtual(),
1024 Base->getAccessSpecifierAsWritten(),
1025 BaseType,
1026 /*FIXME: Not totally accurate */
1027 Base->getSourceRange().getBegin()))
1028 InstantiatedBases.push_back(InstantiatedBase);
1029 else
1030 Invalid = true;
1031 }
1032
Douglas Gregord9572a12009-03-10 18:52:44 +00001033 if (!Invalid &&
1034 AttachBaseSpecifiers(ClassTemplateSpec, &InstantiatedBases[0],
Douglas Gregored3a3982009-03-03 04:44:36 +00001035 InstantiatedBases.size()))
1036 Invalid = true;
1037
1038 return Invalid;
1039}
1040
1041bool
1042Sema::InstantiateClassTemplateSpecialization(
1043 ClassTemplateSpecializationDecl *ClassTemplateSpec,
1044 bool ExplicitInstantiation) {
1045 // Perform the actual instantiation on the canonical declaration.
1046 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
1047 Context.getCanonicalDecl(ClassTemplateSpec));
1048
1049 // We can only instantiate something that hasn't already been
1050 // instantiated or specialized. Fail without any diagnostics: our
1051 // caller will provide an error message.
1052 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared)
1053 return true;
1054
1055 // FIXME: Push this class template instantiation onto the
1056 // instantiation stack, checking for recursion that exceeds a
1057 // certain depth.
1058
1059 // FIXME: Perform class template partial specialization to select
1060 // the best template.
1061 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
1062
Douglas Gregor47bde7c2009-03-19 17:26:29 +00001063 RecordDecl *Pattern = cast_or_null<RecordDecl>(
1064 Template->getTemplatedDecl()->getDefinition(Context));
1065 if (!Pattern) {
Douglas Gregored3a3982009-03-03 04:44:36 +00001066 Diag(ClassTemplateSpec->getLocation(),
1067 diag::err_template_implicit_instantiate_undefined)
1068 << Context.getTypeDeclType(ClassTemplateSpec);
1069 Diag(Template->getTemplatedDecl()->getLocation(),
1070 diag::note_template_decl_here);
1071 return true;
1072 }
1073
1074 // Note that this is an instantiation.
1075 ClassTemplateSpec->setSpecializationKind(
1076 ExplicitInstantiation? TSK_ExplicitInstantiation
1077 : TSK_ImplicitInstantiation);
1078
1079
1080 bool Invalid = false;
1081
Douglas Gregor375733c2009-03-10 00:06:19 +00001082 InstantiatingTemplate Inst(*this, ClassTemplateSpec->getLocation(),
1083 ClassTemplateSpec);
1084 if (Inst)
1085 return true;
1086
Douglas Gregored3a3982009-03-03 04:44:36 +00001087 // Enter the scope of this instantiation. We don't use
1088 // PushDeclContext because we don't have a scope.
1089 DeclContext *PreviousContext = CurContext;
1090 CurContext = ClassTemplateSpec;
1091
1092 // Start the definition of this instantiation.
1093 ClassTemplateSpec->startDefinition();
1094
Douglas Gregored3a3982009-03-03 04:44:36 +00001095 // Instantiate the base class specifiers.
1096 if (InstantiateBaseSpecifiers(ClassTemplateSpec, Template))
1097 Invalid = true;
1098
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00001099 // FIXME: Create the injected-class-name for the
1100 // instantiation. Should this be a typedef or something like it?
1101
Douglas Gregor0e518af2009-03-11 18:59:21 +00001102 llvm::SmallVector<DeclTy *, 32> Fields;
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00001103 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
1104 MemberEnd = Pattern->decls_end();
1105 Member != MemberEnd; ++Member) {
Douglas Gregor1b39ef42009-03-17 21:15:40 +00001106 Decl *NewMember = InstantiateDecl(*Member, ClassTemplateSpec,
1107 ClassTemplateSpec->getTemplateArgs(),
1108 ClassTemplateSpec->getNumTemplateArgs());
1109 if (NewMember) {
1110 if (NewMember->isInvalidDecl())
Anders Carlssonc45057a2009-03-15 18:44:04 +00001111 Invalid = true;
Douglas Gregor1b39ef42009-03-17 21:15:40 +00001112 else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
1113 Fields.push_back(Field);
1114 } else {
1115 // FIXME: Eventually, a NULL return will mean that one of the
1116 // instantiations was a semantic disaster, and we'll want to set
1117 // Invalid = true. For now, we expect to skip some members that
1118 // we can't yet handle.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00001119 }
1120 }
1121
Douglas Gregor0e518af2009-03-11 18:59:21 +00001122 // Finish checking fields.
1123 ActOnFields(0, ClassTemplateSpec->getLocation(), ClassTemplateSpec,
1124 &Fields[0], Fields.size(), SourceLocation(), SourceLocation(),
1125 0);
1126
Douglas Gregored3a3982009-03-03 04:44:36 +00001127 // Add any implicitly-declared members that we might need.
1128 AddImplicitlyDeclaredMembersToClass(ClassTemplateSpec);
1129
Douglas Gregored3a3982009-03-03 04:44:36 +00001130 // Exit the scope of this instantiation.
1131 CurContext = PreviousContext;
1132
1133 return Invalid;
1134}
Douglas Gregor47bde7c2009-03-19 17:26:29 +00001135
1136/// \brief Instantiate a sequence of nested-name-specifiers into a
1137/// scope specifier.
1138CXXScopeSpec
1139Sema::InstantiateScopeSpecifier(const NestedNameSpecifier *Components,
1140 unsigned NumComponents,
1141 SourceRange Range,
1142 const TemplateArgument *TemplateArgs,
1143 unsigned NumTemplateArgs) {
1144 CXXScopeSpec SS;
1145 for (unsigned Comp = 0; Comp < NumComponents; ++Comp) {
1146 if (Type *T = Components[Comp].getAsType()) {
1147 QualType NewT = InstantiateType(QualType(T, 0), TemplateArgs,
1148 NumTemplateArgs, Range.getBegin(),
1149 DeclarationName());
1150 if (NewT.isNull())
1151 return SS;
1152 NestedNameSpecifier NNS(NewT.getTypePtr());
1153 SS.addScopeRep(NNS.getAsOpaquePtr());
1154 } else {
1155 DeclContext *DC = Components[Comp].getAsDeclContext();
1156 // FIXME: injected-class-name might be dependent, and therefore
1157 // would need instantiation.
1158 NestedNameSpecifier NNS(DC);
1159 SS.addScopeRep(NNS.getAsOpaquePtr());
1160 }
1161 }
1162
1163 SS.setRange(Range);
1164 return SS;
1165}