blob: e18f1437ab6394054bb19e043a1a01aa0379f9a1 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ExprCXX.h"
Steve Naroff210679c2007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +000017#include "clang/Parse/DeclSpec.h"
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +000018#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000019#include "clang/Basic/Diagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000020#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021using namespace clang;
22
Douglas Gregor487a75a2008-11-19 19:09:45 +000023/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregor2def4832008-11-17 20:34:05 +000024/// name (e.g., operator void const *) as an expression. This is
25/// very similar to ActOnIdentifierExpr, except that instead of
26/// providing an identifier the parser provides the type of the
27/// conversion function.
Douglas Gregor487a75a2008-11-19 19:09:45 +000028Sema::ExprResult
29Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
30 TypeTy *Ty, bool HasTrailingLParen,
31 const CXXScopeSpec &SS) {
Douglas Gregor2def4832008-11-17 20:34:05 +000032 QualType ConvType = QualType::getFromOpaquePtr(Ty);
33 QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
34 DeclarationName ConvName
35 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Douglas Gregor10c42622008-11-18 15:03:34 +000036 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor487a75a2008-11-19 19:09:45 +000037 &SS);
Douglas Gregor2def4832008-11-17 20:34:05 +000038}
Sebastian Redlc42e1182008-11-11 11:37:55 +000039
Douglas Gregor487a75a2008-11-19 19:09:45 +000040/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-11-18 14:39:36 +000041/// name (e.g., @c operator+ ) as an expression. This is very
42/// similar to ActOnIdentifierExpr, except that instead of providing
43/// an identifier the parser provides the kind of overloaded
44/// operator that was parsed.
Douglas Gregor487a75a2008-11-19 19:09:45 +000045Sema::ExprResult
46Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
47 OverloadedOperatorKind Op,
48 bool HasTrailingLParen,
49 const CXXScopeSpec &SS) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000050 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor487a75a2008-11-19 19:09:45 +000051 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000052}
53
Sebastian Redlc42e1182008-11-11 11:37:55 +000054/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
55Action::ExprResult
56Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
57 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
58 const NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000059 if (!StdNs)
60 return Diag(OpLoc, diag::err_need_header_before_typeid);
61
62 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
63 Decl *TypeInfoDecl = LookupDecl(TypeInfoII,
Sebastian Redlc42e1182008-11-11 11:37:55 +000064 Decl::IDNS_Tag | Decl::IDNS_Ordinary,
65 0, StdNs, /*createBuiltins=*/false);
66 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000067 if (!TypeInfoRecordDecl)
68 return Diag(OpLoc, diag::err_need_header_before_typeid);
Sebastian Redlc42e1182008-11-11 11:37:55 +000069
70 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
71
72 return new CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(),
73 SourceRange(OpLoc, RParenLoc));
74}
75
Steve Naroff1b273c42007-09-16 14:56:35 +000076/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Reid Spencer5f016e22007-07-11 17:01:13 +000077Action::ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000078Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000079 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000080 "Unknown C++ Boolean value!");
Steve Naroff210679c2007-08-25 14:02:58 +000081 return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +000082}
Chris Lattner50dd2892008-02-26 00:51:44 +000083
84/// ActOnCXXThrow - Parse throw expressions.
85Action::ExprResult
86Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
87 return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
88}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000089
90Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
91 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
92 /// is a non-lvalue expression whose value is the address of the object for
93 /// which the function is called.
94
95 if (!isa<FunctionDecl>(CurContext)) {
96 Diag(ThisLoc, diag::err_invalid_this_use);
97 return ExprResult(true);
98 }
99
100 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
101 if (MD->isInstance())
Douglas Gregor796da182008-11-04 14:32:21 +0000102 return new CXXThisExpr(ThisLoc, MD->getThisType(Context));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000103
104 return Diag(ThisLoc, diag::err_invalid_this_use);
105}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000106
107/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
108/// Can be interpreted either as function-style casting ("int(x)")
109/// or class type construction ("ClassType(x,y,z)")
110/// or creation of a value-initialized type ("int()").
111Action::ExprResult
112Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
113 SourceLocation LParenLoc,
114 ExprTy **ExprTys, unsigned NumExprs,
115 SourceLocation *CommaLocs,
116 SourceLocation RParenLoc) {
117 assert(TypeRep && "Missing type!");
118 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
119 Expr **Exprs = (Expr**)ExprTys;
120 SourceLocation TyBeginLoc = TypeRange.getBegin();
121 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
122
123 if (const RecordType *RT = Ty->getAsRecordType()) {
124 // C++ 5.2.3p1:
125 // If the simple-type-specifier specifies a class type, the class type shall
126 // be complete.
127 //
128 if (!RT->getDecl()->isDefinition())
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000129 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use)
Chris Lattnerd1625842008-11-24 06:25:27 +0000130 << Ty << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000131
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +0000132 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
133 "class constructors are not supported yet");
134 return Diag(TyBeginLoc, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000135 }
136
137 // C++ 5.2.3p1:
138 // If the expression list is a single expression, the type conversion
139 // expression is equivalent (in definedness, and if defined in meaning) to the
140 // corresponding cast expression.
141 //
142 if (NumExprs == 1) {
143 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
144 return true;
Douglas Gregor49badde2008-10-27 19:41:14 +0000145 return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc,
146 Exprs[0], RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000147 }
148
149 // C++ 5.2.3p1:
150 // If the expression list specifies more than a single value, the type shall
151 // be a class with a suitably declared constructor.
152 //
153 if (NumExprs > 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000154 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg)
155 << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000156
157 assert(NumExprs == 0 && "Expected 0 expressions");
158
159 // C++ 5.2.3p2:
160 // The expression T(), where T is a simple-type-specifier for a non-array
161 // complete object type or the (possibly cv-qualified) void type, creates an
162 // rvalue of the specified type, which is value-initialized.
163 //
164 if (Ty->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000165 return Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange;
Douglas Gregor898574e2008-12-05 23:32:09 +0000166 if (!Ty->isDependentType() && Ty->isIncompleteType() && !Ty->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000167 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use)
Douglas Gregor898574e2008-12-05 23:32:09 +0000168 << Ty << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000169
170 return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
171}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000172
173
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000174/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
175/// @code new (memory) int[size][4] @endcode
176/// or
177/// @code ::new Foo(23, "hello") @endcode
178/// For the interpretation of this heap of arguments, consult the base version.
179Action::ExprResult
180Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
181 SourceLocation PlacementLParen,
182 ExprTy **PlacementArgs, unsigned NumPlaceArgs,
183 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000184 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000185 ExprTy **ConstructorArgs, unsigned NumConsArgs,
186 SourceLocation ConstructorRParen)
187{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000188 // FIXME: Throughout this function, we have rather bad location information.
189 // Implementing Declarator::getSourceRange() would go a long way toward
190 // fixing that.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000191
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000192 Expr *ArraySize = 0;
193 unsigned Skip = 0;
194 // If the specified type is an array, unwrap it and save the expression.
195 if (D.getNumTypeObjects() > 0 &&
196 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
197 DeclaratorChunk &Chunk = D.getTypeObject(0);
198 if (Chunk.Arr.hasStatic)
199 return Diag(Chunk.Loc, diag::err_static_illegal_in_new);
200 if (!Chunk.Arr.NumElts)
201 return Diag(Chunk.Loc, diag::err_array_new_needs_size);
202 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
203 Skip = 1;
204 }
205
206 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
207 if (D.getInvalidType())
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000208 return true;
209
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000210 if (CheckAllocatedType(AllocType, D))
211 return true;
212
213 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000214
215 // That every array dimension except the first is constant was already
216 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000217
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000218 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
219 // or enumeration type with a non-negative value."
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000220 if (ArraySize) {
221 QualType SizeType = ArraySize->getType();
222 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
223 return Diag(ArraySize->getSourceRange().getBegin(),
224 diag::err_array_size_not_integral)
225 << SizeType << ArraySize->getSourceRange();
226 // Let's see if this is a constant < 0. If so, we reject it out of hand.
227 // We don't care about special rules, so we tell the machinery it's not
228 // evaluated - it gives us a result in more cases.
229 llvm::APSInt Value;
230 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
231 if (Value < llvm::APSInt(
232 llvm::APInt::getNullValue(Value.getBitWidth()), false))
233 return Diag(ArraySize->getSourceRange().getBegin(),
234 diag::err_typecheck_negative_array_size)
235 << ArraySize->getSourceRange();
236 }
237 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000238
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000239 FunctionDecl *OperatorNew = 0;
240 FunctionDecl *OperatorDelete = 0;
241 Expr **PlaceArgs = (Expr**)PlacementArgs;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000242 if (FindAllocationFunctions(StartLoc, UseGlobal, AllocType, ArraySize,
243 PlaceArgs, NumPlaceArgs, OperatorNew,
244 OperatorDelete))
245 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000246
247 bool Init = ConstructorLParen.isValid();
248 // --- Choosing a constructor ---
249 // C++ 5.3.4p15
250 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
251 // the object is not initialized. If the object, or any part of it, is
252 // const-qualified, it's an error.
253 // 2) If T is a POD and there's an empty initializer, the object is value-
254 // initialized.
255 // 3) If T is a POD and there's one initializer argument, the object is copy-
256 // constructed.
257 // 4) If T is a POD and there's more initializer arguments, it's an error.
258 // 5) If T is not a POD, the initializer arguments are used as constructor
259 // arguments.
260 //
261 // Or by the C++0x formulation:
262 // 1) If there's no initializer, the object is default-initialized according
263 // to C++0x rules.
264 // 2) Otherwise, the object is direct-initialized.
265 CXXConstructorDecl *Constructor = 0;
266 Expr **ConsArgs = (Expr**)ConstructorArgs;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000267 if (const RecordType *RT = AllocType->getAsRecordType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000268 // FIXME: This is incorrect for when there is an empty initializer and
269 // no user-defined constructor. Must zero-initialize, not default-construct.
270 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000271 AllocType, ConsArgs, NumConsArgs,
272 D.getDeclSpec().getSourceRange().getBegin(),
273 SourceRange(D.getDeclSpec().getSourceRange().getBegin(),
274 ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000275 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000276 NumConsArgs != 0 ? IK_Direct : IK_Default);
277 if (!Constructor)
278 return true;
279 } else {
280 if (!Init) {
281 // FIXME: Check that no subpart is const.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000282 if (AllocType.isConstQualified()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000283 Diag(StartLoc, diag::err_new_uninitialized_const)
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000284 << D.getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000285 return true;
286 }
287 } else if (NumConsArgs == 0) {
288 // Object is value-initialized. Do nothing.
289 } else if (NumConsArgs == 1) {
290 // Object is direct-initialized.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000291 // FIXME: WHAT DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000292 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
293 DeclarationName() /*AllocType.getAsString()*/))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000294 return true;
295 } else {
296 Diag(StartLoc, diag::err_builtin_direct_init_more_than_one_arg)
297 << SourceRange(ConstructorLParen, ConstructorRParen);
298 }
299 }
300
301 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
302
303 return new CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs, NumPlaceArgs,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000304 ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000305 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000306 StartLoc, Init ? ConstructorRParen : SourceLocation());
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000307}
308
309/// CheckAllocatedType - Checks that a type is suitable as the allocated type
310/// in a new-expression.
311/// dimension off and stores the size expression in ArraySize.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000312bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000313{
314 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
315 // abstract class type or array thereof.
316 // FIXME: We don't have abstract types yet.
317 // FIXME: Under C++ semantics, an incomplete object type is still an object
318 // type. This code assumes the C semantics, where it's not.
319 if (!AllocType->isObjectType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000320 unsigned type; // For the select in the message.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000321 if (AllocType->isFunctionType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000322 type = 0;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000323 } else if(AllocType->isIncompleteType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000324 type = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000325 } else {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000326 assert(AllocType->isReferenceType() && "What else could it be?");
327 type = 2;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000328 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000329 SourceRange TyR = D.getDeclSpec().getSourceRange();
330 // FIXME: This is very much a guess and won't work for, e.g., pointers.
331 if (D.getNumTypeObjects() > 0)
332 TyR.setEnd(D.getTypeObject(0).Loc);
333 Diag(TyR.getBegin(), diag::err_bad_new_type)
334 << AllocType.getAsString() << type << TyR;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000335 return true;
336 }
337
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000338 // Every dimension shall be of constant size.
339 unsigned i = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000340 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
341 if (!Array->isConstantArrayType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000342 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
343 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000344 return true;
345 }
346 AllocType = Array->getElementType();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000347 ++i;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000348 }
349
350 return false;
351}
352
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000353/// FindAllocationFunctions - Finds the overloads of operator new and delete
354/// that are appropriate for the allocation.
355bool Sema::FindAllocationFunctions(SourceLocation StartLoc, bool UseGlobal,
356 QualType AllocType, bool IsArray,
357 Expr **PlaceArgs, unsigned NumPlaceArgs,
358 FunctionDecl *&OperatorNew,
359 FunctionDecl *&OperatorDelete)
360{
361 // --- Choosing an allocation function ---
362 // C++ 5.3.4p8 - 14 & 18
363 // 1) If UseGlobal is true, only look in the global scope. Else, also look
364 // in the scope of the allocated class.
365 // 2) If an array size is given, look for operator new[], else look for
366 // operator new.
367 // 3) The first argument is always size_t. Append the arguments from the
368 // placement form.
369 // FIXME: Also find the appropriate delete operator.
370
371 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
372 // We don't care about the actual value of this argument.
373 // FIXME: Should the Sema create the expression and embed it in the syntax
374 // tree? Or should the consumer just recalculate the value?
375 AllocArgs[0] = new IntegerLiteral(llvm::APInt::getNullValue(
376 Context.Target.getPointerWidth(0)),
377 Context.getSizeType(),
378 SourceLocation());
379 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
380
381 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
382 IsArray ? OO_Array_New : OO_New);
383 if (AllocType->isRecordType() && !UseGlobal) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000384 CXXRecordDecl *Record = cast<CXXRecordType>(AllocType->getAsRecordType())
385 ->getDecl();
386 // FIXME: We fail to find inherited overloads.
387 if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0],
388 AllocArgs.size(), Record, /*AllowMissing=*/true,
389 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000390 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000391 }
392 if (!OperatorNew) {
393 // Didn't find a member overload. Look for a global one.
394 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000395 DeclContext *TUDecl = Context.getTranslationUnitDecl();
396 if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0],
397 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
398 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000399 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000400 }
401
Sebastian Redl7f662392008-12-04 22:20:51 +0000402 // FIXME: This is leaked on error. But so much is currently in Sema that it's
403 // easier to clean it in one go.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000404 AllocArgs[0]->Destroy(Context);
405 return false;
406}
407
Sebastian Redl7f662392008-12-04 22:20:51 +0000408/// FindAllocationOverload - Find an fitting overload for the allocation
409/// function in the specified scope.
410bool Sema::FindAllocationOverload(SourceLocation StartLoc, DeclarationName Name,
411 Expr** Args, unsigned NumArgs,
412 DeclContext *Ctx, bool AllowMissing,
413 FunctionDecl *&Operator)
414{
Douglas Gregor44b43212008-12-11 16:49:14 +0000415 DeclContext::lookup_result Lookup = Ctx->lookup(Context, Name);
416 if (Lookup.first == Lookup.second) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000417 if (AllowMissing)
418 return false;
419 // FIXME: Bad location information.
420 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
421 << Name << 0;
422 }
423
424 OverloadCandidateSet Candidates;
Douglas Gregor44b43212008-12-11 16:49:14 +0000425 NamedDecl *Decl = *Lookup.first;
Sebastian Redl7f662392008-12-04 22:20:51 +0000426 // Even member operator new/delete are implicitly treated as static, so don't
427 // use AddMemberCandidate.
428 if (FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Decl))
429 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
430 /*SuppressUserConversions=*/false);
431 else if (OverloadedFunctionDecl *Ovl
432 = dyn_cast_or_null<OverloadedFunctionDecl>(Decl)) {
433 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
434 FEnd = Ovl->function_end();
435 F != FEnd; ++F) {
436 if (FunctionDecl *Fn = *F)
437 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
438 /*SuppressUserConversions=*/false);
439 }
440 }
441
442 // Do the resolution.
443 OverloadCandidateSet::iterator Best;
444 switch(BestViableFunction(Candidates, Best)) {
445 case OR_Success: {
446 // Got one!
447 FunctionDecl *FnDecl = Best->Function;
448 // The first argument is size_t, and the first parameter must be size_t,
449 // too. This is checked on declaration and can be assumed. (It can't be
450 // asserted on, though, since invalid decls are left in there.)
451 for (unsigned i = 1; i < NumArgs; ++i) {
452 // FIXME: Passing word to diagnostic.
453 if (PerformCopyInitialization(Args[i-1],
454 FnDecl->getParamDecl(i)->getType(),
455 "passing"))
456 return true;
457 }
458 Operator = FnDecl;
459 return false;
460 }
461
462 case OR_No_Viable_Function:
463 if (AllowMissing)
464 return false;
465 // FIXME: Bad location information.
466 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
467 << Name << (unsigned)Candidates.size();
468 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
469 return true;
470
471 case OR_Ambiguous:
472 // FIXME: Bad location information.
473 Diag(StartLoc, diag::err_ovl_ambiguous_call)
474 << Name;
475 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
476 return true;
477 }
478 assert(false && "Unreachable, bad result from BestViableFunction");
479 return true;
480}
481
482
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000483/// DeclareGlobalNewDelete - Declare the global forms of operator new and
484/// delete. These are:
485/// @code
486/// void* operator new(std::size_t) throw(std::bad_alloc);
487/// void* operator new[](std::size_t) throw(std::bad_alloc);
488/// void operator delete(void *) throw();
489/// void operator delete[](void *) throw();
490/// @endcode
491/// Note that the placement and nothrow forms of new are *not* implicitly
492/// declared. Their use requires including \<new\>.
493void Sema::DeclareGlobalNewDelete()
494{
495 if (GlobalNewDeleteDeclared)
496 return;
497 GlobalNewDeleteDeclared = true;
498
499 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
500 QualType SizeT = Context.getSizeType();
501
502 // FIXME: Exception specifications are not added.
503 DeclareGlobalAllocationFunction(
504 Context.DeclarationNames.getCXXOperatorName(OO_New),
505 VoidPtr, SizeT);
506 DeclareGlobalAllocationFunction(
507 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
508 VoidPtr, SizeT);
509 DeclareGlobalAllocationFunction(
510 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
511 Context.VoidTy, VoidPtr);
512 DeclareGlobalAllocationFunction(
513 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
514 Context.VoidTy, VoidPtr);
515}
516
517/// DeclareGlobalAllocationFunction - Declares a single implicit global
518/// allocation function if it doesn't already exist.
519void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
520 QualType Return, QualType Argument)
521{
522 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
523
524 // Check if this function is already declared.
525 IdentifierResolver::iterator I = IdResolver.begin(Name, GlobalCtx,
526 /*CheckParent=*/false);
527
528 if (I != IdResolver.end()) {
529 NamedDecl *Decl = *I;
530 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(Decl)) {
531 // The return type fits. This is checked when the function is declared.
532 if (Fn->getNumParams() == 1 &&
533 Context.getCanonicalType(Fn->getParamDecl(0)->getType()) == Argument)
534 return;
535 } else if(OverloadedFunctionDecl *Ovl =
536 dyn_cast<OverloadedFunctionDecl>(Decl)) {
537 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
538 FEnd = Ovl->function_end();
539 F != FEnd; ++F) {
540 if ((*F)->getNumParams() == 1 &&
541 Context.getCanonicalType((*F)->getParamDecl(0)->getType())
542 == Argument)
543 return;
544 }
545 }
546 }
547
548 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
549 FunctionDecl *Alloc =
550 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
551 FnType, FunctionDecl::None, false, 0,
552 SourceLocation());
553 Alloc->setImplicit();
554 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
555 0, Argument, VarDecl::None, 0, 0);
556 Alloc->setParams(&Param, 1);
557
558 PushOnScopeChains(Alloc, TUScope);
559}
560
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000561/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
562/// @code ::delete ptr; @endcode
563/// or
564/// @code delete [] ptr; @endcode
565Action::ExprResult
566Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
567 bool ArrayForm, ExprTy *Operand)
568{
569 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
570 // having a single conversion function to a pointer type. The result has
571 // type void."
572 // DR599 amends "pointer type" to "pointer to object type" in both cases.
573
574 Expr *Ex = (Expr *)Operand;
575 QualType Type = Ex->getType();
576
577 if (Type->isRecordType()) {
578 // FIXME: Find that one conversion function and amend the type.
579 }
580
581 if (!Type->isPointerType()) {
Chris Lattnerd1625842008-11-24 06:25:27 +0000582 Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000583 return true;
584 }
585
586 QualType Pointee = Type->getAsPointerType()->getPointeeType();
587 if (Pointee->isIncompleteType() && !Pointee->isVoidType())
588 Diag(StartLoc, diag::warn_delete_incomplete)
Chris Lattnerd1625842008-11-24 06:25:27 +0000589 << Pointee << Ex->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000590 else if (!Pointee->isObjectType()) {
591 Diag(StartLoc, diag::err_delete_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +0000592 << Type << Ex->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000593 return true;
594 }
595
596 // FIXME: Look up the correct operator delete overload and pass a pointer
597 // along.
598 // FIXME: Check access and ambiguity of operator delete and destructor.
599
600 return new CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 0, Ex,
601 StartLoc);
602}
603
604
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000605/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
606/// C++ if/switch/while/for statement.
607/// e.g: "if (int x = f()) {...}"
608Action::ExprResult
609Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
610 Declarator &D,
611 SourceLocation EqualLoc,
612 ExprTy *AssignExprVal) {
613 assert(AssignExprVal && "Null assignment expression");
614
615 // C++ 6.4p2:
616 // The declarator shall not specify a function or an array.
617 // The type-specifier-seq shall not contain typedef and shall not declare a
618 // new class or enumeration.
619
620 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
621 "Parser allowed 'typedef' as storage class of condition decl.");
622
623 QualType Ty = GetTypeForDeclarator(D, S);
624
625 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
626 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
627 // would be created and CXXConditionDeclExpr wants a VarDecl.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000628 return Diag(StartLoc, diag::err_invalid_use_of_function_type)
629 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000630 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000631 Diag(StartLoc, diag::err_invalid_use_of_array_type)
632 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000633 } else if (const RecordType *RT = Ty->getAsRecordType()) {
634 RecordDecl *RD = RT->getDecl();
635 // The type-specifier-seq shall not declare a new class...
636 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
637 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
638 } else if (const EnumType *ET = Ty->getAsEnumType()) {
639 EnumDecl *ED = ET->getDecl();
640 // ...or enumeration.
641 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
642 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
643 }
644
645 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
646 if (!Dcl)
647 return true;
Sebastian Redl798d1192008-12-13 16:23:55 +0000648 AddInitializerToDecl(Dcl, ExprArg(*this, AssignExprVal));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000649
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000650 // Mark this variable as one that is declared within a conditional.
651 if (VarDecl *VD = dyn_cast<VarDecl>((Decl *)Dcl))
652 VD->setDeclaredInCondition(true);
653
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000654 return new CXXConditionDeclExpr(StartLoc, EqualLoc,
655 cast<VarDecl>(static_cast<Decl *>(Dcl)));
656}
657
658/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
659bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
660 // C++ 6.4p4:
661 // The value of a condition that is an initialized declaration in a statement
662 // other than a switch statement is the value of the declared variable
663 // implicitly converted to type bool. If that conversion is ill-formed, the
664 // program is ill-formed.
665 // The value of a condition that is an expression is the value of the
666 // expression, implicitly converted to bool.
667 //
668 QualType Ty = CondExpr->getType(); // Save the type.
669 AssignConvertType
670 ConvTy = CheckSingleAssignmentConstraints(Context.BoolTy, CondExpr);
671 if (ConvTy == Incompatible)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000672 return Diag(CondExpr->getLocStart(), diag::err_typecheck_bool_condition)
Chris Lattnerd1625842008-11-24 06:25:27 +0000673 << Ty << CondExpr->getSourceRange();
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000674 return false;
675}
Douglas Gregor77a52232008-09-12 00:47:35 +0000676
677/// Helper function to determine whether this is the (deprecated) C++
678/// conversion from a string literal to a pointer to non-const char or
679/// non-const wchar_t (for narrow and wide string literals,
680/// respectively).
681bool
682Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
683 // Look inside the implicit cast, if it exists.
684 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
685 From = Cast->getSubExpr();
686
687 // A string literal (2.13.4) that is not a wide string literal can
688 // be converted to an rvalue of type "pointer to char"; a wide
689 // string literal can be converted to an rvalue of type "pointer
690 // to wchar_t" (C++ 4.2p2).
691 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
692 if (const PointerType *ToPtrType = ToType->getAsPointerType())
693 if (const BuiltinType *ToPointeeType
694 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
695 // This conversion is considered only when there is an
696 // explicit appropriate pointer target type (C++ 4.2p2).
697 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
698 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
699 (!StrLit->isWide() &&
700 (ToPointeeType->getKind() == BuiltinType::Char_U ||
701 ToPointeeType->getKind() == BuiltinType::Char_S))))
702 return true;
703 }
704
705 return false;
706}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000707
708/// PerformImplicitConversion - Perform an implicit conversion of the
709/// expression From to the type ToType. Returns true if there was an
710/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000711/// converted expression. Flavor is the kind of conversion we're
712/// performing, used in the error message.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000713bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000714Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
715 const char *Flavor)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000716{
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000717 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000718 switch (ICS.ConversionKind) {
719 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000720 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000721 return true;
722 break;
723
724 case ImplicitConversionSequence::UserDefinedConversion:
725 // FIXME: This is, of course, wrong. We'll need to actually call
726 // the constructor or conversion operator, and then cope with the
727 // standard conversions.
728 ImpCastExprToType(From, ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000729 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000730
731 case ImplicitConversionSequence::EllipsisConversion:
732 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000733 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000734
735 case ImplicitConversionSequence::BadConversion:
736 return true;
737 }
738
739 // Everything went well.
740 return false;
741}
742
743/// PerformImplicitConversion - Perform an implicit conversion of the
744/// expression From to the type ToType by following the standard
745/// conversion sequence SCS. Returns true if there was an error, false
746/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000747/// expression. Flavor is the context in which we're performing this
748/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000749bool
750Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000751 const StandardConversionSequence& SCS,
752 const char *Flavor)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000753{
754 // Overall FIXME: we are recomputing too many types here and doing
755 // far too much extra work. What this means is that we need to keep
756 // track of more information that is computed when we try the
757 // implicit conversion initially, so that we don't need to recompute
758 // anything here.
759 QualType FromType = From->getType();
760
Douglas Gregor225c41e2008-11-03 19:09:14 +0000761 if (SCS.CopyConstructor) {
762 // FIXME: Create a temporary object by calling the copy
763 // constructor.
764 ImpCastExprToType(From, ToType);
765 return false;
766 }
767
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000768 // Perform the first implicit conversion.
769 switch (SCS.First) {
770 case ICK_Identity:
771 case ICK_Lvalue_To_Rvalue:
772 // Nothing to do.
773 break;
774
775 case ICK_Array_To_Pointer:
Douglas Gregor904eed32008-11-10 20:40:00 +0000776 if (FromType->isOverloadType()) {
777 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
778 if (!Fn)
779 return true;
780
781 FixOverloadedFunctionReference(From, Fn);
782 FromType = From->getType();
783 } else {
784 FromType = Context.getArrayDecayedType(FromType);
785 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000786 ImpCastExprToType(From, FromType);
787 break;
788
789 case ICK_Function_To_Pointer:
790 FromType = Context.getPointerType(FromType);
791 ImpCastExprToType(From, FromType);
792 break;
793
794 default:
795 assert(false && "Improper first standard conversion");
796 break;
797 }
798
799 // Perform the second implicit conversion
800 switch (SCS.Second) {
801 case ICK_Identity:
802 // Nothing to do.
803 break;
804
805 case ICK_Integral_Promotion:
806 case ICK_Floating_Promotion:
807 case ICK_Integral_Conversion:
808 case ICK_Floating_Conversion:
809 case ICK_Floating_Integral:
810 FromType = ToType.getUnqualifiedType();
811 ImpCastExprToType(From, FromType);
812 break;
813
814 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000815 if (SCS.IncompatibleObjC) {
816 // Diagnose incompatible Objective-C conversions
817 Diag(From->getSourceRange().getBegin(),
818 diag::ext_typecheck_convert_incompatible_pointer)
819 << From->getType() << ToType << Flavor
820 << From->getSourceRange();
821 }
822
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000823 if (CheckPointerConversion(From, ToType))
824 return true;
825 ImpCastExprToType(From, ToType);
826 break;
827
828 case ICK_Pointer_Member:
829 // FIXME: Implement pointer-to-member conversions.
830 assert(false && "Pointer-to-member conversions are unsupported");
831 break;
832
833 case ICK_Boolean_Conversion:
834 FromType = Context.BoolTy;
835 ImpCastExprToType(From, FromType);
836 break;
837
838 default:
839 assert(false && "Improper second standard conversion");
840 break;
841 }
842
843 switch (SCS.Third) {
844 case ICK_Identity:
845 // Nothing to do.
846 break;
847
848 case ICK_Qualification:
849 ImpCastExprToType(From, ToType);
850 break;
851
852 default:
853 assert(false && "Improper second standard conversion");
854 break;
855 }
856
857 return false;
858}
859