blob: a8eb2cbc7e6165cae17c9c930b21e4a297b1d4a2 [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"
Steve Naroffac5d4f12007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.h"
Anders Carlssonb5247af2009-08-26 22:59:12 +000017#include "clang/AST/ExprCXX.h"
18#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5ee8742008-12-03 20:26:15 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssonb5247af2009-08-26 22:59:12 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Parse/DeclSpec.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000022#include "llvm/ADT/STLExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023using namespace clang;
24
Douglas Gregor24094772008-11-19 19:09:45 +000025/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregorb0212bd2008-11-17 20:34:05 +000026/// name (e.g., operator void const *) as an expression. This is
27/// very similar to ActOnIdentifierExpr, except that instead of
28/// providing an identifier the parser provides the type of the
29/// conversion function.
Sebastian Redlcd883f72009-01-18 18:53:16 +000030Sema::OwningExprResult
Douglas Gregor24094772008-11-19 19:09:45 +000031Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
32 TypeTy *Ty, bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +000033 const CXXScopeSpec &SS,
34 bool isAddressOfOperand) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +000035 //FIXME: Preserve type source info.
36 QualType ConvType = GetTypeFromParser(Ty);
Douglas Gregorcfe6ae52009-08-05 05:36:45 +000037 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
Douglas Gregorb0212bd2008-11-17 20:34:05 +000038 DeclarationName ConvName
39 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd883f72009-01-18 18:53:16 +000040 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +000041 &SS, isAddressOfOperand);
Douglas Gregorb0212bd2008-11-17 20:34:05 +000042}
Sebastian Redlb93b49c2008-11-11 11:37:55 +000043
Douglas Gregor24094772008-11-19 19:09:45 +000044/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregor96a32dd2008-11-18 14:39:36 +000045/// name (e.g., @c operator+ ) as an expression. This is very
46/// similar to ActOnIdentifierExpr, except that instead of providing
47/// an identifier the parser provides the kind of overloaded
48/// operator that was parsed.
Sebastian Redlcd883f72009-01-18 18:53:16 +000049Sema::OwningExprResult
Douglas Gregor24094772008-11-19 19:09:45 +000050Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
51 OverloadedOperatorKind Op,
52 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +000053 const CXXScopeSpec &SS,
54 bool isAddressOfOperand) {
Douglas Gregor96a32dd2008-11-18 14:39:36 +000055 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redl0c9da212009-02-03 20:19:35 +000056 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +000057 isAddressOfOperand);
Douglas Gregor96a32dd2008-11-18 14:39:36 +000058}
59
Sebastian Redlb93b49c2008-11-11 11:37:55 +000060/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000061Action::OwningExprResult
Sebastian Redlb93b49c2008-11-11 11:37:55 +000062Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
63 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor52ae30c2009-01-30 01:04:22 +000064 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattnerc2a5f512008-11-20 05:51:55 +000065 if (!StdNs)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000066 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +000067
68 if (isType)
69 // FIXME: Preserve type source info.
70 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
71
Chris Lattnerc2a5f512008-11-20 05:51:55 +000072 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor52ae30c2009-01-30 01:04:22 +000073 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlb93b49c2008-11-11 11:37:55 +000074 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattnerc2a5f512008-11-20 05:51:55 +000075 if (!TypeInfoRecordDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000076 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlb93b49c2008-11-11 11:37:55 +000077
78 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
79
Douglas Gregora8b2fbf2009-06-22 20:57:11 +000080 if (!isType) {
81 // C++0x [expr.typeid]p3:
82 // When typeid is applied to an expression other than an lvalue of a
83 // polymorphic class type [...] [the] expression is an unevaluated
84 // operand.
85
86 // FIXME: if the type of the expression is a class type, the class
87 // shall be completely defined.
88 bool isUnevaluatedOperand = true;
89 Expr *E = static_cast<Expr *>(TyOrExpr);
90 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
91 QualType T = E->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +000092 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregora8b2fbf2009-06-22 20:57:11 +000093 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
94 if (RecordD->isPolymorphic())
95 isUnevaluatedOperand = false;
96 }
97 }
98
99 // If this is an unevaluated operand, clear out the set of declaration
100 // references we have been computing.
101 if (isUnevaluatedOperand)
102 PotentiallyReferencedDeclStack.back().clear();
103 }
104
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000105 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
106 TypeInfoType.withConst(),
107 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000108}
109
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000110/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000111Action::OwningExprResult
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000112Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregorf8e92702008-10-24 15:36:09 +0000113 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Chris Lattner4b009652007-07-25 00:24:17 +0000114 "Unknown C++ Boolean value!");
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000115 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
116 Context.BoolTy, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000117}
Chris Lattnera7447ba2008-02-26 00:51:44 +0000118
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000119/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
120Action::OwningExprResult
121Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
122 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
123}
124
Chris Lattnera7447ba2008-02-26 00:51:44 +0000125/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000126Action::OwningExprResult
127Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl9949a5e2009-04-27 20:27:31 +0000128 Expr *Ex = E.takeAs<Expr>();
129 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
130 return ExprError();
131 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
132}
133
134/// CheckCXXThrowOperand - Validate the operand of a throw.
135bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
136 // C++ [except.throw]p3:
137 // [...] adjusting the type from "array of T" or "function returning T"
138 // to "pointer to T" or "pointer to function returning T", [...]
139 DefaultFunctionArrayConversion(E);
140
141 // If the type of the exception would be an incomplete type or a pointer
142 // to an incomplete type other than (cv) void the program is ill-formed.
143 QualType Ty = E->getType();
144 int isPointer = 0;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000145 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl9949a5e2009-04-27 20:27:31 +0000146 Ty = Ptr->getPointeeType();
147 isPointer = 1;
148 }
149 if (!isPointer || !Ty->isVoidType()) {
150 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssonb5247af2009-08-26 22:59:12 +0000151 PDiag(isPointer ? diag::err_throw_incomplete_ptr
152 : diag::err_throw_incomplete)
153 << E->getSourceRange()))
Sebastian Redl9949a5e2009-04-27 20:27:31 +0000154 return true;
155 }
156
157 // FIXME: Construct a temporary here.
158 return false;
Chris Lattnera7447ba2008-02-26 00:51:44 +0000159}
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000160
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000161Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000162 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
163 /// is a non-lvalue expression whose value is the address of the object for
164 /// which the function is called.
165
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000166 if (!isa<FunctionDecl>(CurContext))
167 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000168
169 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
170 if (MD->isInstance())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000171 return Owned(new (Context) CXXThisExpr(ThisLoc,
172 MD->getThisType(Context)));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000173
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000174 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000175}
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000176
177/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
178/// Can be interpreted either as function-style casting ("int(x)")
179/// or class type construction ("ClassType(x,y,z)")
180/// or creation of a value-initialized type ("int()").
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000181Action::OwningExprResult
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000182Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
183 SourceLocation LParenLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000184 MultiExprArg exprs,
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000185 SourceLocation *CommaLocs,
186 SourceLocation RParenLoc) {
187 assert(TypeRep && "Missing type!");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000188 // FIXME: Preserve type source info.
189 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000190 unsigned NumExprs = exprs.size();
191 Expr **Exprs = (Expr**)exprs.get();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000192 SourceLocation TyBeginLoc = TypeRange.getBegin();
193 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
194
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000195 if (Ty->isDependentType() ||
Douglas Gregor396f1142009-03-13 21:01:28 +0000196 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000197 exprs.release();
Anders Carlssonebbd7cd2009-04-24 05:23:13 +0000198
Douglas Gregorf27b7652009-05-20 18:46:25 +0000199 return Owned(CXXUnresolvedConstructExpr::Create(Context,
200 TypeRange.getBegin(), Ty,
201 LParenLoc,
202 Exprs, NumExprs,
203 RParenLoc));
Douglas Gregor396f1142009-03-13 21:01:28 +0000204 }
205
206
Douglas Gregor861e7902009-01-16 18:33:17 +0000207 // C++ [expr.type.conv]p1:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000208 // If the expression list is a single expression, the type conversion
209 // expression is equivalent (in definedness, and if defined in meaning) to the
210 // corresponding cast expression.
211 //
212 if (NumExprs == 1) {
Anders Carlsson9583fa72009-08-07 22:21:05 +0000213 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +0000214 CXXMethodDecl *ConversionDecl = 0;
215 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, ConversionDecl,
216 /*functional-style*/true))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000217 return ExprError();
218 exprs.release();
219 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
Fariborz Jahanianc3e81132009-08-26 20:34:58 +0000220 Ty, TyBeginLoc,
221 CastExpr::CK_UserDefinedConversion,
222 Exprs[0], ConversionDecl,
223 RParenLoc));
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000224 }
225
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000226 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor861e7902009-01-16 18:33:17 +0000227 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000228
Anders Carlssonf0967d72009-05-17 18:41:29 +0000229 // FIXME: We should always create a CXXTemporaryObjectExpr here unless
230 // both the ctor and dtor are trivial.
Douglas Gregor861e7902009-01-16 18:33:17 +0000231 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
232 CXXConstructorDecl *Constructor
233 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
234 TypeRange.getBegin(),
235 SourceRange(TypeRange.getBegin(),
236 RParenLoc),
237 DeclarationName(),
238 IK_Direct);
Douglas Gregor861e7902009-01-16 18:33:17 +0000239
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000240 if (!Constructor)
241 return ExprError();
242
243 exprs.release();
Anders Carlsson7b7b2552009-05-30 20:56:46 +0000244 Expr *E = new (Context) CXXTemporaryObjectExpr(Context, Constructor,
Anders Carlssona05fa102009-05-30 20:36:53 +0000245 Ty, TyBeginLoc, Exprs,
246 NumExprs, RParenLoc);
247 return MaybeBindToTemporary(E);
Douglas Gregor861e7902009-01-16 18:33:17 +0000248 }
249
250 // Fall through to value-initialize an object of class type that
251 // doesn't have a user-declared default constructor.
252 }
253
254 // C++ [expr.type.conv]p1:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000255 // If the expression list specifies more than a single value, the type shall
256 // be a class with a suitably declared constructor.
257 //
258 if (NumExprs > 1)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000259 return ExprError(Diag(CommaLocs[0],
260 diag::err_builtin_func_cast_more_than_one_arg)
261 << FullRange);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000262
263 assert(NumExprs == 0 && "Expected 0 expressions");
264
Douglas Gregor861e7902009-01-16 18:33:17 +0000265 // C++ [expr.type.conv]p2:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000266 // The expression T(), where T is a simple-type-specifier for a non-array
267 // complete object type or the (possibly cv-qualified) void type, creates an
268 // rvalue of the specified type, which is value-initialized.
269 //
270 if (Ty->isArrayType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000271 return ExprError(Diag(TyBeginLoc,
272 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000273 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000274 RequireCompleteType(TyBeginLoc, Ty,
275 diag::err_invalid_incomplete_type_use, FullRange))
276 return ExprError();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000277
Anders Carlsson412c3402009-03-24 01:19:16 +0000278 if (RequireNonAbstractType(TyBeginLoc, Ty,
279 diag::err_allocation_of_abstract_type))
Anders Carlssonc263c9b2009-03-23 19:10:31 +0000280 return ExprError();
281
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000282 exprs.release();
283 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000284}
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000285
286
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000287/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
288/// @code new (memory) int[size][4] @endcode
289/// or
290/// @code ::new Foo(23, "hello") @endcode
291/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000292Action::OwningExprResult
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000293Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000294 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000295 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000296 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000297 MultiExprArg ConstructorArgs,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000298 SourceLocation ConstructorRParen)
299{
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000300 Expr *ArraySize = 0;
301 unsigned Skip = 0;
302 // If the specified type is an array, unwrap it and save the expression.
303 if (D.getNumTypeObjects() > 0 &&
304 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
305 DeclaratorChunk &Chunk = D.getTypeObject(0);
306 if (Chunk.Arr.hasStatic)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000307 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
308 << D.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000309 if (!Chunk.Arr.NumElts)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000310 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
311 << D.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000312 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
313 Skip = 1;
314 }
315
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000316 //FIXME: Store DeclaratorInfo in CXXNew expression.
317 DeclaratorInfo *DInfo = 0;
318 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
Chris Lattner34c61332009-04-25 08:06:05 +0000319 if (D.isInvalidType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000320 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000321
Douglas Gregord8c23702009-05-21 00:00:09 +0000322 // Every dimension shall be of constant size.
323 unsigned i = 1;
324 QualType ElementType = AllocType;
325 while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
326 if (!Array->isConstantArrayType()) {
327 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
328 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
329 return ExprError();
330 }
331 ElementType = Array->getElementType();
332 ++i;
333 }
334
335 return BuildCXXNew(StartLoc, UseGlobal,
336 PlacementLParen,
337 move(PlacementArgs),
338 PlacementRParen,
339 ParenTypeId,
340 AllocType,
341 D.getSourceRange().getBegin(),
342 D.getSourceRange(),
343 Owned(ArraySize),
344 ConstructorLParen,
345 move(ConstructorArgs),
346 ConstructorRParen);
347}
348
349Sema::OwningExprResult
350Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
351 SourceLocation PlacementLParen,
352 MultiExprArg PlacementArgs,
353 SourceLocation PlacementRParen,
354 bool ParenTypeId,
355 QualType AllocType,
356 SourceLocation TypeLoc,
357 SourceRange TypeRange,
358 ExprArg ArraySizeE,
359 SourceLocation ConstructorLParen,
360 MultiExprArg ConstructorArgs,
361 SourceLocation ConstructorRParen) {
362 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000363 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000364
Douglas Gregord8c23702009-05-21 00:00:09 +0000365 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000366
367 // That every array dimension except the first is constant was already
368 // checked by the type check above.
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000369
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000370 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
371 // or enumeration type with a non-negative value."
Douglas Gregord8c23702009-05-21 00:00:09 +0000372 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000373 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000374 QualType SizeType = ArraySize->getType();
375 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000376 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
377 diag::err_array_size_not_integral)
378 << SizeType << ArraySize->getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000379 // Let's see if this is a constant < 0. If so, we reject it out of hand.
380 // We don't care about special rules, so we tell the machinery it's not
381 // evaluated - it gives us a result in more cases.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000382 if (!ArraySize->isValueDependent()) {
383 llvm::APSInt Value;
384 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
385 if (Value < llvm::APSInt(
386 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000387 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
388 diag::err_typecheck_negative_array_size)
389 << ArraySize->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000390 }
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000391 }
392 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000393
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000394 FunctionDecl *OperatorNew = 0;
395 FunctionDecl *OperatorDelete = 0;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000396 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
397 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000398 if (!AllocType->isDependentType() &&
399 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
400 FindAllocationFunctions(StartLoc,
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000401 SourceRange(PlacementLParen, PlacementRParen),
402 UseGlobal, AllocType, ArraySize, PlaceArgs,
403 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000404 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000405
406 bool Init = ConstructorLParen.isValid();
407 // --- Choosing a constructor ---
408 // C++ 5.3.4p15
409 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
410 // the object is not initialized. If the object, or any part of it, is
411 // const-qualified, it's an error.
412 // 2) If T is a POD and there's an empty initializer, the object is value-
413 // initialized.
414 // 3) If T is a POD and there's one initializer argument, the object is copy-
415 // constructed.
416 // 4) If T is a POD and there's more initializer arguments, it's an error.
417 // 5) If T is not a POD, the initializer arguments are used as constructor
418 // arguments.
419 //
420 // Or by the C++0x formulation:
421 // 1) If there's no initializer, the object is default-initialized according
422 // to C++0x rules.
423 // 2) Otherwise, the object is direct-initialized.
424 CXXConstructorDecl *Constructor = 0;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000425 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl091cf8d2009-05-07 16:14:23 +0000426 const RecordType *RT;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000427 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000428 if (AllocType->isDependentType()) {
429 // Skip all the checks.
Mike Stump90fc78e2009-08-04 21:02:39 +0000430 } else if ((RT = AllocType->getAs<RecordType>()) &&
431 !AllocType->isAggregateType()) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000432 Constructor = PerformInitializationByConstructor(
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000433 AllocType, ConsArgs, NumConsArgs,
Douglas Gregord8c23702009-05-21 00:00:09 +0000434 TypeLoc,
435 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattner271d4c22008-11-24 05:29:24 +0000436 RT->getDecl()->getDeclName(),
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000437 NumConsArgs != 0 ? IK_Direct : IK_Default);
438 if (!Constructor)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000439 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000440 } else {
441 if (!Init) {
442 // FIXME: Check that no subpart is const.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000443 if (AllocType.isConstQualified())
444 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregord8c23702009-05-21 00:00:09 +0000445 << TypeRange);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000446 } else if (NumConsArgs == 0) {
447 // Object is value-initialized. Do nothing.
448 } else if (NumConsArgs == 1) {
449 // Object is direct-initialized.
Sebastian Redl091cf8d2009-05-07 16:14:23 +0000450 // FIXME: What DeclarationName do we pass in here?
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000451 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000452 DeclarationName() /*AllocType.getAsString()*/,
453 /*DirectInit=*/true))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000454 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000455 } else {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000456 return ExprError(Diag(StartLoc,
457 diag::err_builtin_direct_init_more_than_one_arg)
458 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000459 }
460 }
461
462 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
463
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000464 PlacementArgs.release();
465 ConstructorArgs.release();
Douglas Gregord8c23702009-05-21 00:00:09 +0000466 ArraySizeE.release();
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000467 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek0c97e042009-02-07 01:47:29 +0000468 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000469 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Douglas Gregord8c23702009-05-21 00:00:09 +0000470 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000471}
472
473/// CheckAllocatedType - Checks that a type is suitable as the allocated type
474/// in a new-expression.
475/// dimension off and stores the size expression in ArraySize.
Douglas Gregord8c23702009-05-21 00:00:09 +0000476bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
477 SourceRange R)
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000478{
479 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
480 // abstract class type or array thereof.
Douglas Gregor05e28f62009-03-24 19:52:54 +0000481 if (AllocType->isFunctionType())
Douglas Gregord8c23702009-05-21 00:00:09 +0000482 return Diag(Loc, diag::err_bad_new_type)
483 << AllocType << 0 << R;
Douglas Gregor05e28f62009-03-24 19:52:54 +0000484 else if (AllocType->isReferenceType())
Douglas Gregord8c23702009-05-21 00:00:09 +0000485 return Diag(Loc, diag::err_bad_new_type)
486 << AllocType << 1 << R;
Douglas Gregor05e28f62009-03-24 19:52:54 +0000487 else if (!AllocType->isDependentType() &&
Douglas Gregord8c23702009-05-21 00:00:09 +0000488 RequireCompleteType(Loc, AllocType,
Douglas Gregor05e28f62009-03-24 19:52:54 +0000489 diag::err_new_incomplete_type,
Douglas Gregord8c23702009-05-21 00:00:09 +0000490 R))
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000491 return true;
Douglas Gregord8c23702009-05-21 00:00:09 +0000492 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregor05e28f62009-03-24 19:52:54 +0000493 diag::err_allocation_of_abstract_type))
494 return true;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000495
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000496 return false;
497}
498
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000499/// FindAllocationFunctions - Finds the overloads of operator new and delete
500/// that are appropriate for the allocation.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000501bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
502 bool UseGlobal, QualType AllocType,
503 bool IsArray, Expr **PlaceArgs,
504 unsigned NumPlaceArgs,
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000505 FunctionDecl *&OperatorNew,
506 FunctionDecl *&OperatorDelete)
507{
508 // --- Choosing an allocation function ---
509 // C++ 5.3.4p8 - 14 & 18
510 // 1) If UseGlobal is true, only look in the global scope. Else, also look
511 // in the scope of the allocated class.
512 // 2) If an array size is given, look for operator new[], else look for
513 // operator new.
514 // 3) The first argument is always size_t. Append the arguments from the
515 // placement form.
516 // FIXME: Also find the appropriate delete operator.
517
518 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
519 // We don't care about the actual value of this argument.
520 // FIXME: Should the Sema create the expression and embed it in the syntax
521 // tree? Or should the consumer just recalculate the value?
Anders Carlsson44443f82009-08-16 20:29:29 +0000522 IntegerLiteral Size(llvm::APInt::getNullValue(
523 Context.Target.getPointerWidth(0)),
524 Context.getSizeType(),
525 SourceLocation());
526 AllocArgs[0] = &Size;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000527 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
528
529 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
530 IsArray ? OO_Array_New : OO_New);
531 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregor2e047592009-02-28 01:32:25 +0000532 CXXRecordDecl *Record
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000533 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redlec5f3262008-12-04 22:20:51 +0000534 // FIXME: We fail to find inherited overloads.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000535 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000536 AllocArgs.size(), Record, /*AllowMissing=*/true,
537 OperatorNew))
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000538 return true;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000539 }
540 if (!OperatorNew) {
541 // Didn't find a member overload. Look for a global one.
542 DeclareGlobalNewDelete();
Sebastian Redlec5f3262008-12-04 22:20:51 +0000543 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000544 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000545 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
546 OperatorNew))
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000547 return true;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000548 }
549
Anders Carlsson0db4ade2009-05-31 20:26:12 +0000550 // FindAllocationOverload can change the passed in arguments, so we need to
551 // copy them back.
552 if (NumPlaceArgs > 0)
553 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
554
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000555 return false;
556}
557
Sebastian Redlec5f3262008-12-04 22:20:51 +0000558/// FindAllocationOverload - Find an fitting overload for the allocation
559/// function in the specified scope.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000560bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
561 DeclarationName Name, Expr** Args,
562 unsigned NumArgs, DeclContext *Ctx,
563 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redlec5f3262008-12-04 22:20:51 +0000564{
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000565 DeclContext::lookup_iterator Alloc, AllocEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000566 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000567 if (Alloc == AllocEnd) {
Sebastian Redlec5f3262008-12-04 22:20:51 +0000568 if (AllowMissing)
569 return false;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000570 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +0000571 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000572 }
573
574 OverloadCandidateSet Candidates;
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000575 for (; Alloc != AllocEnd; ++Alloc) {
576 // Even member operator new/delete are implicitly treated as
577 // static, so don't use AddMemberCandidate.
578 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
579 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
580 /*SuppressUserConversions=*/false);
Sebastian Redlec5f3262008-12-04 22:20:51 +0000581 }
582
583 // Do the resolution.
584 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +0000585 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redlec5f3262008-12-04 22:20:51 +0000586 case OR_Success: {
587 // Got one!
588 FunctionDecl *FnDecl = Best->Function;
589 // The first argument is size_t, and the first parameter must be size_t,
590 // too. This is checked on declaration and can be assumed. (It can't be
591 // asserted on, though, since invalid decls are left in there.)
592 for (unsigned i = 1; i < NumArgs; ++i) {
593 // FIXME: Passing word to diagnostic.
Anders Carlsson88719742009-05-31 19:49:47 +0000594 if (PerformCopyInitialization(Args[i],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000595 FnDecl->getParamDecl(i)->getType(),
596 "passing"))
597 return true;
598 }
599 Operator = FnDecl;
600 return false;
601 }
602
603 case OR_No_Viable_Function:
Sebastian Redlec5f3262008-12-04 22:20:51 +0000604 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +0000605 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000606 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
607 return true;
608
609 case OR_Ambiguous:
Sebastian Redlec5f3262008-12-04 22:20:51 +0000610 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000611 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000612 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
613 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +0000614
615 case OR_Deleted:
616 Diag(StartLoc, diag::err_ovl_deleted_call)
617 << Best->Function->isDeleted()
618 << Name << Range;
619 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
620 return true;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000621 }
622 assert(false && "Unreachable, bad result from BestViableFunction");
623 return true;
624}
625
626
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000627/// DeclareGlobalNewDelete - Declare the global forms of operator new and
628/// delete. These are:
629/// @code
630/// void* operator new(std::size_t) throw(std::bad_alloc);
631/// void* operator new[](std::size_t) throw(std::bad_alloc);
632/// void operator delete(void *) throw();
633/// void operator delete[](void *) throw();
634/// @endcode
635/// Note that the placement and nothrow forms of new are *not* implicitly
636/// declared. Their use requires including \<new\>.
637void Sema::DeclareGlobalNewDelete()
638{
639 if (GlobalNewDeleteDeclared)
640 return;
641 GlobalNewDeleteDeclared = true;
642
643 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
644 QualType SizeT = Context.getSizeType();
645
646 // FIXME: Exception specifications are not added.
647 DeclareGlobalAllocationFunction(
648 Context.DeclarationNames.getCXXOperatorName(OO_New),
649 VoidPtr, SizeT);
650 DeclareGlobalAllocationFunction(
651 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
652 VoidPtr, SizeT);
653 DeclareGlobalAllocationFunction(
654 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
655 Context.VoidTy, VoidPtr);
656 DeclareGlobalAllocationFunction(
657 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
658 Context.VoidTy, VoidPtr);
659}
660
661/// DeclareGlobalAllocationFunction - Declares a single implicit global
662/// allocation function if it doesn't already exist.
663void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
664 QualType Return, QualType Argument)
665{
666 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
667
668 // Check if this function is already declared.
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000669 {
Douglas Gregor7c865852008-12-23 22:05:29 +0000670 DeclContext::lookup_iterator Alloc, AllocEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000671 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000672 Alloc != AllocEnd; ++Alloc) {
673 // FIXME: Do we need to check for default arguments here?
674 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
675 if (Func->getNumParams() == 1 &&
Ted Kremenek0c97e042009-02-07 01:47:29 +0000676 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000677 return;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000678 }
679 }
680
681 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
682 FunctionDecl *Alloc =
683 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argiris Kirtzidis42556e42009-08-21 00:31:54 +0000684 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000685 Alloc->setImplicit();
686 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000687 0, Argument, /*DInfo=*/0,
688 VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000689 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000690
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000691 // FIXME: Also add this declaration to the IdentifierResolver, but
692 // make sure it is at the end of the chain to coincide with the
693 // global scope.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000694 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000695}
696
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000697/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
698/// @code ::delete ptr; @endcode
699/// or
700/// @code delete [] ptr; @endcode
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000701Action::OwningExprResult
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000702Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000703 bool ArrayForm, ExprArg Operand)
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000704{
705 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
706 // having a single conversion function to a pointer type. The result has
707 // type void."
708 // DR599 amends "pointer type" to "pointer to object type" in both cases.
709
Anders Carlsson44443f82009-08-16 20:29:29 +0000710 FunctionDecl *OperatorDelete = 0;
711
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000712 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000713 if (!Ex->isTypeDependent()) {
714 QualType Type = Ex->getType();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000715
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000716 if (Type->isRecordType()) {
717 // FIXME: Find that one conversion function and amend the type.
718 }
719
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000720 if (!Type->isPointerType())
721 return ExprError(Diag(StartLoc, diag::err_delete_operand)
722 << Type << Ex->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000723
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000724 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorcde3a2d2009-03-24 20:13:58 +0000725 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000726 return ExprError(Diag(StartLoc, diag::err_delete_operand)
727 << Type << Ex->getSourceRange());
Douglas Gregorcde3a2d2009-03-24 20:13:58 +0000728 else if (!Pointee->isDependentType() &&
729 RequireCompleteType(StartLoc, Pointee,
730 diag::warn_delete_incomplete,
731 Ex->getSourceRange()))
732 return ExprError();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000733
Anders Carlsson44443f82009-08-16 20:29:29 +0000734 // FIXME: This should be shared with the code for finding the delete
735 // operator in ActOnCXXNew.
736 IntegerLiteral Size(llvm::APInt::getNullValue(
737 Context.Target.getPointerWidth(0)),
738 Context.getSizeType(),
739 SourceLocation());
740 ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy),
741 CastExpr::CK_Unknown, &Size, false);
742 Expr *DeleteArg = &Cast;
743
744 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
745 ArrayForm ? OO_Array_Delete : OO_Delete);
746
747 if (Pointee->isRecordType() && !UseGlobal) {
748 CXXRecordDecl *Record
749 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
750 // FIXME: We fail to find inherited overloads.
751 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
752 &DeleteArg, 1, Record, /*AllowMissing=*/true,
753 OperatorDelete))
754 return ExprError();
755 }
756
757 if (!OperatorDelete) {
758 // Didn't find a member overload. Look for a global one.
759 DeclareGlobalNewDelete();
760 DeclContext *TUDecl = Context.getTranslationUnitDecl();
761 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
762 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false,
763 OperatorDelete))
764 return ExprError();
765 }
766
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000767 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000768 }
769
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000770 Operand.release();
771 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlsson44443f82009-08-16 20:29:29 +0000772 OperatorDelete, Ex, StartLoc));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000773}
774
775
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000776/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
777/// C++ if/switch/while/for statement.
778/// e.g: "if (int x = f()) {...}"
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000779Action::OwningExprResult
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000780Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
781 Declarator &D,
782 SourceLocation EqualLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000783 ExprArg AssignExprVal) {
784 assert(AssignExprVal.get() && "Null assignment expression");
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000785
786 // C++ 6.4p2:
787 // The declarator shall not specify a function or an array.
788 // The type-specifier-seq shall not contain typedef and shall not declare a
789 // new class or enumeration.
790
791 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
792 "Parser allowed 'typedef' as storage class of condition decl.");
793
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000794 // FIXME: Store DeclaratorInfo in the expression.
795 DeclaratorInfo *DInfo = 0;
Argiris Kirtzidis40688ad2009-08-11 05:20:41 +0000796 TagDecl *OwnedTag = 0;
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000797 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000798
799 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
800 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
801 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000802 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
803 << SourceRange(StartLoc, EqualLoc));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000804 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattner9d2cf082008-11-19 05:27:50 +0000805 Diag(StartLoc, diag::err_invalid_use_of_array_type)
806 << SourceRange(StartLoc, EqualLoc);
Argiris Kirtzidis40688ad2009-08-11 05:20:41 +0000807 } else if (OwnedTag && OwnedTag->isDefinition()) {
808 // The type-specifier-seq shall not declare a new class or enumeration.
809 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000810 }
811
Douglas Gregore153fcf2009-06-23 21:43:56 +0000812 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000813 if (!Dcl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000814 return ExprError();
Anders Carlssonf9f05b82009-05-30 21:37:25 +0000815 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000816
Douglas Gregor48840c72008-12-10 23:01:14 +0000817 // Mark this variable as one that is declared within a conditional.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000818 // We know that the decl had to be a VarDecl because that is the only type of
819 // decl that can be assigned and the grammar requires an '='.
820 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
821 VD->setDeclaredInCondition(true);
822 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000823}
824
825/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
826bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
827 // C++ 6.4p4:
828 // The value of a condition that is an initialized declaration in a statement
829 // other than a switch statement is the value of the declared variable
830 // implicitly converted to type bool. If that conversion is ill-formed, the
831 // program is ill-formed.
832 // The value of a condition that is an expression is the value of the
833 // expression, implicitly converted to bool.
834 //
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000835 return PerformContextuallyConvertToBool(CondExpr);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000836}
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000837
838/// Helper function to determine whether this is the (deprecated) C++
839/// conversion from a string literal to a pointer to non-const char or
840/// non-const wchar_t (for narrow and wide string literals,
841/// respectively).
842bool
843Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
844 // Look inside the implicit cast, if it exists.
845 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
846 From = Cast->getSubExpr();
847
848 // A string literal (2.13.4) that is not a wide string literal can
849 // be converted to an rvalue of type "pointer to char"; a wide
850 // string literal can be converted to an rvalue of type "pointer
851 // to wchar_t" (C++ 4.2p2).
852 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000853 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000854 if (const BuiltinType *ToPointeeType
855 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
856 // This conversion is considered only when there is an
857 // explicit appropriate pointer target type (C++ 4.2p2).
858 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
859 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
860 (!StrLit->isWide() &&
861 (ToPointeeType->getKind() == BuiltinType::Char_U ||
862 ToPointeeType->getKind() == BuiltinType::Char_S))))
863 return true;
864 }
865
866 return false;
867}
Douglas Gregorbb461502008-10-24 04:54:22 +0000868
869/// PerformImplicitConversion - Perform an implicit conversion of the
870/// expression From to the type ToType. Returns true if there was an
871/// error, false otherwise. The expression From is replaced with the
Douglas Gregor6fd35572008-12-19 17:40:08 +0000872/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000873/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redla55834a2009-04-12 17:16:29 +0000874/// explicit user-defined conversions are permitted. @p Elidable should be true
875/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
876/// resolution works differently in that case.
877bool
Douglas Gregor6fd35572008-12-19 17:40:08 +0000878Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +0000879 const char *Flavor, bool AllowExplicit,
880 bool Elidable)
Douglas Gregorbb461502008-10-24 04:54:22 +0000881{
Sebastian Redla55834a2009-04-12 17:16:29 +0000882 ImplicitConversionSequence ICS;
883 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
884 if (Elidable && getLangOptions().CPlusPlus0x) {
885 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
886 AllowExplicit, /*ForceRValue*/true);
887 }
888 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
889 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
890 }
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000891 return PerformImplicitConversion(From, ToType, ICS, Flavor);
892}
893
894/// PerformImplicitConversion - Perform an implicit conversion of the
895/// expression From to the type ToType using the pre-computed implicit
896/// conversion sequence ICS. Returns true if there was an error, false
897/// otherwise. The expression From is replaced with the converted
898/// expression. Flavor is the kind of conversion we're performing,
899/// used in the error message.
900bool
901Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
902 const ImplicitConversionSequence &ICS,
903 const char* Flavor) {
Douglas Gregorbb461502008-10-24 04:54:22 +0000904 switch (ICS.ConversionKind) {
905 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor6fd35572008-12-19 17:40:08 +0000906 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregorbb461502008-10-24 04:54:22 +0000907 return true;
908 break;
909
910 case ImplicitConversionSequence::UserDefinedConversion:
Fariborz Jahanianc3e81132009-08-26 20:34:58 +0000911 // FIXME. Support other kinds of user defined convesions.
912 if (CXXConversionDecl *CV =
913 dyn_cast<CXXConversionDecl>(ICS.UserDefined.ConversionFunction))
914 // FIXME. Get actual Source Location.
915 From =
916 new (Context) CXXFunctionalCastExpr(ToType.getNonReferenceType(),
917 ToType, SourceLocation(),
918 CastExpr::CK_UserDefinedConversion,
919 From, CV,
920 SourceLocation());
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000921 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +0000922 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +0000923 ToType->isLValueReferenceType());
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000924 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000925
926 case ImplicitConversionSequence::EllipsisConversion:
927 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000928 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000929
930 case ImplicitConversionSequence::BadConversion:
931 return true;
932 }
933
934 // Everything went well.
935 return false;
936}
937
938/// PerformImplicitConversion - Perform an implicit conversion of the
939/// expression From to the type ToType by following the standard
940/// conversion sequence SCS. Returns true if there was an error, false
941/// otherwise. The expression From is replaced with the converted
Douglas Gregor6fd35572008-12-19 17:40:08 +0000942/// expression. Flavor is the context in which we're performing this
943/// conversion, for use in error messages.
Douglas Gregorbb461502008-10-24 04:54:22 +0000944bool
945Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000946 const StandardConversionSequence& SCS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000947 const char *Flavor) {
Mike Stumpe127ae32009-05-16 07:39:55 +0000948 // Overall FIXME: we are recomputing too many types here and doing far too
949 // much extra work. What this means is that we need to keep track of more
950 // information that is computed when we try the implicit conversion initially,
951 // so that we don't need to recompute anything here.
Douglas Gregorbb461502008-10-24 04:54:22 +0000952 QualType FromType = From->getType();
953
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000954 if (SCS.CopyConstructor) {
Anders Carlsson0e098352009-05-19 04:45:15 +0000955 // FIXME: When can ToType be a reference type?
956 assert(!ToType->isReferenceType());
957
Anders Carlsson665e4692009-08-25 05:12:04 +0000958 OwningExprResult FromResult =
959 BuildCXXConstructExpr(ToType, SCS.CopyConstructor, &From, 1);
960
961 if (FromResult.isInvalid())
962 return true;
963
964 From = FromResult.takeAs<Expr>();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000965 return false;
966 }
967
Douglas Gregorbb461502008-10-24 04:54:22 +0000968 // Perform the first implicit conversion.
969 switch (SCS.First) {
970 case ICK_Identity:
971 case ICK_Lvalue_To_Rvalue:
972 // Nothing to do.
973 break;
974
975 case ICK_Array_To_Pointer:
Douglas Gregoraa57e862009-02-18 21:56:37 +0000976 FromType = Context.getArrayDecayedType(FromType);
Anders Carlssond6e11722009-08-08 21:04:35 +0000977 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregoraa57e862009-02-18 21:56:37 +0000978 break;
979
980 case ICK_Function_To_Pointer:
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000981 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor45014fd2008-11-10 20:40:00 +0000982 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
983 if (!Fn)
984 return true;
985
Douglas Gregoraa57e862009-02-18 21:56:37 +0000986 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
987 return true;
988
Douglas Gregor45014fd2008-11-10 20:40:00 +0000989 FixOverloadedFunctionReference(From, Fn);
990 FromType = From->getType();
Douglas Gregor45014fd2008-11-10 20:40:00 +0000991 }
Douglas Gregorbb461502008-10-24 04:54:22 +0000992 FromType = Context.getPointerType(FromType);
993 ImpCastExprToType(From, FromType);
994 break;
995
996 default:
997 assert(false && "Improper first standard conversion");
998 break;
999 }
1000
1001 // Perform the second implicit conversion
1002 switch (SCS.Second) {
1003 case ICK_Identity:
1004 // Nothing to do.
1005 break;
1006
1007 case ICK_Integral_Promotion:
1008 case ICK_Floating_Promotion:
Douglas Gregore819caf2009-02-12 00:15:05 +00001009 case ICK_Complex_Promotion:
Douglas Gregorbb461502008-10-24 04:54:22 +00001010 case ICK_Integral_Conversion:
1011 case ICK_Floating_Conversion:
Douglas Gregore819caf2009-02-12 00:15:05 +00001012 case ICK_Complex_Conversion:
Douglas Gregorbb461502008-10-24 04:54:22 +00001013 case ICK_Floating_Integral:
Douglas Gregore819caf2009-02-12 00:15:05 +00001014 case ICK_Complex_Real:
Douglas Gregorfcb19192009-02-11 23:02:49 +00001015 case ICK_Compatible_Conversion:
1016 // FIXME: Go deeper to get the unqualified type!
Douglas Gregorbb461502008-10-24 04:54:22 +00001017 FromType = ToType.getUnqualifiedType();
1018 ImpCastExprToType(From, FromType);
1019 break;
1020
1021 case ICK_Pointer_Conversion:
Douglas Gregor6fd35572008-12-19 17:40:08 +00001022 if (SCS.IncompatibleObjC) {
1023 // Diagnose incompatible Objective-C conversions
1024 Diag(From->getSourceRange().getBegin(),
1025 diag::ext_typecheck_convert_incompatible_pointer)
1026 << From->getType() << ToType << Flavor
1027 << From->getSourceRange();
1028 }
1029
Douglas Gregorbb461502008-10-24 04:54:22 +00001030 if (CheckPointerConversion(From, ToType))
1031 return true;
1032 ImpCastExprToType(From, ToType);
1033 break;
1034
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001035 case ICK_Pointer_Member: {
1036 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1037 if (CheckMemberPointerConversion(From, ToType, Kind))
1038 return true;
1039 ImpCastExprToType(From, ToType, Kind);
1040 break;
1041 }
Douglas Gregorbb461502008-10-24 04:54:22 +00001042 case ICK_Boolean_Conversion:
1043 FromType = Context.BoolTy;
1044 ImpCastExprToType(From, FromType);
1045 break;
1046
1047 default:
1048 assert(false && "Improper second standard conversion");
1049 break;
1050 }
1051
1052 switch (SCS.Third) {
1053 case ICK_Identity:
1054 // Nothing to do.
1055 break;
1056
1057 case ICK_Qualification:
Mike Stumpe127ae32009-05-16 07:39:55 +00001058 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1059 // references.
Douglas Gregor5ac8ffa2009-01-16 19:38:23 +00001060 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +00001061 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +00001062 ToType->isLValueReferenceType());
Douglas Gregorbb461502008-10-24 04:54:22 +00001063 break;
1064
1065 default:
1066 assert(false && "Improper second standard conversion");
1067 break;
1068 }
1069
1070 return false;
1071}
1072
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001073Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1074 SourceLocation KWLoc,
1075 SourceLocation LParen,
1076 TypeTy *Ty,
1077 SourceLocation RParen) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001078 QualType T = GetTypeFromParser(Ty);
Anders Carlsson1b749a02009-07-07 19:06:02 +00001079
1080 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1081 // all traits except __is_class, __is_enum and __is_union require a the type
1082 // to be complete.
1083 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1084 if (RequireCompleteType(KWLoc, T,
Anders Carlssonb5247af2009-08-26 22:59:12 +00001085 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1b749a02009-07-07 19:06:02 +00001086 return ExprError();
1087 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001088
1089 // There is no point in eagerly computing the value. The traits are designed
1090 // to be used from type trait templates, so Ty will be a template parameter
1091 // 99% of the time.
Anders Carlsson1b749a02009-07-07 19:06:02 +00001092 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1093 RParen, Context.BoolTy));
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001094}
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001095
1096QualType Sema::CheckPointerToMemberOperands(
1097 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
1098{
1099 const char *OpSpelling = isIndirect ? "->*" : ".*";
1100 // C++ 5.5p2
1101 // The binary operator .* [p3: ->*] binds its second operand, which shall
1102 // be of type "pointer to member of T" (where T is a completely-defined
1103 // class type) [...]
1104 QualType RType = rex->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001105 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregor05e28f62009-03-24 19:52:54 +00001106 if (!MemPtr) {
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001107 Diag(Loc, diag::err_bad_memptr_rhs)
1108 << OpSpelling << RType << rex->getSourceRange();
1109 return QualType();
Douglas Gregor96b6df92009-05-14 00:28:11 +00001110 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00001111
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001112 QualType Class(MemPtr->getClass(), 0);
1113
1114 // C++ 5.5p2
1115 // [...] to its first operand, which shall be of class T or of a class of
1116 // which T is an unambiguous and accessible base class. [p3: a pointer to
1117 // such a class]
1118 QualType LType = lex->getType();
1119 if (isIndirect) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001120 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001121 LType = Ptr->getPointeeType().getNonReferenceType();
1122 else {
1123 Diag(Loc, diag::err_bad_memptr_lhs)
1124 << OpSpelling << 1 << LType << lex->getSourceRange();
1125 return QualType();
1126 }
1127 }
1128
1129 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1130 Context.getCanonicalType(LType).getUnqualifiedType()) {
1131 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1132 /*DetectVirtual=*/false);
Mike Stumpe127ae32009-05-16 07:39:55 +00001133 // FIXME: Would it be useful to print full ambiguity paths, or is that
1134 // overkill?
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001135 if (!IsDerivedFrom(LType, Class, Paths) ||
1136 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1137 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1138 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1139 return QualType();
1140 }
1141 }
1142
1143 // C++ 5.5p2
1144 // The result is an object or a function of the type specified by the
1145 // second operand.
1146 // The cv qualifiers are the union of those in the pointer and the left side,
1147 // in accordance with 5.5p5 and 5.2.5.
1148 // FIXME: This returns a dereferenced member function pointer as a normal
1149 // function type. However, the only operation valid on such functions is
Mike Stumpe127ae32009-05-16 07:39:55 +00001150 // calling them. There's also a GCC extension to get a function pointer to the
1151 // thing, which is another complication, because this type - unlike the type
1152 // that is the result of this expression - takes the class as the first
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001153 // argument.
1154 // We probably need a "MemberFunctionClosureType" or something like that.
1155 QualType Result = MemPtr->getPointeeType();
1156 if (LType.isConstQualified())
1157 Result.addConst();
1158 if (LType.isVolatileQualified())
1159 Result.addVolatile();
1160 return Result;
1161}
Sebastian Redlbd261962009-04-16 17:51:27 +00001162
1163/// \brief Get the target type of a standard or user-defined conversion.
1164static QualType TargetType(const ImplicitConversionSequence &ICS) {
1165 assert((ICS.ConversionKind ==
1166 ImplicitConversionSequence::StandardConversion ||
1167 ICS.ConversionKind ==
1168 ImplicitConversionSequence::UserDefinedConversion) &&
1169 "function only valid for standard or user-defined conversions");
1170 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1171 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1172 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1173}
1174
1175/// \brief Try to convert a type to another according to C++0x 5.16p3.
1176///
1177/// This is part of the parameter validation for the ? operator. If either
1178/// value operand is a class type, the two operands are attempted to be
1179/// converted to each other. This function does the conversion in one direction.
1180/// It emits a diagnostic and returns true only if it finds an ambiguous
1181/// conversion.
1182static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1183 SourceLocation QuestionLoc,
1184 ImplicitConversionSequence &ICS)
1185{
1186 // C++0x 5.16p3
1187 // The process for determining whether an operand expression E1 of type T1
1188 // can be converted to match an operand expression E2 of type T2 is defined
1189 // as follows:
1190 // -- If E2 is an lvalue:
1191 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1192 // E1 can be converted to match E2 if E1 can be implicitly converted to
1193 // type "lvalue reference to T2", subject to the constraint that in the
1194 // conversion the reference must bind directly to E1.
1195 if (!Self.CheckReferenceInit(From,
1196 Self.Context.getLValueReferenceType(To->getType()),
1197 &ICS))
1198 {
1199 assert((ICS.ConversionKind ==
1200 ImplicitConversionSequence::StandardConversion ||
1201 ICS.ConversionKind ==
1202 ImplicitConversionSequence::UserDefinedConversion) &&
1203 "expected a definite conversion");
1204 bool DirectBinding =
1205 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1206 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1207 if (DirectBinding)
1208 return false;
1209 }
1210 }
1211 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1212 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1213 // -- if E1 and E2 have class type, and the underlying class types are
1214 // the same or one is a base class of the other:
1215 QualType FTy = From->getType();
1216 QualType TTy = To->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001217 const RecordType *FRec = FTy->getAs<RecordType>();
1218 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redlbd261962009-04-16 17:51:27 +00001219 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1220 if (FRec && TRec && (FRec == TRec ||
1221 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1222 // E1 can be converted to match E2 if the class of T2 is the
1223 // same type as, or a base class of, the class of T1, and
1224 // [cv2 > cv1].
1225 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1226 // Could still fail if there's no copy constructor.
1227 // FIXME: Is this a hard error then, or just a conversion failure? The
1228 // standard doesn't say.
1229 ICS = Self.TryCopyInitialization(From, TTy);
1230 }
1231 } else {
1232 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1233 // implicitly converted to the type that expression E2 would have
1234 // if E2 were converted to an rvalue.
1235 // First find the decayed type.
1236 if (TTy->isFunctionType())
1237 TTy = Self.Context.getPointerType(TTy);
1238 else if(TTy->isArrayType())
1239 TTy = Self.Context.getArrayDecayedType(TTy);
1240
1241 // Now try the implicit conversion.
1242 // FIXME: This doesn't detect ambiguities.
1243 ICS = Self.TryImplicitConversion(From, TTy);
1244 }
1245 return false;
1246}
1247
1248/// \brief Try to find a common type for two according to C++0x 5.16p5.
1249///
1250/// This is part of the parameter validation for the ? operator. If either
1251/// value operand is a class type, overload resolution is used to find a
1252/// conversion to a common type.
1253static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1254 SourceLocation Loc) {
1255 Expr *Args[2] = { LHS, RHS };
1256 OverloadCandidateSet CandidateSet;
1257 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1258
1259 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001260 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00001261 case Sema::OR_Success:
1262 // We found a match. Perform the conversions on the arguments and move on.
1263 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1264 Best->Conversions[0], "converting") ||
1265 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1266 Best->Conversions[1], "converting"))
1267 break;
1268 return false;
1269
1270 case Sema::OR_No_Viable_Function:
1271 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1272 << LHS->getType() << RHS->getType()
1273 << LHS->getSourceRange() << RHS->getSourceRange();
1274 return true;
1275
1276 case Sema::OR_Ambiguous:
1277 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1278 << LHS->getType() << RHS->getType()
1279 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpe127ae32009-05-16 07:39:55 +00001280 // FIXME: Print the possible common types by printing the return types of
1281 // the viable candidates.
Sebastian Redlbd261962009-04-16 17:51:27 +00001282 break;
1283
1284 case Sema::OR_Deleted:
1285 assert(false && "Conditional operator has only built-in overloads");
1286 break;
1287 }
1288 return true;
1289}
1290
Sebastian Redld3169132009-04-17 16:30:52 +00001291/// \brief Perform an "extended" implicit conversion as returned by
1292/// TryClassUnification.
1293///
1294/// TryClassUnification generates ICSs that include reference bindings.
1295/// PerformImplicitConversion is not suitable for this; it chokes if the
1296/// second part of a standard conversion is ICK_DerivedToBase. This function
1297/// handles the reference binding specially.
1298static bool ConvertForConditional(Sema &Self, Expr *&E,
1299 const ImplicitConversionSequence &ICS)
1300{
1301 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1302 ICS.Standard.ReferenceBinding) {
1303 assert(ICS.Standard.DirectBinding &&
1304 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf6b86182009-04-26 11:21:02 +00001305 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1306 // redoing all the work.
1307 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1308 TargetType(ICS)));
Sebastian Redld3169132009-04-17 16:30:52 +00001309 }
1310 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1311 ICS.UserDefined.After.ReferenceBinding) {
1312 assert(ICS.UserDefined.After.DirectBinding &&
1313 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf6b86182009-04-26 11:21:02 +00001314 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1315 TargetType(ICS)));
Sebastian Redld3169132009-04-17 16:30:52 +00001316 }
1317 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1318 return true;
1319 return false;
1320}
1321
Sebastian Redlbd261962009-04-16 17:51:27 +00001322/// \brief Check the operands of ?: under C++ semantics.
1323///
1324/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1325/// extension. In this case, LHS == Cond. (But they're not aliases.)
1326QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1327 SourceLocation QuestionLoc) {
Mike Stumpe127ae32009-05-16 07:39:55 +00001328 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1329 // interface pointers.
Sebastian Redlbd261962009-04-16 17:51:27 +00001330
1331 // C++0x 5.16p1
1332 // The first expression is contextually converted to bool.
1333 if (!Cond->isTypeDependent()) {
1334 if (CheckCXXBooleanCondition(Cond))
1335 return QualType();
1336 }
1337
1338 // Either of the arguments dependent?
1339 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1340 return Context.DependentTy;
1341
1342 // C++0x 5.16p2
1343 // If either the second or the third operand has type (cv) void, ...
1344 QualType LTy = LHS->getType();
1345 QualType RTy = RHS->getType();
1346 bool LVoid = LTy->isVoidType();
1347 bool RVoid = RTy->isVoidType();
1348 if (LVoid || RVoid) {
1349 // ... then the [l2r] conversions are performed on the second and third
1350 // operands ...
1351 DefaultFunctionArrayConversion(LHS);
1352 DefaultFunctionArrayConversion(RHS);
1353 LTy = LHS->getType();
1354 RTy = RHS->getType();
1355
1356 // ... and one of the following shall hold:
1357 // -- The second or the third operand (but not both) is a throw-
1358 // expression; the result is of the type of the other and is an rvalue.
1359 bool LThrow = isa<CXXThrowExpr>(LHS);
1360 bool RThrow = isa<CXXThrowExpr>(RHS);
1361 if (LThrow && !RThrow)
1362 return RTy;
1363 if (RThrow && !LThrow)
1364 return LTy;
1365
1366 // -- Both the second and third operands have type void; the result is of
1367 // type void and is an rvalue.
1368 if (LVoid && RVoid)
1369 return Context.VoidTy;
1370
1371 // Neither holds, error.
1372 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1373 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1374 << LHS->getSourceRange() << RHS->getSourceRange();
1375 return QualType();
1376 }
1377
1378 // Neither is void.
1379
1380 // C++0x 5.16p3
1381 // Otherwise, if the second and third operand have different types, and
1382 // either has (cv) class type, and attempt is made to convert each of those
1383 // operands to the other.
1384 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1385 (LTy->isRecordType() || RTy->isRecordType())) {
1386 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1387 // These return true if a single direction is already ambiguous.
1388 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1389 return QualType();
1390 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1391 return QualType();
1392
1393 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1394 ImplicitConversionSequence::BadConversion;
1395 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1396 ImplicitConversionSequence::BadConversion;
1397 // If both can be converted, [...] the program is ill-formed.
1398 if (HaveL2R && HaveR2L) {
1399 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1400 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1401 return QualType();
1402 }
1403
1404 // If exactly one conversion is possible, that conversion is applied to
1405 // the chosen operand and the converted operands are used in place of the
1406 // original operands for the remainder of this section.
1407 if (HaveL2R) {
Sebastian Redld3169132009-04-17 16:30:52 +00001408 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redlbd261962009-04-16 17:51:27 +00001409 return QualType();
1410 LTy = LHS->getType();
1411 } else if (HaveR2L) {
Sebastian Redld3169132009-04-17 16:30:52 +00001412 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redlbd261962009-04-16 17:51:27 +00001413 return QualType();
1414 RTy = RHS->getType();
1415 }
1416 }
1417
1418 // C++0x 5.16p4
1419 // If the second and third operands are lvalues and have the same type,
1420 // the result is of that type [...]
1421 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1422 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1423 RHS->isLvalue(Context) == Expr::LV_Valid)
1424 return LTy;
1425
1426 // C++0x 5.16p5
1427 // Otherwise, the result is an rvalue. If the second and third operands
1428 // do not have the same type, and either has (cv) class type, ...
1429 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1430 // ... overload resolution is used to determine the conversions (if any)
1431 // to be applied to the operands. If the overload resolution fails, the
1432 // program is ill-formed.
1433 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1434 return QualType();
1435 }
1436
1437 // C++0x 5.16p6
1438 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1439 // conversions are performed on the second and third operands.
1440 DefaultFunctionArrayConversion(LHS);
1441 DefaultFunctionArrayConversion(RHS);
1442 LTy = LHS->getType();
1443 RTy = RHS->getType();
1444
1445 // After those conversions, one of the following shall hold:
1446 // -- The second and third operands have the same type; the result
1447 // is of that type.
1448 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1449 return LTy;
1450
1451 // -- The second and third operands have arithmetic or enumeration type;
1452 // the usual arithmetic conversions are performed to bring them to a
1453 // common type, and the result is of that type.
1454 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1455 UsualArithmeticConversions(LHS, RHS);
1456 return LHS->getType();
1457 }
1458
1459 // -- The second and third operands have pointer type, or one has pointer
1460 // type and the other is a null pointer constant; pointer conversions
1461 // and qualification conversions are performed to bring them to their
1462 // composite pointer type. The result is of the composite pointer type.
Sebastian Redl42b81a22009-04-19 19:26:31 +00001463 QualType Composite = FindCompositePointerType(LHS, RHS);
1464 if (!Composite.isNull())
1465 return Composite;
Sebastian Redlbd261962009-04-16 17:51:27 +00001466
Sebastian Redl5b3fcf82009-04-19 21:15:26 +00001467 // Fourth bullet is same for pointers-to-member. However, the possible
1468 // conversions are far more limited: we have null-to-pointer, upcast of
1469 // containing class, and second-level cv-ness.
1470 // cv-ness is not a union, but must match one of the two operands. (Which,
1471 // frankly, is stupid.)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001472 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1473 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Sebastian Redl5b3fcf82009-04-19 21:15:26 +00001474 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1475 ImpCastExprToType(RHS, LTy);
1476 return LTy;
1477 }
1478 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1479 ImpCastExprToType(LHS, RTy);
1480 return RTy;
1481 }
1482 if (LMemPtr && RMemPtr) {
1483 QualType LPointee = LMemPtr->getPointeeType();
1484 QualType RPointee = RMemPtr->getPointeeType();
1485 // First, we check that the unqualified pointee type is the same. If it's
1486 // not, there's no conversion that will unify the two pointers.
1487 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1488 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1489 // Second, we take the greater of the two cv qualifications. If neither
1490 // is greater than the other, the conversion is not possible.
1491 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1492 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1493 // Third, we check if either of the container classes is derived from
1494 // the other.
1495 QualType LContainer(LMemPtr->getClass(), 0);
1496 QualType RContainer(RMemPtr->getClass(), 0);
1497 QualType MoreDerived;
1498 if (Context.getCanonicalType(LContainer) ==
1499 Context.getCanonicalType(RContainer))
1500 MoreDerived = LContainer;
1501 else if (IsDerivedFrom(LContainer, RContainer))
1502 MoreDerived = LContainer;
1503 else if (IsDerivedFrom(RContainer, LContainer))
1504 MoreDerived = RContainer;
1505
1506 if (!MoreDerived.isNull()) {
1507 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1508 // We don't use ImpCastExprToType here because this could still fail
1509 // for ambiguous or inaccessible conversions.
1510 QualType Common = Context.getMemberPointerType(
1511 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1512 if (PerformImplicitConversion(LHS, Common, "converting"))
1513 return QualType();
1514 if (PerformImplicitConversion(RHS, Common, "converting"))
1515 return QualType();
1516 return Common;
1517 }
1518 }
1519 }
1520 }
1521
Sebastian Redlbd261962009-04-16 17:51:27 +00001522 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1523 << LHS->getType() << RHS->getType()
1524 << LHS->getSourceRange() << RHS->getSourceRange();
1525 return QualType();
1526}
Sebastian Redl42b81a22009-04-19 19:26:31 +00001527
1528/// \brief Find a merged pointer type and convert the two expressions to it.
1529///
Douglas Gregor70be4db2009-08-24 17:42:35 +00001530/// This finds the composite pointer type (or member pointer type) for @p E1
1531/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1532/// type and returns it.
Sebastian Redl42b81a22009-04-19 19:26:31 +00001533/// It does not emit diagnostics.
1534QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1535 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1536 QualType T1 = E1->getType(), T2 = E2->getType();
Douglas Gregor70be4db2009-08-24 17:42:35 +00001537
1538 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1539 !T2->isPointerType() && !T2->isMemberPointerType())
1540 return QualType();
Sebastian Redl42b81a22009-04-19 19:26:31 +00001541
Douglas Gregor70be4db2009-08-24 17:42:35 +00001542 // FIXME: Do we need to work on the canonical types?
1543
Sebastian Redl42b81a22009-04-19 19:26:31 +00001544 // C++0x 5.9p2
1545 // Pointer conversions and qualification conversions are performed on
1546 // pointer operands to bring them to their composite pointer type. If
1547 // one operand is a null pointer constant, the composite pointer type is
1548 // the type of the other operand.
1549 if (E1->isNullPointerConstant(Context)) {
1550 ImpCastExprToType(E1, T2);
1551 return T2;
1552 }
1553 if (E2->isNullPointerConstant(Context)) {
1554 ImpCastExprToType(E2, T1);
1555 return T1;
1556 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00001557
1558 // Now both have to be pointers or member pointers.
1559 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1560 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redl42b81a22009-04-19 19:26:31 +00001561 return QualType();
1562
1563 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1564 // the other has type "pointer to cv2 T" and the composite pointer type is
1565 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1566 // Otherwise, the composite pointer type is a pointer type similar to the
1567 // type of one of the operands, with a cv-qualification signature that is
1568 // the union of the cv-qualification signatures of the operand types.
1569 // In practice, the first part here is redundant; it's subsumed by the second.
1570 // What we do here is, we build the two possible composite types, and try the
1571 // conversions in both directions. If only one works, or if the two composite
1572 // types are the same, we have succeeded.
1573 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregor70be4db2009-08-24 17:42:35 +00001574 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redl42b81a22009-04-19 19:26:31 +00001575 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregor70be4db2009-08-24 17:42:35 +00001576 do {
1577 const PointerType *Ptr1, *Ptr2;
1578 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1579 (Ptr2 = Composite2->getAs<PointerType>())) {
1580 Composite1 = Ptr1->getPointeeType();
1581 Composite2 = Ptr2->getPointeeType();
1582 QualifierUnion.push_back(
1583 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1584 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1585 continue;
1586 }
1587
1588 const MemberPointerType *MemPtr1, *MemPtr2;
1589 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1590 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1591 Composite1 = MemPtr1->getPointeeType();
1592 Composite2 = MemPtr2->getPointeeType();
1593 QualifierUnion.push_back(
1594 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1595 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1596 MemPtr2->getClass()));
1597 continue;
1598 }
1599
1600 // FIXME: block pointer types?
1601
1602 // Cannot unwrap any more types.
1603 break;
1604 } while (true);
1605
1606 // Rewrap the composites as pointers or member pointers with the union CVRs.
1607 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1608 = MemberOfClass.begin();
1609 for (llvm::SmallVector<unsigned, 4>::iterator
1610 I = QualifierUnion.begin(),
1611 E = QualifierUnion.end();
1612 I != E; (void)++I, ++MOC) {
1613 if (MOC->first && MOC->second) {
1614 // Rebuild member pointer type
1615 Composite1 = Context.getMemberPointerType(Composite1.getQualifiedType(*I),
1616 MOC->first);
1617 Composite2 = Context.getMemberPointerType(Composite2.getQualifiedType(*I),
1618 MOC->second);
1619 } else {
1620 // Rebuild pointer type
1621 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1622 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1623 }
Sebastian Redl42b81a22009-04-19 19:26:31 +00001624 }
1625
1626 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1627 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1628 ImplicitConversionSequence E1ToC2, E2ToC2;
1629 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1630 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1631 if (Context.getCanonicalType(Composite1) !=
1632 Context.getCanonicalType(Composite2)) {
1633 E1ToC2 = TryImplicitConversion(E1, Composite2);
1634 E2ToC2 = TryImplicitConversion(E2, Composite2);
1635 }
1636
1637 bool ToC1Viable = E1ToC1.ConversionKind !=
1638 ImplicitConversionSequence::BadConversion
1639 && E2ToC1.ConversionKind !=
1640 ImplicitConversionSequence::BadConversion;
1641 bool ToC2Viable = E1ToC2.ConversionKind !=
1642 ImplicitConversionSequence::BadConversion
1643 && E2ToC2.ConversionKind !=
1644 ImplicitConversionSequence::BadConversion;
1645 if (ToC1Viable && !ToC2Viable) {
1646 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1647 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1648 return Composite1;
1649 }
1650 if (ToC2Viable && !ToC1Viable) {
1651 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1652 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1653 return Composite2;
1654 }
1655 return QualType();
1656}
Anders Carlssonf0967d72009-05-17 18:41:29 +00001657
Anders Carlssona05fa102009-05-30 20:36:53 +00001658Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson1bfe1c42009-08-15 23:41:35 +00001659 if (!Context.getLangOptions().CPlusPlus)
1660 return Owned(E);
1661
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001662 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssona05fa102009-05-30 20:36:53 +00001663 if (!RT)
1664 return Owned(E);
1665
1666 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1667 if (RD->hasTrivialDestructor())
1668 return Owned(E);
1669
1670 CXXTemporary *Temp = CXXTemporary::Create(Context,
1671 RD->getDestructor(Context));
Anders Carlsson1ef0ee92009-05-30 21:21:49 +00001672 ExprTemporaries.push_back(Temp);
Fariborz Jahaniancd208112009-08-03 19:13:25 +00001673 if (CXXDestructorDecl *Destructor =
1674 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1675 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssona05fa102009-05-30 20:36:53 +00001676 // FIXME: Add the temporary to the temporaries vector.
1677 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1678}
1679
Anders Carlsson8f75fbc2009-06-05 15:38:08 +00001680Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00001681 bool ShouldDestroyTemps) {
Anders Carlsson8f75fbc2009-06-05 15:38:08 +00001682 assert(SubExpr && "sub expression can't be null!");
1683
1684 if (ExprTemporaries.empty())
1685 return SubExpr;
1686
1687 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1688 &ExprTemporaries[0],
1689 ExprTemporaries.size(),
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00001690 ShouldDestroyTemps);
Anders Carlsson8f75fbc2009-06-05 15:38:08 +00001691 ExprTemporaries.clear();
1692
1693 return E;
1694}
1695
Anders Carlsson093ba8b2009-08-25 23:46:41 +00001696Sema::OwningExprResult
Anders Carlsson691e04e2009-08-26 17:36:19 +00001697Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
Anders Carlsson093ba8b2009-08-25 23:46:41 +00001698 SourceLocation OpLoc,
1699 tok::TokenKind OpKind,
1700 SourceLocation ClassNameLoc,
1701 IdentifierInfo *ClassName,
1702 const CXXScopeSpec *SS) {
1703 if (SS && SS->isInvalid())
1704 return ExprError();
Anders Carlsson3d567482009-08-26 19:22:42 +00001705
1706 Expr *BaseExpr = (Expr *)Base.get();
Anders Carlsson093ba8b2009-08-25 23:46:41 +00001707
Anders Carlsson3d567482009-08-26 19:22:42 +00001708 if (BaseExpr->isTypeDependent() ||
1709 (SS && isDependentScopeSpecifier(*SS))) {
1710 // FIXME: Return an unresolved ref expr.
1711 return ExprError();
1712 }
1713
1714 TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, SS);
1715 if (!BaseTy) {
1716 Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
1717 << ClassName;
1718 return ExprError();
1719 }
Anders Carlsson093ba8b2009-08-25 23:46:41 +00001720
Anders Carlsson3d567482009-08-26 19:22:42 +00001721 QualType BaseType = GetTypeFromParser(BaseTy);
1722 if (!BaseType->isRecordType()) {
1723 Diag(ClassNameLoc, diag::err_type_in_pseudo_dtor_not_a_class_type)
1724 << BaseType;
1725 return ExprError();
1726 }
Anders Carlsson093ba8b2009-08-25 23:46:41 +00001727
Anders Carlsson3d567482009-08-26 19:22:42 +00001728 CanQualType CanBaseType = Context.getCanonicalType(BaseType);
1729 DeclarationName DtorName =
1730 Context.DeclarationNames.getCXXDestructorName(CanBaseType);
1731
1732 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1733 DtorName, DeclPtrTy(), SS);
Anders Carlsson093ba8b2009-08-25 23:46:41 +00001734}
1735
Anders Carlssonf0967d72009-05-17 18:41:29 +00001736Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1737 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson8f75fbc2009-06-05 15:38:08 +00001738 if (FullExpr)
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00001739 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
1740 /*ShouldDestroyTemps=*/true);
Anders Carlssonf0967d72009-05-17 18:41:29 +00001741
Anders Carlsson093ba8b2009-08-25 23:46:41 +00001742
Anders Carlssonf0967d72009-05-17 18:41:29 +00001743 return Owned(FullExpr);
1744}