blob: 109247f977e17f2a9f7aa0de2714da77e2089fc9 [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
Sebastian Redl5d0ead72009-05-10 18:38:11 +000088/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
89Action::OwningExprResult
90Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
91 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
92}
93
Chris Lattnera7447ba2008-02-26 00:51:44 +000094/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000095Action::OwningExprResult
96Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl9949a5e2009-04-27 20:27:31 +000097 Expr *Ex = E.takeAs<Expr>();
98 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
99 return ExprError();
100 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
101}
102
103/// CheckCXXThrowOperand - Validate the operand of a throw.
104bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
105 // C++ [except.throw]p3:
106 // [...] adjusting the type from "array of T" or "function returning T"
107 // to "pointer to T" or "pointer to function returning T", [...]
108 DefaultFunctionArrayConversion(E);
109
110 // If the type of the exception would be an incomplete type or a pointer
111 // to an incomplete type other than (cv) void the program is ill-formed.
112 QualType Ty = E->getType();
113 int isPointer = 0;
114 if (const PointerType* Ptr = Ty->getAsPointerType()) {
115 Ty = Ptr->getPointeeType();
116 isPointer = 1;
117 }
118 if (!isPointer || !Ty->isVoidType()) {
119 if (RequireCompleteType(ThrowLoc, Ty,
120 isPointer ? diag::err_throw_incomplete_ptr
121 : diag::err_throw_incomplete,
122 E->getSourceRange(), SourceRange(), QualType()))
123 return true;
124 }
125
126 // FIXME: Construct a temporary here.
127 return false;
Chris Lattnera7447ba2008-02-26 00:51:44 +0000128}
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000129
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000130Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000131 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
132 /// is a non-lvalue expression whose value is the address of the object for
133 /// which the function is called.
134
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000135 if (!isa<FunctionDecl>(CurContext))
136 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000137
138 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
139 if (MD->isInstance())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000140 return Owned(new (Context) CXXThisExpr(ThisLoc,
141 MD->getThisType(Context)));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000142
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000143 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000144}
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000145
146/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
147/// Can be interpreted either as function-style casting ("int(x)")
148/// or class type construction ("ClassType(x,y,z)")
149/// or creation of a value-initialized type ("int()").
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000150Action::OwningExprResult
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000151Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
152 SourceLocation LParenLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000153 MultiExprArg exprs,
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000154 SourceLocation *CommaLocs,
155 SourceLocation RParenLoc) {
156 assert(TypeRep && "Missing type!");
157 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000158 unsigned NumExprs = exprs.size();
159 Expr **Exprs = (Expr**)exprs.get();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000160 SourceLocation TyBeginLoc = TypeRange.getBegin();
161 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
162
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000163 if (Ty->isDependentType() ||
Douglas Gregor396f1142009-03-13 21:01:28 +0000164 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000165 exprs.release();
Anders Carlssonebbd7cd2009-04-24 05:23:13 +0000166
Anders Carlssonf0967d72009-05-17 18:41:29 +0000167 // FIXME: Is this correct (I don't think so). Instead, we should have an
168 // CXXUnresolvedTemporaryObjectExpr node for this.
Anders Carlssonebbd7cd2009-04-24 05:23:13 +0000169 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty);
Anders Carlssonf0967d72009-05-17 18:41:29 +0000170
Anders Carlssonaf443ed2009-04-24 05:44:25 +0000171 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Temp, 0, Ty,
172 TyBeginLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000173 Exprs, NumExprs,
174 RParenLoc));
Douglas Gregor396f1142009-03-13 21:01:28 +0000175 }
176
177
Douglas Gregor861e7902009-01-16 18:33:17 +0000178 // C++ [expr.type.conv]p1:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000179 // If the expression list is a single expression, the type conversion
180 // expression is equivalent (in definedness, and if defined in meaning) to the
181 // corresponding cast expression.
182 //
183 if (NumExprs == 1) {
184 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000185 return ExprError();
186 exprs.release();
187 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
188 Ty, TyBeginLoc, Exprs[0],
189 RParenLoc));
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000190 }
191
Douglas Gregor861e7902009-01-16 18:33:17 +0000192 if (const RecordType *RT = Ty->getAsRecordType()) {
193 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000194
Anders Carlssonf0967d72009-05-17 18:41:29 +0000195 // FIXME: We should always create a CXXTemporaryObjectExpr here unless
196 // both the ctor and dtor are trivial.
Douglas Gregor861e7902009-01-16 18:33:17 +0000197 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
198 CXXConstructorDecl *Constructor
199 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
200 TypeRange.getBegin(),
201 SourceRange(TypeRange.getBegin(),
202 RParenLoc),
203 DeclarationName(),
204 IK_Direct);
Douglas Gregor861e7902009-01-16 18:33:17 +0000205
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000206 if (!Constructor)
207 return ExprError();
208
Anders Carlssonebbd7cd2009-04-24 05:23:13 +0000209 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty);
Anders Carlssonf0967d72009-05-17 18:41:29 +0000210 ExprTemporaries.push_back(Temp);
211
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000212 exprs.release();
Anders Carlssonaf443ed2009-04-24 05:44:25 +0000213 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Temp,
214 Constructor, Ty,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000215 TyBeginLoc, Exprs,
216 NumExprs, RParenLoc));
Douglas Gregor861e7902009-01-16 18:33:17 +0000217 }
218
219 // Fall through to value-initialize an object of class type that
220 // doesn't have a user-declared default constructor.
221 }
222
223 // C++ [expr.type.conv]p1:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000224 // If the expression list specifies more than a single value, the type shall
225 // be a class with a suitably declared constructor.
226 //
227 if (NumExprs > 1)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000228 return ExprError(Diag(CommaLocs[0],
229 diag::err_builtin_func_cast_more_than_one_arg)
230 << FullRange);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000231
232 assert(NumExprs == 0 && "Expected 0 expressions");
233
Douglas Gregor861e7902009-01-16 18:33:17 +0000234 // C++ [expr.type.conv]p2:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000235 // The expression T(), where T is a simple-type-specifier for a non-array
236 // complete object type or the (possibly cv-qualified) void type, creates an
237 // rvalue of the specified type, which is value-initialized.
238 //
239 if (Ty->isArrayType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000240 return ExprError(Diag(TyBeginLoc,
241 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000242 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000243 RequireCompleteType(TyBeginLoc, Ty,
244 diag::err_invalid_incomplete_type_use, FullRange))
245 return ExprError();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000246
Anders Carlsson412c3402009-03-24 01:19:16 +0000247 if (RequireNonAbstractType(TyBeginLoc, Ty,
248 diag::err_allocation_of_abstract_type))
Anders Carlssonc263c9b2009-03-23 19:10:31 +0000249 return ExprError();
250
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000251 exprs.release();
252 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000253}
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000254
255
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000256/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
257/// @code new (memory) int[size][4] @endcode
258/// or
259/// @code ::new Foo(23, "hello") @endcode
260/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000261Action::OwningExprResult
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000262Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000263 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000264 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000265 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000266 MultiExprArg ConstructorArgs,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000267 SourceLocation ConstructorRParen)
268{
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000269 Expr *ArraySize = 0;
270 unsigned Skip = 0;
271 // If the specified type is an array, unwrap it and save the expression.
272 if (D.getNumTypeObjects() > 0 &&
273 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
274 DeclaratorChunk &Chunk = D.getTypeObject(0);
275 if (Chunk.Arr.hasStatic)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000276 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
277 << D.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000278 if (!Chunk.Arr.NumElts)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000279 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
280 << D.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000281 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
282 Skip = 1;
283 }
284
285 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
Chris Lattner34c61332009-04-25 08:06:05 +0000286 if (D.isInvalidType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000287 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000288
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000289 if (CheckAllocatedType(AllocType, D))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000290 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000291
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000292 QualType ResultType = AllocType->isDependentType()
293 ? Context.DependentTy
294 : Context.getPointerType(AllocType);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000295
296 // That every array dimension except the first is constant was already
297 // checked by the type check above.
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000298
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000299 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
300 // or enumeration type with a non-negative value."
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000301 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000302 QualType SizeType = ArraySize->getType();
303 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000304 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
305 diag::err_array_size_not_integral)
306 << SizeType << ArraySize->getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000307 // Let's see if this is a constant < 0. If so, we reject it out of hand.
308 // We don't care about special rules, so we tell the machinery it's not
309 // evaluated - it gives us a result in more cases.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000310 if (!ArraySize->isValueDependent()) {
311 llvm::APSInt Value;
312 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
313 if (Value < llvm::APSInt(
314 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000315 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
316 diag::err_typecheck_negative_array_size)
317 << ArraySize->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000318 }
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000319 }
320 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000321
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000322 FunctionDecl *OperatorNew = 0;
323 FunctionDecl *OperatorDelete = 0;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000324 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
325 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000326 if (!AllocType->isDependentType() &&
327 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
328 FindAllocationFunctions(StartLoc,
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000329 SourceRange(PlacementLParen, PlacementRParen),
330 UseGlobal, AllocType, ArraySize, PlaceArgs,
331 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000332 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000333
334 bool Init = ConstructorLParen.isValid();
335 // --- Choosing a constructor ---
336 // C++ 5.3.4p15
337 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
338 // the object is not initialized. If the object, or any part of it, is
339 // const-qualified, it's an error.
340 // 2) If T is a POD and there's an empty initializer, the object is value-
341 // initialized.
342 // 3) If T is a POD and there's one initializer argument, the object is copy-
343 // constructed.
344 // 4) If T is a POD and there's more initializer arguments, it's an error.
345 // 5) If T is not a POD, the initializer arguments are used as constructor
346 // arguments.
347 //
348 // Or by the C++0x formulation:
349 // 1) If there's no initializer, the object is default-initialized according
350 // to C++0x rules.
351 // 2) Otherwise, the object is direct-initialized.
352 CXXConstructorDecl *Constructor = 0;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000353 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl091cf8d2009-05-07 16:14:23 +0000354 const RecordType *RT;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000355 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000356 if (AllocType->isDependentType()) {
357 // Skip all the checks.
358 }
Sebastian Redl091cf8d2009-05-07 16:14:23 +0000359 else if ((RT = AllocType->getAsRecordType()) &&
360 !AllocType->isAggregateType()) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000361 Constructor = PerformInitializationByConstructor(
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000362 AllocType, ConsArgs, NumConsArgs,
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000363 D.getSourceRange().getBegin(),
364 SourceRange(D.getSourceRange().getBegin(),
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000365 ConstructorRParen),
Chris Lattner271d4c22008-11-24 05:29:24 +0000366 RT->getDecl()->getDeclName(),
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000367 NumConsArgs != 0 ? IK_Direct : IK_Default);
368 if (!Constructor)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000369 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000370 } else {
371 if (!Init) {
372 // FIXME: Check that no subpart is const.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000373 if (AllocType.isConstQualified())
374 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
375 << D.getSourceRange());
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000376 } else if (NumConsArgs == 0) {
377 // Object is value-initialized. Do nothing.
378 } else if (NumConsArgs == 1) {
379 // Object is direct-initialized.
Sebastian Redl091cf8d2009-05-07 16:14:23 +0000380 // FIXME: What DeclarationName do we pass in here?
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000381 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000382 DeclarationName() /*AllocType.getAsString()*/,
383 /*DirectInit=*/true))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000384 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000385 } else {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000386 return ExprError(Diag(StartLoc,
387 diag::err_builtin_direct_init_more_than_one_arg)
388 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000389 }
390 }
391
392 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
393
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000394 PlacementArgs.release();
395 ConstructorArgs.release();
396 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek0c97e042009-02-07 01:47:29 +0000397 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000398 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000399 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000400}
401
402/// CheckAllocatedType - Checks that a type is suitable as the allocated type
403/// in a new-expression.
404/// dimension off and stores the size expression in ArraySize.
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000405bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000406{
407 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
408 // abstract class type or array thereof.
Douglas Gregor05e28f62009-03-24 19:52:54 +0000409 if (AllocType->isFunctionType())
410 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
411 << AllocType << 0 << D.getSourceRange();
412 else if (AllocType->isReferenceType())
413 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
414 << AllocType << 1 << D.getSourceRange();
415 else if (!AllocType->isDependentType() &&
416 RequireCompleteType(D.getSourceRange().getBegin(), AllocType,
417 diag::err_new_incomplete_type,
418 D.getSourceRange()))
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000419 return true;
Douglas Gregor05e28f62009-03-24 19:52:54 +0000420 else if (RequireNonAbstractType(D.getSourceRange().getBegin(), AllocType,
421 diag::err_allocation_of_abstract_type))
422 return true;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000423
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000424 // Every dimension shall be of constant size.
425 unsigned i = 1;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000426 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
427 if (!Array->isConstantArrayType()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000428 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
429 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000430 return true;
431 }
432 AllocType = Array->getElementType();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000433 ++i;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000434 }
435
436 return false;
437}
438
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000439/// FindAllocationFunctions - Finds the overloads of operator new and delete
440/// that are appropriate for the allocation.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000441bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
442 bool UseGlobal, QualType AllocType,
443 bool IsArray, Expr **PlaceArgs,
444 unsigned NumPlaceArgs,
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000445 FunctionDecl *&OperatorNew,
446 FunctionDecl *&OperatorDelete)
447{
448 // --- Choosing an allocation function ---
449 // C++ 5.3.4p8 - 14 & 18
450 // 1) If UseGlobal is true, only look in the global scope. Else, also look
451 // in the scope of the allocated class.
452 // 2) If an array size is given, look for operator new[], else look for
453 // operator new.
454 // 3) The first argument is always size_t. Append the arguments from the
455 // placement form.
456 // FIXME: Also find the appropriate delete operator.
457
458 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
459 // We don't care about the actual value of this argument.
460 // FIXME: Should the Sema create the expression and embed it in the syntax
461 // tree? Or should the consumer just recalculate the value?
Ted Kremenek0c97e042009-02-07 01:47:29 +0000462 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000463 Context.Target.getPointerWidth(0)),
464 Context.getSizeType(),
465 SourceLocation());
466 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
467
468 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
469 IsArray ? OO_Array_New : OO_New);
470 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregor2e047592009-02-28 01:32:25 +0000471 CXXRecordDecl *Record
472 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
Sebastian Redlec5f3262008-12-04 22:20:51 +0000473 // FIXME: We fail to find inherited overloads.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000474 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000475 AllocArgs.size(), Record, /*AllowMissing=*/true,
476 OperatorNew))
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000477 return true;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000478 }
479 if (!OperatorNew) {
480 // Didn't find a member overload. Look for a global one.
481 DeclareGlobalNewDelete();
Sebastian Redlec5f3262008-12-04 22:20:51 +0000482 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000483 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000484 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
485 OperatorNew))
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000486 return true;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000487 }
488
Sebastian Redlec5f3262008-12-04 22:20:51 +0000489 // FIXME: This is leaked on error. But so much is currently in Sema that it's
490 // easier to clean it in one go.
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000491 AllocArgs[0]->Destroy(Context);
492 return false;
493}
494
Sebastian Redlec5f3262008-12-04 22:20:51 +0000495/// FindAllocationOverload - Find an fitting overload for the allocation
496/// function in the specified scope.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000497bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
498 DeclarationName Name, Expr** Args,
499 unsigned NumArgs, DeclContext *Ctx,
500 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redlec5f3262008-12-04 22:20:51 +0000501{
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000502 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000503 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000504 if (Alloc == AllocEnd) {
Sebastian Redlec5f3262008-12-04 22:20:51 +0000505 if (AllowMissing)
506 return false;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000507 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +0000508 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000509 }
510
511 OverloadCandidateSet Candidates;
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000512 for (; Alloc != AllocEnd; ++Alloc) {
513 // Even member operator new/delete are implicitly treated as
514 // static, so don't use AddMemberCandidate.
515 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
516 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
517 /*SuppressUserConversions=*/false);
Sebastian Redlec5f3262008-12-04 22:20:51 +0000518 }
519
520 // Do the resolution.
521 OverloadCandidateSet::iterator Best;
522 switch(BestViableFunction(Candidates, Best)) {
523 case OR_Success: {
524 // Got one!
525 FunctionDecl *FnDecl = Best->Function;
526 // The first argument is size_t, and the first parameter must be size_t,
527 // too. This is checked on declaration and can be assumed. (It can't be
528 // asserted on, though, since invalid decls are left in there.)
529 for (unsigned i = 1; i < NumArgs; ++i) {
530 // FIXME: Passing word to diagnostic.
531 if (PerformCopyInitialization(Args[i-1],
532 FnDecl->getParamDecl(i)->getType(),
533 "passing"))
534 return true;
535 }
536 Operator = FnDecl;
537 return false;
538 }
539
540 case OR_No_Viable_Function:
Sebastian Redlec5f3262008-12-04 22:20:51 +0000541 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +0000542 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000543 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
544 return true;
545
546 case OR_Ambiguous:
Sebastian Redlec5f3262008-12-04 22:20:51 +0000547 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000548 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000549 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
550 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +0000551
552 case OR_Deleted:
553 Diag(StartLoc, diag::err_ovl_deleted_call)
554 << Best->Function->isDeleted()
555 << Name << Range;
556 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
557 return true;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000558 }
559 assert(false && "Unreachable, bad result from BestViableFunction");
560 return true;
561}
562
563
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000564/// DeclareGlobalNewDelete - Declare the global forms of operator new and
565/// delete. These are:
566/// @code
567/// void* operator new(std::size_t) throw(std::bad_alloc);
568/// void* operator new[](std::size_t) throw(std::bad_alloc);
569/// void operator delete(void *) throw();
570/// void operator delete[](void *) throw();
571/// @endcode
572/// Note that the placement and nothrow forms of new are *not* implicitly
573/// declared. Their use requires including \<new\>.
574void Sema::DeclareGlobalNewDelete()
575{
576 if (GlobalNewDeleteDeclared)
577 return;
578 GlobalNewDeleteDeclared = true;
579
580 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
581 QualType SizeT = Context.getSizeType();
582
583 // FIXME: Exception specifications are not added.
584 DeclareGlobalAllocationFunction(
585 Context.DeclarationNames.getCXXOperatorName(OO_New),
586 VoidPtr, SizeT);
587 DeclareGlobalAllocationFunction(
588 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
589 VoidPtr, SizeT);
590 DeclareGlobalAllocationFunction(
591 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
592 Context.VoidTy, VoidPtr);
593 DeclareGlobalAllocationFunction(
594 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
595 Context.VoidTy, VoidPtr);
596}
597
598/// DeclareGlobalAllocationFunction - Declares a single implicit global
599/// allocation function if it doesn't already exist.
600void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
601 QualType Return, QualType Argument)
602{
603 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
604
605 // Check if this function is already declared.
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000606 {
Douglas Gregor7c865852008-12-23 22:05:29 +0000607 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000608 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Context, Name);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000609 Alloc != AllocEnd; ++Alloc) {
610 // FIXME: Do we need to check for default arguments here?
611 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
612 if (Func->getNumParams() == 1 &&
Ted Kremenek0c97e042009-02-07 01:47:29 +0000613 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000614 return;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000615 }
616 }
617
618 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
619 FunctionDecl *Alloc =
620 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000621 FnType, FunctionDecl::None, false, true,
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000622 SourceLocation());
623 Alloc->setImplicit();
624 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000625 0, Argument, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000626 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000627
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000628 // FIXME: Also add this declaration to the IdentifierResolver, but
629 // make sure it is at the end of the chain to coincide with the
630 // global scope.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000631 ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000632}
633
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000634/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
635/// @code ::delete ptr; @endcode
636/// or
637/// @code delete [] ptr; @endcode
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000638Action::OwningExprResult
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000639Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000640 bool ArrayForm, ExprArg Operand)
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000641{
642 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
643 // having a single conversion function to a pointer type. The result has
644 // type void."
645 // DR599 amends "pointer type" to "pointer to object type" in both cases.
646
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000647 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000648 if (!Ex->isTypeDependent()) {
649 QualType Type = Ex->getType();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000650
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000651 if (Type->isRecordType()) {
652 // FIXME: Find that one conversion function and amend the type.
653 }
654
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000655 if (!Type->isPointerType())
656 return ExprError(Diag(StartLoc, diag::err_delete_operand)
657 << Type << Ex->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000658
659 QualType Pointee = Type->getAsPointerType()->getPointeeType();
Douglas Gregorcde3a2d2009-03-24 20:13:58 +0000660 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000661 return ExprError(Diag(StartLoc, diag::err_delete_operand)
662 << Type << Ex->getSourceRange());
Douglas Gregorcde3a2d2009-03-24 20:13:58 +0000663 else if (!Pointee->isDependentType() &&
664 RequireCompleteType(StartLoc, Pointee,
665 diag::warn_delete_incomplete,
666 Ex->getSourceRange()))
667 return ExprError();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000668
669 // FIXME: Look up the correct operator delete overload and pass a pointer
670 // along.
671 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000672 }
673
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000674 Operand.release();
675 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
676 0, Ex, StartLoc));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000677}
678
679
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000680/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
681/// C++ if/switch/while/for statement.
682/// e.g: "if (int x = f()) {...}"
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000683Action::OwningExprResult
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000684Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
685 Declarator &D,
686 SourceLocation EqualLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000687 ExprArg AssignExprVal) {
688 assert(AssignExprVal.get() && "Null assignment expression");
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000689
690 // C++ 6.4p2:
691 // The declarator shall not specify a function or an array.
692 // The type-specifier-seq shall not contain typedef and shall not declare a
693 // new class or enumeration.
694
695 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
696 "Parser allowed 'typedef' as storage class of condition decl.");
697
698 QualType Ty = GetTypeForDeclarator(D, S);
699
700 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
701 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
702 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000703 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
704 << SourceRange(StartLoc, EqualLoc));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000705 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattner9d2cf082008-11-19 05:27:50 +0000706 Diag(StartLoc, diag::err_invalid_use_of_array_type)
707 << SourceRange(StartLoc, EqualLoc);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000708 } else if (const RecordType *RT = Ty->getAsRecordType()) {
709 RecordDecl *RD = RT->getDecl();
710 // The type-specifier-seq shall not declare a new class...
Chris Lattner5261d0c2009-03-28 19:18:32 +0000711 if (RD->isDefinition() &&
712 (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD))))
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000713 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
714 } else if (const EnumType *ET = Ty->getAsEnumType()) {
715 EnumDecl *ED = ET->getDecl();
716 // ...or enumeration.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000717 if (ED->isDefinition() &&
718 (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED))))
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000719 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
720 }
721
Chris Lattner5261d0c2009-03-28 19:18:32 +0000722 DeclPtrTy Dcl = ActOnDeclarator(S, D, DeclPtrTy());
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000723 if (!Dcl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000724 return ExprError();
725 AddInitializerToDecl(Dcl, move(AssignExprVal));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000726
Douglas Gregor48840c72008-12-10 23:01:14 +0000727 // Mark this variable as one that is declared within a conditional.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000728 // We know that the decl had to be a VarDecl because that is the only type of
729 // decl that can be assigned and the grammar requires an '='.
730 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
731 VD->setDeclaredInCondition(true);
732 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000733}
734
735/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
736bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
737 // C++ 6.4p4:
738 // The value of a condition that is an initialized declaration in a statement
739 // other than a switch statement is the value of the declared variable
740 // implicitly converted to type bool. If that conversion is ill-formed, the
741 // program is ill-formed.
742 // The value of a condition that is an expression is the value of the
743 // expression, implicitly converted to bool.
744 //
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000745 return PerformContextuallyConvertToBool(CondExpr);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000746}
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000747
748/// Helper function to determine whether this is the (deprecated) C++
749/// conversion from a string literal to a pointer to non-const char or
750/// non-const wchar_t (for narrow and wide string literals,
751/// respectively).
752bool
753Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
754 // Look inside the implicit cast, if it exists.
755 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
756 From = Cast->getSubExpr();
757
758 // A string literal (2.13.4) that is not a wide string literal can
759 // be converted to an rvalue of type "pointer to char"; a wide
760 // string literal can be converted to an rvalue of type "pointer
761 // to wchar_t" (C++ 4.2p2).
762 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
763 if (const PointerType *ToPtrType = ToType->getAsPointerType())
764 if (const BuiltinType *ToPointeeType
765 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
766 // This conversion is considered only when there is an
767 // explicit appropriate pointer target type (C++ 4.2p2).
768 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
769 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
770 (!StrLit->isWide() &&
771 (ToPointeeType->getKind() == BuiltinType::Char_U ||
772 ToPointeeType->getKind() == BuiltinType::Char_S))))
773 return true;
774 }
775
776 return false;
777}
Douglas Gregorbb461502008-10-24 04:54:22 +0000778
779/// PerformImplicitConversion - Perform an implicit conversion of the
780/// expression From to the type ToType. Returns true if there was an
781/// error, false otherwise. The expression From is replaced with the
Douglas Gregor6fd35572008-12-19 17:40:08 +0000782/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000783/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redla55834a2009-04-12 17:16:29 +0000784/// explicit user-defined conversions are permitted. @p Elidable should be true
785/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
786/// resolution works differently in that case.
787bool
Douglas Gregor6fd35572008-12-19 17:40:08 +0000788Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +0000789 const char *Flavor, bool AllowExplicit,
790 bool Elidable)
Douglas Gregorbb461502008-10-24 04:54:22 +0000791{
Sebastian Redla55834a2009-04-12 17:16:29 +0000792 ImplicitConversionSequence ICS;
793 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
794 if (Elidable && getLangOptions().CPlusPlus0x) {
795 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
796 AllowExplicit, /*ForceRValue*/true);
797 }
798 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
799 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
800 }
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000801 return PerformImplicitConversion(From, ToType, ICS, Flavor);
802}
803
804/// PerformImplicitConversion - Perform an implicit conversion of the
805/// expression From to the type ToType using the pre-computed implicit
806/// conversion sequence ICS. Returns true if there was an error, false
807/// otherwise. The expression From is replaced with the converted
808/// expression. Flavor is the kind of conversion we're performing,
809/// used in the error message.
810bool
811Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
812 const ImplicitConversionSequence &ICS,
813 const char* Flavor) {
Douglas Gregorbb461502008-10-24 04:54:22 +0000814 switch (ICS.ConversionKind) {
815 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor6fd35572008-12-19 17:40:08 +0000816 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregorbb461502008-10-24 04:54:22 +0000817 return true;
818 break;
819
820 case ImplicitConversionSequence::UserDefinedConversion:
Mike Stumpe127ae32009-05-16 07:39:55 +0000821 // FIXME: This is, of course, wrong. We'll need to actually call the
822 // constructor or conversion operator, and then cope with the standard
823 // conversions.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000824 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +0000825 ToType->isLValueReferenceType());
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000826 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000827
828 case ImplicitConversionSequence::EllipsisConversion:
829 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000830 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000831
832 case ImplicitConversionSequence::BadConversion:
833 return true;
834 }
835
836 // Everything went well.
837 return false;
838}
839
840/// PerformImplicitConversion - Perform an implicit conversion of the
841/// expression From to the type ToType by following the standard
842/// conversion sequence SCS. Returns true if there was an error, false
843/// otherwise. The expression From is replaced with the converted
Douglas Gregor6fd35572008-12-19 17:40:08 +0000844/// expression. Flavor is the context in which we're performing this
845/// conversion, for use in error messages.
Douglas Gregorbb461502008-10-24 04:54:22 +0000846bool
847Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000848 const StandardConversionSequence& SCS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000849 const char *Flavor) {
Mike Stumpe127ae32009-05-16 07:39:55 +0000850 // Overall FIXME: we are recomputing too many types here and doing far too
851 // much extra work. What this means is that we need to keep track of more
852 // information that is computed when we try the implicit conversion initially,
853 // so that we don't need to recompute anything here.
Douglas Gregorbb461502008-10-24 04:54:22 +0000854 QualType FromType = From->getType();
855
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000856 if (SCS.CopyConstructor) {
Mike Stumpe127ae32009-05-16 07:39:55 +0000857 // FIXME: Create a temporary object by calling the copy constructor.
Douglas Gregor5ac8ffa2009-01-16 19:38:23 +0000858 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +0000859 ToType->isLValueReferenceType());
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000860 return false;
861 }
862
Douglas Gregorbb461502008-10-24 04:54:22 +0000863 // Perform the first implicit conversion.
864 switch (SCS.First) {
865 case ICK_Identity:
866 case ICK_Lvalue_To_Rvalue:
867 // Nothing to do.
868 break;
869
870 case ICK_Array_To_Pointer:
Douglas Gregoraa57e862009-02-18 21:56:37 +0000871 FromType = Context.getArrayDecayedType(FromType);
872 ImpCastExprToType(From, FromType);
873 break;
874
875 case ICK_Function_To_Pointer:
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000876 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor45014fd2008-11-10 20:40:00 +0000877 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
878 if (!Fn)
879 return true;
880
Douglas Gregoraa57e862009-02-18 21:56:37 +0000881 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
882 return true;
883
Douglas Gregor45014fd2008-11-10 20:40:00 +0000884 FixOverloadedFunctionReference(From, Fn);
885 FromType = From->getType();
Douglas Gregor45014fd2008-11-10 20:40:00 +0000886 }
Douglas Gregorbb461502008-10-24 04:54:22 +0000887 FromType = Context.getPointerType(FromType);
888 ImpCastExprToType(From, FromType);
889 break;
890
891 default:
892 assert(false && "Improper first standard conversion");
893 break;
894 }
895
896 // Perform the second implicit conversion
897 switch (SCS.Second) {
898 case ICK_Identity:
899 // Nothing to do.
900 break;
901
902 case ICK_Integral_Promotion:
903 case ICK_Floating_Promotion:
Douglas Gregore819caf2009-02-12 00:15:05 +0000904 case ICK_Complex_Promotion:
Douglas Gregorbb461502008-10-24 04:54:22 +0000905 case ICK_Integral_Conversion:
906 case ICK_Floating_Conversion:
Douglas Gregore819caf2009-02-12 00:15:05 +0000907 case ICK_Complex_Conversion:
Douglas Gregorbb461502008-10-24 04:54:22 +0000908 case ICK_Floating_Integral:
Douglas Gregore819caf2009-02-12 00:15:05 +0000909 case ICK_Complex_Real:
Douglas Gregorfcb19192009-02-11 23:02:49 +0000910 case ICK_Compatible_Conversion:
911 // FIXME: Go deeper to get the unqualified type!
Douglas Gregorbb461502008-10-24 04:54:22 +0000912 FromType = ToType.getUnqualifiedType();
913 ImpCastExprToType(From, FromType);
914 break;
915
916 case ICK_Pointer_Conversion:
Douglas Gregor6fd35572008-12-19 17:40:08 +0000917 if (SCS.IncompatibleObjC) {
918 // Diagnose incompatible Objective-C conversions
919 Diag(From->getSourceRange().getBegin(),
920 diag::ext_typecheck_convert_incompatible_pointer)
921 << From->getType() << ToType << Flavor
922 << From->getSourceRange();
923 }
924
Douglas Gregorbb461502008-10-24 04:54:22 +0000925 if (CheckPointerConversion(From, ToType))
926 return true;
927 ImpCastExprToType(From, ToType);
928 break;
929
930 case ICK_Pointer_Member:
Sebastian Redlba387562009-01-25 19:43:20 +0000931 if (CheckMemberPointerConversion(From, ToType))
932 return true;
933 ImpCastExprToType(From, ToType);
Douglas Gregorbb461502008-10-24 04:54:22 +0000934 break;
935
936 case ICK_Boolean_Conversion:
937 FromType = Context.BoolTy;
938 ImpCastExprToType(From, FromType);
939 break;
940
941 default:
942 assert(false && "Improper second standard conversion");
943 break;
944 }
945
946 switch (SCS.Third) {
947 case ICK_Identity:
948 // Nothing to do.
949 break;
950
951 case ICK_Qualification:
Mike Stumpe127ae32009-05-16 07:39:55 +0000952 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
953 // references.
Douglas Gregor5ac8ffa2009-01-16 19:38:23 +0000954 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +0000955 ToType->isLValueReferenceType());
Douglas Gregorbb461502008-10-24 04:54:22 +0000956 break;
957
958 default:
959 assert(false && "Improper second standard conversion");
960 break;
961 }
962
963 return false;
964}
965
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000966Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
967 SourceLocation KWLoc,
968 SourceLocation LParen,
969 TypeTy *Ty,
970 SourceLocation RParen) {
971 // FIXME: Some of the type traits have requirements. Interestingly, only the
Mike Stumpe127ae32009-05-16 07:39:55 +0000972 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed, G++
973 // accepts __is_pod(Incomplete) without complaints, and claims that the type
974 // is indeed a POD.
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000975
976 // There is no point in eagerly computing the value. The traits are designed
977 // to be used from type trait templates, so Ty will be a template parameter
978 // 99% of the time.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000979 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000980 QualType::getFromOpaquePtr(Ty),
981 RParen, Context.BoolTy));
982}
Sebastian Redlaa4c3732009-02-07 20:10:22 +0000983
984QualType Sema::CheckPointerToMemberOperands(
985 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
986{
987 const char *OpSpelling = isIndirect ? "->*" : ".*";
988 // C++ 5.5p2
989 // The binary operator .* [p3: ->*] binds its second operand, which shall
990 // be of type "pointer to member of T" (where T is a completely-defined
991 // class type) [...]
992 QualType RType = rex->getType();
993 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
Douglas Gregor05e28f62009-03-24 19:52:54 +0000994 if (!MemPtr) {
Sebastian Redlaa4c3732009-02-07 20:10:22 +0000995 Diag(Loc, diag::err_bad_memptr_rhs)
996 << OpSpelling << RType << rex->getSourceRange();
997 return QualType();
Douglas Gregor96b6df92009-05-14 00:28:11 +0000998 }
Douglas Gregor05e28f62009-03-24 19:52:54 +0000999
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001000 QualType Class(MemPtr->getClass(), 0);
1001
1002 // C++ 5.5p2
1003 // [...] to its first operand, which shall be of class T or of a class of
1004 // which T is an unambiguous and accessible base class. [p3: a pointer to
1005 // such a class]
1006 QualType LType = lex->getType();
1007 if (isIndirect) {
1008 if (const PointerType *Ptr = LType->getAsPointerType())
1009 LType = Ptr->getPointeeType().getNonReferenceType();
1010 else {
1011 Diag(Loc, diag::err_bad_memptr_lhs)
1012 << OpSpelling << 1 << LType << lex->getSourceRange();
1013 return QualType();
1014 }
1015 }
1016
1017 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1018 Context.getCanonicalType(LType).getUnqualifiedType()) {
1019 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1020 /*DetectVirtual=*/false);
Mike Stumpe127ae32009-05-16 07:39:55 +00001021 // FIXME: Would it be useful to print full ambiguity paths, or is that
1022 // overkill?
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001023 if (!IsDerivedFrom(LType, Class, Paths) ||
1024 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1025 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1026 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1027 return QualType();
1028 }
1029 }
1030
1031 // C++ 5.5p2
1032 // The result is an object or a function of the type specified by the
1033 // second operand.
1034 // The cv qualifiers are the union of those in the pointer and the left side,
1035 // in accordance with 5.5p5 and 5.2.5.
1036 // FIXME: This returns a dereferenced member function pointer as a normal
1037 // function type. However, the only operation valid on such functions is
Mike Stumpe127ae32009-05-16 07:39:55 +00001038 // calling them. There's also a GCC extension to get a function pointer to the
1039 // thing, which is another complication, because this type - unlike the type
1040 // that is the result of this expression - takes the class as the first
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001041 // argument.
1042 // We probably need a "MemberFunctionClosureType" or something like that.
1043 QualType Result = MemPtr->getPointeeType();
1044 if (LType.isConstQualified())
1045 Result.addConst();
1046 if (LType.isVolatileQualified())
1047 Result.addVolatile();
1048 return Result;
1049}
Sebastian Redlbd261962009-04-16 17:51:27 +00001050
1051/// \brief Get the target type of a standard or user-defined conversion.
1052static QualType TargetType(const ImplicitConversionSequence &ICS) {
1053 assert((ICS.ConversionKind ==
1054 ImplicitConversionSequence::StandardConversion ||
1055 ICS.ConversionKind ==
1056 ImplicitConversionSequence::UserDefinedConversion) &&
1057 "function only valid for standard or user-defined conversions");
1058 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1059 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1060 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1061}
1062
1063/// \brief Try to convert a type to another according to C++0x 5.16p3.
1064///
1065/// This is part of the parameter validation for the ? operator. If either
1066/// value operand is a class type, the two operands are attempted to be
1067/// converted to each other. This function does the conversion in one direction.
1068/// It emits a diagnostic and returns true only if it finds an ambiguous
1069/// conversion.
1070static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1071 SourceLocation QuestionLoc,
1072 ImplicitConversionSequence &ICS)
1073{
1074 // C++0x 5.16p3
1075 // The process for determining whether an operand expression E1 of type T1
1076 // can be converted to match an operand expression E2 of type T2 is defined
1077 // as follows:
1078 // -- If E2 is an lvalue:
1079 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1080 // E1 can be converted to match E2 if E1 can be implicitly converted to
1081 // type "lvalue reference to T2", subject to the constraint that in the
1082 // conversion the reference must bind directly to E1.
1083 if (!Self.CheckReferenceInit(From,
1084 Self.Context.getLValueReferenceType(To->getType()),
1085 &ICS))
1086 {
1087 assert((ICS.ConversionKind ==
1088 ImplicitConversionSequence::StandardConversion ||
1089 ICS.ConversionKind ==
1090 ImplicitConversionSequence::UserDefinedConversion) &&
1091 "expected a definite conversion");
1092 bool DirectBinding =
1093 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1094 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1095 if (DirectBinding)
1096 return false;
1097 }
1098 }
1099 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1100 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1101 // -- if E1 and E2 have class type, and the underlying class types are
1102 // the same or one is a base class of the other:
1103 QualType FTy = From->getType();
1104 QualType TTy = To->getType();
1105 const RecordType *FRec = FTy->getAsRecordType();
1106 const RecordType *TRec = TTy->getAsRecordType();
1107 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1108 if (FRec && TRec && (FRec == TRec ||
1109 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1110 // E1 can be converted to match E2 if the class of T2 is the
1111 // same type as, or a base class of, the class of T1, and
1112 // [cv2 > cv1].
1113 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1114 // Could still fail if there's no copy constructor.
1115 // FIXME: Is this a hard error then, or just a conversion failure? The
1116 // standard doesn't say.
1117 ICS = Self.TryCopyInitialization(From, TTy);
1118 }
1119 } else {
1120 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1121 // implicitly converted to the type that expression E2 would have
1122 // if E2 were converted to an rvalue.
1123 // First find the decayed type.
1124 if (TTy->isFunctionType())
1125 TTy = Self.Context.getPointerType(TTy);
1126 else if(TTy->isArrayType())
1127 TTy = Self.Context.getArrayDecayedType(TTy);
1128
1129 // Now try the implicit conversion.
1130 // FIXME: This doesn't detect ambiguities.
1131 ICS = Self.TryImplicitConversion(From, TTy);
1132 }
1133 return false;
1134}
1135
1136/// \brief Try to find a common type for two according to C++0x 5.16p5.
1137///
1138/// This is part of the parameter validation for the ? operator. If either
1139/// value operand is a class type, overload resolution is used to find a
1140/// conversion to a common type.
1141static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1142 SourceLocation Loc) {
1143 Expr *Args[2] = { LHS, RHS };
1144 OverloadCandidateSet CandidateSet;
1145 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1146
1147 OverloadCandidateSet::iterator Best;
1148 switch (Self.BestViableFunction(CandidateSet, Best)) {
1149 case Sema::OR_Success:
1150 // We found a match. Perform the conversions on the arguments and move on.
1151 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1152 Best->Conversions[0], "converting") ||
1153 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1154 Best->Conversions[1], "converting"))
1155 break;
1156 return false;
1157
1158 case Sema::OR_No_Viable_Function:
1159 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1160 << LHS->getType() << RHS->getType()
1161 << LHS->getSourceRange() << RHS->getSourceRange();
1162 return true;
1163
1164 case Sema::OR_Ambiguous:
1165 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1166 << LHS->getType() << RHS->getType()
1167 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpe127ae32009-05-16 07:39:55 +00001168 // FIXME: Print the possible common types by printing the return types of
1169 // the viable candidates.
Sebastian Redlbd261962009-04-16 17:51:27 +00001170 break;
1171
1172 case Sema::OR_Deleted:
1173 assert(false && "Conditional operator has only built-in overloads");
1174 break;
1175 }
1176 return true;
1177}
1178
Sebastian Redld3169132009-04-17 16:30:52 +00001179/// \brief Perform an "extended" implicit conversion as returned by
1180/// TryClassUnification.
1181///
1182/// TryClassUnification generates ICSs that include reference bindings.
1183/// PerformImplicitConversion is not suitable for this; it chokes if the
1184/// second part of a standard conversion is ICK_DerivedToBase. This function
1185/// handles the reference binding specially.
1186static bool ConvertForConditional(Sema &Self, Expr *&E,
1187 const ImplicitConversionSequence &ICS)
1188{
1189 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1190 ICS.Standard.ReferenceBinding) {
1191 assert(ICS.Standard.DirectBinding &&
1192 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf6b86182009-04-26 11:21:02 +00001193 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1194 // redoing all the work.
1195 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1196 TargetType(ICS)));
Sebastian Redld3169132009-04-17 16:30:52 +00001197 }
1198 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1199 ICS.UserDefined.After.ReferenceBinding) {
1200 assert(ICS.UserDefined.After.DirectBinding &&
1201 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf6b86182009-04-26 11:21:02 +00001202 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1203 TargetType(ICS)));
Sebastian Redld3169132009-04-17 16:30:52 +00001204 }
1205 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1206 return true;
1207 return false;
1208}
1209
Sebastian Redlbd261962009-04-16 17:51:27 +00001210/// \brief Check the operands of ?: under C++ semantics.
1211///
1212/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1213/// extension. In this case, LHS == Cond. (But they're not aliases.)
1214QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1215 SourceLocation QuestionLoc) {
Mike Stumpe127ae32009-05-16 07:39:55 +00001216 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1217 // interface pointers.
Sebastian Redlbd261962009-04-16 17:51:27 +00001218
1219 // C++0x 5.16p1
1220 // The first expression is contextually converted to bool.
1221 if (!Cond->isTypeDependent()) {
1222 if (CheckCXXBooleanCondition(Cond))
1223 return QualType();
1224 }
1225
1226 // Either of the arguments dependent?
1227 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1228 return Context.DependentTy;
1229
1230 // C++0x 5.16p2
1231 // If either the second or the third operand has type (cv) void, ...
1232 QualType LTy = LHS->getType();
1233 QualType RTy = RHS->getType();
1234 bool LVoid = LTy->isVoidType();
1235 bool RVoid = RTy->isVoidType();
1236 if (LVoid || RVoid) {
1237 // ... then the [l2r] conversions are performed on the second and third
1238 // operands ...
1239 DefaultFunctionArrayConversion(LHS);
1240 DefaultFunctionArrayConversion(RHS);
1241 LTy = LHS->getType();
1242 RTy = RHS->getType();
1243
1244 // ... and one of the following shall hold:
1245 // -- The second or the third operand (but not both) is a throw-
1246 // expression; the result is of the type of the other and is an rvalue.
1247 bool LThrow = isa<CXXThrowExpr>(LHS);
1248 bool RThrow = isa<CXXThrowExpr>(RHS);
1249 if (LThrow && !RThrow)
1250 return RTy;
1251 if (RThrow && !LThrow)
1252 return LTy;
1253
1254 // -- Both the second and third operands have type void; the result is of
1255 // type void and is an rvalue.
1256 if (LVoid && RVoid)
1257 return Context.VoidTy;
1258
1259 // Neither holds, error.
1260 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1261 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1262 << LHS->getSourceRange() << RHS->getSourceRange();
1263 return QualType();
1264 }
1265
1266 // Neither is void.
1267
1268 // C++0x 5.16p3
1269 // Otherwise, if the second and third operand have different types, and
1270 // either has (cv) class type, and attempt is made to convert each of those
1271 // operands to the other.
1272 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1273 (LTy->isRecordType() || RTy->isRecordType())) {
1274 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1275 // These return true if a single direction is already ambiguous.
1276 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1277 return QualType();
1278 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1279 return QualType();
1280
1281 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1282 ImplicitConversionSequence::BadConversion;
1283 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1284 ImplicitConversionSequence::BadConversion;
1285 // If both can be converted, [...] the program is ill-formed.
1286 if (HaveL2R && HaveR2L) {
1287 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1288 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1289 return QualType();
1290 }
1291
1292 // If exactly one conversion is possible, that conversion is applied to
1293 // the chosen operand and the converted operands are used in place of the
1294 // original operands for the remainder of this section.
1295 if (HaveL2R) {
Sebastian Redld3169132009-04-17 16:30:52 +00001296 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redlbd261962009-04-16 17:51:27 +00001297 return QualType();
1298 LTy = LHS->getType();
1299 } else if (HaveR2L) {
Sebastian Redld3169132009-04-17 16:30:52 +00001300 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redlbd261962009-04-16 17:51:27 +00001301 return QualType();
1302 RTy = RHS->getType();
1303 }
1304 }
1305
1306 // C++0x 5.16p4
1307 // If the second and third operands are lvalues and have the same type,
1308 // the result is of that type [...]
1309 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1310 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1311 RHS->isLvalue(Context) == Expr::LV_Valid)
1312 return LTy;
1313
1314 // C++0x 5.16p5
1315 // Otherwise, the result is an rvalue. If the second and third operands
1316 // do not have the same type, and either has (cv) class type, ...
1317 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1318 // ... overload resolution is used to determine the conversions (if any)
1319 // to be applied to the operands. If the overload resolution fails, the
1320 // program is ill-formed.
1321 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1322 return QualType();
1323 }
1324
1325 // C++0x 5.16p6
1326 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1327 // conversions are performed on the second and third operands.
1328 DefaultFunctionArrayConversion(LHS);
1329 DefaultFunctionArrayConversion(RHS);
1330 LTy = LHS->getType();
1331 RTy = RHS->getType();
1332
1333 // After those conversions, one of the following shall hold:
1334 // -- The second and third operands have the same type; the result
1335 // is of that type.
1336 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1337 return LTy;
1338
1339 // -- The second and third operands have arithmetic or enumeration type;
1340 // the usual arithmetic conversions are performed to bring them to a
1341 // common type, and the result is of that type.
1342 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1343 UsualArithmeticConversions(LHS, RHS);
1344 return LHS->getType();
1345 }
1346
1347 // -- The second and third operands have pointer type, or one has pointer
1348 // type and the other is a null pointer constant; pointer conversions
1349 // and qualification conversions are performed to bring them to their
1350 // composite pointer type. The result is of the composite pointer type.
Sebastian Redl42b81a22009-04-19 19:26:31 +00001351 QualType Composite = FindCompositePointerType(LHS, RHS);
1352 if (!Composite.isNull())
1353 return Composite;
Sebastian Redlbd261962009-04-16 17:51:27 +00001354
Sebastian Redl5b3fcf82009-04-19 21:15:26 +00001355 // Fourth bullet is same for pointers-to-member. However, the possible
1356 // conversions are far more limited: we have null-to-pointer, upcast of
1357 // containing class, and second-level cv-ness.
1358 // cv-ness is not a union, but must match one of the two operands. (Which,
1359 // frankly, is stupid.)
1360 const MemberPointerType *LMemPtr = LTy->getAsMemberPointerType();
1361 const MemberPointerType *RMemPtr = RTy->getAsMemberPointerType();
1362 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1363 ImpCastExprToType(RHS, LTy);
1364 return LTy;
1365 }
1366 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1367 ImpCastExprToType(LHS, RTy);
1368 return RTy;
1369 }
1370 if (LMemPtr && RMemPtr) {
1371 QualType LPointee = LMemPtr->getPointeeType();
1372 QualType RPointee = RMemPtr->getPointeeType();
1373 // First, we check that the unqualified pointee type is the same. If it's
1374 // not, there's no conversion that will unify the two pointers.
1375 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1376 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1377 // Second, we take the greater of the two cv qualifications. If neither
1378 // is greater than the other, the conversion is not possible.
1379 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1380 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1381 // Third, we check if either of the container classes is derived from
1382 // the other.
1383 QualType LContainer(LMemPtr->getClass(), 0);
1384 QualType RContainer(RMemPtr->getClass(), 0);
1385 QualType MoreDerived;
1386 if (Context.getCanonicalType(LContainer) ==
1387 Context.getCanonicalType(RContainer))
1388 MoreDerived = LContainer;
1389 else if (IsDerivedFrom(LContainer, RContainer))
1390 MoreDerived = LContainer;
1391 else if (IsDerivedFrom(RContainer, LContainer))
1392 MoreDerived = RContainer;
1393
1394 if (!MoreDerived.isNull()) {
1395 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1396 // We don't use ImpCastExprToType here because this could still fail
1397 // for ambiguous or inaccessible conversions.
1398 QualType Common = Context.getMemberPointerType(
1399 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1400 if (PerformImplicitConversion(LHS, Common, "converting"))
1401 return QualType();
1402 if (PerformImplicitConversion(RHS, Common, "converting"))
1403 return QualType();
1404 return Common;
1405 }
1406 }
1407 }
1408 }
1409
Sebastian Redlbd261962009-04-16 17:51:27 +00001410 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1411 << LHS->getType() << RHS->getType()
1412 << LHS->getSourceRange() << RHS->getSourceRange();
1413 return QualType();
1414}
Sebastian Redl42b81a22009-04-19 19:26:31 +00001415
1416/// \brief Find a merged pointer type and convert the two expressions to it.
1417///
1418/// This finds the composite pointer type for @p E1 and @p E2 according to
1419/// C++0x 5.9p2. It converts both expressions to this type and returns it.
1420/// It does not emit diagnostics.
1421QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1422 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1423 QualType T1 = E1->getType(), T2 = E2->getType();
1424 if(!T1->isPointerType() && !T2->isPointerType())
1425 return QualType();
1426
1427 // C++0x 5.9p2
1428 // Pointer conversions and qualification conversions are performed on
1429 // pointer operands to bring them to their composite pointer type. If
1430 // one operand is a null pointer constant, the composite pointer type is
1431 // the type of the other operand.
1432 if (E1->isNullPointerConstant(Context)) {
1433 ImpCastExprToType(E1, T2);
1434 return T2;
1435 }
1436 if (E2->isNullPointerConstant(Context)) {
1437 ImpCastExprToType(E2, T1);
1438 return T1;
1439 }
1440 // Now both have to be pointers.
1441 if(!T1->isPointerType() || !T2->isPointerType())
1442 return QualType();
1443
1444 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1445 // the other has type "pointer to cv2 T" and the composite pointer type is
1446 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1447 // Otherwise, the composite pointer type is a pointer type similar to the
1448 // type of one of the operands, with a cv-qualification signature that is
1449 // the union of the cv-qualification signatures of the operand types.
1450 // In practice, the first part here is redundant; it's subsumed by the second.
1451 // What we do here is, we build the two possible composite types, and try the
1452 // conversions in both directions. If only one works, or if the two composite
1453 // types are the same, we have succeeded.
1454 llvm::SmallVector<unsigned, 4> QualifierUnion;
1455 QualType Composite1 = T1, Composite2 = T2;
1456 const PointerType *Ptr1, *Ptr2;
1457 while ((Ptr1 = Composite1->getAsPointerType()) &&
1458 (Ptr2 = Composite2->getAsPointerType())) {
1459 Composite1 = Ptr1->getPointeeType();
1460 Composite2 = Ptr2->getPointeeType();
1461 QualifierUnion.push_back(
1462 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1463 }
1464 // Rewrap the composites as pointers with the union CVRs.
1465 for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(),
1466 E = QualifierUnion.end(); I != E; ++I) {
1467 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1468 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1469 }
1470
1471 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1472 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1473 ImplicitConversionSequence E1ToC2, E2ToC2;
1474 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1475 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1476 if (Context.getCanonicalType(Composite1) !=
1477 Context.getCanonicalType(Composite2)) {
1478 E1ToC2 = TryImplicitConversion(E1, Composite2);
1479 E2ToC2 = TryImplicitConversion(E2, Composite2);
1480 }
1481
1482 bool ToC1Viable = E1ToC1.ConversionKind !=
1483 ImplicitConversionSequence::BadConversion
1484 && E2ToC1.ConversionKind !=
1485 ImplicitConversionSequence::BadConversion;
1486 bool ToC2Viable = E1ToC2.ConversionKind !=
1487 ImplicitConversionSequence::BadConversion
1488 && E2ToC2.ConversionKind !=
1489 ImplicitConversionSequence::BadConversion;
1490 if (ToC1Viable && !ToC2Viable) {
1491 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1492 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1493 return Composite1;
1494 }
1495 if (ToC2Viable && !ToC1Viable) {
1496 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1497 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1498 return Composite2;
1499 }
1500 return QualType();
1501}
Anders Carlssonf0967d72009-05-17 18:41:29 +00001502
1503Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1504 Expr *FullExpr = Arg.takeAs<Expr>();
1505 assert(FullExpr && "Null full expr!");
1506
1507 if (!ExprTemporaries.empty()) {
1508 // Create a cleanup expr.
1509 FullExpr =
1510 new (Context) CXXExprWithTemporaries(FullExpr, &ExprTemporaries[0],
1511 ExprTemporaries.size());
1512 ExprTemporaries.clear();
1513 }
1514
1515 return Owned(FullExpr);
1516}