blob: 2705d9900b4945a4bedfab37bf942856ed974a2a [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);
Douglas Gregorcfe6ae52009-08-05 05:36:45 +000035 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
Douglas Gregorb0212bd2008-11-17 20:34:05 +000036 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
Douglas Gregora8b2fbf2009-06-22 20:57:11 +000074 if (!isType) {
75 // C++0x [expr.typeid]p3:
76 // When typeid is applied to an expression other than an lvalue of a
77 // polymorphic class type [...] [the] expression is an unevaluated
78 // operand.
79
80 // FIXME: if the type of the expression is a class type, the class
81 // shall be completely defined.
82 bool isUnevaluatedOperand = true;
83 Expr *E = static_cast<Expr *>(TyOrExpr);
84 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
85 QualType T = E->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +000086 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregora8b2fbf2009-06-22 20:57:11 +000087 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
88 if (RecordD->isPolymorphic())
89 isUnevaluatedOperand = false;
90 }
91 }
92
93 // If this is an unevaluated operand, clear out the set of declaration
94 // references we have been computing.
95 if (isUnevaluatedOperand)
96 PotentiallyReferencedDeclStack.back().clear();
97 }
98
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000099 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
100 TypeInfoType.withConst(),
101 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000102}
103
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000104/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000105Action::OwningExprResult
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000106Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregorf8e92702008-10-24 15:36:09 +0000107 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Chris Lattner4b009652007-07-25 00:24:17 +0000108 "Unknown C++ Boolean value!");
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000109 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
110 Context.BoolTy, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000111}
Chris Lattnera7447ba2008-02-26 00:51:44 +0000112
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000113/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
114Action::OwningExprResult
115Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
116 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
117}
118
Chris Lattnera7447ba2008-02-26 00:51:44 +0000119/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000120Action::OwningExprResult
121Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl9949a5e2009-04-27 20:27:31 +0000122 Expr *Ex = E.takeAs<Expr>();
123 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
124 return ExprError();
125 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
126}
127
128/// CheckCXXThrowOperand - Validate the operand of a throw.
129bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
130 // C++ [except.throw]p3:
131 // [...] adjusting the type from "array of T" or "function returning T"
132 // to "pointer to T" or "pointer to function returning T", [...]
133 DefaultFunctionArrayConversion(E);
134
135 // If the type of the exception would be an incomplete type or a pointer
136 // to an incomplete type other than (cv) void the program is ill-formed.
137 QualType Ty = E->getType();
138 int isPointer = 0;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000139 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl9949a5e2009-04-27 20:27:31 +0000140 Ty = Ptr->getPointeeType();
141 isPointer = 1;
142 }
143 if (!isPointer || !Ty->isVoidType()) {
144 if (RequireCompleteType(ThrowLoc, Ty,
145 isPointer ? diag::err_throw_incomplete_ptr
146 : diag::err_throw_incomplete,
147 E->getSourceRange(), SourceRange(), QualType()))
148 return true;
149 }
150
151 // FIXME: Construct a temporary here.
152 return false;
Chris Lattnera7447ba2008-02-26 00:51:44 +0000153}
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000154
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000155Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000156 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
157 /// is a non-lvalue expression whose value is the address of the object for
158 /// which the function is called.
159
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000160 if (!isa<FunctionDecl>(CurContext))
161 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000162
163 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
164 if (MD->isInstance())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000165 return Owned(new (Context) CXXThisExpr(ThisLoc,
166 MD->getThisType(Context)));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000167
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000168 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000169}
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000170
171/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
172/// Can be interpreted either as function-style casting ("int(x)")
173/// or class type construction ("ClassType(x,y,z)")
174/// or creation of a value-initialized type ("int()").
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000175Action::OwningExprResult
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000176Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
177 SourceLocation LParenLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000178 MultiExprArg exprs,
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000179 SourceLocation *CommaLocs,
180 SourceLocation RParenLoc) {
181 assert(TypeRep && "Missing type!");
182 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000183 unsigned NumExprs = exprs.size();
184 Expr **Exprs = (Expr**)exprs.get();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000185 SourceLocation TyBeginLoc = TypeRange.getBegin();
186 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
187
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000188 if (Ty->isDependentType() ||
Douglas Gregor396f1142009-03-13 21:01:28 +0000189 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000190 exprs.release();
Anders Carlssonebbd7cd2009-04-24 05:23:13 +0000191
Douglas Gregorf27b7652009-05-20 18:46:25 +0000192 return Owned(CXXUnresolvedConstructExpr::Create(Context,
193 TypeRange.getBegin(), Ty,
194 LParenLoc,
195 Exprs, NumExprs,
196 RParenLoc));
Douglas Gregor396f1142009-03-13 21:01:28 +0000197 }
198
199
Douglas Gregor861e7902009-01-16 18:33:17 +0000200 // C++ [expr.type.conv]p1:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000201 // If the expression list is a single expression, the type conversion
202 // expression is equivalent (in definedness, and if defined in meaning) to the
203 // corresponding cast expression.
204 //
205 if (NumExprs == 1) {
Anders Carlsson9583fa72009-08-07 22:21:05 +0000206 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
207 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, /*functional-style*/true))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000208 return ExprError();
209 exprs.release();
210 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +0000211 Ty, TyBeginLoc, Kind,
Anders Carlsson7ef181c2009-07-31 00:48:10 +0000212 Exprs[0], RParenLoc));
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000213 }
214
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000215 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor861e7902009-01-16 18:33:17 +0000216 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000217
Anders Carlssonf0967d72009-05-17 18:41:29 +0000218 // FIXME: We should always create a CXXTemporaryObjectExpr here unless
219 // both the ctor and dtor are trivial.
Douglas Gregor861e7902009-01-16 18:33:17 +0000220 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
221 CXXConstructorDecl *Constructor
222 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
223 TypeRange.getBegin(),
224 SourceRange(TypeRange.getBegin(),
225 RParenLoc),
226 DeclarationName(),
227 IK_Direct);
Douglas Gregor861e7902009-01-16 18:33:17 +0000228
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000229 if (!Constructor)
230 return ExprError();
231
232 exprs.release();
Anders Carlsson7b7b2552009-05-30 20:56:46 +0000233 Expr *E = new (Context) CXXTemporaryObjectExpr(Context, Constructor,
Anders Carlssona05fa102009-05-30 20:36:53 +0000234 Ty, TyBeginLoc, Exprs,
235 NumExprs, RParenLoc);
236 return MaybeBindToTemporary(E);
Douglas Gregor861e7902009-01-16 18:33:17 +0000237 }
238
239 // Fall through to value-initialize an object of class type that
240 // doesn't have a user-declared default constructor.
241 }
242
243 // C++ [expr.type.conv]p1:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000244 // If the expression list specifies more than a single value, the type shall
245 // be a class with a suitably declared constructor.
246 //
247 if (NumExprs > 1)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000248 return ExprError(Diag(CommaLocs[0],
249 diag::err_builtin_func_cast_more_than_one_arg)
250 << FullRange);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000251
252 assert(NumExprs == 0 && "Expected 0 expressions");
253
Douglas Gregor861e7902009-01-16 18:33:17 +0000254 // C++ [expr.type.conv]p2:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000255 // The expression T(), where T is a simple-type-specifier for a non-array
256 // complete object type or the (possibly cv-qualified) void type, creates an
257 // rvalue of the specified type, which is value-initialized.
258 //
259 if (Ty->isArrayType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000260 return ExprError(Diag(TyBeginLoc,
261 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000262 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000263 RequireCompleteType(TyBeginLoc, Ty,
264 diag::err_invalid_incomplete_type_use, FullRange))
265 return ExprError();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000266
Anders Carlsson412c3402009-03-24 01:19:16 +0000267 if (RequireNonAbstractType(TyBeginLoc, Ty,
268 diag::err_allocation_of_abstract_type))
Anders Carlssonc263c9b2009-03-23 19:10:31 +0000269 return ExprError();
270
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000271 exprs.release();
272 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000273}
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000274
275
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000276/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
277/// @code new (memory) int[size][4] @endcode
278/// or
279/// @code ::new Foo(23, "hello") @endcode
280/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000281Action::OwningExprResult
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000282Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000283 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000284 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000285 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000286 MultiExprArg ConstructorArgs,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000287 SourceLocation ConstructorRParen)
288{
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000289 Expr *ArraySize = 0;
290 unsigned Skip = 0;
291 // If the specified type is an array, unwrap it and save the expression.
292 if (D.getNumTypeObjects() > 0 &&
293 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
294 DeclaratorChunk &Chunk = D.getTypeObject(0);
295 if (Chunk.Arr.hasStatic)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000296 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
297 << D.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000298 if (!Chunk.Arr.NumElts)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000299 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
300 << D.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000301 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
302 Skip = 1;
303 }
304
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000305 //FIXME: Store DeclaratorInfo in CXXNew expression.
306 DeclaratorInfo *DInfo = 0;
307 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
Chris Lattner34c61332009-04-25 08:06:05 +0000308 if (D.isInvalidType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000309 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000310
Douglas Gregord8c23702009-05-21 00:00:09 +0000311 // Every dimension shall be of constant size.
312 unsigned i = 1;
313 QualType ElementType = AllocType;
314 while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
315 if (!Array->isConstantArrayType()) {
316 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
317 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
318 return ExprError();
319 }
320 ElementType = Array->getElementType();
321 ++i;
322 }
323
324 return BuildCXXNew(StartLoc, UseGlobal,
325 PlacementLParen,
326 move(PlacementArgs),
327 PlacementRParen,
328 ParenTypeId,
329 AllocType,
330 D.getSourceRange().getBegin(),
331 D.getSourceRange(),
332 Owned(ArraySize),
333 ConstructorLParen,
334 move(ConstructorArgs),
335 ConstructorRParen);
336}
337
338Sema::OwningExprResult
339Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
340 SourceLocation PlacementLParen,
341 MultiExprArg PlacementArgs,
342 SourceLocation PlacementRParen,
343 bool ParenTypeId,
344 QualType AllocType,
345 SourceLocation TypeLoc,
346 SourceRange TypeRange,
347 ExprArg ArraySizeE,
348 SourceLocation ConstructorLParen,
349 MultiExprArg ConstructorArgs,
350 SourceLocation ConstructorRParen) {
351 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000352 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000353
Douglas Gregord8c23702009-05-21 00:00:09 +0000354 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000355
356 // That every array dimension except the first is constant was already
357 // checked by the type check above.
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000358
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000359 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
360 // or enumeration type with a non-negative value."
Douglas Gregord8c23702009-05-21 00:00:09 +0000361 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000362 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000363 QualType SizeType = ArraySize->getType();
364 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000365 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
366 diag::err_array_size_not_integral)
367 << SizeType << ArraySize->getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000368 // Let's see if this is a constant < 0. If so, we reject it out of hand.
369 // We don't care about special rules, so we tell the machinery it's not
370 // evaluated - it gives us a result in more cases.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000371 if (!ArraySize->isValueDependent()) {
372 llvm::APSInt Value;
373 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
374 if (Value < llvm::APSInt(
375 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000376 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
377 diag::err_typecheck_negative_array_size)
378 << ArraySize->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000379 }
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000380 }
381 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000382
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000383 FunctionDecl *OperatorNew = 0;
384 FunctionDecl *OperatorDelete = 0;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000385 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
386 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000387 if (!AllocType->isDependentType() &&
388 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
389 FindAllocationFunctions(StartLoc,
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000390 SourceRange(PlacementLParen, PlacementRParen),
391 UseGlobal, AllocType, ArraySize, PlaceArgs,
392 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000393 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000394
395 bool Init = ConstructorLParen.isValid();
396 // --- Choosing a constructor ---
397 // C++ 5.3.4p15
398 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
399 // the object is not initialized. If the object, or any part of it, is
400 // const-qualified, it's an error.
401 // 2) If T is a POD and there's an empty initializer, the object is value-
402 // initialized.
403 // 3) If T is a POD and there's one initializer argument, the object is copy-
404 // constructed.
405 // 4) If T is a POD and there's more initializer arguments, it's an error.
406 // 5) If T is not a POD, the initializer arguments are used as constructor
407 // arguments.
408 //
409 // Or by the C++0x formulation:
410 // 1) If there's no initializer, the object is default-initialized according
411 // to C++0x rules.
412 // 2) Otherwise, the object is direct-initialized.
413 CXXConstructorDecl *Constructor = 0;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000414 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl091cf8d2009-05-07 16:14:23 +0000415 const RecordType *RT;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000416 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000417 if (AllocType->isDependentType()) {
418 // Skip all the checks.
Mike Stump90fc78e2009-08-04 21:02:39 +0000419 } else if ((RT = AllocType->getAs<RecordType>()) &&
420 !AllocType->isAggregateType()) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000421 Constructor = PerformInitializationByConstructor(
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000422 AllocType, ConsArgs, NumConsArgs,
Douglas Gregord8c23702009-05-21 00:00:09 +0000423 TypeLoc,
424 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattner271d4c22008-11-24 05:29:24 +0000425 RT->getDecl()->getDeclName(),
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000426 NumConsArgs != 0 ? IK_Direct : IK_Default);
427 if (!Constructor)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000428 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000429 } else {
430 if (!Init) {
431 // FIXME: Check that no subpart is const.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000432 if (AllocType.isConstQualified())
433 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregord8c23702009-05-21 00:00:09 +0000434 << TypeRange);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000435 } else if (NumConsArgs == 0) {
436 // Object is value-initialized. Do nothing.
437 } else if (NumConsArgs == 1) {
438 // Object is direct-initialized.
Sebastian Redl091cf8d2009-05-07 16:14:23 +0000439 // FIXME: What DeclarationName do we pass in here?
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000440 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000441 DeclarationName() /*AllocType.getAsString()*/,
442 /*DirectInit=*/true))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000443 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000444 } else {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000445 return ExprError(Diag(StartLoc,
446 diag::err_builtin_direct_init_more_than_one_arg)
447 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000448 }
449 }
450
451 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
452
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000453 PlacementArgs.release();
454 ConstructorArgs.release();
Douglas Gregord8c23702009-05-21 00:00:09 +0000455 ArraySizeE.release();
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000456 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek0c97e042009-02-07 01:47:29 +0000457 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000458 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Douglas Gregord8c23702009-05-21 00:00:09 +0000459 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000460}
461
462/// CheckAllocatedType - Checks that a type is suitable as the allocated type
463/// in a new-expression.
464/// dimension off and stores the size expression in ArraySize.
Douglas Gregord8c23702009-05-21 00:00:09 +0000465bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
466 SourceRange R)
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000467{
468 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
469 // abstract class type or array thereof.
Douglas Gregor05e28f62009-03-24 19:52:54 +0000470 if (AllocType->isFunctionType())
Douglas Gregord8c23702009-05-21 00:00:09 +0000471 return Diag(Loc, diag::err_bad_new_type)
472 << AllocType << 0 << R;
Douglas Gregor05e28f62009-03-24 19:52:54 +0000473 else if (AllocType->isReferenceType())
Douglas Gregord8c23702009-05-21 00:00:09 +0000474 return Diag(Loc, diag::err_bad_new_type)
475 << AllocType << 1 << R;
Douglas Gregor05e28f62009-03-24 19:52:54 +0000476 else if (!AllocType->isDependentType() &&
Douglas Gregord8c23702009-05-21 00:00:09 +0000477 RequireCompleteType(Loc, AllocType,
Douglas Gregor05e28f62009-03-24 19:52:54 +0000478 diag::err_new_incomplete_type,
Douglas Gregord8c23702009-05-21 00:00:09 +0000479 R))
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000480 return true;
Douglas Gregord8c23702009-05-21 00:00:09 +0000481 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregor05e28f62009-03-24 19:52:54 +0000482 diag::err_allocation_of_abstract_type))
483 return true;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000484
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000485 return false;
486}
487
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000488/// FindAllocationFunctions - Finds the overloads of operator new and delete
489/// that are appropriate for the allocation.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000490bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
491 bool UseGlobal, QualType AllocType,
492 bool IsArray, Expr **PlaceArgs,
493 unsigned NumPlaceArgs,
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000494 FunctionDecl *&OperatorNew,
495 FunctionDecl *&OperatorDelete)
496{
497 // --- Choosing an allocation function ---
498 // C++ 5.3.4p8 - 14 & 18
499 // 1) If UseGlobal is true, only look in the global scope. Else, also look
500 // in the scope of the allocated class.
501 // 2) If an array size is given, look for operator new[], else look for
502 // operator new.
503 // 3) The first argument is always size_t. Append the arguments from the
504 // placement form.
505 // FIXME: Also find the appropriate delete operator.
506
507 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
508 // We don't care about the actual value of this argument.
509 // FIXME: Should the Sema create the expression and embed it in the syntax
510 // tree? Or should the consumer just recalculate the value?
Anders Carlsson44443f82009-08-16 20:29:29 +0000511 IntegerLiteral Size(llvm::APInt::getNullValue(
512 Context.Target.getPointerWidth(0)),
513 Context.getSizeType(),
514 SourceLocation());
515 AllocArgs[0] = &Size;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000516 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
517
518 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
519 IsArray ? OO_Array_New : OO_New);
520 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregor2e047592009-02-28 01:32:25 +0000521 CXXRecordDecl *Record
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000522 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redlec5f3262008-12-04 22:20:51 +0000523 // FIXME: We fail to find inherited overloads.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000524 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000525 AllocArgs.size(), Record, /*AllowMissing=*/true,
526 OperatorNew))
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000527 return true;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000528 }
529 if (!OperatorNew) {
530 // Didn't find a member overload. Look for a global one.
531 DeclareGlobalNewDelete();
Sebastian Redlec5f3262008-12-04 22:20:51 +0000532 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000533 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000534 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
535 OperatorNew))
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000536 return true;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000537 }
538
Anders Carlsson0db4ade2009-05-31 20:26:12 +0000539 // FindAllocationOverload can change the passed in arguments, so we need to
540 // copy them back.
541 if (NumPlaceArgs > 0)
542 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
543
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000544 return false;
545}
546
Sebastian Redlec5f3262008-12-04 22:20:51 +0000547/// FindAllocationOverload - Find an fitting overload for the allocation
548/// function in the specified scope.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000549bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
550 DeclarationName Name, Expr** Args,
551 unsigned NumArgs, DeclContext *Ctx,
552 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redlec5f3262008-12-04 22:20:51 +0000553{
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000554 DeclContext::lookup_iterator Alloc, AllocEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000555 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000556 if (Alloc == AllocEnd) {
Sebastian Redlec5f3262008-12-04 22:20:51 +0000557 if (AllowMissing)
558 return false;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000559 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +0000560 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000561 }
562
563 OverloadCandidateSet Candidates;
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000564 for (; Alloc != AllocEnd; ++Alloc) {
565 // Even member operator new/delete are implicitly treated as
566 // static, so don't use AddMemberCandidate.
567 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
568 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
569 /*SuppressUserConversions=*/false);
Sebastian Redlec5f3262008-12-04 22:20:51 +0000570 }
571
572 // Do the resolution.
573 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +0000574 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redlec5f3262008-12-04 22:20:51 +0000575 case OR_Success: {
576 // Got one!
577 FunctionDecl *FnDecl = Best->Function;
578 // The first argument is size_t, and the first parameter must be size_t,
579 // too. This is checked on declaration and can be assumed. (It can't be
580 // asserted on, though, since invalid decls are left in there.)
581 for (unsigned i = 1; i < NumArgs; ++i) {
582 // FIXME: Passing word to diagnostic.
Anders Carlsson88719742009-05-31 19:49:47 +0000583 if (PerformCopyInitialization(Args[i],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000584 FnDecl->getParamDecl(i)->getType(),
585 "passing"))
586 return true;
587 }
588 Operator = FnDecl;
589 return false;
590 }
591
592 case OR_No_Viable_Function:
Sebastian Redlec5f3262008-12-04 22:20:51 +0000593 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +0000594 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000595 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
596 return true;
597
598 case OR_Ambiguous:
Sebastian Redlec5f3262008-12-04 22:20:51 +0000599 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000600 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000601 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
602 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +0000603
604 case OR_Deleted:
605 Diag(StartLoc, diag::err_ovl_deleted_call)
606 << Best->Function->isDeleted()
607 << Name << Range;
608 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
609 return true;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000610 }
611 assert(false && "Unreachable, bad result from BestViableFunction");
612 return true;
613}
614
615
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000616/// DeclareGlobalNewDelete - Declare the global forms of operator new and
617/// delete. These are:
618/// @code
619/// void* operator new(std::size_t) throw(std::bad_alloc);
620/// void* operator new[](std::size_t) throw(std::bad_alloc);
621/// void operator delete(void *) throw();
622/// void operator delete[](void *) throw();
623/// @endcode
624/// Note that the placement and nothrow forms of new are *not* implicitly
625/// declared. Their use requires including \<new\>.
626void Sema::DeclareGlobalNewDelete()
627{
628 if (GlobalNewDeleteDeclared)
629 return;
630 GlobalNewDeleteDeclared = true;
631
632 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
633 QualType SizeT = Context.getSizeType();
634
635 // FIXME: Exception specifications are not added.
636 DeclareGlobalAllocationFunction(
637 Context.DeclarationNames.getCXXOperatorName(OO_New),
638 VoidPtr, SizeT);
639 DeclareGlobalAllocationFunction(
640 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
641 VoidPtr, SizeT);
642 DeclareGlobalAllocationFunction(
643 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
644 Context.VoidTy, VoidPtr);
645 DeclareGlobalAllocationFunction(
646 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
647 Context.VoidTy, VoidPtr);
648}
649
650/// DeclareGlobalAllocationFunction - Declares a single implicit global
651/// allocation function if it doesn't already exist.
652void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
653 QualType Return, QualType Argument)
654{
655 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
656
657 // Check if this function is already declared.
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000658 {
Douglas Gregor7c865852008-12-23 22:05:29 +0000659 DeclContext::lookup_iterator Alloc, AllocEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000660 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000661 Alloc != AllocEnd; ++Alloc) {
662 // FIXME: Do we need to check for default arguments here?
663 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
664 if (Func->getNumParams() == 1 &&
Ted Kremenek0c97e042009-02-07 01:47:29 +0000665 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000666 return;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000667 }
668 }
669
670 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
671 FunctionDecl *Alloc =
672 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000673 FnType, /*DInfo=*/0, FunctionDecl::None, false, true,
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000674 SourceLocation());
675 Alloc->setImplicit();
676 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000677 0, Argument, /*DInfo=*/0,
678 VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000679 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000680
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000681 // FIXME: Also add this declaration to the IdentifierResolver, but
682 // make sure it is at the end of the chain to coincide with the
683 // global scope.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000684 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000685}
686
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000687/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
688/// @code ::delete ptr; @endcode
689/// or
690/// @code delete [] ptr; @endcode
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000691Action::OwningExprResult
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000692Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000693 bool ArrayForm, ExprArg Operand)
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000694{
695 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
696 // having a single conversion function to a pointer type. The result has
697 // type void."
698 // DR599 amends "pointer type" to "pointer to object type" in both cases.
699
Anders Carlsson44443f82009-08-16 20:29:29 +0000700 FunctionDecl *OperatorDelete = 0;
701
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000702 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000703 if (!Ex->isTypeDependent()) {
704 QualType Type = Ex->getType();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000705
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000706 if (Type->isRecordType()) {
707 // FIXME: Find that one conversion function and amend the type.
708 }
709
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000710 if (!Type->isPointerType())
711 return ExprError(Diag(StartLoc, diag::err_delete_operand)
712 << Type << Ex->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000713
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000714 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorcde3a2d2009-03-24 20:13:58 +0000715 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000716 return ExprError(Diag(StartLoc, diag::err_delete_operand)
717 << Type << Ex->getSourceRange());
Douglas Gregorcde3a2d2009-03-24 20:13:58 +0000718 else if (!Pointee->isDependentType() &&
719 RequireCompleteType(StartLoc, Pointee,
720 diag::warn_delete_incomplete,
721 Ex->getSourceRange()))
722 return ExprError();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000723
Anders Carlsson44443f82009-08-16 20:29:29 +0000724 // FIXME: This should be shared with the code for finding the delete
725 // operator in ActOnCXXNew.
726 IntegerLiteral Size(llvm::APInt::getNullValue(
727 Context.Target.getPointerWidth(0)),
728 Context.getSizeType(),
729 SourceLocation());
730 ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy),
731 CastExpr::CK_Unknown, &Size, false);
732 Expr *DeleteArg = &Cast;
733
734 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
735 ArrayForm ? OO_Array_Delete : OO_Delete);
736
737 if (Pointee->isRecordType() && !UseGlobal) {
738 CXXRecordDecl *Record
739 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
740 // FIXME: We fail to find inherited overloads.
741 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
742 &DeleteArg, 1, Record, /*AllowMissing=*/true,
743 OperatorDelete))
744 return ExprError();
745 }
746
747 if (!OperatorDelete) {
748 // Didn't find a member overload. Look for a global one.
749 DeclareGlobalNewDelete();
750 DeclContext *TUDecl = Context.getTranslationUnitDecl();
751 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
752 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false,
753 OperatorDelete))
754 return ExprError();
755 }
756
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000757 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000758 }
759
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000760 Operand.release();
761 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlsson44443f82009-08-16 20:29:29 +0000762 OperatorDelete, Ex, StartLoc));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000763}
764
765
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000766/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
767/// C++ if/switch/while/for statement.
768/// e.g: "if (int x = f()) {...}"
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000769Action::OwningExprResult
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000770Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
771 Declarator &D,
772 SourceLocation EqualLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000773 ExprArg AssignExprVal) {
774 assert(AssignExprVal.get() && "Null assignment expression");
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000775
776 // C++ 6.4p2:
777 // The declarator shall not specify a function or an array.
778 // The type-specifier-seq shall not contain typedef and shall not declare a
779 // new class or enumeration.
780
781 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
782 "Parser allowed 'typedef' as storage class of condition decl.");
783
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000784 // FIXME: Store DeclaratorInfo in the expression.
785 DeclaratorInfo *DInfo = 0;
Argiris Kirtzidis40688ad2009-08-11 05:20:41 +0000786 TagDecl *OwnedTag = 0;
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000787 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000788
789 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
790 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
791 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000792 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
793 << SourceRange(StartLoc, EqualLoc));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000794 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattner9d2cf082008-11-19 05:27:50 +0000795 Diag(StartLoc, diag::err_invalid_use_of_array_type)
796 << SourceRange(StartLoc, EqualLoc);
Argiris Kirtzidis40688ad2009-08-11 05:20:41 +0000797 } else if (OwnedTag && OwnedTag->isDefinition()) {
798 // The type-specifier-seq shall not declare a new class or enumeration.
799 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000800 }
801
Douglas Gregore153fcf2009-06-23 21:43:56 +0000802 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000803 if (!Dcl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000804 return ExprError();
Anders Carlssonf9f05b82009-05-30 21:37:25 +0000805 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000806
Douglas Gregor48840c72008-12-10 23:01:14 +0000807 // Mark this variable as one that is declared within a conditional.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000808 // We know that the decl had to be a VarDecl because that is the only type of
809 // decl that can be assigned and the grammar requires an '='.
810 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
811 VD->setDeclaredInCondition(true);
812 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000813}
814
815/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
816bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
817 // C++ 6.4p4:
818 // The value of a condition that is an initialized declaration in a statement
819 // other than a switch statement is the value of the declared variable
820 // implicitly converted to type bool. If that conversion is ill-formed, the
821 // program is ill-formed.
822 // The value of a condition that is an expression is the value of the
823 // expression, implicitly converted to bool.
824 //
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000825 return PerformContextuallyConvertToBool(CondExpr);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000826}
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000827
828/// Helper function to determine whether this is the (deprecated) C++
829/// conversion from a string literal to a pointer to non-const char or
830/// non-const wchar_t (for narrow and wide string literals,
831/// respectively).
832bool
833Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
834 // Look inside the implicit cast, if it exists.
835 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
836 From = Cast->getSubExpr();
837
838 // A string literal (2.13.4) that is not a wide string literal can
839 // be converted to an rvalue of type "pointer to char"; a wide
840 // string literal can be converted to an rvalue of type "pointer
841 // to wchar_t" (C++ 4.2p2).
842 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000843 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000844 if (const BuiltinType *ToPointeeType
845 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
846 // This conversion is considered only when there is an
847 // explicit appropriate pointer target type (C++ 4.2p2).
848 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
849 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
850 (!StrLit->isWide() &&
851 (ToPointeeType->getKind() == BuiltinType::Char_U ||
852 ToPointeeType->getKind() == BuiltinType::Char_S))))
853 return true;
854 }
855
856 return false;
857}
Douglas Gregorbb461502008-10-24 04:54:22 +0000858
859/// PerformImplicitConversion - Perform an implicit conversion of the
860/// expression From to the type ToType. Returns true if there was an
861/// error, false otherwise. The expression From is replaced with the
Douglas Gregor6fd35572008-12-19 17:40:08 +0000862/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000863/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redla55834a2009-04-12 17:16:29 +0000864/// explicit user-defined conversions are permitted. @p Elidable should be true
865/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
866/// resolution works differently in that case.
867bool
Douglas Gregor6fd35572008-12-19 17:40:08 +0000868Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +0000869 const char *Flavor, bool AllowExplicit,
870 bool Elidable)
Douglas Gregorbb461502008-10-24 04:54:22 +0000871{
Sebastian Redla55834a2009-04-12 17:16:29 +0000872 ImplicitConversionSequence ICS;
873 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
874 if (Elidable && getLangOptions().CPlusPlus0x) {
875 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
876 AllowExplicit, /*ForceRValue*/true);
877 }
878 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
879 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
880 }
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000881 return PerformImplicitConversion(From, ToType, ICS, Flavor);
882}
883
884/// PerformImplicitConversion - Perform an implicit conversion of the
885/// expression From to the type ToType using the pre-computed implicit
886/// conversion sequence ICS. Returns true if there was an error, false
887/// otherwise. The expression From is replaced with the converted
888/// expression. Flavor is the kind of conversion we're performing,
889/// used in the error message.
890bool
891Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
892 const ImplicitConversionSequence &ICS,
893 const char* Flavor) {
Douglas Gregorbb461502008-10-24 04:54:22 +0000894 switch (ICS.ConversionKind) {
895 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor6fd35572008-12-19 17:40:08 +0000896 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregorbb461502008-10-24 04:54:22 +0000897 return true;
898 break;
899
900 case ImplicitConversionSequence::UserDefinedConversion:
Mike Stumpe127ae32009-05-16 07:39:55 +0000901 // FIXME: This is, of course, wrong. We'll need to actually call the
902 // constructor or conversion operator, and then cope with the standard
903 // conversions.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000904 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +0000905 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +0000906 ToType->isLValueReferenceType());
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000907 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000908
909 case ImplicitConversionSequence::EllipsisConversion:
910 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000911 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000912
913 case ImplicitConversionSequence::BadConversion:
914 return true;
915 }
916
917 // Everything went well.
918 return false;
919}
920
921/// PerformImplicitConversion - Perform an implicit conversion of the
922/// expression From to the type ToType by following the standard
923/// conversion sequence SCS. Returns true if there was an error, false
924/// otherwise. The expression From is replaced with the converted
Douglas Gregor6fd35572008-12-19 17:40:08 +0000925/// expression. Flavor is the context in which we're performing this
926/// conversion, for use in error messages.
Douglas Gregorbb461502008-10-24 04:54:22 +0000927bool
928Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000929 const StandardConversionSequence& SCS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000930 const char *Flavor) {
Mike Stumpe127ae32009-05-16 07:39:55 +0000931 // Overall FIXME: we are recomputing too many types here and doing far too
932 // much extra work. What this means is that we need to keep track of more
933 // information that is computed when we try the implicit conversion initially,
934 // so that we don't need to recompute anything here.
Douglas Gregorbb461502008-10-24 04:54:22 +0000935 QualType FromType = From->getType();
936
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000937 if (SCS.CopyConstructor) {
Anders Carlsson0e098352009-05-19 04:45:15 +0000938 // FIXME: When can ToType be a reference type?
939 assert(!ToType->isReferenceType());
940
Anders Carlssonbd9f51a2009-08-16 05:13:48 +0000941 From = BuildCXXConstructExpr(ToType, SCS.CopyConstructor, &From, 1);
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000942 return false;
943 }
944
Douglas Gregorbb461502008-10-24 04:54:22 +0000945 // Perform the first implicit conversion.
946 switch (SCS.First) {
947 case ICK_Identity:
948 case ICK_Lvalue_To_Rvalue:
949 // Nothing to do.
950 break;
951
952 case ICK_Array_To_Pointer:
Douglas Gregoraa57e862009-02-18 21:56:37 +0000953 FromType = Context.getArrayDecayedType(FromType);
Anders Carlssond6e11722009-08-08 21:04:35 +0000954 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregoraa57e862009-02-18 21:56:37 +0000955 break;
956
957 case ICK_Function_To_Pointer:
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000958 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor45014fd2008-11-10 20:40:00 +0000959 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
960 if (!Fn)
961 return true;
962
Douglas Gregoraa57e862009-02-18 21:56:37 +0000963 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
964 return true;
965
Douglas Gregor45014fd2008-11-10 20:40:00 +0000966 FixOverloadedFunctionReference(From, Fn);
967 FromType = From->getType();
Douglas Gregor45014fd2008-11-10 20:40:00 +0000968 }
Douglas Gregorbb461502008-10-24 04:54:22 +0000969 FromType = Context.getPointerType(FromType);
970 ImpCastExprToType(From, FromType);
971 break;
972
973 default:
974 assert(false && "Improper first standard conversion");
975 break;
976 }
977
978 // Perform the second implicit conversion
979 switch (SCS.Second) {
980 case ICK_Identity:
981 // Nothing to do.
982 break;
983
984 case ICK_Integral_Promotion:
985 case ICK_Floating_Promotion:
Douglas Gregore819caf2009-02-12 00:15:05 +0000986 case ICK_Complex_Promotion:
Douglas Gregorbb461502008-10-24 04:54:22 +0000987 case ICK_Integral_Conversion:
988 case ICK_Floating_Conversion:
Douglas Gregore819caf2009-02-12 00:15:05 +0000989 case ICK_Complex_Conversion:
Douglas Gregorbb461502008-10-24 04:54:22 +0000990 case ICK_Floating_Integral:
Douglas Gregore819caf2009-02-12 00:15:05 +0000991 case ICK_Complex_Real:
Douglas Gregorfcb19192009-02-11 23:02:49 +0000992 case ICK_Compatible_Conversion:
993 // FIXME: Go deeper to get the unqualified type!
Douglas Gregorbb461502008-10-24 04:54:22 +0000994 FromType = ToType.getUnqualifiedType();
995 ImpCastExprToType(From, FromType);
996 break;
997
998 case ICK_Pointer_Conversion:
Douglas Gregor6fd35572008-12-19 17:40:08 +0000999 if (SCS.IncompatibleObjC) {
1000 // Diagnose incompatible Objective-C conversions
1001 Diag(From->getSourceRange().getBegin(),
1002 diag::ext_typecheck_convert_incompatible_pointer)
1003 << From->getType() << ToType << Flavor
1004 << From->getSourceRange();
1005 }
1006
Douglas Gregorbb461502008-10-24 04:54:22 +00001007 if (CheckPointerConversion(From, ToType))
1008 return true;
1009 ImpCastExprToType(From, ToType);
1010 break;
1011
1012 case ICK_Pointer_Member:
Sebastian Redlba387562009-01-25 19:43:20 +00001013 if (CheckMemberPointerConversion(From, ToType))
1014 return true;
1015 ImpCastExprToType(From, ToType);
Douglas Gregorbb461502008-10-24 04:54:22 +00001016 break;
1017
1018 case ICK_Boolean_Conversion:
1019 FromType = Context.BoolTy;
1020 ImpCastExprToType(From, FromType);
1021 break;
1022
1023 default:
1024 assert(false && "Improper second standard conversion");
1025 break;
1026 }
1027
1028 switch (SCS.Third) {
1029 case ICK_Identity:
1030 // Nothing to do.
1031 break;
1032
1033 case ICK_Qualification:
Mike Stumpe127ae32009-05-16 07:39:55 +00001034 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1035 // references.
Douglas Gregor5ac8ffa2009-01-16 19:38:23 +00001036 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +00001037 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +00001038 ToType->isLValueReferenceType());
Douglas Gregorbb461502008-10-24 04:54:22 +00001039 break;
1040
1041 default:
1042 assert(false && "Improper second standard conversion");
1043 break;
1044 }
1045
1046 return false;
1047}
1048
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001049Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1050 SourceLocation KWLoc,
1051 SourceLocation LParen,
1052 TypeTy *Ty,
1053 SourceLocation RParen) {
Anders Carlsson1b749a02009-07-07 19:06:02 +00001054 QualType T = QualType::getFromOpaquePtr(Ty);
1055
1056 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1057 // all traits except __is_class, __is_enum and __is_union require a the type
1058 // to be complete.
1059 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1060 if (RequireCompleteType(KWLoc, T,
1061 diag::err_incomplete_type_used_in_type_trait_expr,
1062 SourceRange(), SourceRange(), T))
1063 return ExprError();
1064 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001065
1066 // There is no point in eagerly computing the value. The traits are designed
1067 // to be used from type trait templates, so Ty will be a template parameter
1068 // 99% of the time.
Anders Carlsson1b749a02009-07-07 19:06:02 +00001069 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1070 RParen, Context.BoolTy));
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001071}
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001072
1073QualType Sema::CheckPointerToMemberOperands(
1074 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
1075{
1076 const char *OpSpelling = isIndirect ? "->*" : ".*";
1077 // C++ 5.5p2
1078 // The binary operator .* [p3: ->*] binds its second operand, which shall
1079 // be of type "pointer to member of T" (where T is a completely-defined
1080 // class type) [...]
1081 QualType RType = rex->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001082 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregor05e28f62009-03-24 19:52:54 +00001083 if (!MemPtr) {
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001084 Diag(Loc, diag::err_bad_memptr_rhs)
1085 << OpSpelling << RType << rex->getSourceRange();
1086 return QualType();
Douglas Gregor96b6df92009-05-14 00:28:11 +00001087 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00001088
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001089 QualType Class(MemPtr->getClass(), 0);
1090
1091 // C++ 5.5p2
1092 // [...] to its first operand, which shall be of class T or of a class of
1093 // which T is an unambiguous and accessible base class. [p3: a pointer to
1094 // such a class]
1095 QualType LType = lex->getType();
1096 if (isIndirect) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001097 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001098 LType = Ptr->getPointeeType().getNonReferenceType();
1099 else {
1100 Diag(Loc, diag::err_bad_memptr_lhs)
1101 << OpSpelling << 1 << LType << lex->getSourceRange();
1102 return QualType();
1103 }
1104 }
1105
1106 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1107 Context.getCanonicalType(LType).getUnqualifiedType()) {
1108 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1109 /*DetectVirtual=*/false);
Mike Stumpe127ae32009-05-16 07:39:55 +00001110 // FIXME: Would it be useful to print full ambiguity paths, or is that
1111 // overkill?
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001112 if (!IsDerivedFrom(LType, Class, Paths) ||
1113 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1114 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1115 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1116 return QualType();
1117 }
1118 }
1119
1120 // C++ 5.5p2
1121 // The result is an object or a function of the type specified by the
1122 // second operand.
1123 // The cv qualifiers are the union of those in the pointer and the left side,
1124 // in accordance with 5.5p5 and 5.2.5.
1125 // FIXME: This returns a dereferenced member function pointer as a normal
1126 // function type. However, the only operation valid on such functions is
Mike Stumpe127ae32009-05-16 07:39:55 +00001127 // calling them. There's also a GCC extension to get a function pointer to the
1128 // thing, which is another complication, because this type - unlike the type
1129 // that is the result of this expression - takes the class as the first
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001130 // argument.
1131 // We probably need a "MemberFunctionClosureType" or something like that.
1132 QualType Result = MemPtr->getPointeeType();
1133 if (LType.isConstQualified())
1134 Result.addConst();
1135 if (LType.isVolatileQualified())
1136 Result.addVolatile();
1137 return Result;
1138}
Sebastian Redlbd261962009-04-16 17:51:27 +00001139
1140/// \brief Get the target type of a standard or user-defined conversion.
1141static QualType TargetType(const ImplicitConversionSequence &ICS) {
1142 assert((ICS.ConversionKind ==
1143 ImplicitConversionSequence::StandardConversion ||
1144 ICS.ConversionKind ==
1145 ImplicitConversionSequence::UserDefinedConversion) &&
1146 "function only valid for standard or user-defined conversions");
1147 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1148 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1149 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1150}
1151
1152/// \brief Try to convert a type to another according to C++0x 5.16p3.
1153///
1154/// This is part of the parameter validation for the ? operator. If either
1155/// value operand is a class type, the two operands are attempted to be
1156/// converted to each other. This function does the conversion in one direction.
1157/// It emits a diagnostic and returns true only if it finds an ambiguous
1158/// conversion.
1159static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1160 SourceLocation QuestionLoc,
1161 ImplicitConversionSequence &ICS)
1162{
1163 // C++0x 5.16p3
1164 // The process for determining whether an operand expression E1 of type T1
1165 // can be converted to match an operand expression E2 of type T2 is defined
1166 // as follows:
1167 // -- If E2 is an lvalue:
1168 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1169 // E1 can be converted to match E2 if E1 can be implicitly converted to
1170 // type "lvalue reference to T2", subject to the constraint that in the
1171 // conversion the reference must bind directly to E1.
1172 if (!Self.CheckReferenceInit(From,
1173 Self.Context.getLValueReferenceType(To->getType()),
1174 &ICS))
1175 {
1176 assert((ICS.ConversionKind ==
1177 ImplicitConversionSequence::StandardConversion ||
1178 ICS.ConversionKind ==
1179 ImplicitConversionSequence::UserDefinedConversion) &&
1180 "expected a definite conversion");
1181 bool DirectBinding =
1182 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1183 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1184 if (DirectBinding)
1185 return false;
1186 }
1187 }
1188 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1189 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1190 // -- if E1 and E2 have class type, and the underlying class types are
1191 // the same or one is a base class of the other:
1192 QualType FTy = From->getType();
1193 QualType TTy = To->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001194 const RecordType *FRec = FTy->getAs<RecordType>();
1195 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redlbd261962009-04-16 17:51:27 +00001196 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1197 if (FRec && TRec && (FRec == TRec ||
1198 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1199 // E1 can be converted to match E2 if the class of T2 is the
1200 // same type as, or a base class of, the class of T1, and
1201 // [cv2 > cv1].
1202 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1203 // Could still fail if there's no copy constructor.
1204 // FIXME: Is this a hard error then, or just a conversion failure? The
1205 // standard doesn't say.
1206 ICS = Self.TryCopyInitialization(From, TTy);
1207 }
1208 } else {
1209 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1210 // implicitly converted to the type that expression E2 would have
1211 // if E2 were converted to an rvalue.
1212 // First find the decayed type.
1213 if (TTy->isFunctionType())
1214 TTy = Self.Context.getPointerType(TTy);
1215 else if(TTy->isArrayType())
1216 TTy = Self.Context.getArrayDecayedType(TTy);
1217
1218 // Now try the implicit conversion.
1219 // FIXME: This doesn't detect ambiguities.
1220 ICS = Self.TryImplicitConversion(From, TTy);
1221 }
1222 return false;
1223}
1224
1225/// \brief Try to find a common type for two according to C++0x 5.16p5.
1226///
1227/// This is part of the parameter validation for the ? operator. If either
1228/// value operand is a class type, overload resolution is used to find a
1229/// conversion to a common type.
1230static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1231 SourceLocation Loc) {
1232 Expr *Args[2] = { LHS, RHS };
1233 OverloadCandidateSet CandidateSet;
1234 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1235
1236 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001237 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00001238 case Sema::OR_Success:
1239 // We found a match. Perform the conversions on the arguments and move on.
1240 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1241 Best->Conversions[0], "converting") ||
1242 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1243 Best->Conversions[1], "converting"))
1244 break;
1245 return false;
1246
1247 case Sema::OR_No_Viable_Function:
1248 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1249 << LHS->getType() << RHS->getType()
1250 << LHS->getSourceRange() << RHS->getSourceRange();
1251 return true;
1252
1253 case Sema::OR_Ambiguous:
1254 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1255 << LHS->getType() << RHS->getType()
1256 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpe127ae32009-05-16 07:39:55 +00001257 // FIXME: Print the possible common types by printing the return types of
1258 // the viable candidates.
Sebastian Redlbd261962009-04-16 17:51:27 +00001259 break;
1260
1261 case Sema::OR_Deleted:
1262 assert(false && "Conditional operator has only built-in overloads");
1263 break;
1264 }
1265 return true;
1266}
1267
Sebastian Redld3169132009-04-17 16:30:52 +00001268/// \brief Perform an "extended" implicit conversion as returned by
1269/// TryClassUnification.
1270///
1271/// TryClassUnification generates ICSs that include reference bindings.
1272/// PerformImplicitConversion is not suitable for this; it chokes if the
1273/// second part of a standard conversion is ICK_DerivedToBase. This function
1274/// handles the reference binding specially.
1275static bool ConvertForConditional(Sema &Self, Expr *&E,
1276 const ImplicitConversionSequence &ICS)
1277{
1278 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1279 ICS.Standard.ReferenceBinding) {
1280 assert(ICS.Standard.DirectBinding &&
1281 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf6b86182009-04-26 11:21:02 +00001282 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1283 // redoing all the work.
1284 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1285 TargetType(ICS)));
Sebastian Redld3169132009-04-17 16:30:52 +00001286 }
1287 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1288 ICS.UserDefined.After.ReferenceBinding) {
1289 assert(ICS.UserDefined.After.DirectBinding &&
1290 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf6b86182009-04-26 11:21:02 +00001291 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1292 TargetType(ICS)));
Sebastian Redld3169132009-04-17 16:30:52 +00001293 }
1294 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1295 return true;
1296 return false;
1297}
1298
Sebastian Redlbd261962009-04-16 17:51:27 +00001299/// \brief Check the operands of ?: under C++ semantics.
1300///
1301/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1302/// extension. In this case, LHS == Cond. (But they're not aliases.)
1303QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1304 SourceLocation QuestionLoc) {
Mike Stumpe127ae32009-05-16 07:39:55 +00001305 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1306 // interface pointers.
Sebastian Redlbd261962009-04-16 17:51:27 +00001307
1308 // C++0x 5.16p1
1309 // The first expression is contextually converted to bool.
1310 if (!Cond->isTypeDependent()) {
1311 if (CheckCXXBooleanCondition(Cond))
1312 return QualType();
1313 }
1314
1315 // Either of the arguments dependent?
1316 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1317 return Context.DependentTy;
1318
1319 // C++0x 5.16p2
1320 // If either the second or the third operand has type (cv) void, ...
1321 QualType LTy = LHS->getType();
1322 QualType RTy = RHS->getType();
1323 bool LVoid = LTy->isVoidType();
1324 bool RVoid = RTy->isVoidType();
1325 if (LVoid || RVoid) {
1326 // ... then the [l2r] conversions are performed on the second and third
1327 // operands ...
1328 DefaultFunctionArrayConversion(LHS);
1329 DefaultFunctionArrayConversion(RHS);
1330 LTy = LHS->getType();
1331 RTy = RHS->getType();
1332
1333 // ... and one of the following shall hold:
1334 // -- The second or the third operand (but not both) is a throw-
1335 // expression; the result is of the type of the other and is an rvalue.
1336 bool LThrow = isa<CXXThrowExpr>(LHS);
1337 bool RThrow = isa<CXXThrowExpr>(RHS);
1338 if (LThrow && !RThrow)
1339 return RTy;
1340 if (RThrow && !LThrow)
1341 return LTy;
1342
1343 // -- Both the second and third operands have type void; the result is of
1344 // type void and is an rvalue.
1345 if (LVoid && RVoid)
1346 return Context.VoidTy;
1347
1348 // Neither holds, error.
1349 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1350 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1351 << LHS->getSourceRange() << RHS->getSourceRange();
1352 return QualType();
1353 }
1354
1355 // Neither is void.
1356
1357 // C++0x 5.16p3
1358 // Otherwise, if the second and third operand have different types, and
1359 // either has (cv) class type, and attempt is made to convert each of those
1360 // operands to the other.
1361 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1362 (LTy->isRecordType() || RTy->isRecordType())) {
1363 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1364 // These return true if a single direction is already ambiguous.
1365 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1366 return QualType();
1367 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1368 return QualType();
1369
1370 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1371 ImplicitConversionSequence::BadConversion;
1372 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1373 ImplicitConversionSequence::BadConversion;
1374 // If both can be converted, [...] the program is ill-formed.
1375 if (HaveL2R && HaveR2L) {
1376 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1377 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1378 return QualType();
1379 }
1380
1381 // If exactly one conversion is possible, that conversion is applied to
1382 // the chosen operand and the converted operands are used in place of the
1383 // original operands for the remainder of this section.
1384 if (HaveL2R) {
Sebastian Redld3169132009-04-17 16:30:52 +00001385 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redlbd261962009-04-16 17:51:27 +00001386 return QualType();
1387 LTy = LHS->getType();
1388 } else if (HaveR2L) {
Sebastian Redld3169132009-04-17 16:30:52 +00001389 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redlbd261962009-04-16 17:51:27 +00001390 return QualType();
1391 RTy = RHS->getType();
1392 }
1393 }
1394
1395 // C++0x 5.16p4
1396 // If the second and third operands are lvalues and have the same type,
1397 // the result is of that type [...]
1398 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1399 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1400 RHS->isLvalue(Context) == Expr::LV_Valid)
1401 return LTy;
1402
1403 // C++0x 5.16p5
1404 // Otherwise, the result is an rvalue. If the second and third operands
1405 // do not have the same type, and either has (cv) class type, ...
1406 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1407 // ... overload resolution is used to determine the conversions (if any)
1408 // to be applied to the operands. If the overload resolution fails, the
1409 // program is ill-formed.
1410 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1411 return QualType();
1412 }
1413
1414 // C++0x 5.16p6
1415 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1416 // conversions are performed on the second and third operands.
1417 DefaultFunctionArrayConversion(LHS);
1418 DefaultFunctionArrayConversion(RHS);
1419 LTy = LHS->getType();
1420 RTy = RHS->getType();
1421
1422 // After those conversions, one of the following shall hold:
1423 // -- The second and third operands have the same type; the result
1424 // is of that type.
1425 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1426 return LTy;
1427
1428 // -- The second and third operands have arithmetic or enumeration type;
1429 // the usual arithmetic conversions are performed to bring them to a
1430 // common type, and the result is of that type.
1431 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1432 UsualArithmeticConversions(LHS, RHS);
1433 return LHS->getType();
1434 }
1435
1436 // -- The second and third operands have pointer type, or one has pointer
1437 // type and the other is a null pointer constant; pointer conversions
1438 // and qualification conversions are performed to bring them to their
1439 // composite pointer type. The result is of the composite pointer type.
Sebastian Redl42b81a22009-04-19 19:26:31 +00001440 QualType Composite = FindCompositePointerType(LHS, RHS);
1441 if (!Composite.isNull())
1442 return Composite;
Sebastian Redlbd261962009-04-16 17:51:27 +00001443
Sebastian Redl5b3fcf82009-04-19 21:15:26 +00001444 // Fourth bullet is same for pointers-to-member. However, the possible
1445 // conversions are far more limited: we have null-to-pointer, upcast of
1446 // containing class, and second-level cv-ness.
1447 // cv-ness is not a union, but must match one of the two operands. (Which,
1448 // frankly, is stupid.)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001449 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1450 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Sebastian Redl5b3fcf82009-04-19 21:15:26 +00001451 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1452 ImpCastExprToType(RHS, LTy);
1453 return LTy;
1454 }
1455 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1456 ImpCastExprToType(LHS, RTy);
1457 return RTy;
1458 }
1459 if (LMemPtr && RMemPtr) {
1460 QualType LPointee = LMemPtr->getPointeeType();
1461 QualType RPointee = RMemPtr->getPointeeType();
1462 // First, we check that the unqualified pointee type is the same. If it's
1463 // not, there's no conversion that will unify the two pointers.
1464 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1465 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1466 // Second, we take the greater of the two cv qualifications. If neither
1467 // is greater than the other, the conversion is not possible.
1468 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1469 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1470 // Third, we check if either of the container classes is derived from
1471 // the other.
1472 QualType LContainer(LMemPtr->getClass(), 0);
1473 QualType RContainer(RMemPtr->getClass(), 0);
1474 QualType MoreDerived;
1475 if (Context.getCanonicalType(LContainer) ==
1476 Context.getCanonicalType(RContainer))
1477 MoreDerived = LContainer;
1478 else if (IsDerivedFrom(LContainer, RContainer))
1479 MoreDerived = LContainer;
1480 else if (IsDerivedFrom(RContainer, LContainer))
1481 MoreDerived = RContainer;
1482
1483 if (!MoreDerived.isNull()) {
1484 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1485 // We don't use ImpCastExprToType here because this could still fail
1486 // for ambiguous or inaccessible conversions.
1487 QualType Common = Context.getMemberPointerType(
1488 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1489 if (PerformImplicitConversion(LHS, Common, "converting"))
1490 return QualType();
1491 if (PerformImplicitConversion(RHS, Common, "converting"))
1492 return QualType();
1493 return Common;
1494 }
1495 }
1496 }
1497 }
1498
Sebastian Redlbd261962009-04-16 17:51:27 +00001499 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1500 << LHS->getType() << RHS->getType()
1501 << LHS->getSourceRange() << RHS->getSourceRange();
1502 return QualType();
1503}
Sebastian Redl42b81a22009-04-19 19:26:31 +00001504
1505/// \brief Find a merged pointer type and convert the two expressions to it.
1506///
1507/// This finds the composite pointer type for @p E1 and @p E2 according to
1508/// C++0x 5.9p2. It converts both expressions to this type and returns it.
1509/// It does not emit diagnostics.
1510QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1511 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1512 QualType T1 = E1->getType(), T2 = E2->getType();
Steve Naroff79ae19a2009-07-14 18:25:06 +00001513 if(!T1->isAnyPointerType() && !T2->isAnyPointerType())
Sebastian Redl42b81a22009-04-19 19:26:31 +00001514 return QualType();
1515
1516 // C++0x 5.9p2
1517 // Pointer conversions and qualification conversions are performed on
1518 // pointer operands to bring them to their composite pointer type. If
1519 // one operand is a null pointer constant, the composite pointer type is
1520 // the type of the other operand.
1521 if (E1->isNullPointerConstant(Context)) {
1522 ImpCastExprToType(E1, T2);
1523 return T2;
1524 }
1525 if (E2->isNullPointerConstant(Context)) {
1526 ImpCastExprToType(E2, T1);
1527 return T1;
1528 }
1529 // Now both have to be pointers.
1530 if(!T1->isPointerType() || !T2->isPointerType())
1531 return QualType();
1532
1533 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1534 // the other has type "pointer to cv2 T" and the composite pointer type is
1535 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1536 // Otherwise, the composite pointer type is a pointer type similar to the
1537 // type of one of the operands, with a cv-qualification signature that is
1538 // the union of the cv-qualification signatures of the operand types.
1539 // In practice, the first part here is redundant; it's subsumed by the second.
1540 // What we do here is, we build the two possible composite types, and try the
1541 // conversions in both directions. If only one works, or if the two composite
1542 // types are the same, we have succeeded.
1543 llvm::SmallVector<unsigned, 4> QualifierUnion;
1544 QualType Composite1 = T1, Composite2 = T2;
1545 const PointerType *Ptr1, *Ptr2;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001546 while ((Ptr1 = Composite1->getAs<PointerType>()) &&
1547 (Ptr2 = Composite2->getAs<PointerType>())) {
Sebastian Redl42b81a22009-04-19 19:26:31 +00001548 Composite1 = Ptr1->getPointeeType();
1549 Composite2 = Ptr2->getPointeeType();
1550 QualifierUnion.push_back(
1551 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1552 }
1553 // Rewrap the composites as pointers with the union CVRs.
1554 for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(),
1555 E = QualifierUnion.end(); I != E; ++I) {
1556 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1557 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1558 }
1559
1560 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1561 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1562 ImplicitConversionSequence E1ToC2, E2ToC2;
1563 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1564 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1565 if (Context.getCanonicalType(Composite1) !=
1566 Context.getCanonicalType(Composite2)) {
1567 E1ToC2 = TryImplicitConversion(E1, Composite2);
1568 E2ToC2 = TryImplicitConversion(E2, Composite2);
1569 }
1570
1571 bool ToC1Viable = E1ToC1.ConversionKind !=
1572 ImplicitConversionSequence::BadConversion
1573 && E2ToC1.ConversionKind !=
1574 ImplicitConversionSequence::BadConversion;
1575 bool ToC2Viable = E1ToC2.ConversionKind !=
1576 ImplicitConversionSequence::BadConversion
1577 && E2ToC2.ConversionKind !=
1578 ImplicitConversionSequence::BadConversion;
1579 if (ToC1Viable && !ToC2Viable) {
1580 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1581 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1582 return Composite1;
1583 }
1584 if (ToC2Viable && !ToC1Viable) {
1585 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1586 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1587 return Composite2;
1588 }
1589 return QualType();
1590}
Anders Carlssonf0967d72009-05-17 18:41:29 +00001591
Anders Carlssona05fa102009-05-30 20:36:53 +00001592Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson1bfe1c42009-08-15 23:41:35 +00001593 if (!Context.getLangOptions().CPlusPlus)
1594 return Owned(E);
1595
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001596 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssona05fa102009-05-30 20:36:53 +00001597 if (!RT)
1598 return Owned(E);
1599
1600 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1601 if (RD->hasTrivialDestructor())
1602 return Owned(E);
1603
1604 CXXTemporary *Temp = CXXTemporary::Create(Context,
1605 RD->getDestructor(Context));
Anders Carlsson1ef0ee92009-05-30 21:21:49 +00001606 ExprTemporaries.push_back(Temp);
Fariborz Jahaniancd208112009-08-03 19:13:25 +00001607 if (CXXDestructorDecl *Destructor =
1608 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1609 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssona05fa102009-05-30 20:36:53 +00001610 // FIXME: Add the temporary to the temporaries vector.
1611 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1612}
1613
Anders Carlsson8f75fbc2009-06-05 15:38:08 +00001614Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00001615 bool ShouldDestroyTemps) {
Anders Carlsson8f75fbc2009-06-05 15:38:08 +00001616 assert(SubExpr && "sub expression can't be null!");
1617
1618 if (ExprTemporaries.empty())
1619 return SubExpr;
1620
1621 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1622 &ExprTemporaries[0],
1623 ExprTemporaries.size(),
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00001624 ShouldDestroyTemps);
Anders Carlsson8f75fbc2009-06-05 15:38:08 +00001625 ExprTemporaries.clear();
1626
1627 return E;
1628}
1629
Anders Carlssonf0967d72009-05-17 18:41:29 +00001630Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1631 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson8f75fbc2009-06-05 15:38:08 +00001632 if (FullExpr)
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00001633 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
1634 /*ShouldDestroyTemps=*/true);
Anders Carlssonf0967d72009-05-17 18:41:29 +00001635
1636 return Owned(FullExpr);
1637}