blob: 2abf87b23f5184fcddd6ebb8f449f1e578b4c5d5 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
Sebastian Redlaa4c3732009-02-07 20:10:22 +000014#include "SemaInherit.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "Sema.h"
16#include "clang/AST/ExprCXX.h"
Steve Naroffac5d4f12007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +000018#include "clang/Parse/DeclSpec.h"
Argiris Kirtzidiscf4e8f82008-10-06 23:16:35 +000019#include "clang/Lex/Preprocessor.h"
Sebastian Redlb5ee8742008-12-03 20:26:15 +000020#include "clang/Basic/TargetInfo.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000021#include "llvm/ADT/STLExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022using namespace clang;
23
Douglas Gregor24094772008-11-19 19:09:45 +000024/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregorb0212bd2008-11-17 20:34:05 +000025/// name (e.g., operator void const *) as an expression. This is
26/// very similar to ActOnIdentifierExpr, except that instead of
27/// providing an identifier the parser provides the type of the
28/// conversion function.
Sebastian Redlcd883f72009-01-18 18:53:16 +000029Sema::OwningExprResult
Douglas Gregor24094772008-11-19 19:09:45 +000030Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
31 TypeTy *Ty, bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +000032 const CXXScopeSpec &SS,
33 bool isAddressOfOperand) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +000034 QualType ConvType = QualType::getFromOpaquePtr(Ty);
35 QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
36 DeclarationName ConvName
37 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd883f72009-01-18 18:53:16 +000038 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +000039 &SS, isAddressOfOperand);
Douglas Gregorb0212bd2008-11-17 20:34:05 +000040}
Sebastian Redlb93b49c2008-11-11 11:37:55 +000041
Douglas Gregor24094772008-11-19 19:09:45 +000042/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregor96a32dd2008-11-18 14:39:36 +000043/// name (e.g., @c operator+ ) as an expression. This is very
44/// similar to ActOnIdentifierExpr, except that instead of providing
45/// an identifier the parser provides the kind of overloaded
46/// operator that was parsed.
Sebastian Redlcd883f72009-01-18 18:53:16 +000047Sema::OwningExprResult
Douglas Gregor24094772008-11-19 19:09:45 +000048Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
49 OverloadedOperatorKind Op,
50 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +000051 const CXXScopeSpec &SS,
52 bool isAddressOfOperand) {
Douglas Gregor96a32dd2008-11-18 14:39:36 +000053 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redl0c9da212009-02-03 20:19:35 +000054 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +000055 isAddressOfOperand);
Douglas Gregor96a32dd2008-11-18 14:39:36 +000056}
57
Sebastian Redlb93b49c2008-11-11 11:37:55 +000058/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000059Action::OwningExprResult
Sebastian Redlb93b49c2008-11-11 11:37:55 +000060Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
61 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor52ae30c2009-01-30 01:04:22 +000062 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattnerc2a5f512008-11-20 05:51:55 +000063 if (!StdNs)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000064 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Chris Lattnerc2a5f512008-11-20 05:51:55 +000065
66 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor52ae30c2009-01-30 01:04:22 +000067 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlb93b49c2008-11-11 11:37:55 +000068 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattnerc2a5f512008-11-20 05:51:55 +000069 if (!TypeInfoRecordDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000070 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlb93b49c2008-11-11 11:37:55 +000071
72 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
73
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000074 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
75 TypeInfoType.withConst(),
76 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlb93b49c2008-11-11 11:37:55 +000077}
78
Steve Naroff5cbb02f2007-09-16 14:56:35 +000079/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000080Action::OwningExprResult
Steve Naroff5cbb02f2007-09-16 14:56:35 +000081Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregorf8e92702008-10-24 15:36:09 +000082 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Chris Lattner4b009652007-07-25 00:24:17 +000083 "Unknown C++ Boolean value!");
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000084 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
85 Context.BoolTy, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +000086}
Chris Lattnera7447ba2008-02-26 00:51:44 +000087
88/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000089Action::OwningExprResult
90Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
91 return Owned(new (Context) CXXThrowExpr((Expr*)E.release(), Context.VoidTy,
92 OpLoc));
Chris Lattnera7447ba2008-02-26 00:51:44 +000093}
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000094
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000095Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000096 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
97 /// is a non-lvalue expression whose value is the address of the object for
98 /// which the function is called.
99
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000100 if (!isa<FunctionDecl>(CurContext))
101 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000102
103 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
104 if (MD->isInstance())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000105 return Owned(new (Context) CXXThisExpr(ThisLoc,
106 MD->getThisType(Context)));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000107
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000108 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000109}
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000110
111/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
112/// Can be interpreted either as function-style casting ("int(x)")
113/// or class type construction ("ClassType(x,y,z)")
114/// or creation of a value-initialized type ("int()").
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000115Action::OwningExprResult
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000116Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
117 SourceLocation LParenLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000118 MultiExprArg exprs,
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000119 SourceLocation *CommaLocs,
120 SourceLocation RParenLoc) {
121 assert(TypeRep && "Missing type!");
122 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000123 unsigned NumExprs = exprs.size();
124 Expr **Exprs = (Expr**)exprs.get();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000125 SourceLocation TyBeginLoc = TypeRange.getBegin();
126 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
127
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000128 if (Ty->isDependentType() ||
Douglas Gregor396f1142009-03-13 21:01:28 +0000129 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000130 exprs.release();
131 return Owned(new (Context) CXXTemporaryObjectExpr(0, Ty, TyBeginLoc,
132 Exprs, NumExprs,
133 RParenLoc));
Douglas Gregor396f1142009-03-13 21:01:28 +0000134 }
135
136
Douglas Gregor861e7902009-01-16 18:33:17 +0000137 // C++ [expr.type.conv]p1:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000138 // 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]))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000144 return ExprError();
145 exprs.release();
146 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
147 Ty, TyBeginLoc, Exprs[0],
148 RParenLoc));
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000149 }
150
Douglas Gregor861e7902009-01-16 18:33:17 +0000151 if (const RecordType *RT = Ty->getAsRecordType()) {
152 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000153
Douglas Gregor861e7902009-01-16 18:33:17 +0000154 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
155 CXXConstructorDecl *Constructor
156 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
157 TypeRange.getBegin(),
158 SourceRange(TypeRange.getBegin(),
159 RParenLoc),
160 DeclarationName(),
161 IK_Direct);
Douglas Gregor861e7902009-01-16 18:33:17 +0000162
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000163 if (!Constructor)
164 return ExprError();
165
166 exprs.release();
167 return Owned(new (Context) CXXTemporaryObjectExpr(Constructor, Ty,
168 TyBeginLoc, Exprs,
169 NumExprs, RParenLoc));
Douglas Gregor861e7902009-01-16 18:33:17 +0000170 }
171
172 // Fall through to value-initialize an object of class type that
173 // doesn't have a user-declared default constructor.
174 }
175
176 // C++ [expr.type.conv]p1:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000177 // If the expression list specifies more than a single value, the type shall
178 // be a class with a suitably declared constructor.
179 //
180 if (NumExprs > 1)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000181 return ExprError(Diag(CommaLocs[0],
182 diag::err_builtin_func_cast_more_than_one_arg)
183 << FullRange);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000184
185 assert(NumExprs == 0 && "Expected 0 expressions");
186
Douglas Gregor861e7902009-01-16 18:33:17 +0000187 // C++ [expr.type.conv]p2:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000188 // The expression T(), where T is a simple-type-specifier for a non-array
189 // complete object type or the (possibly cv-qualified) void type, creates an
190 // rvalue of the specified type, which is value-initialized.
191 //
192 if (Ty->isArrayType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000193 return ExprError(Diag(TyBeginLoc,
194 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000195 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000196 RequireCompleteType(TyBeginLoc, Ty,
197 diag::err_invalid_incomplete_type_use, FullRange))
198 return ExprError();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000199
Anders Carlsson412c3402009-03-24 01:19:16 +0000200 if (RequireNonAbstractType(TyBeginLoc, Ty,
201 diag::err_allocation_of_abstract_type))
Anders Carlssonc263c9b2009-03-23 19:10:31 +0000202 return ExprError();
203
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000204 exprs.release();
205 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000206}
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000207
208
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000209/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
210/// @code new (memory) int[size][4] @endcode
211/// or
212/// @code ::new Foo(23, "hello") @endcode
213/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000214Action::OwningExprResult
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000215Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000216 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000217 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000218 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000219 MultiExprArg ConstructorArgs,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000220 SourceLocation ConstructorRParen)
221{
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000222 Expr *ArraySize = 0;
223 unsigned Skip = 0;
224 // If the specified type is an array, unwrap it and save the expression.
225 if (D.getNumTypeObjects() > 0 &&
226 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
227 DeclaratorChunk &Chunk = D.getTypeObject(0);
228 if (Chunk.Arr.hasStatic)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000229 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
230 << D.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000231 if (!Chunk.Arr.NumElts)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000232 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
233 << D.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000234 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
235 Skip = 1;
236 }
237
238 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
239 if (D.getInvalidType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000240 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000241
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000242 if (CheckAllocatedType(AllocType, D))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000243 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000244
Anders Carlssond5a94982009-03-23 17:49:10 +0000245 if (RequireNonAbstractType(D.getSourceRange().getBegin(), AllocType,
Anders Carlsson412c3402009-03-24 01:19:16 +0000246 diag::err_allocation_of_abstract_type))
Anders Carlssond5a94982009-03-23 17:49:10 +0000247 return ExprError();
248
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000249 QualType ResultType = AllocType->isDependentType()
250 ? Context.DependentTy
251 : Context.getPointerType(AllocType);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000252
253 // That every array dimension except the first is constant was already
254 // checked by the type check above.
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000255
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000256 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
257 // or enumeration type with a non-negative value."
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000258 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000259 QualType SizeType = ArraySize->getType();
260 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000261 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
262 diag::err_array_size_not_integral)
263 << SizeType << ArraySize->getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000264 // Let's see if this is a constant < 0. If so, we reject it out of hand.
265 // We don't care about special rules, so we tell the machinery it's not
266 // evaluated - it gives us a result in more cases.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000267 if (!ArraySize->isValueDependent()) {
268 llvm::APSInt Value;
269 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
270 if (Value < llvm::APSInt(
271 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000272 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
273 diag::err_typecheck_negative_array_size)
274 << ArraySize->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000275 }
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000276 }
277 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000278
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000279 FunctionDecl *OperatorNew = 0;
280 FunctionDecl *OperatorDelete = 0;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000281 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
282 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000283 if (!AllocType->isDependentType() &&
284 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
285 FindAllocationFunctions(StartLoc,
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000286 SourceRange(PlacementLParen, PlacementRParen),
287 UseGlobal, AllocType, ArraySize, PlaceArgs,
288 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000289 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000290
291 bool Init = ConstructorLParen.isValid();
292 // --- Choosing a constructor ---
293 // C++ 5.3.4p15
294 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
295 // the object is not initialized. If the object, or any part of it, is
296 // const-qualified, it's an error.
297 // 2) If T is a POD and there's an empty initializer, the object is value-
298 // initialized.
299 // 3) If T is a POD and there's one initializer argument, the object is copy-
300 // constructed.
301 // 4) If T is a POD and there's more initializer arguments, it's an error.
302 // 5) If T is not a POD, the initializer arguments are used as constructor
303 // arguments.
304 //
305 // Or by the C++0x formulation:
306 // 1) If there's no initializer, the object is default-initialized according
307 // to C++0x rules.
308 // 2) Otherwise, the object is direct-initialized.
309 CXXConstructorDecl *Constructor = 0;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000310 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
311 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000312 if (AllocType->isDependentType()) {
313 // Skip all the checks.
314 }
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000315 // FIXME: Should check for primitive/aggregate here, not record.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000316 else if (const RecordType *RT = AllocType->getAsRecordType()) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000317 // FIXME: This is incorrect for when there is an empty initializer and
318 // no user-defined constructor. Must zero-initialize, not default-construct.
319 Constructor = PerformInitializationByConstructor(
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000320 AllocType, ConsArgs, NumConsArgs,
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000321 D.getSourceRange().getBegin(),
322 SourceRange(D.getSourceRange().getBegin(),
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000323 ConstructorRParen),
Chris Lattner271d4c22008-11-24 05:29:24 +0000324 RT->getDecl()->getDeclName(),
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000325 NumConsArgs != 0 ? IK_Direct : IK_Default);
326 if (!Constructor)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000327 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000328 } else {
329 if (!Init) {
330 // FIXME: Check that no subpart is const.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000331 if (AllocType.isConstQualified())
332 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
333 << D.getSourceRange());
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000334 } else if (NumConsArgs == 0) {
335 // Object is value-initialized. Do nothing.
336 } else if (NumConsArgs == 1) {
337 // Object is direct-initialized.
Chris Lattner271d4c22008-11-24 05:29:24 +0000338 // FIXME: WHAT DeclarationName do we pass in here?
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000339 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000340 DeclarationName() /*AllocType.getAsString()*/,
341 /*DirectInit=*/true))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000342 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000343 } else {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000344 return ExprError(Diag(StartLoc,
345 diag::err_builtin_direct_init_more_than_one_arg)
346 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000347 }
348 }
349
350 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
351
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000352 PlacementArgs.release();
353 ConstructorArgs.release();
354 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek0c97e042009-02-07 01:47:29 +0000355 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000356 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000357 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000358}
359
360/// CheckAllocatedType - Checks that a type is suitable as the allocated type
361/// in a new-expression.
362/// dimension off and stores the size expression in ArraySize.
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000363bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000364{
365 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
366 // abstract class type or array thereof.
367 // FIXME: We don't have abstract types yet.
368 // FIXME: Under C++ semantics, an incomplete object type is still an object
369 // type. This code assumes the C semantics, where it's not.
370 if (!AllocType->isObjectType()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000371 unsigned type; // For the select in the message.
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000372 if (AllocType->isFunctionType()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000373 type = 0;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000374 } else if(AllocType->isIncompleteType()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000375 type = 1;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000376 } else {
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000377 assert(AllocType->isReferenceType() && "Unhandled non-object type.");
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000378 type = 2;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000379 }
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000380 Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
381 << AllocType << type << D.getSourceRange();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000382 return true;
383 }
384
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000385 // Every dimension shall be of constant size.
386 unsigned i = 1;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000387 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
388 if (!Array->isConstantArrayType()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000389 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
390 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000391 return true;
392 }
393 AllocType = Array->getElementType();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000394 ++i;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000395 }
396
397 return false;
398}
399
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000400/// FindAllocationFunctions - Finds the overloads of operator new and delete
401/// that are appropriate for the allocation.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000402bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
403 bool UseGlobal, QualType AllocType,
404 bool IsArray, Expr **PlaceArgs,
405 unsigned NumPlaceArgs,
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000406 FunctionDecl *&OperatorNew,
407 FunctionDecl *&OperatorDelete)
408{
409 // --- Choosing an allocation function ---
410 // C++ 5.3.4p8 - 14 & 18
411 // 1) If UseGlobal is true, only look in the global scope. Else, also look
412 // in the scope of the allocated class.
413 // 2) If an array size is given, look for operator new[], else look for
414 // operator new.
415 // 3) The first argument is always size_t. Append the arguments from the
416 // placement form.
417 // FIXME: Also find the appropriate delete operator.
418
419 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
420 // We don't care about the actual value of this argument.
421 // FIXME: Should the Sema create the expression and embed it in the syntax
422 // tree? Or should the consumer just recalculate the value?
Ted Kremenek0c97e042009-02-07 01:47:29 +0000423 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000424 Context.Target.getPointerWidth(0)),
425 Context.getSizeType(),
426 SourceLocation());
427 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
428
429 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
430 IsArray ? OO_Array_New : OO_New);
431 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregor2e047592009-02-28 01:32:25 +0000432 CXXRecordDecl *Record
433 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
Sebastian Redlec5f3262008-12-04 22:20:51 +0000434 // FIXME: We fail to find inherited overloads.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000435 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000436 AllocArgs.size(), Record, /*AllowMissing=*/true,
437 OperatorNew))
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000438 return true;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000439 }
440 if (!OperatorNew) {
441 // Didn't find a member overload. Look for a global one.
442 DeclareGlobalNewDelete();
Sebastian Redlec5f3262008-12-04 22:20:51 +0000443 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000444 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000445 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
446 OperatorNew))
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000447 return true;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000448 }
449
Sebastian Redlec5f3262008-12-04 22:20:51 +0000450 // FIXME: This is leaked on error. But so much is currently in Sema that it's
451 // easier to clean it in one go.
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000452 AllocArgs[0]->Destroy(Context);
453 return false;
454}
455
Sebastian Redlec5f3262008-12-04 22:20:51 +0000456/// FindAllocationOverload - Find an fitting overload for the allocation
457/// function in the specified scope.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000458bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
459 DeclarationName Name, Expr** Args,
460 unsigned NumArgs, DeclContext *Ctx,
461 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redlec5f3262008-12-04 22:20:51 +0000462{
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000463 DeclContext::lookup_iterator Alloc, AllocEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +0000464 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000465 if (Alloc == AllocEnd) {
Sebastian Redlec5f3262008-12-04 22:20:51 +0000466 if (AllowMissing)
467 return false;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000468 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +0000469 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000470 }
471
472 OverloadCandidateSet Candidates;
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000473 for (; Alloc != AllocEnd; ++Alloc) {
474 // Even member operator new/delete are implicitly treated as
475 // static, so don't use AddMemberCandidate.
476 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
477 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
478 /*SuppressUserConversions=*/false);
Sebastian Redlec5f3262008-12-04 22:20:51 +0000479 }
480
481 // Do the resolution.
482 OverloadCandidateSet::iterator Best;
483 switch(BestViableFunction(Candidates, Best)) {
484 case OR_Success: {
485 // Got one!
486 FunctionDecl *FnDecl = Best->Function;
487 // The first argument is size_t, and the first parameter must be size_t,
488 // too. This is checked on declaration and can be assumed. (It can't be
489 // asserted on, though, since invalid decls are left in there.)
490 for (unsigned i = 1; i < NumArgs; ++i) {
491 // FIXME: Passing word to diagnostic.
492 if (PerformCopyInitialization(Args[i-1],
493 FnDecl->getParamDecl(i)->getType(),
494 "passing"))
495 return true;
496 }
497 Operator = FnDecl;
498 return false;
499 }
500
501 case OR_No_Viable_Function:
502 if (AllowMissing)
503 return false;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000504 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +0000505 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000506 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
507 return true;
508
509 case OR_Ambiguous:
Sebastian Redlec5f3262008-12-04 22:20:51 +0000510 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000511 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000512 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
513 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +0000514
515 case OR_Deleted:
516 Diag(StartLoc, diag::err_ovl_deleted_call)
517 << Best->Function->isDeleted()
518 << Name << Range;
519 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
520 return true;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000521 }
522 assert(false && "Unreachable, bad result from BestViableFunction");
523 return true;
524}
525
526
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000527/// DeclareGlobalNewDelete - Declare the global forms of operator new and
528/// delete. These are:
529/// @code
530/// void* operator new(std::size_t) throw(std::bad_alloc);
531/// void* operator new[](std::size_t) throw(std::bad_alloc);
532/// void operator delete(void *) throw();
533/// void operator delete[](void *) throw();
534/// @endcode
535/// Note that the placement and nothrow forms of new are *not* implicitly
536/// declared. Their use requires including \<new\>.
537void Sema::DeclareGlobalNewDelete()
538{
539 if (GlobalNewDeleteDeclared)
540 return;
541 GlobalNewDeleteDeclared = true;
542
543 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
544 QualType SizeT = Context.getSizeType();
545
546 // FIXME: Exception specifications are not added.
547 DeclareGlobalAllocationFunction(
548 Context.DeclarationNames.getCXXOperatorName(OO_New),
549 VoidPtr, SizeT);
550 DeclareGlobalAllocationFunction(
551 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
552 VoidPtr, SizeT);
553 DeclareGlobalAllocationFunction(
554 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
555 Context.VoidTy, VoidPtr);
556 DeclareGlobalAllocationFunction(
557 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
558 Context.VoidTy, VoidPtr);
559}
560
561/// DeclareGlobalAllocationFunction - Declares a single implicit global
562/// allocation function if it doesn't already exist.
563void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
564 QualType Return, QualType Argument)
565{
566 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
567
568 // Check if this function is already declared.
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000569 {
Douglas Gregor7c865852008-12-23 22:05:29 +0000570 DeclContext::lookup_iterator Alloc, AllocEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +0000571 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000572 Alloc != AllocEnd; ++Alloc) {
573 // FIXME: Do we need to check for default arguments here?
574 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
575 if (Func->getNumParams() == 1 &&
Ted Kremenek0c97e042009-02-07 01:47:29 +0000576 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000577 return;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000578 }
579 }
580
581 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
582 FunctionDecl *Alloc =
583 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000584 FnType, FunctionDecl::None, false, true,
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000585 SourceLocation());
586 Alloc->setImplicit();
587 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000588 0, Argument, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000589 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000590
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000591 // FIXME: Also add this declaration to the IdentifierResolver, but
592 // make sure it is at the end of the chain to coincide with the
593 // global scope.
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000594 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000595}
596
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000597/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
598/// @code ::delete ptr; @endcode
599/// or
600/// @code delete [] ptr; @endcode
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000601Action::OwningExprResult
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000602Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000603 bool ArrayForm, ExprArg Operand)
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000604{
605 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
606 // having a single conversion function to a pointer type. The result has
607 // type void."
608 // DR599 amends "pointer type" to "pointer to object type" in both cases.
609
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000610 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000611 if (!Ex->isTypeDependent()) {
612 QualType Type = Ex->getType();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000613
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000614 if (Type->isRecordType()) {
615 // FIXME: Find that one conversion function and amend the type.
616 }
617
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000618 if (!Type->isPointerType())
619 return ExprError(Diag(StartLoc, diag::err_delete_operand)
620 << Type << Ex->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000621
622 QualType Pointee = Type->getAsPointerType()->getPointeeType();
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000623 if (!Pointee->isVoidType() &&
Douglas Gregorc84d8932009-03-09 16:13:40 +0000624 RequireCompleteType(StartLoc, Pointee, diag::warn_delete_incomplete,
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000625 Ex->getSourceRange()))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000626 return ExprError();
627 else if (!Pointee->isObjectType())
628 return ExprError(Diag(StartLoc, diag::err_delete_operand)
629 << Type << Ex->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000630
631 // FIXME: Look up the correct operator delete overload and pass a pointer
632 // along.
633 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000634 }
635
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000636 Operand.release();
637 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
638 0, Ex, StartLoc));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000639}
640
641
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000642/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
643/// C++ if/switch/while/for statement.
644/// e.g: "if (int x = f()) {...}"
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000645Action::OwningExprResult
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000646Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
647 Declarator &D,
648 SourceLocation EqualLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000649 ExprArg AssignExprVal) {
650 assert(AssignExprVal.get() && "Null assignment expression");
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000651
652 // C++ 6.4p2:
653 // The declarator shall not specify a function or an array.
654 // The type-specifier-seq shall not contain typedef and shall not declare a
655 // new class or enumeration.
656
657 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
658 "Parser allowed 'typedef' as storage class of condition decl.");
659
660 QualType Ty = GetTypeForDeclarator(D, S);
661
662 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
663 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
664 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000665 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
666 << SourceRange(StartLoc, EqualLoc));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000667 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattner9d2cf082008-11-19 05:27:50 +0000668 Diag(StartLoc, diag::err_invalid_use_of_array_type)
669 << SourceRange(StartLoc, EqualLoc);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000670 } else if (const RecordType *RT = Ty->getAsRecordType()) {
671 RecordDecl *RD = RT->getDecl();
672 // The type-specifier-seq shall not declare a new class...
673 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
674 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
675 } else if (const EnumType *ET = Ty->getAsEnumType()) {
676 EnumDecl *ED = ET->getDecl();
677 // ...or enumeration.
678 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
679 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
680 }
681
682 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
683 if (!Dcl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000684 return ExprError();
685 AddInitializerToDecl(Dcl, move(AssignExprVal));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000686
Douglas Gregor48840c72008-12-10 23:01:14 +0000687 // Mark this variable as one that is declared within a conditional.
688 if (VarDecl *VD = dyn_cast<VarDecl>((Decl *)Dcl))
689 VD->setDeclaredInCondition(true);
690
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000691 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc,
692 cast<VarDecl>(static_cast<Decl *>(Dcl))));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000693}
694
695/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
696bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
697 // C++ 6.4p4:
698 // The value of a condition that is an initialized declaration in a statement
699 // other than a switch statement is the value of the declared variable
700 // implicitly converted to type bool. If that conversion is ill-formed, the
701 // program is ill-formed.
702 // The value of a condition that is an expression is the value of the
703 // expression, implicitly converted to bool.
704 //
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000705 return PerformContextuallyConvertToBool(CondExpr);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000706}
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000707
708/// Helper function to determine whether this is the (deprecated) C++
709/// conversion from a string literal to a pointer to non-const char or
710/// non-const wchar_t (for narrow and wide string literals,
711/// respectively).
712bool
713Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
714 // Look inside the implicit cast, if it exists.
715 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
716 From = Cast->getSubExpr();
717
718 // A string literal (2.13.4) that is not a wide string literal can
719 // be converted to an rvalue of type "pointer to char"; a wide
720 // string literal can be converted to an rvalue of type "pointer
721 // to wchar_t" (C++ 4.2p2).
722 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
723 if (const PointerType *ToPtrType = ToType->getAsPointerType())
724 if (const BuiltinType *ToPointeeType
725 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
726 // This conversion is considered only when there is an
727 // explicit appropriate pointer target type (C++ 4.2p2).
728 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
729 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
730 (!StrLit->isWide() &&
731 (ToPointeeType->getKind() == BuiltinType::Char_U ||
732 ToPointeeType->getKind() == BuiltinType::Char_S))))
733 return true;
734 }
735
736 return false;
737}
Douglas Gregorbb461502008-10-24 04:54:22 +0000738
739/// PerformImplicitConversion - Perform an implicit conversion of the
740/// expression From to the type ToType. Returns true if there was an
741/// error, false otherwise. The expression From is replaced with the
Douglas Gregor6fd35572008-12-19 17:40:08 +0000742/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000743/// performing, used in the error message. If @p AllowExplicit,
744/// explicit user-defined conversions are permitted.
Douglas Gregorbb461502008-10-24 04:54:22 +0000745bool
Douglas Gregor6fd35572008-12-19 17:40:08 +0000746Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000747 const char *Flavor, bool AllowExplicit)
Douglas Gregorbb461502008-10-24 04:54:22 +0000748{
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000749 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType, false,
750 AllowExplicit);
751 return PerformImplicitConversion(From, ToType, ICS, Flavor);
752}
753
754/// PerformImplicitConversion - Perform an implicit conversion of the
755/// expression From to the type ToType using the pre-computed implicit
756/// conversion sequence ICS. Returns true if there was an error, false
757/// otherwise. The expression From is replaced with the converted
758/// expression. Flavor is the kind of conversion we're performing,
759/// used in the error message.
760bool
761Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
762 const ImplicitConversionSequence &ICS,
763 const char* Flavor) {
Douglas Gregorbb461502008-10-24 04:54:22 +0000764 switch (ICS.ConversionKind) {
765 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor6fd35572008-12-19 17:40:08 +0000766 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregorbb461502008-10-24 04:54:22 +0000767 return true;
768 break;
769
770 case ImplicitConversionSequence::UserDefinedConversion:
771 // FIXME: This is, of course, wrong. We'll need to actually call
772 // the constructor or conversion operator, and then cope with the
773 // standard conversions.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000774 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +0000775 ToType->isLValueReferenceType());
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000776 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000777
778 case ImplicitConversionSequence::EllipsisConversion:
779 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000780 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000781
782 case ImplicitConversionSequence::BadConversion:
783 return true;
784 }
785
786 // Everything went well.
787 return false;
788}
789
790/// PerformImplicitConversion - Perform an implicit conversion of the
791/// expression From to the type ToType by following the standard
792/// conversion sequence SCS. Returns true if there was an error, false
793/// otherwise. The expression From is replaced with the converted
Douglas Gregor6fd35572008-12-19 17:40:08 +0000794/// expression. Flavor is the context in which we're performing this
795/// conversion, for use in error messages.
Douglas Gregorbb461502008-10-24 04:54:22 +0000796bool
797Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000798 const StandardConversionSequence& SCS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000799 const char *Flavor) {
Douglas Gregorbb461502008-10-24 04:54:22 +0000800 // Overall FIXME: we are recomputing too many types here and doing
801 // far too much extra work. What this means is that we need to keep
802 // track of more information that is computed when we try the
803 // implicit conversion initially, so that we don't need to recompute
804 // anything here.
805 QualType FromType = From->getType();
806
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000807 if (SCS.CopyConstructor) {
808 // FIXME: Create a temporary object by calling the copy
809 // constructor.
Douglas Gregor5ac8ffa2009-01-16 19:38:23 +0000810 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +0000811 ToType->isLValueReferenceType());
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000812 return false;
813 }
814
Douglas Gregorbb461502008-10-24 04:54:22 +0000815 // Perform the first implicit conversion.
816 switch (SCS.First) {
817 case ICK_Identity:
818 case ICK_Lvalue_To_Rvalue:
819 // Nothing to do.
820 break;
821
822 case ICK_Array_To_Pointer:
Douglas Gregoraa57e862009-02-18 21:56:37 +0000823 FromType = Context.getArrayDecayedType(FromType);
824 ImpCastExprToType(From, FromType);
825 break;
826
827 case ICK_Function_To_Pointer:
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000828 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor45014fd2008-11-10 20:40:00 +0000829 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
830 if (!Fn)
831 return true;
832
Douglas Gregoraa57e862009-02-18 21:56:37 +0000833 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
834 return true;
835
Douglas Gregor45014fd2008-11-10 20:40:00 +0000836 FixOverloadedFunctionReference(From, Fn);
837 FromType = From->getType();
Douglas Gregor45014fd2008-11-10 20:40:00 +0000838 }
Douglas Gregorbb461502008-10-24 04:54:22 +0000839 FromType = Context.getPointerType(FromType);
840 ImpCastExprToType(From, FromType);
841 break;
842
843 default:
844 assert(false && "Improper first standard conversion");
845 break;
846 }
847
848 // Perform the second implicit conversion
849 switch (SCS.Second) {
850 case ICK_Identity:
851 // Nothing to do.
852 break;
853
854 case ICK_Integral_Promotion:
855 case ICK_Floating_Promotion:
Douglas Gregore819caf2009-02-12 00:15:05 +0000856 case ICK_Complex_Promotion:
Douglas Gregorbb461502008-10-24 04:54:22 +0000857 case ICK_Integral_Conversion:
858 case ICK_Floating_Conversion:
Douglas Gregore819caf2009-02-12 00:15:05 +0000859 case ICK_Complex_Conversion:
Douglas Gregorbb461502008-10-24 04:54:22 +0000860 case ICK_Floating_Integral:
Douglas Gregore819caf2009-02-12 00:15:05 +0000861 case ICK_Complex_Real:
Douglas Gregorfcb19192009-02-11 23:02:49 +0000862 case ICK_Compatible_Conversion:
863 // FIXME: Go deeper to get the unqualified type!
Douglas Gregorbb461502008-10-24 04:54:22 +0000864 FromType = ToType.getUnqualifiedType();
865 ImpCastExprToType(From, FromType);
866 break;
867
868 case ICK_Pointer_Conversion:
Douglas Gregor6fd35572008-12-19 17:40:08 +0000869 if (SCS.IncompatibleObjC) {
870 // Diagnose incompatible Objective-C conversions
871 Diag(From->getSourceRange().getBegin(),
872 diag::ext_typecheck_convert_incompatible_pointer)
873 << From->getType() << ToType << Flavor
874 << From->getSourceRange();
875 }
876
Douglas Gregorbb461502008-10-24 04:54:22 +0000877 if (CheckPointerConversion(From, ToType))
878 return true;
879 ImpCastExprToType(From, ToType);
880 break;
881
882 case ICK_Pointer_Member:
Sebastian Redlba387562009-01-25 19:43:20 +0000883 if (CheckMemberPointerConversion(From, ToType))
884 return true;
885 ImpCastExprToType(From, ToType);
Douglas Gregorbb461502008-10-24 04:54:22 +0000886 break;
887
888 case ICK_Boolean_Conversion:
889 FromType = Context.BoolTy;
890 ImpCastExprToType(From, FromType);
891 break;
892
893 default:
894 assert(false && "Improper second standard conversion");
895 break;
896 }
897
898 switch (SCS.Third) {
899 case ICK_Identity:
900 // Nothing to do.
901 break;
902
903 case ICK_Qualification:
Sebastian Redlce6fff02009-03-16 23:22:08 +0000904 // FIXME: Not sure about lvalue vs rvalue here in the presence of
905 // rvalue references.
Douglas Gregor5ac8ffa2009-01-16 19:38:23 +0000906 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +0000907 ToType->isLValueReferenceType());
Douglas Gregorbb461502008-10-24 04:54:22 +0000908 break;
909
910 default:
911 assert(false && "Improper second standard conversion");
912 break;
913 }
914
915 return false;
916}
917
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000918Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
919 SourceLocation KWLoc,
920 SourceLocation LParen,
921 TypeTy *Ty,
922 SourceLocation RParen) {
923 // FIXME: Some of the type traits have requirements. Interestingly, only the
924 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed,
925 // G++ accepts __is_pod(Incomplete) without complaints, and claims that the
926 // type is indeed a POD.
927
928 // There is no point in eagerly computing the value. The traits are designed
929 // to be used from type trait templates, so Ty will be a template parameter
930 // 99% of the time.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000931 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000932 QualType::getFromOpaquePtr(Ty),
933 RParen, Context.BoolTy));
934}
Sebastian Redlaa4c3732009-02-07 20:10:22 +0000935
936QualType Sema::CheckPointerToMemberOperands(
937 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
938{
939 const char *OpSpelling = isIndirect ? "->*" : ".*";
940 // C++ 5.5p2
941 // The binary operator .* [p3: ->*] binds its second operand, which shall
942 // be of type "pointer to member of T" (where T is a completely-defined
943 // class type) [...]
944 QualType RType = rex->getType();
945 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
946 if (!MemPtr || MemPtr->getClass()->isIncompleteType()) {
947 Diag(Loc, diag::err_bad_memptr_rhs)
948 << OpSpelling << RType << rex->getSourceRange();
949 return QualType();
950 }
951 QualType Class(MemPtr->getClass(), 0);
952
953 // C++ 5.5p2
954 // [...] to its first operand, which shall be of class T or of a class of
955 // which T is an unambiguous and accessible base class. [p3: a pointer to
956 // such a class]
957 QualType LType = lex->getType();
958 if (isIndirect) {
959 if (const PointerType *Ptr = LType->getAsPointerType())
960 LType = Ptr->getPointeeType().getNonReferenceType();
961 else {
962 Diag(Loc, diag::err_bad_memptr_lhs)
963 << OpSpelling << 1 << LType << lex->getSourceRange();
964 return QualType();
965 }
966 }
967
968 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
969 Context.getCanonicalType(LType).getUnqualifiedType()) {
970 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
971 /*DetectVirtual=*/false);
972 // FIXME: Would it be useful to print full ambiguity paths,
973 // or is that overkill?
974 if (!IsDerivedFrom(LType, Class, Paths) ||
975 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
976 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
977 << (int)isIndirect << lex->getType() << lex->getSourceRange();
978 return QualType();
979 }
980 }
981
982 // C++ 5.5p2
983 // The result is an object or a function of the type specified by the
984 // second operand.
985 // The cv qualifiers are the union of those in the pointer and the left side,
986 // in accordance with 5.5p5 and 5.2.5.
987 // FIXME: This returns a dereferenced member function pointer as a normal
988 // function type. However, the only operation valid on such functions is
989 // calling them. There's also a GCC extension to get a function pointer to
990 // the thing, which is another complication, because this type - unlike the
991 // type that is the result of this expression - takes the class as the first
992 // argument.
993 // We probably need a "MemberFunctionClosureType" or something like that.
994 QualType Result = MemPtr->getPointeeType();
995 if (LType.isConstQualified())
996 Result.addConst();
997 if (LType.isVolatileQualified())
998 Result.addVolatile();
999 return Result;
1000}