blob: cf52bae86ca5db332f35c8440923a7cc686d9b68 [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) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +000034 //FIXME: Preserve type source info.
35 QualType ConvType = GetTypeFromParser(Ty);
Douglas Gregorcfe6ae52009-08-05 05:36:45 +000036 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
Douglas Gregorb0212bd2008-11-17 20:34:05 +000037 DeclarationName ConvName
38 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd883f72009-01-18 18:53:16 +000039 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +000040 &SS, isAddressOfOperand);
Douglas Gregorb0212bd2008-11-17 20:34:05 +000041}
Sebastian Redlb93b49c2008-11-11 11:37:55 +000042
Douglas Gregor24094772008-11-19 19:09:45 +000043/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregor96a32dd2008-11-18 14:39:36 +000044/// name (e.g., @c operator+ ) as an expression. This is very
45/// similar to ActOnIdentifierExpr, except that instead of providing
46/// an identifier the parser provides the kind of overloaded
47/// operator that was parsed.
Sebastian Redlcd883f72009-01-18 18:53:16 +000048Sema::OwningExprResult
Douglas Gregor24094772008-11-19 19:09:45 +000049Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
50 OverloadedOperatorKind Op,
51 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +000052 const CXXScopeSpec &SS,
53 bool isAddressOfOperand) {
Douglas Gregor96a32dd2008-11-18 14:39:36 +000054 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redl0c9da212009-02-03 20:19:35 +000055 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +000056 isAddressOfOperand);
Douglas Gregor96a32dd2008-11-18 14:39:36 +000057}
58
Sebastian Redlb93b49c2008-11-11 11:37:55 +000059/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000060Action::OwningExprResult
Sebastian Redlb93b49c2008-11-11 11:37:55 +000061Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
62 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor52ae30c2009-01-30 01:04:22 +000063 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattnerc2a5f512008-11-20 05:51:55 +000064 if (!StdNs)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000065 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +000066
67 if (isType)
68 // FIXME: Preserve type source info.
69 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
70
Chris Lattnerc2a5f512008-11-20 05:51:55 +000071 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor52ae30c2009-01-30 01:04:22 +000072 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlb93b49c2008-11-11 11:37:55 +000073 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattnerc2a5f512008-11-20 05:51:55 +000074 if (!TypeInfoRecordDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000075 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlb93b49c2008-11-11 11:37:55 +000076
77 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
78
Douglas Gregora8b2fbf2009-06-22 20:57:11 +000079 if (!isType) {
80 // C++0x [expr.typeid]p3:
81 // When typeid is applied to an expression other than an lvalue of a
82 // polymorphic class type [...] [the] expression is an unevaluated
83 // operand.
84
85 // FIXME: if the type of the expression is a class type, the class
86 // shall be completely defined.
87 bool isUnevaluatedOperand = true;
88 Expr *E = static_cast<Expr *>(TyOrExpr);
89 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
90 QualType T = E->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +000091 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregora8b2fbf2009-06-22 20:57:11 +000092 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
93 if (RecordD->isPolymorphic())
94 isUnevaluatedOperand = false;
95 }
96 }
97
98 // If this is an unevaluated operand, clear out the set of declaration
99 // references we have been computing.
100 if (isUnevaluatedOperand)
101 PotentiallyReferencedDeclStack.back().clear();
102 }
103
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000104 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
105 TypeInfoType.withConst(),
106 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000107}
108
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000109/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000110Action::OwningExprResult
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000111Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregorf8e92702008-10-24 15:36:09 +0000112 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Chris Lattner4b009652007-07-25 00:24:17 +0000113 "Unknown C++ Boolean value!");
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000114 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
115 Context.BoolTy, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000116}
Chris Lattnera7447ba2008-02-26 00:51:44 +0000117
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000118/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
119Action::OwningExprResult
120Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
121 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
122}
123
Chris Lattnera7447ba2008-02-26 00:51:44 +0000124/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000125Action::OwningExprResult
126Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl9949a5e2009-04-27 20:27:31 +0000127 Expr *Ex = E.takeAs<Expr>();
128 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
129 return ExprError();
130 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
131}
132
133/// CheckCXXThrowOperand - Validate the operand of a throw.
134bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
135 // C++ [except.throw]p3:
136 // [...] adjusting the type from "array of T" or "function returning T"
137 // to "pointer to T" or "pointer to function returning T", [...]
138 DefaultFunctionArrayConversion(E);
139
140 // If the type of the exception would be an incomplete type or a pointer
141 // to an incomplete type other than (cv) void the program is ill-formed.
142 QualType Ty = E->getType();
143 int isPointer = 0;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000144 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl9949a5e2009-04-27 20:27:31 +0000145 Ty = Ptr->getPointeeType();
146 isPointer = 1;
147 }
148 if (!isPointer || !Ty->isVoidType()) {
149 if (RequireCompleteType(ThrowLoc, Ty,
150 isPointer ? diag::err_throw_incomplete_ptr
151 : diag::err_throw_incomplete,
152 E->getSourceRange(), SourceRange(), QualType()))
153 return true;
154 }
155
156 // FIXME: Construct a temporary here.
157 return false;
Chris Lattnera7447ba2008-02-26 00:51:44 +0000158}
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000159
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000160Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000161 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
162 /// is a non-lvalue expression whose value is the address of the object for
163 /// which the function is called.
164
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000165 if (!isa<FunctionDecl>(CurContext))
166 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000167
168 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
169 if (MD->isInstance())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000170 return Owned(new (Context) CXXThisExpr(ThisLoc,
171 MD->getThisType(Context)));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000172
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000173 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000174}
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000175
176/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
177/// Can be interpreted either as function-style casting ("int(x)")
178/// or class type construction ("ClassType(x,y,z)")
179/// or creation of a value-initialized type ("int()").
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000180Action::OwningExprResult
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000181Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
182 SourceLocation LParenLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000183 MultiExprArg exprs,
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000184 SourceLocation *CommaLocs,
185 SourceLocation RParenLoc) {
186 assert(TypeRep && "Missing type!");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000187 // FIXME: Preserve type source info.
188 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000189 unsigned NumExprs = exprs.size();
190 Expr **Exprs = (Expr**)exprs.get();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000191 SourceLocation TyBeginLoc = TypeRange.getBegin();
192 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
193
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000194 if (Ty->isDependentType() ||
Douglas Gregor396f1142009-03-13 21:01:28 +0000195 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000196 exprs.release();
Anders Carlssonebbd7cd2009-04-24 05:23:13 +0000197
Douglas Gregorf27b7652009-05-20 18:46:25 +0000198 return Owned(CXXUnresolvedConstructExpr::Create(Context,
199 TypeRange.getBegin(), Ty,
200 LParenLoc,
201 Exprs, NumExprs,
202 RParenLoc));
Douglas Gregor396f1142009-03-13 21:01:28 +0000203 }
204
205
Douglas Gregor861e7902009-01-16 18:33:17 +0000206 // C++ [expr.type.conv]p1:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000207 // If the expression list is a single expression, the type conversion
208 // expression is equivalent (in definedness, and if defined in meaning) to the
209 // corresponding cast expression.
210 //
211 if (NumExprs == 1) {
Anders Carlsson9583fa72009-08-07 22:21:05 +0000212 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +0000213 CXXMethodDecl *ConversionDecl = 0;
214 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, ConversionDecl,
215 /*functional-style*/true))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000216 return ExprError();
217 exprs.release();
218 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +0000219 Ty, TyBeginLoc, Kind,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +0000220 Exprs[0], ConversionDecl,
221 RParenLoc));
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000222 }
223
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000224 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor861e7902009-01-16 18:33:17 +0000225 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000226
Anders Carlssonf0967d72009-05-17 18:41:29 +0000227 // FIXME: We should always create a CXXTemporaryObjectExpr here unless
228 // both the ctor and dtor are trivial.
Douglas Gregor861e7902009-01-16 18:33:17 +0000229 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
230 CXXConstructorDecl *Constructor
231 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
232 TypeRange.getBegin(),
233 SourceRange(TypeRange.getBegin(),
234 RParenLoc),
235 DeclarationName(),
236 IK_Direct);
Douglas Gregor861e7902009-01-16 18:33:17 +0000237
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000238 if (!Constructor)
239 return ExprError();
240
241 exprs.release();
Anders Carlsson7b7b2552009-05-30 20:56:46 +0000242 Expr *E = new (Context) CXXTemporaryObjectExpr(Context, Constructor,
Anders Carlssona05fa102009-05-30 20:36:53 +0000243 Ty, TyBeginLoc, Exprs,
244 NumExprs, RParenLoc);
245 return MaybeBindToTemporary(E);
Douglas Gregor861e7902009-01-16 18:33:17 +0000246 }
247
248 // Fall through to value-initialize an object of class type that
249 // doesn't have a user-declared default constructor.
250 }
251
252 // C++ [expr.type.conv]p1:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000253 // If the expression list specifies more than a single value, the type shall
254 // be a class with a suitably declared constructor.
255 //
256 if (NumExprs > 1)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000257 return ExprError(Diag(CommaLocs[0],
258 diag::err_builtin_func_cast_more_than_one_arg)
259 << FullRange);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000260
261 assert(NumExprs == 0 && "Expected 0 expressions");
262
Douglas Gregor861e7902009-01-16 18:33:17 +0000263 // C++ [expr.type.conv]p2:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000264 // The expression T(), where T is a simple-type-specifier for a non-array
265 // complete object type or the (possibly cv-qualified) void type, creates an
266 // rvalue of the specified type, which is value-initialized.
267 //
268 if (Ty->isArrayType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000269 return ExprError(Diag(TyBeginLoc,
270 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000271 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000272 RequireCompleteType(TyBeginLoc, Ty,
273 diag::err_invalid_incomplete_type_use, FullRange))
274 return ExprError();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000275
Anders Carlsson412c3402009-03-24 01:19:16 +0000276 if (RequireNonAbstractType(TyBeginLoc, Ty,
277 diag::err_allocation_of_abstract_type))
Anders Carlssonc263c9b2009-03-23 19:10:31 +0000278 return ExprError();
279
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000280 exprs.release();
281 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000282}
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000283
284
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000285/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
286/// @code new (memory) int[size][4] @endcode
287/// or
288/// @code ::new Foo(23, "hello") @endcode
289/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000290Action::OwningExprResult
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000291Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000292 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000293 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000294 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000295 MultiExprArg ConstructorArgs,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000296 SourceLocation ConstructorRParen)
297{
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000298 Expr *ArraySize = 0;
299 unsigned Skip = 0;
300 // If the specified type is an array, unwrap it and save the expression.
301 if (D.getNumTypeObjects() > 0 &&
302 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
303 DeclaratorChunk &Chunk = D.getTypeObject(0);
304 if (Chunk.Arr.hasStatic)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000305 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
306 << D.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000307 if (!Chunk.Arr.NumElts)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000308 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
309 << D.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000310 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
311 Skip = 1;
312 }
313
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000314 //FIXME: Store DeclaratorInfo in CXXNew expression.
315 DeclaratorInfo *DInfo = 0;
316 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
Chris Lattner34c61332009-04-25 08:06:05 +0000317 if (D.isInvalidType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000318 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000319
Douglas Gregord8c23702009-05-21 00:00:09 +0000320 // Every dimension shall be of constant size.
321 unsigned i = 1;
322 QualType ElementType = AllocType;
323 while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
324 if (!Array->isConstantArrayType()) {
325 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
326 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
327 return ExprError();
328 }
329 ElementType = Array->getElementType();
330 ++i;
331 }
332
333 return BuildCXXNew(StartLoc, UseGlobal,
334 PlacementLParen,
335 move(PlacementArgs),
336 PlacementRParen,
337 ParenTypeId,
338 AllocType,
339 D.getSourceRange().getBegin(),
340 D.getSourceRange(),
341 Owned(ArraySize),
342 ConstructorLParen,
343 move(ConstructorArgs),
344 ConstructorRParen);
345}
346
347Sema::OwningExprResult
348Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
349 SourceLocation PlacementLParen,
350 MultiExprArg PlacementArgs,
351 SourceLocation PlacementRParen,
352 bool ParenTypeId,
353 QualType AllocType,
354 SourceLocation TypeLoc,
355 SourceRange TypeRange,
356 ExprArg ArraySizeE,
357 SourceLocation ConstructorLParen,
358 MultiExprArg ConstructorArgs,
359 SourceLocation ConstructorRParen) {
360 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000361 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000362
Douglas Gregord8c23702009-05-21 00:00:09 +0000363 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000364
365 // That every array dimension except the first is constant was already
366 // checked by the type check above.
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000367
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000368 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
369 // or enumeration type with a non-negative value."
Douglas Gregord8c23702009-05-21 00:00:09 +0000370 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000371 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000372 QualType SizeType = ArraySize->getType();
373 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000374 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
375 diag::err_array_size_not_integral)
376 << SizeType << ArraySize->getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000377 // Let's see if this is a constant < 0. If so, we reject it out of hand.
378 // We don't care about special rules, so we tell the machinery it's not
379 // evaluated - it gives us a result in more cases.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000380 if (!ArraySize->isValueDependent()) {
381 llvm::APSInt Value;
382 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
383 if (Value < llvm::APSInt(
384 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000385 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
386 diag::err_typecheck_negative_array_size)
387 << ArraySize->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000388 }
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000389 }
390 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000391
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000392 FunctionDecl *OperatorNew = 0;
393 FunctionDecl *OperatorDelete = 0;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000394 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
395 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000396 if (!AllocType->isDependentType() &&
397 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
398 FindAllocationFunctions(StartLoc,
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000399 SourceRange(PlacementLParen, PlacementRParen),
400 UseGlobal, AllocType, ArraySize, PlaceArgs,
401 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000402 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000403
404 bool Init = ConstructorLParen.isValid();
405 // --- Choosing a constructor ---
406 // C++ 5.3.4p15
407 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
408 // the object is not initialized. If the object, or any part of it, is
409 // const-qualified, it's an error.
410 // 2) If T is a POD and there's an empty initializer, the object is value-
411 // initialized.
412 // 3) If T is a POD and there's one initializer argument, the object is copy-
413 // constructed.
414 // 4) If T is a POD and there's more initializer arguments, it's an error.
415 // 5) If T is not a POD, the initializer arguments are used as constructor
416 // arguments.
417 //
418 // Or by the C++0x formulation:
419 // 1) If there's no initializer, the object is default-initialized according
420 // to C++0x rules.
421 // 2) Otherwise, the object is direct-initialized.
422 CXXConstructorDecl *Constructor = 0;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000423 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl091cf8d2009-05-07 16:14:23 +0000424 const RecordType *RT;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000425 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000426 if (AllocType->isDependentType()) {
427 // Skip all the checks.
Mike Stump90fc78e2009-08-04 21:02:39 +0000428 } else if ((RT = AllocType->getAs<RecordType>()) &&
429 !AllocType->isAggregateType()) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000430 Constructor = PerformInitializationByConstructor(
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000431 AllocType, ConsArgs, NumConsArgs,
Douglas Gregord8c23702009-05-21 00:00:09 +0000432 TypeLoc,
433 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattner271d4c22008-11-24 05:29:24 +0000434 RT->getDecl()->getDeclName(),
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000435 NumConsArgs != 0 ? IK_Direct : IK_Default);
436 if (!Constructor)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000437 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000438 } else {
439 if (!Init) {
440 // FIXME: Check that no subpart is const.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000441 if (AllocType.isConstQualified())
442 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregord8c23702009-05-21 00:00:09 +0000443 << TypeRange);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000444 } else if (NumConsArgs == 0) {
445 // Object is value-initialized. Do nothing.
446 } else if (NumConsArgs == 1) {
447 // Object is direct-initialized.
Sebastian Redl091cf8d2009-05-07 16:14:23 +0000448 // FIXME: What DeclarationName do we pass in here?
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000449 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000450 DeclarationName() /*AllocType.getAsString()*/,
451 /*DirectInit=*/true))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000452 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000453 } else {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000454 return ExprError(Diag(StartLoc,
455 diag::err_builtin_direct_init_more_than_one_arg)
456 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000457 }
458 }
459
460 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
461
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000462 PlacementArgs.release();
463 ConstructorArgs.release();
Douglas Gregord8c23702009-05-21 00:00:09 +0000464 ArraySizeE.release();
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000465 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek0c97e042009-02-07 01:47:29 +0000466 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000467 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Douglas Gregord8c23702009-05-21 00:00:09 +0000468 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000469}
470
471/// CheckAllocatedType - Checks that a type is suitable as the allocated type
472/// in a new-expression.
473/// dimension off and stores the size expression in ArraySize.
Douglas Gregord8c23702009-05-21 00:00:09 +0000474bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
475 SourceRange R)
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000476{
477 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
478 // abstract class type or array thereof.
Douglas Gregor05e28f62009-03-24 19:52:54 +0000479 if (AllocType->isFunctionType())
Douglas Gregord8c23702009-05-21 00:00:09 +0000480 return Diag(Loc, diag::err_bad_new_type)
481 << AllocType << 0 << R;
Douglas Gregor05e28f62009-03-24 19:52:54 +0000482 else if (AllocType->isReferenceType())
Douglas Gregord8c23702009-05-21 00:00:09 +0000483 return Diag(Loc, diag::err_bad_new_type)
484 << AllocType << 1 << R;
Douglas Gregor05e28f62009-03-24 19:52:54 +0000485 else if (!AllocType->isDependentType() &&
Douglas Gregord8c23702009-05-21 00:00:09 +0000486 RequireCompleteType(Loc, AllocType,
Douglas Gregor05e28f62009-03-24 19:52:54 +0000487 diag::err_new_incomplete_type,
Douglas Gregord8c23702009-05-21 00:00:09 +0000488 R))
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000489 return true;
Douglas Gregord8c23702009-05-21 00:00:09 +0000490 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregor05e28f62009-03-24 19:52:54 +0000491 diag::err_allocation_of_abstract_type))
492 return true;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000493
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000494 return false;
495}
496
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000497/// FindAllocationFunctions - Finds the overloads of operator new and delete
498/// that are appropriate for the allocation.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000499bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
500 bool UseGlobal, QualType AllocType,
501 bool IsArray, Expr **PlaceArgs,
502 unsigned NumPlaceArgs,
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000503 FunctionDecl *&OperatorNew,
504 FunctionDecl *&OperatorDelete)
505{
506 // --- Choosing an allocation function ---
507 // C++ 5.3.4p8 - 14 & 18
508 // 1) If UseGlobal is true, only look in the global scope. Else, also look
509 // in the scope of the allocated class.
510 // 2) If an array size is given, look for operator new[], else look for
511 // operator new.
512 // 3) The first argument is always size_t. Append the arguments from the
513 // placement form.
514 // FIXME: Also find the appropriate delete operator.
515
516 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
517 // We don't care about the actual value of this argument.
518 // FIXME: Should the Sema create the expression and embed it in the syntax
519 // tree? Or should the consumer just recalculate the value?
Anders Carlsson44443f82009-08-16 20:29:29 +0000520 IntegerLiteral Size(llvm::APInt::getNullValue(
521 Context.Target.getPointerWidth(0)),
522 Context.getSizeType(),
523 SourceLocation());
524 AllocArgs[0] = &Size;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000525 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
526
527 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
528 IsArray ? OO_Array_New : OO_New);
529 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregor2e047592009-02-28 01:32:25 +0000530 CXXRecordDecl *Record
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000531 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redlec5f3262008-12-04 22:20:51 +0000532 // FIXME: We fail to find inherited overloads.
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(), Record, /*AllowMissing=*/true,
535 OperatorNew))
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000536 return true;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000537 }
538 if (!OperatorNew) {
539 // Didn't find a member overload. Look for a global one.
540 DeclareGlobalNewDelete();
Sebastian Redlec5f3262008-12-04 22:20:51 +0000541 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000542 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000543 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
544 OperatorNew))
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000545 return true;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000546 }
547
Anders Carlsson0db4ade2009-05-31 20:26:12 +0000548 // FindAllocationOverload can change the passed in arguments, so we need to
549 // copy them back.
550 if (NumPlaceArgs > 0)
551 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
552
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000553 return false;
554}
555
Sebastian Redlec5f3262008-12-04 22:20:51 +0000556/// FindAllocationOverload - Find an fitting overload for the allocation
557/// function in the specified scope.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000558bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
559 DeclarationName Name, Expr** Args,
560 unsigned NumArgs, DeclContext *Ctx,
561 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redlec5f3262008-12-04 22:20:51 +0000562{
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000563 DeclContext::lookup_iterator Alloc, AllocEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000564 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000565 if (Alloc == AllocEnd) {
Sebastian Redlec5f3262008-12-04 22:20:51 +0000566 if (AllowMissing)
567 return false;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000568 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +0000569 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000570 }
571
572 OverloadCandidateSet Candidates;
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000573 for (; Alloc != AllocEnd; ++Alloc) {
574 // Even member operator new/delete are implicitly treated as
575 // static, so don't use AddMemberCandidate.
576 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
577 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
578 /*SuppressUserConversions=*/false);
Sebastian Redlec5f3262008-12-04 22:20:51 +0000579 }
580
581 // Do the resolution.
582 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +0000583 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redlec5f3262008-12-04 22:20:51 +0000584 case OR_Success: {
585 // Got one!
586 FunctionDecl *FnDecl = Best->Function;
587 // The first argument is size_t, and the first parameter must be size_t,
588 // too. This is checked on declaration and can be assumed. (It can't be
589 // asserted on, though, since invalid decls are left in there.)
590 for (unsigned i = 1; i < NumArgs; ++i) {
591 // FIXME: Passing word to diagnostic.
Anders Carlsson88719742009-05-31 19:49:47 +0000592 if (PerformCopyInitialization(Args[i],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000593 FnDecl->getParamDecl(i)->getType(),
594 "passing"))
595 return true;
596 }
597 Operator = FnDecl;
598 return false;
599 }
600
601 case OR_No_Viable_Function:
Sebastian Redlec5f3262008-12-04 22:20:51 +0000602 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +0000603 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000604 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
605 return true;
606
607 case OR_Ambiguous:
Sebastian Redlec5f3262008-12-04 22:20:51 +0000608 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000609 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000610 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
611 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +0000612
613 case OR_Deleted:
614 Diag(StartLoc, diag::err_ovl_deleted_call)
615 << Best->Function->isDeleted()
616 << Name << Range;
617 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
618 return true;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000619 }
620 assert(false && "Unreachable, bad result from BestViableFunction");
621 return true;
622}
623
624
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000625/// DeclareGlobalNewDelete - Declare the global forms of operator new and
626/// delete. These are:
627/// @code
628/// void* operator new(std::size_t) throw(std::bad_alloc);
629/// void* operator new[](std::size_t) throw(std::bad_alloc);
630/// void operator delete(void *) throw();
631/// void operator delete[](void *) throw();
632/// @endcode
633/// Note that the placement and nothrow forms of new are *not* implicitly
634/// declared. Their use requires including \<new\>.
635void Sema::DeclareGlobalNewDelete()
636{
637 if (GlobalNewDeleteDeclared)
638 return;
639 GlobalNewDeleteDeclared = true;
640
641 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
642 QualType SizeT = Context.getSizeType();
643
644 // FIXME: Exception specifications are not added.
645 DeclareGlobalAllocationFunction(
646 Context.DeclarationNames.getCXXOperatorName(OO_New),
647 VoidPtr, SizeT);
648 DeclareGlobalAllocationFunction(
649 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
650 VoidPtr, SizeT);
651 DeclareGlobalAllocationFunction(
652 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
653 Context.VoidTy, VoidPtr);
654 DeclareGlobalAllocationFunction(
655 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
656 Context.VoidTy, VoidPtr);
657}
658
659/// DeclareGlobalAllocationFunction - Declares a single implicit global
660/// allocation function if it doesn't already exist.
661void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
662 QualType Return, QualType Argument)
663{
664 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
665
666 // Check if this function is already declared.
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000667 {
Douglas Gregor7c865852008-12-23 22:05:29 +0000668 DeclContext::lookup_iterator Alloc, AllocEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000669 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000670 Alloc != AllocEnd; ++Alloc) {
671 // FIXME: Do we need to check for default arguments here?
672 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
673 if (Func->getNumParams() == 1 &&
Ted Kremenek0c97e042009-02-07 01:47:29 +0000674 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000675 return;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000676 }
677 }
678
679 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
680 FunctionDecl *Alloc =
681 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argiris Kirtzidis42556e42009-08-21 00:31:54 +0000682 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000683 Alloc->setImplicit();
684 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000685 0, Argument, /*DInfo=*/0,
686 VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000687 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000688
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000689 // FIXME: Also add this declaration to the IdentifierResolver, but
690 // make sure it is at the end of the chain to coincide with the
691 // global scope.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000692 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000693}
694
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000695/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
696/// @code ::delete ptr; @endcode
697/// or
698/// @code delete [] ptr; @endcode
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000699Action::OwningExprResult
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000700Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000701 bool ArrayForm, ExprArg Operand)
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000702{
703 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
704 // having a single conversion function to a pointer type. The result has
705 // type void."
706 // DR599 amends "pointer type" to "pointer to object type" in both cases.
707
Anders Carlsson44443f82009-08-16 20:29:29 +0000708 FunctionDecl *OperatorDelete = 0;
709
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000710 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000711 if (!Ex->isTypeDependent()) {
712 QualType Type = Ex->getType();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000713
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000714 if (Type->isRecordType()) {
715 // FIXME: Find that one conversion function and amend the type.
716 }
717
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000718 if (!Type->isPointerType())
719 return ExprError(Diag(StartLoc, diag::err_delete_operand)
720 << Type << Ex->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000721
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000722 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorcde3a2d2009-03-24 20:13:58 +0000723 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000724 return ExprError(Diag(StartLoc, diag::err_delete_operand)
725 << Type << Ex->getSourceRange());
Douglas Gregorcde3a2d2009-03-24 20:13:58 +0000726 else if (!Pointee->isDependentType() &&
727 RequireCompleteType(StartLoc, Pointee,
728 diag::warn_delete_incomplete,
729 Ex->getSourceRange()))
730 return ExprError();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000731
Anders Carlsson44443f82009-08-16 20:29:29 +0000732 // FIXME: This should be shared with the code for finding the delete
733 // operator in ActOnCXXNew.
734 IntegerLiteral Size(llvm::APInt::getNullValue(
735 Context.Target.getPointerWidth(0)),
736 Context.getSizeType(),
737 SourceLocation());
738 ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy),
739 CastExpr::CK_Unknown, &Size, false);
740 Expr *DeleteArg = &Cast;
741
742 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
743 ArrayForm ? OO_Array_Delete : OO_Delete);
744
745 if (Pointee->isRecordType() && !UseGlobal) {
746 CXXRecordDecl *Record
747 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
748 // FIXME: We fail to find inherited overloads.
749 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
750 &DeleteArg, 1, Record, /*AllowMissing=*/true,
751 OperatorDelete))
752 return ExprError();
753 }
754
755 if (!OperatorDelete) {
756 // Didn't find a member overload. Look for a global one.
757 DeclareGlobalNewDelete();
758 DeclContext *TUDecl = Context.getTranslationUnitDecl();
759 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
760 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false,
761 OperatorDelete))
762 return ExprError();
763 }
764
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000765 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000766 }
767
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000768 Operand.release();
769 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlsson44443f82009-08-16 20:29:29 +0000770 OperatorDelete, Ex, StartLoc));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000771}
772
773
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000774/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
775/// C++ if/switch/while/for statement.
776/// e.g: "if (int x = f()) {...}"
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000777Action::OwningExprResult
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000778Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
779 Declarator &D,
780 SourceLocation EqualLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000781 ExprArg AssignExprVal) {
782 assert(AssignExprVal.get() && "Null assignment expression");
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000783
784 // C++ 6.4p2:
785 // The declarator shall not specify a function or an array.
786 // The type-specifier-seq shall not contain typedef and shall not declare a
787 // new class or enumeration.
788
789 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
790 "Parser allowed 'typedef' as storage class of condition decl.");
791
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000792 // FIXME: Store DeclaratorInfo in the expression.
793 DeclaratorInfo *DInfo = 0;
Argiris Kirtzidis40688ad2009-08-11 05:20:41 +0000794 TagDecl *OwnedTag = 0;
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000795 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000796
797 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
798 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
799 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000800 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
801 << SourceRange(StartLoc, EqualLoc));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000802 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattner9d2cf082008-11-19 05:27:50 +0000803 Diag(StartLoc, diag::err_invalid_use_of_array_type)
804 << SourceRange(StartLoc, EqualLoc);
Argiris Kirtzidis40688ad2009-08-11 05:20:41 +0000805 } else if (OwnedTag && OwnedTag->isDefinition()) {
806 // The type-specifier-seq shall not declare a new class or enumeration.
807 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000808 }
809
Douglas Gregore153fcf2009-06-23 21:43:56 +0000810 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000811 if (!Dcl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000812 return ExprError();
Anders Carlssonf9f05b82009-05-30 21:37:25 +0000813 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000814
Douglas Gregor48840c72008-12-10 23:01:14 +0000815 // Mark this variable as one that is declared within a conditional.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000816 // We know that the decl had to be a VarDecl because that is the only type of
817 // decl that can be assigned and the grammar requires an '='.
818 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
819 VD->setDeclaredInCondition(true);
820 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000821}
822
823/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
824bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
825 // C++ 6.4p4:
826 // The value of a condition that is an initialized declaration in a statement
827 // other than a switch statement is the value of the declared variable
828 // implicitly converted to type bool. If that conversion is ill-formed, the
829 // program is ill-formed.
830 // The value of a condition that is an expression is the value of the
831 // expression, implicitly converted to bool.
832 //
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000833 return PerformContextuallyConvertToBool(CondExpr);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000834}
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000835
836/// Helper function to determine whether this is the (deprecated) C++
837/// conversion from a string literal to a pointer to non-const char or
838/// non-const wchar_t (for narrow and wide string literals,
839/// respectively).
840bool
841Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
842 // Look inside the implicit cast, if it exists.
843 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
844 From = Cast->getSubExpr();
845
846 // A string literal (2.13.4) that is not a wide string literal can
847 // be converted to an rvalue of type "pointer to char"; a wide
848 // string literal can be converted to an rvalue of type "pointer
849 // to wchar_t" (C++ 4.2p2).
850 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000851 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000852 if (const BuiltinType *ToPointeeType
853 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
854 // This conversion is considered only when there is an
855 // explicit appropriate pointer target type (C++ 4.2p2).
856 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
857 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
858 (!StrLit->isWide() &&
859 (ToPointeeType->getKind() == BuiltinType::Char_U ||
860 ToPointeeType->getKind() == BuiltinType::Char_S))))
861 return true;
862 }
863
864 return false;
865}
Douglas Gregorbb461502008-10-24 04:54:22 +0000866
867/// PerformImplicitConversion - Perform an implicit conversion of the
868/// expression From to the type ToType. Returns true if there was an
869/// error, false otherwise. The expression From is replaced with the
Douglas Gregor6fd35572008-12-19 17:40:08 +0000870/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000871/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redla55834a2009-04-12 17:16:29 +0000872/// explicit user-defined conversions are permitted. @p Elidable should be true
873/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
874/// resolution works differently in that case.
875bool
Douglas Gregor6fd35572008-12-19 17:40:08 +0000876Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +0000877 const char *Flavor, bool AllowExplicit,
878 bool Elidable)
Douglas Gregorbb461502008-10-24 04:54:22 +0000879{
Sebastian Redla55834a2009-04-12 17:16:29 +0000880 ImplicitConversionSequence ICS;
881 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
882 if (Elidable && getLangOptions().CPlusPlus0x) {
883 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
884 AllowExplicit, /*ForceRValue*/true);
885 }
886 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
887 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
888 }
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000889 return PerformImplicitConversion(From, ToType, ICS, Flavor);
890}
891
892/// PerformImplicitConversion - Perform an implicit conversion of the
893/// expression From to the type ToType using the pre-computed implicit
894/// conversion sequence ICS. Returns true if there was an error, false
895/// otherwise. The expression From is replaced with the converted
896/// expression. Flavor is the kind of conversion we're performing,
897/// used in the error message.
898bool
899Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
900 const ImplicitConversionSequence &ICS,
901 const char* Flavor) {
Douglas Gregorbb461502008-10-24 04:54:22 +0000902 switch (ICS.ConversionKind) {
903 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor6fd35572008-12-19 17:40:08 +0000904 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregorbb461502008-10-24 04:54:22 +0000905 return true;
906 break;
907
908 case ImplicitConversionSequence::UserDefinedConversion:
Mike Stumpe127ae32009-05-16 07:39:55 +0000909 // FIXME: This is, of course, wrong. We'll need to actually call the
910 // constructor or conversion operator, and then cope with the standard
911 // conversions.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000912 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +0000913 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +0000914 ToType->isLValueReferenceType());
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000915 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000916
917 case ImplicitConversionSequence::EllipsisConversion:
918 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000919 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000920
921 case ImplicitConversionSequence::BadConversion:
922 return true;
923 }
924
925 // Everything went well.
926 return false;
927}
928
929/// PerformImplicitConversion - Perform an implicit conversion of the
930/// expression From to the type ToType by following the standard
931/// conversion sequence SCS. Returns true if there was an error, false
932/// otherwise. The expression From is replaced with the converted
Douglas Gregor6fd35572008-12-19 17:40:08 +0000933/// expression. Flavor is the context in which we're performing this
934/// conversion, for use in error messages.
Douglas Gregorbb461502008-10-24 04:54:22 +0000935bool
936Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000937 const StandardConversionSequence& SCS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000938 const char *Flavor) {
Mike Stumpe127ae32009-05-16 07:39:55 +0000939 // Overall FIXME: we are recomputing too many types here and doing far too
940 // much extra work. What this means is that we need to keep track of more
941 // information that is computed when we try the implicit conversion initially,
942 // so that we don't need to recompute anything here.
Douglas Gregorbb461502008-10-24 04:54:22 +0000943 QualType FromType = From->getType();
944
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000945 if (SCS.CopyConstructor) {
Anders Carlsson0e098352009-05-19 04:45:15 +0000946 // FIXME: When can ToType be a reference type?
947 assert(!ToType->isReferenceType());
948
Anders Carlsson665e4692009-08-25 05:12:04 +0000949 OwningExprResult FromResult =
950 BuildCXXConstructExpr(ToType, SCS.CopyConstructor, &From, 1);
951
952 if (FromResult.isInvalid())
953 return true;
954
955 From = FromResult.takeAs<Expr>();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000956 return false;
957 }
958
Douglas Gregorbb461502008-10-24 04:54:22 +0000959 // Perform the first implicit conversion.
960 switch (SCS.First) {
961 case ICK_Identity:
962 case ICK_Lvalue_To_Rvalue:
963 // Nothing to do.
964 break;
965
966 case ICK_Array_To_Pointer:
Douglas Gregoraa57e862009-02-18 21:56:37 +0000967 FromType = Context.getArrayDecayedType(FromType);
Anders Carlssond6e11722009-08-08 21:04:35 +0000968 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregoraa57e862009-02-18 21:56:37 +0000969 break;
970
971 case ICK_Function_To_Pointer:
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000972 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor45014fd2008-11-10 20:40:00 +0000973 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
974 if (!Fn)
975 return true;
976
Douglas Gregoraa57e862009-02-18 21:56:37 +0000977 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
978 return true;
979
Douglas Gregor45014fd2008-11-10 20:40:00 +0000980 FixOverloadedFunctionReference(From, Fn);
981 FromType = From->getType();
Douglas Gregor45014fd2008-11-10 20:40:00 +0000982 }
Douglas Gregorbb461502008-10-24 04:54:22 +0000983 FromType = Context.getPointerType(FromType);
984 ImpCastExprToType(From, FromType);
985 break;
986
987 default:
988 assert(false && "Improper first standard conversion");
989 break;
990 }
991
992 // Perform the second implicit conversion
993 switch (SCS.Second) {
994 case ICK_Identity:
995 // Nothing to do.
996 break;
997
998 case ICK_Integral_Promotion:
999 case ICK_Floating_Promotion:
Douglas Gregore819caf2009-02-12 00:15:05 +00001000 case ICK_Complex_Promotion:
Douglas Gregorbb461502008-10-24 04:54:22 +00001001 case ICK_Integral_Conversion:
1002 case ICK_Floating_Conversion:
Douglas Gregore819caf2009-02-12 00:15:05 +00001003 case ICK_Complex_Conversion:
Douglas Gregorbb461502008-10-24 04:54:22 +00001004 case ICK_Floating_Integral:
Douglas Gregore819caf2009-02-12 00:15:05 +00001005 case ICK_Complex_Real:
Douglas Gregorfcb19192009-02-11 23:02:49 +00001006 case ICK_Compatible_Conversion:
1007 // FIXME: Go deeper to get the unqualified type!
Douglas Gregorbb461502008-10-24 04:54:22 +00001008 FromType = ToType.getUnqualifiedType();
1009 ImpCastExprToType(From, FromType);
1010 break;
1011
1012 case ICK_Pointer_Conversion:
Douglas Gregor6fd35572008-12-19 17:40:08 +00001013 if (SCS.IncompatibleObjC) {
1014 // Diagnose incompatible Objective-C conversions
1015 Diag(From->getSourceRange().getBegin(),
1016 diag::ext_typecheck_convert_incompatible_pointer)
1017 << From->getType() << ToType << Flavor
1018 << From->getSourceRange();
1019 }
1020
Douglas Gregorbb461502008-10-24 04:54:22 +00001021 if (CheckPointerConversion(From, ToType))
1022 return true;
1023 ImpCastExprToType(From, ToType);
1024 break;
1025
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001026 case ICK_Pointer_Member: {
1027 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1028 if (CheckMemberPointerConversion(From, ToType, Kind))
1029 return true;
1030 ImpCastExprToType(From, ToType, Kind);
1031 break;
1032 }
Douglas Gregorbb461502008-10-24 04:54:22 +00001033 case ICK_Boolean_Conversion:
1034 FromType = Context.BoolTy;
1035 ImpCastExprToType(From, FromType);
1036 break;
1037
1038 default:
1039 assert(false && "Improper second standard conversion");
1040 break;
1041 }
1042
1043 switch (SCS.Third) {
1044 case ICK_Identity:
1045 // Nothing to do.
1046 break;
1047
1048 case ICK_Qualification:
Mike Stumpe127ae32009-05-16 07:39:55 +00001049 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1050 // references.
Douglas Gregor5ac8ffa2009-01-16 19:38:23 +00001051 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +00001052 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +00001053 ToType->isLValueReferenceType());
Douglas Gregorbb461502008-10-24 04:54:22 +00001054 break;
1055
1056 default:
1057 assert(false && "Improper second standard conversion");
1058 break;
1059 }
1060
1061 return false;
1062}
1063
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001064Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1065 SourceLocation KWLoc,
1066 SourceLocation LParen,
1067 TypeTy *Ty,
1068 SourceLocation RParen) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001069 QualType T = GetTypeFromParser(Ty);
Anders Carlsson1b749a02009-07-07 19:06:02 +00001070
1071 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1072 // all traits except __is_class, __is_enum and __is_union require a the type
1073 // to be complete.
1074 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1075 if (RequireCompleteType(KWLoc, T,
1076 diag::err_incomplete_type_used_in_type_trait_expr,
1077 SourceRange(), SourceRange(), T))
1078 return ExprError();
1079 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001080
1081 // There is no point in eagerly computing the value. The traits are designed
1082 // to be used from type trait templates, so Ty will be a template parameter
1083 // 99% of the time.
Anders Carlsson1b749a02009-07-07 19:06:02 +00001084 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1085 RParen, Context.BoolTy));
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001086}
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001087
1088QualType Sema::CheckPointerToMemberOperands(
1089 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
1090{
1091 const char *OpSpelling = isIndirect ? "->*" : ".*";
1092 // C++ 5.5p2
1093 // The binary operator .* [p3: ->*] binds its second operand, which shall
1094 // be of type "pointer to member of T" (where T is a completely-defined
1095 // class type) [...]
1096 QualType RType = rex->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001097 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregor05e28f62009-03-24 19:52:54 +00001098 if (!MemPtr) {
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001099 Diag(Loc, diag::err_bad_memptr_rhs)
1100 << OpSpelling << RType << rex->getSourceRange();
1101 return QualType();
Douglas Gregor96b6df92009-05-14 00:28:11 +00001102 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00001103
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001104 QualType Class(MemPtr->getClass(), 0);
1105
1106 // C++ 5.5p2
1107 // [...] to its first operand, which shall be of class T or of a class of
1108 // which T is an unambiguous and accessible base class. [p3: a pointer to
1109 // such a class]
1110 QualType LType = lex->getType();
1111 if (isIndirect) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001112 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001113 LType = Ptr->getPointeeType().getNonReferenceType();
1114 else {
1115 Diag(Loc, diag::err_bad_memptr_lhs)
1116 << OpSpelling << 1 << LType << lex->getSourceRange();
1117 return QualType();
1118 }
1119 }
1120
1121 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1122 Context.getCanonicalType(LType).getUnqualifiedType()) {
1123 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1124 /*DetectVirtual=*/false);
Mike Stumpe127ae32009-05-16 07:39:55 +00001125 // FIXME: Would it be useful to print full ambiguity paths, or is that
1126 // overkill?
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001127 if (!IsDerivedFrom(LType, Class, Paths) ||
1128 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1129 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1130 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1131 return QualType();
1132 }
1133 }
1134
1135 // C++ 5.5p2
1136 // The result is an object or a function of the type specified by the
1137 // second operand.
1138 // The cv qualifiers are the union of those in the pointer and the left side,
1139 // in accordance with 5.5p5 and 5.2.5.
1140 // FIXME: This returns a dereferenced member function pointer as a normal
1141 // function type. However, the only operation valid on such functions is
Mike Stumpe127ae32009-05-16 07:39:55 +00001142 // calling them. There's also a GCC extension to get a function pointer to the
1143 // thing, which is another complication, because this type - unlike the type
1144 // that is the result of this expression - takes the class as the first
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001145 // argument.
1146 // We probably need a "MemberFunctionClosureType" or something like that.
1147 QualType Result = MemPtr->getPointeeType();
1148 if (LType.isConstQualified())
1149 Result.addConst();
1150 if (LType.isVolatileQualified())
1151 Result.addVolatile();
1152 return Result;
1153}
Sebastian Redlbd261962009-04-16 17:51:27 +00001154
1155/// \brief Get the target type of a standard or user-defined conversion.
1156static QualType TargetType(const ImplicitConversionSequence &ICS) {
1157 assert((ICS.ConversionKind ==
1158 ImplicitConversionSequence::StandardConversion ||
1159 ICS.ConversionKind ==
1160 ImplicitConversionSequence::UserDefinedConversion) &&
1161 "function only valid for standard or user-defined conversions");
1162 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1163 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1164 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1165}
1166
1167/// \brief Try to convert a type to another according to C++0x 5.16p3.
1168///
1169/// This is part of the parameter validation for the ? operator. If either
1170/// value operand is a class type, the two operands are attempted to be
1171/// converted to each other. This function does the conversion in one direction.
1172/// It emits a diagnostic and returns true only if it finds an ambiguous
1173/// conversion.
1174static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1175 SourceLocation QuestionLoc,
1176 ImplicitConversionSequence &ICS)
1177{
1178 // C++0x 5.16p3
1179 // The process for determining whether an operand expression E1 of type T1
1180 // can be converted to match an operand expression E2 of type T2 is defined
1181 // as follows:
1182 // -- If E2 is an lvalue:
1183 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1184 // E1 can be converted to match E2 if E1 can be implicitly converted to
1185 // type "lvalue reference to T2", subject to the constraint that in the
1186 // conversion the reference must bind directly to E1.
1187 if (!Self.CheckReferenceInit(From,
1188 Self.Context.getLValueReferenceType(To->getType()),
1189 &ICS))
1190 {
1191 assert((ICS.ConversionKind ==
1192 ImplicitConversionSequence::StandardConversion ||
1193 ICS.ConversionKind ==
1194 ImplicitConversionSequence::UserDefinedConversion) &&
1195 "expected a definite conversion");
1196 bool DirectBinding =
1197 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1198 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1199 if (DirectBinding)
1200 return false;
1201 }
1202 }
1203 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1204 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1205 // -- if E1 and E2 have class type, and the underlying class types are
1206 // the same or one is a base class of the other:
1207 QualType FTy = From->getType();
1208 QualType TTy = To->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001209 const RecordType *FRec = FTy->getAs<RecordType>();
1210 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redlbd261962009-04-16 17:51:27 +00001211 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1212 if (FRec && TRec && (FRec == TRec ||
1213 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1214 // E1 can be converted to match E2 if the class of T2 is the
1215 // same type as, or a base class of, the class of T1, and
1216 // [cv2 > cv1].
1217 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1218 // Could still fail if there's no copy constructor.
1219 // FIXME: Is this a hard error then, or just a conversion failure? The
1220 // standard doesn't say.
1221 ICS = Self.TryCopyInitialization(From, TTy);
1222 }
1223 } else {
1224 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1225 // implicitly converted to the type that expression E2 would have
1226 // if E2 were converted to an rvalue.
1227 // First find the decayed type.
1228 if (TTy->isFunctionType())
1229 TTy = Self.Context.getPointerType(TTy);
1230 else if(TTy->isArrayType())
1231 TTy = Self.Context.getArrayDecayedType(TTy);
1232
1233 // Now try the implicit conversion.
1234 // FIXME: This doesn't detect ambiguities.
1235 ICS = Self.TryImplicitConversion(From, TTy);
1236 }
1237 return false;
1238}
1239
1240/// \brief Try to find a common type for two according to C++0x 5.16p5.
1241///
1242/// This is part of the parameter validation for the ? operator. If either
1243/// value operand is a class type, overload resolution is used to find a
1244/// conversion to a common type.
1245static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1246 SourceLocation Loc) {
1247 Expr *Args[2] = { LHS, RHS };
1248 OverloadCandidateSet CandidateSet;
1249 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1250
1251 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001252 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00001253 case Sema::OR_Success:
1254 // We found a match. Perform the conversions on the arguments and move on.
1255 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1256 Best->Conversions[0], "converting") ||
1257 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1258 Best->Conversions[1], "converting"))
1259 break;
1260 return false;
1261
1262 case Sema::OR_No_Viable_Function:
1263 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1264 << LHS->getType() << RHS->getType()
1265 << LHS->getSourceRange() << RHS->getSourceRange();
1266 return true;
1267
1268 case Sema::OR_Ambiguous:
1269 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1270 << LHS->getType() << RHS->getType()
1271 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpe127ae32009-05-16 07:39:55 +00001272 // FIXME: Print the possible common types by printing the return types of
1273 // the viable candidates.
Sebastian Redlbd261962009-04-16 17:51:27 +00001274 break;
1275
1276 case Sema::OR_Deleted:
1277 assert(false && "Conditional operator has only built-in overloads");
1278 break;
1279 }
1280 return true;
1281}
1282
Sebastian Redld3169132009-04-17 16:30:52 +00001283/// \brief Perform an "extended" implicit conversion as returned by
1284/// TryClassUnification.
1285///
1286/// TryClassUnification generates ICSs that include reference bindings.
1287/// PerformImplicitConversion is not suitable for this; it chokes if the
1288/// second part of a standard conversion is ICK_DerivedToBase. This function
1289/// handles the reference binding specially.
1290static bool ConvertForConditional(Sema &Self, Expr *&E,
1291 const ImplicitConversionSequence &ICS)
1292{
1293 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1294 ICS.Standard.ReferenceBinding) {
1295 assert(ICS.Standard.DirectBinding &&
1296 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf6b86182009-04-26 11:21:02 +00001297 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1298 // redoing all the work.
1299 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1300 TargetType(ICS)));
Sebastian Redld3169132009-04-17 16:30:52 +00001301 }
1302 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1303 ICS.UserDefined.After.ReferenceBinding) {
1304 assert(ICS.UserDefined.After.DirectBinding &&
1305 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf6b86182009-04-26 11:21:02 +00001306 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1307 TargetType(ICS)));
Sebastian Redld3169132009-04-17 16:30:52 +00001308 }
1309 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1310 return true;
1311 return false;
1312}
1313
Sebastian Redlbd261962009-04-16 17:51:27 +00001314/// \brief Check the operands of ?: under C++ semantics.
1315///
1316/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1317/// extension. In this case, LHS == Cond. (But they're not aliases.)
1318QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1319 SourceLocation QuestionLoc) {
Mike Stumpe127ae32009-05-16 07:39:55 +00001320 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1321 // interface pointers.
Sebastian Redlbd261962009-04-16 17:51:27 +00001322
1323 // C++0x 5.16p1
1324 // The first expression is contextually converted to bool.
1325 if (!Cond->isTypeDependent()) {
1326 if (CheckCXXBooleanCondition(Cond))
1327 return QualType();
1328 }
1329
1330 // Either of the arguments dependent?
1331 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1332 return Context.DependentTy;
1333
1334 // C++0x 5.16p2
1335 // If either the second or the third operand has type (cv) void, ...
1336 QualType LTy = LHS->getType();
1337 QualType RTy = RHS->getType();
1338 bool LVoid = LTy->isVoidType();
1339 bool RVoid = RTy->isVoidType();
1340 if (LVoid || RVoid) {
1341 // ... then the [l2r] conversions are performed on the second and third
1342 // operands ...
1343 DefaultFunctionArrayConversion(LHS);
1344 DefaultFunctionArrayConversion(RHS);
1345 LTy = LHS->getType();
1346 RTy = RHS->getType();
1347
1348 // ... and one of the following shall hold:
1349 // -- The second or the third operand (but not both) is a throw-
1350 // expression; the result is of the type of the other and is an rvalue.
1351 bool LThrow = isa<CXXThrowExpr>(LHS);
1352 bool RThrow = isa<CXXThrowExpr>(RHS);
1353 if (LThrow && !RThrow)
1354 return RTy;
1355 if (RThrow && !LThrow)
1356 return LTy;
1357
1358 // -- Both the second and third operands have type void; the result is of
1359 // type void and is an rvalue.
1360 if (LVoid && RVoid)
1361 return Context.VoidTy;
1362
1363 // Neither holds, error.
1364 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1365 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1366 << LHS->getSourceRange() << RHS->getSourceRange();
1367 return QualType();
1368 }
1369
1370 // Neither is void.
1371
1372 // C++0x 5.16p3
1373 // Otherwise, if the second and third operand have different types, and
1374 // either has (cv) class type, and attempt is made to convert each of those
1375 // operands to the other.
1376 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1377 (LTy->isRecordType() || RTy->isRecordType())) {
1378 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1379 // These return true if a single direction is already ambiguous.
1380 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1381 return QualType();
1382 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1383 return QualType();
1384
1385 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1386 ImplicitConversionSequence::BadConversion;
1387 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1388 ImplicitConversionSequence::BadConversion;
1389 // If both can be converted, [...] the program is ill-formed.
1390 if (HaveL2R && HaveR2L) {
1391 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1392 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1393 return QualType();
1394 }
1395
1396 // If exactly one conversion is possible, that conversion is applied to
1397 // the chosen operand and the converted operands are used in place of the
1398 // original operands for the remainder of this section.
1399 if (HaveL2R) {
Sebastian Redld3169132009-04-17 16:30:52 +00001400 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redlbd261962009-04-16 17:51:27 +00001401 return QualType();
1402 LTy = LHS->getType();
1403 } else if (HaveR2L) {
Sebastian Redld3169132009-04-17 16:30:52 +00001404 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redlbd261962009-04-16 17:51:27 +00001405 return QualType();
1406 RTy = RHS->getType();
1407 }
1408 }
1409
1410 // C++0x 5.16p4
1411 // If the second and third operands are lvalues and have the same type,
1412 // the result is of that type [...]
1413 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1414 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1415 RHS->isLvalue(Context) == Expr::LV_Valid)
1416 return LTy;
1417
1418 // C++0x 5.16p5
1419 // Otherwise, the result is an rvalue. If the second and third operands
1420 // do not have the same type, and either has (cv) class type, ...
1421 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1422 // ... overload resolution is used to determine the conversions (if any)
1423 // to be applied to the operands. If the overload resolution fails, the
1424 // program is ill-formed.
1425 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1426 return QualType();
1427 }
1428
1429 // C++0x 5.16p6
1430 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1431 // conversions are performed on the second and third operands.
1432 DefaultFunctionArrayConversion(LHS);
1433 DefaultFunctionArrayConversion(RHS);
1434 LTy = LHS->getType();
1435 RTy = RHS->getType();
1436
1437 // After those conversions, one of the following shall hold:
1438 // -- The second and third operands have the same type; the result
1439 // is of that type.
1440 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1441 return LTy;
1442
1443 // -- The second and third operands have arithmetic or enumeration type;
1444 // the usual arithmetic conversions are performed to bring them to a
1445 // common type, and the result is of that type.
1446 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1447 UsualArithmeticConversions(LHS, RHS);
1448 return LHS->getType();
1449 }
1450
1451 // -- The second and third operands have pointer type, or one has pointer
1452 // type and the other is a null pointer constant; pointer conversions
1453 // and qualification conversions are performed to bring them to their
1454 // composite pointer type. The result is of the composite pointer type.
Sebastian Redl42b81a22009-04-19 19:26:31 +00001455 QualType Composite = FindCompositePointerType(LHS, RHS);
1456 if (!Composite.isNull())
1457 return Composite;
Sebastian Redlbd261962009-04-16 17:51:27 +00001458
Sebastian Redl5b3fcf82009-04-19 21:15:26 +00001459 // Fourth bullet is same for pointers-to-member. However, the possible
1460 // conversions are far more limited: we have null-to-pointer, upcast of
1461 // containing class, and second-level cv-ness.
1462 // cv-ness is not a union, but must match one of the two operands. (Which,
1463 // frankly, is stupid.)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001464 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1465 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Sebastian Redl5b3fcf82009-04-19 21:15:26 +00001466 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1467 ImpCastExprToType(RHS, LTy);
1468 return LTy;
1469 }
1470 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1471 ImpCastExprToType(LHS, RTy);
1472 return RTy;
1473 }
1474 if (LMemPtr && RMemPtr) {
1475 QualType LPointee = LMemPtr->getPointeeType();
1476 QualType RPointee = RMemPtr->getPointeeType();
1477 // First, we check that the unqualified pointee type is the same. If it's
1478 // not, there's no conversion that will unify the two pointers.
1479 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1480 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1481 // Second, we take the greater of the two cv qualifications. If neither
1482 // is greater than the other, the conversion is not possible.
1483 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1484 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1485 // Third, we check if either of the container classes is derived from
1486 // the other.
1487 QualType LContainer(LMemPtr->getClass(), 0);
1488 QualType RContainer(RMemPtr->getClass(), 0);
1489 QualType MoreDerived;
1490 if (Context.getCanonicalType(LContainer) ==
1491 Context.getCanonicalType(RContainer))
1492 MoreDerived = LContainer;
1493 else if (IsDerivedFrom(LContainer, RContainer))
1494 MoreDerived = LContainer;
1495 else if (IsDerivedFrom(RContainer, LContainer))
1496 MoreDerived = RContainer;
1497
1498 if (!MoreDerived.isNull()) {
1499 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1500 // We don't use ImpCastExprToType here because this could still fail
1501 // for ambiguous or inaccessible conversions.
1502 QualType Common = Context.getMemberPointerType(
1503 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1504 if (PerformImplicitConversion(LHS, Common, "converting"))
1505 return QualType();
1506 if (PerformImplicitConversion(RHS, Common, "converting"))
1507 return QualType();
1508 return Common;
1509 }
1510 }
1511 }
1512 }
1513
Sebastian Redlbd261962009-04-16 17:51:27 +00001514 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1515 << LHS->getType() << RHS->getType()
1516 << LHS->getSourceRange() << RHS->getSourceRange();
1517 return QualType();
1518}
Sebastian Redl42b81a22009-04-19 19:26:31 +00001519
1520/// \brief Find a merged pointer type and convert the two expressions to it.
1521///
Douglas Gregor70be4db2009-08-24 17:42:35 +00001522/// This finds the composite pointer type (or member pointer type) for @p E1
1523/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1524/// type and returns it.
Sebastian Redl42b81a22009-04-19 19:26:31 +00001525/// It does not emit diagnostics.
1526QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1527 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1528 QualType T1 = E1->getType(), T2 = E2->getType();
Douglas Gregor70be4db2009-08-24 17:42:35 +00001529
1530 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1531 !T2->isPointerType() && !T2->isMemberPointerType())
1532 return QualType();
Sebastian Redl42b81a22009-04-19 19:26:31 +00001533
Douglas Gregor70be4db2009-08-24 17:42:35 +00001534 // FIXME: Do we need to work on the canonical types?
1535
Sebastian Redl42b81a22009-04-19 19:26:31 +00001536 // C++0x 5.9p2
1537 // Pointer conversions and qualification conversions are performed on
1538 // pointer operands to bring them to their composite pointer type. If
1539 // one operand is a null pointer constant, the composite pointer type is
1540 // the type of the other operand.
1541 if (E1->isNullPointerConstant(Context)) {
1542 ImpCastExprToType(E1, T2);
1543 return T2;
1544 }
1545 if (E2->isNullPointerConstant(Context)) {
1546 ImpCastExprToType(E2, T1);
1547 return T1;
1548 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00001549
1550 // Now both have to be pointers or member pointers.
1551 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1552 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redl42b81a22009-04-19 19:26:31 +00001553 return QualType();
1554
1555 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1556 // the other has type "pointer to cv2 T" and the composite pointer type is
1557 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1558 // Otherwise, the composite pointer type is a pointer type similar to the
1559 // type of one of the operands, with a cv-qualification signature that is
1560 // the union of the cv-qualification signatures of the operand types.
1561 // In practice, the first part here is redundant; it's subsumed by the second.
1562 // What we do here is, we build the two possible composite types, and try the
1563 // conversions in both directions. If only one works, or if the two composite
1564 // types are the same, we have succeeded.
1565 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregor70be4db2009-08-24 17:42:35 +00001566 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redl42b81a22009-04-19 19:26:31 +00001567 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregor70be4db2009-08-24 17:42:35 +00001568 do {
1569 const PointerType *Ptr1, *Ptr2;
1570 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1571 (Ptr2 = Composite2->getAs<PointerType>())) {
1572 Composite1 = Ptr1->getPointeeType();
1573 Composite2 = Ptr2->getPointeeType();
1574 QualifierUnion.push_back(
1575 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1576 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1577 continue;
1578 }
1579
1580 const MemberPointerType *MemPtr1, *MemPtr2;
1581 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1582 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1583 Composite1 = MemPtr1->getPointeeType();
1584 Composite2 = MemPtr2->getPointeeType();
1585 QualifierUnion.push_back(
1586 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1587 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1588 MemPtr2->getClass()));
1589 continue;
1590 }
1591
1592 // FIXME: block pointer types?
1593
1594 // Cannot unwrap any more types.
1595 break;
1596 } while (true);
1597
1598 // Rewrap the composites as pointers or member pointers with the union CVRs.
1599 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1600 = MemberOfClass.begin();
1601 for (llvm::SmallVector<unsigned, 4>::iterator
1602 I = QualifierUnion.begin(),
1603 E = QualifierUnion.end();
1604 I != E; (void)++I, ++MOC) {
1605 if (MOC->first && MOC->second) {
1606 // Rebuild member pointer type
1607 Composite1 = Context.getMemberPointerType(Composite1.getQualifiedType(*I),
1608 MOC->first);
1609 Composite2 = Context.getMemberPointerType(Composite2.getQualifiedType(*I),
1610 MOC->second);
1611 } else {
1612 // Rebuild pointer type
1613 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1614 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1615 }
Sebastian Redl42b81a22009-04-19 19:26:31 +00001616 }
1617
1618 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1619 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1620 ImplicitConversionSequence E1ToC2, E2ToC2;
1621 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1622 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1623 if (Context.getCanonicalType(Composite1) !=
1624 Context.getCanonicalType(Composite2)) {
1625 E1ToC2 = TryImplicitConversion(E1, Composite2);
1626 E2ToC2 = TryImplicitConversion(E2, Composite2);
1627 }
1628
1629 bool ToC1Viable = E1ToC1.ConversionKind !=
1630 ImplicitConversionSequence::BadConversion
1631 && E2ToC1.ConversionKind !=
1632 ImplicitConversionSequence::BadConversion;
1633 bool ToC2Viable = E1ToC2.ConversionKind !=
1634 ImplicitConversionSequence::BadConversion
1635 && E2ToC2.ConversionKind !=
1636 ImplicitConversionSequence::BadConversion;
1637 if (ToC1Viable && !ToC2Viable) {
1638 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1639 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1640 return Composite1;
1641 }
1642 if (ToC2Viable && !ToC1Viable) {
1643 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1644 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1645 return Composite2;
1646 }
1647 return QualType();
1648}
Anders Carlssonf0967d72009-05-17 18:41:29 +00001649
Anders Carlssona05fa102009-05-30 20:36:53 +00001650Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson1bfe1c42009-08-15 23:41:35 +00001651 if (!Context.getLangOptions().CPlusPlus)
1652 return Owned(E);
1653
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001654 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssona05fa102009-05-30 20:36:53 +00001655 if (!RT)
1656 return Owned(E);
1657
1658 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1659 if (RD->hasTrivialDestructor())
1660 return Owned(E);
1661
1662 CXXTemporary *Temp = CXXTemporary::Create(Context,
1663 RD->getDestructor(Context));
Anders Carlsson1ef0ee92009-05-30 21:21:49 +00001664 ExprTemporaries.push_back(Temp);
Fariborz Jahaniancd208112009-08-03 19:13:25 +00001665 if (CXXDestructorDecl *Destructor =
1666 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1667 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssona05fa102009-05-30 20:36:53 +00001668 // FIXME: Add the temporary to the temporaries vector.
1669 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1670}
1671
Anders Carlsson8f75fbc2009-06-05 15:38:08 +00001672Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00001673 bool ShouldDestroyTemps) {
Anders Carlsson8f75fbc2009-06-05 15:38:08 +00001674 assert(SubExpr && "sub expression can't be null!");
1675
1676 if (ExprTemporaries.empty())
1677 return SubExpr;
1678
1679 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1680 &ExprTemporaries[0],
1681 ExprTemporaries.size(),
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00001682 ShouldDestroyTemps);
Anders Carlsson8f75fbc2009-06-05 15:38:08 +00001683 ExprTemporaries.clear();
1684
1685 return E;
1686}
1687
Anders Carlsson093ba8b2009-08-25 23:46:41 +00001688Sema::OwningExprResult
Anders Carlsson691e04e2009-08-26 17:36:19 +00001689Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
Anders Carlsson093ba8b2009-08-25 23:46:41 +00001690 SourceLocation OpLoc,
1691 tok::TokenKind OpKind,
1692 SourceLocation ClassNameLoc,
1693 IdentifierInfo *ClassName,
1694 const CXXScopeSpec *SS) {
1695 if (SS && SS->isInvalid())
1696 return ExprError();
1697
1698 // Since this might be a postfix expression, get rid of ParenListExprs.
1699 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1700
1701 Expr *BaseExpr = Base.takeAs<Expr>();
1702 assert(BaseExpr && "no record expression");
1703
1704 // Perform default conversions.
1705 DefaultFunctionArrayConversion(BaseExpr);
1706
1707 QualType BaseType = BaseExpr->getType();
1708 return ExprError();
1709}
1710
Anders Carlssonf0967d72009-05-17 18:41:29 +00001711Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1712 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson8f75fbc2009-06-05 15:38:08 +00001713 if (FullExpr)
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00001714 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
1715 /*ShouldDestroyTemps=*/true);
Anders Carlssonf0967d72009-05-17 18:41:29 +00001716
Anders Carlsson093ba8b2009-08-25 23:46:41 +00001717
Anders Carlssonf0967d72009-05-17 18:41:29 +00001718 return Owned(FullExpr);
1719}