blob: 12f60b99c61a76df1515b9b87bae90415fcfdee8 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
Sebastian Redl7c8bd602009-02-07 20:10:22 +000014#include "SemaInherit.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "Sema.h"
Steve Naroff210679c2007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000017#include "clang/AST/ExprCXX.h"
18#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000022#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24
Douglas Gregor487a75a2008-11-19 19:09:45 +000025/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregor2def4832008-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 Redlcd965b92009-01-18 18:53:16 +000030Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000031Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
32 TypeTy *Ty, bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000033 const CXXScopeSpec &SS,
34 bool isAddressOfOperand) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000035 //FIXME: Preserve type source info.
36 QualType ConvType = GetTypeFromParser(Ty);
Douglas Gregor50d62d12009-08-05 05:36:45 +000037 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
Douglas Gregor2def4832008-11-17 20:34:05 +000038 DeclarationName ConvName
39 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd965b92009-01-18 18:53:16 +000040 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +000041 &SS, isAddressOfOperand);
Douglas Gregor2def4832008-11-17 20:34:05 +000042}
Sebastian Redlc42e1182008-11-11 11:37:55 +000043
Douglas Gregor487a75a2008-11-19 19:09:45 +000044/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-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 Redlcd965b92009-01-18 18:53:16 +000049Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000050Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
51 OverloadedOperatorKind Op,
52 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000053 const CXXScopeSpec &SS,
54 bool isAddressOfOperand) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000055 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redlebc07d52009-02-03 20:19:35 +000056 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor17330012009-02-04 15:01:18 +000057 isAddressOfOperand);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000058}
59
Sebastian Redlc42e1182008-11-11 11:37:55 +000060/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000061Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000062Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
63 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +000064 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000065 if (!StdNs)
Sebastian Redlf53597f2009-03-15 17:47:39 +000066 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000067
68 if (isType)
69 // FIXME: Preserve type source info.
70 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
71
Chris Lattner572af492008-11-20 05:51:55 +000072 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor4c921ae2009-01-30 01:04:22 +000073 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlc42e1182008-11-11 11:37:55 +000074 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000075 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000076 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000077
78 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
79
Douglas Gregorac7610d2009-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 Kremenek6217b802009-07-29 21:53:49 +000092 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-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 Redlf53597f2009-03-15 17:47:39 +0000105 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
106 TypeInfoType.withConst(),
107 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000108}
109
Steve Naroff1b273c42007-09-16 14:56:35 +0000110/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000111Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000112Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000113 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000114 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000115 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
116 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000117}
Chris Lattner50dd2892008-02-26 00:51:44 +0000118
Sebastian Redl6e8ed162009-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 Lattner50dd2892008-02-26 00:51:44 +0000125/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000126Action::OwningExprResult
127Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-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 Kremenek6217b802009-07-29 21:53:49 +0000145 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000146 Ty = Ptr->getPointeeType();
147 isPointer = 1;
148 }
149 if (!isPointer || !Ty->isVoidType()) {
150 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000151 PDiag(isPointer ? diag::err_throw_incomplete_ptr
152 : diag::err_throw_incomplete)
153 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000154 return true;
155 }
156
157 // FIXME: Construct a temporary here.
158 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000159}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000160
Sebastian Redlf53597f2009-03-15 17:47:39 +0000161Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-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 Redlf53597f2009-03-15 17:47:39 +0000166 if (!isa<FunctionDecl>(CurContext))
167 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000168
169 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
170 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000171 return Owned(new (Context) CXXThisExpr(ThisLoc,
172 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000173
Sebastian Redlf53597f2009-03-15 17:47:39 +0000174 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000175}
Argyrios Kyrtzidis987a14b2008-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 Redlf53597f2009-03-15 17:47:39 +0000181Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000182Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
183 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000184 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000185 SourceLocation *CommaLocs,
186 SourceLocation RParenLoc) {
187 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000188 // FIXME: Preserve type source info.
189 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000190 unsigned NumExprs = exprs.size();
191 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000192 SourceLocation TyBeginLoc = TypeRange.getBegin();
193 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
194
Sebastian Redlf53597f2009-03-15 17:47:39 +0000195 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000196 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000197 exprs.release();
Anders Carlsson26de5492009-04-24 05:23:13 +0000198
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000199 return Owned(CXXUnresolvedConstructExpr::Create(Context,
200 TypeRange.getBegin(), Ty,
201 LParenLoc,
202 Exprs, NumExprs,
203 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000204 }
205
Anders Carlssonbb60a502009-08-27 03:53:50 +0000206 if (Ty->isArrayType())
207 return ExprError(Diag(TyBeginLoc,
208 diag::err_value_init_for_array_type) << FullRange);
209 if (!Ty->isVoidType() &&
210 RequireCompleteType(TyBeginLoc, Ty,
211 PDiag(diag::err_invalid_incomplete_type_use)
212 << FullRange))
213 return ExprError();
214
215 if (RequireNonAbstractType(TyBeginLoc, Ty,
216 diag::err_allocation_of_abstract_type))
217 return ExprError();
218
219
Douglas Gregor506ae412009-01-16 18:33:17 +0000220 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000221 // If the expression list is a single expression, the type conversion
222 // expression is equivalent (in definedness, and if defined in meaning) to the
223 // corresponding cast expression.
224 //
225 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000226 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000227 CXXMethodDecl *ConversionDecl = 0;
228 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, ConversionDecl,
229 /*functional-style*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000230 return ExprError();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000231 // We done't build this AST for X(i) where we are constructing an object.
232 if (!ConversionDecl || !isa<CXXConstructorDecl>(ConversionDecl)) {
233 exprs.release();
234 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
Fariborz Jahanian9099ff02009-08-26 20:34:58 +0000235 Ty, TyBeginLoc,
236 CastExpr::CK_UserDefinedConversion,
237 Exprs[0], ConversionDecl,
238 RParenLoc));
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000239 }
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000240 }
241
Ted Kremenek6217b802009-07-29 21:53:49 +0000242 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000243 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000244
Anders Carlssone7624a72009-08-27 05:08:22 +0000245 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
246 !Record->hasTrivialDestructor()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000247 CXXConstructorDecl *Constructor
248 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
249 TypeRange.getBegin(),
250 SourceRange(TypeRange.getBegin(),
251 RParenLoc),
252 DeclarationName(),
253 IK_Direct);
Douglas Gregor506ae412009-01-16 18:33:17 +0000254
Sebastian Redlf53597f2009-03-15 17:47:39 +0000255 if (!Constructor)
256 return ExprError();
257
Anders Carlssone7624a72009-08-27 05:08:22 +0000258 OwningExprResult Result =
259 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
260 move(exprs), RParenLoc);
261 if (Result.isInvalid())
262 return ExprError();
263
264 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000265 }
266
267 // Fall through to value-initialize an object of class type that
268 // doesn't have a user-declared default constructor.
269 }
270
271 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000272 // If the expression list specifies more than a single value, the type shall
273 // be a class with a suitably declared constructor.
274 //
275 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000276 return ExprError(Diag(CommaLocs[0],
277 diag::err_builtin_func_cast_more_than_one_arg)
278 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000279
280 assert(NumExprs == 0 && "Expected 0 expressions");
281
Douglas Gregor506ae412009-01-16 18:33:17 +0000282 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000283 // The expression T(), where T is a simple-type-specifier for a non-array
284 // complete object type or the (possibly cv-qualified) void type, creates an
285 // rvalue of the specified type, which is value-initialized.
286 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000287 exprs.release();
288 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000289}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000290
291
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000292/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
293/// @code new (memory) int[size][4] @endcode
294/// or
295/// @code ::new Foo(23, "hello") @endcode
296/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000297Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000298Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000299 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000300 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000301 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000302 MultiExprArg ConstructorArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000303 SourceLocation ConstructorRParen)
304{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000305 Expr *ArraySize = 0;
306 unsigned Skip = 0;
307 // If the specified type is an array, unwrap it and save the expression.
308 if (D.getNumTypeObjects() > 0 &&
309 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
310 DeclaratorChunk &Chunk = D.getTypeObject(0);
311 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000312 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
313 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000314 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000315 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
316 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000317 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
318 Skip = 1;
319 }
320
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000321 //FIXME: Store DeclaratorInfo in CXXNew expression.
322 DeclaratorInfo *DInfo = 0;
323 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000324 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000325 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000326
Douglas Gregor3433cf72009-05-21 00:00:09 +0000327 // Every dimension shall be of constant size.
328 unsigned i = 1;
329 QualType ElementType = AllocType;
330 while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
331 if (!Array->isConstantArrayType()) {
332 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
333 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
334 return ExprError();
335 }
336 ElementType = Array->getElementType();
337 ++i;
338 }
339
340 return BuildCXXNew(StartLoc, UseGlobal,
341 PlacementLParen,
342 move(PlacementArgs),
343 PlacementRParen,
344 ParenTypeId,
345 AllocType,
346 D.getSourceRange().getBegin(),
347 D.getSourceRange(),
348 Owned(ArraySize),
349 ConstructorLParen,
350 move(ConstructorArgs),
351 ConstructorRParen);
352}
353
354Sema::OwningExprResult
355Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
356 SourceLocation PlacementLParen,
357 MultiExprArg PlacementArgs,
358 SourceLocation PlacementRParen,
359 bool ParenTypeId,
360 QualType AllocType,
361 SourceLocation TypeLoc,
362 SourceRange TypeRange,
363 ExprArg ArraySizeE,
364 SourceLocation ConstructorLParen,
365 MultiExprArg ConstructorArgs,
366 SourceLocation ConstructorRParen) {
367 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000368 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000369
Douglas Gregor3433cf72009-05-21 00:00:09 +0000370 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000371
372 // That every array dimension except the first is constant was already
373 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000374
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000375 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
376 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000377 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000378 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000379 QualType SizeType = ArraySize->getType();
380 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000381 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
382 diag::err_array_size_not_integral)
383 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000384 // Let's see if this is a constant < 0. If so, we reject it out of hand.
385 // We don't care about special rules, so we tell the machinery it's not
386 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000387 if (!ArraySize->isValueDependent()) {
388 llvm::APSInt Value;
389 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
390 if (Value < llvm::APSInt(
391 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000392 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
393 diag::err_typecheck_negative_array_size)
394 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000395 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000396 }
397 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000398
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000399 FunctionDecl *OperatorNew = 0;
400 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000401 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
402 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000403 if (!AllocType->isDependentType() &&
404 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
405 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000406 SourceRange(PlacementLParen, PlacementRParen),
407 UseGlobal, AllocType, ArraySize, PlaceArgs,
408 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000409 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000410
411 bool Init = ConstructorLParen.isValid();
412 // --- Choosing a constructor ---
413 // C++ 5.3.4p15
414 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
415 // the object is not initialized. If the object, or any part of it, is
416 // const-qualified, it's an error.
417 // 2) If T is a POD and there's an empty initializer, the object is value-
418 // initialized.
419 // 3) If T is a POD and there's one initializer argument, the object is copy-
420 // constructed.
421 // 4) If T is a POD and there's more initializer arguments, it's an error.
422 // 5) If T is not a POD, the initializer arguments are used as constructor
423 // arguments.
424 //
425 // Or by the C++0x formulation:
426 // 1) If there's no initializer, the object is default-initialized according
427 // to C++0x rules.
428 // 2) Otherwise, the object is direct-initialized.
429 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000430 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000431 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000432 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000433 if (AllocType->isDependentType()) {
434 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000435 } else if ((RT = AllocType->getAs<RecordType>()) &&
436 !AllocType->isAggregateType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000437 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000438 AllocType, ConsArgs, NumConsArgs,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000439 TypeLoc,
440 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000441 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000442 NumConsArgs != 0 ? IK_Direct : IK_Default);
443 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000444 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000445 } else {
446 if (!Init) {
447 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000448 if (AllocType.isConstQualified())
449 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000450 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000451 } else if (NumConsArgs == 0) {
452 // Object is value-initialized. Do nothing.
453 } else if (NumConsArgs == 1) {
454 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000455 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000456 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000457 DeclarationName() /*AllocType.getAsString()*/,
458 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000459 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000460 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000461 return ExprError(Diag(StartLoc,
462 diag::err_builtin_direct_init_more_than_one_arg)
463 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000464 }
465 }
466
467 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
468
Sebastian Redlf53597f2009-03-15 17:47:39 +0000469 PlacementArgs.release();
470 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000471 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000472 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000473 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000474 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000475 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000476}
477
478/// CheckAllocatedType - Checks that a type is suitable as the allocated type
479/// in a new-expression.
480/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000481bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
482 SourceRange R)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000483{
484 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
485 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000486 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000487 return Diag(Loc, diag::err_bad_new_type)
488 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000489 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000490 return Diag(Loc, diag::err_bad_new_type)
491 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000492 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000493 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000494 PDiag(diag::err_new_incomplete_type)
495 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000496 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000497 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000498 diag::err_allocation_of_abstract_type))
499 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000500
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000501 return false;
502}
503
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000504/// FindAllocationFunctions - Finds the overloads of operator new and delete
505/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000506bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
507 bool UseGlobal, QualType AllocType,
508 bool IsArray, Expr **PlaceArgs,
509 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000510 FunctionDecl *&OperatorNew,
511 FunctionDecl *&OperatorDelete)
512{
513 // --- Choosing an allocation function ---
514 // C++ 5.3.4p8 - 14 & 18
515 // 1) If UseGlobal is true, only look in the global scope. Else, also look
516 // in the scope of the allocated class.
517 // 2) If an array size is given, look for operator new[], else look for
518 // operator new.
519 // 3) The first argument is always size_t. Append the arguments from the
520 // placement form.
521 // FIXME: Also find the appropriate delete operator.
522
523 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
524 // We don't care about the actual value of this argument.
525 // FIXME: Should the Sema create the expression and embed it in the syntax
526 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000527 IntegerLiteral Size(llvm::APInt::getNullValue(
528 Context.Target.getPointerWidth(0)),
529 Context.getSizeType(),
530 SourceLocation());
531 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000532 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
533
534 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
535 IsArray ? OO_Array_New : OO_New);
536 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000537 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000538 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000539 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000540 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000541 AllocArgs.size(), Record, /*AllowMissing=*/true,
542 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000543 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000544 }
545 if (!OperatorNew) {
546 // Didn't find a member overload. Look for a global one.
547 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000548 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000549 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000550 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
551 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000552 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000553 }
554
Anders Carlssond9583892009-05-31 20:26:12 +0000555 // FindAllocationOverload can change the passed in arguments, so we need to
556 // copy them back.
557 if (NumPlaceArgs > 0)
558 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
559
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000560 return false;
561}
562
Sebastian Redl7f662392008-12-04 22:20:51 +0000563/// FindAllocationOverload - Find an fitting overload for the allocation
564/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000565bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
566 DeclarationName Name, Expr** Args,
567 unsigned NumArgs, DeclContext *Ctx,
568 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redl7f662392008-12-04 22:20:51 +0000569{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000570 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000571 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000572 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000573 if (AllowMissing)
574 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000575 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000576 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000577 }
578
579 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000580 for (; Alloc != AllocEnd; ++Alloc) {
581 // Even member operator new/delete are implicitly treated as
582 // static, so don't use AddMemberCandidate.
583 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
584 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
585 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000586 }
587
588 // Do the resolution.
589 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000590 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000591 case OR_Success: {
592 // Got one!
593 FunctionDecl *FnDecl = Best->Function;
594 // The first argument is size_t, and the first parameter must be size_t,
595 // too. This is checked on declaration and can be assumed. (It can't be
596 // asserted on, though, since invalid decls are left in there.)
597 for (unsigned i = 1; i < NumArgs; ++i) {
598 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000599 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000600 FnDecl->getParamDecl(i)->getType(),
601 "passing"))
602 return true;
603 }
604 Operator = FnDecl;
605 return false;
606 }
607
608 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000609 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000610 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000611 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
612 return true;
613
614 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000615 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000616 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000617 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
618 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000619
620 case OR_Deleted:
621 Diag(StartLoc, diag::err_ovl_deleted_call)
622 << Best->Function->isDeleted()
623 << Name << Range;
624 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
625 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000626 }
627 assert(false && "Unreachable, bad result from BestViableFunction");
628 return true;
629}
630
631
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000632/// DeclareGlobalNewDelete - Declare the global forms of operator new and
633/// delete. These are:
634/// @code
635/// void* operator new(std::size_t) throw(std::bad_alloc);
636/// void* operator new[](std::size_t) throw(std::bad_alloc);
637/// void operator delete(void *) throw();
638/// void operator delete[](void *) throw();
639/// @endcode
640/// Note that the placement and nothrow forms of new are *not* implicitly
641/// declared. Their use requires including \<new\>.
642void Sema::DeclareGlobalNewDelete()
643{
644 if (GlobalNewDeleteDeclared)
645 return;
646 GlobalNewDeleteDeclared = true;
647
648 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
649 QualType SizeT = Context.getSizeType();
650
651 // FIXME: Exception specifications are not added.
652 DeclareGlobalAllocationFunction(
653 Context.DeclarationNames.getCXXOperatorName(OO_New),
654 VoidPtr, SizeT);
655 DeclareGlobalAllocationFunction(
656 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
657 VoidPtr, SizeT);
658 DeclareGlobalAllocationFunction(
659 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
660 Context.VoidTy, VoidPtr);
661 DeclareGlobalAllocationFunction(
662 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
663 Context.VoidTy, VoidPtr);
664}
665
666/// DeclareGlobalAllocationFunction - Declares a single implicit global
667/// allocation function if it doesn't already exist.
668void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
669 QualType Return, QualType Argument)
670{
671 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
672
673 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000674 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000675 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000676 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000677 Alloc != AllocEnd; ++Alloc) {
678 // FIXME: Do we need to check for default arguments here?
679 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
680 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000681 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000682 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000683 }
684 }
685
686 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
687 FunctionDecl *Alloc =
688 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000689 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000690 Alloc->setImplicit();
691 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000692 0, Argument, /*DInfo=*/0,
693 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000694 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000695
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000696 // FIXME: Also add this declaration to the IdentifierResolver, but
697 // make sure it is at the end of the chain to coincide with the
698 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000699 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000700}
701
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000702/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
703/// @code ::delete ptr; @endcode
704/// or
705/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000706Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000707Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000708 bool ArrayForm, ExprArg Operand)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000709{
710 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
711 // having a single conversion function to a pointer type. The result has
712 // type void."
713 // DR599 amends "pointer type" to "pointer to object type" in both cases.
714
Anders Carlssond67c4c32009-08-16 20:29:29 +0000715 FunctionDecl *OperatorDelete = 0;
716
Sebastian Redlf53597f2009-03-15 17:47:39 +0000717 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000718 if (!Ex->isTypeDependent()) {
719 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000720
Sebastian Redl28507842009-02-26 14:39:58 +0000721 if (Type->isRecordType()) {
722 // FIXME: Find that one conversion function and amend the type.
723 }
724
Sebastian Redlf53597f2009-03-15 17:47:39 +0000725 if (!Type->isPointerType())
726 return ExprError(Diag(StartLoc, diag::err_delete_operand)
727 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000728
Ted Kremenek6217b802009-07-29 21:53:49 +0000729 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000730 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000731 return ExprError(Diag(StartLoc, diag::err_delete_operand)
732 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000733 else if (!Pointee->isDependentType() &&
734 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000735 PDiag(diag::warn_delete_incomplete)
736 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000737 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000738
Anders Carlssond67c4c32009-08-16 20:29:29 +0000739 // FIXME: This should be shared with the code for finding the delete
740 // operator in ActOnCXXNew.
741 IntegerLiteral Size(llvm::APInt::getNullValue(
742 Context.Target.getPointerWidth(0)),
743 Context.getSizeType(),
744 SourceLocation());
745 ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy),
746 CastExpr::CK_Unknown, &Size, false);
747 Expr *DeleteArg = &Cast;
748
749 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
750 ArrayForm ? OO_Array_Delete : OO_Delete);
751
752 if (Pointee->isRecordType() && !UseGlobal) {
753 CXXRecordDecl *Record
754 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
755 // FIXME: We fail to find inherited overloads.
756 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
757 &DeleteArg, 1, Record, /*AllowMissing=*/true,
758 OperatorDelete))
759 return ExprError();
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000760 if (!Record->hasTrivialDestructor())
761 if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context))
762 MarkDeclarationReferenced(StartLoc,
763 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000764 }
765
766 if (!OperatorDelete) {
767 // Didn't find a member overload. Look for a global one.
768 DeclareGlobalNewDelete();
769 DeclContext *TUDecl = Context.getTranslationUnitDecl();
770 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
771 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false,
772 OperatorDelete))
773 return ExprError();
774 }
775
Sebastian Redl28507842009-02-26 14:39:58 +0000776 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000777 }
778
Sebastian Redlf53597f2009-03-15 17:47:39 +0000779 Operand.release();
780 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000781 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000782}
783
784
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000785/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
786/// C++ if/switch/while/for statement.
787/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000788Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000789Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
790 Declarator &D,
791 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000792 ExprArg AssignExprVal) {
793 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000794
795 // C++ 6.4p2:
796 // The declarator shall not specify a function or an array.
797 // The type-specifier-seq shall not contain typedef and shall not declare a
798 // new class or enumeration.
799
800 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
801 "Parser allowed 'typedef' as storage class of condition decl.");
802
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000803 // FIXME: Store DeclaratorInfo in the expression.
804 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000805 TagDecl *OwnedTag = 0;
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000806 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000807
808 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
809 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
810 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000811 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
812 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000813 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000814 Diag(StartLoc, diag::err_invalid_use_of_array_type)
815 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000816 } else if (OwnedTag && OwnedTag->isDefinition()) {
817 // The type-specifier-seq shall not declare a new class or enumeration.
818 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000819 }
820
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000821 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000822 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000823 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000824 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000825
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000826 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000827 // We know that the decl had to be a VarDecl because that is the only type of
828 // decl that can be assigned and the grammar requires an '='.
829 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
830 VD->setDeclaredInCondition(true);
831 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000832}
833
834/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
835bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
836 // C++ 6.4p4:
837 // The value of a condition that is an initialized declaration in a statement
838 // other than a switch statement is the value of the declared variable
839 // implicitly converted to type bool. If that conversion is ill-formed, the
840 // program is ill-formed.
841 // The value of a condition that is an expression is the value of the
842 // expression, implicitly converted to bool.
843 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000844 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000845}
Douglas Gregor77a52232008-09-12 00:47:35 +0000846
847/// Helper function to determine whether this is the (deprecated) C++
848/// conversion from a string literal to a pointer to non-const char or
849/// non-const wchar_t (for narrow and wide string literals,
850/// respectively).
851bool
852Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
853 // Look inside the implicit cast, if it exists.
854 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
855 From = Cast->getSubExpr();
856
857 // A string literal (2.13.4) that is not a wide string literal can
858 // be converted to an rvalue of type "pointer to char"; a wide
859 // string literal can be converted to an rvalue of type "pointer
860 // to wchar_t" (C++ 4.2p2).
861 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000862 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor77a52232008-09-12 00:47:35 +0000863 if (const BuiltinType *ToPointeeType
864 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
865 // This conversion is considered only when there is an
866 // explicit appropriate pointer target type (C++ 4.2p2).
867 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
868 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
869 (!StrLit->isWide() &&
870 (ToPointeeType->getKind() == BuiltinType::Char_U ||
871 ToPointeeType->getKind() == BuiltinType::Char_S))))
872 return true;
873 }
874
875 return false;
876}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000877
878/// PerformImplicitConversion - Perform an implicit conversion of the
879/// expression From to the type ToType. Returns true if there was an
880/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000881/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000882/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000883/// explicit user-defined conversions are permitted. @p Elidable should be true
884/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
885/// resolution works differently in that case.
886bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000887Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000888 const char *Flavor, bool AllowExplicit,
889 bool Elidable)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000890{
Sebastian Redle2b68332009-04-12 17:16:29 +0000891 ImplicitConversionSequence ICS;
892 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
893 if (Elidable && getLangOptions().CPlusPlus0x) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000894 ICS = TryImplicitConversion(From, ToType,
895 /*SuppressUserConversions=*/false,
896 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +0000897 /*ForceRValue=*/true,
898 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000899 }
900 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000901 ICS = TryImplicitConversion(From, ToType,
902 /*SuppressUserConversions=*/false,
903 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +0000904 /*ForceRValue=*/false,
905 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000906 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000907 return PerformImplicitConversion(From, ToType, ICS, Flavor);
908}
909
910/// PerformImplicitConversion - Perform an implicit conversion of the
911/// expression From to the type ToType using the pre-computed implicit
912/// conversion sequence ICS. Returns true if there was an error, false
913/// otherwise. The expression From is replaced with the converted
914/// expression. Flavor is the kind of conversion we're performing,
915/// used in the error message.
916bool
917Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
918 const ImplicitConversionSequence &ICS,
919 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000920 switch (ICS.ConversionKind) {
921 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000922 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000923 return true;
924 break;
925
926 case ImplicitConversionSequence::UserDefinedConversion:
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +0000927 {
928 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
929 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
930 if (CXXConversionDecl *CV = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian9099ff02009-08-26 20:34:58 +0000931 // FIXME. Get actual Source Location.
932 From =
933 new (Context) CXXFunctionalCastExpr(ToType.getNonReferenceType(),
934 ToType, SourceLocation(),
935 CastExpr::CK_UserDefinedConversion,
936 From, CV,
937 SourceLocation());
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +0000938 CastKind = CastExpr::CK_UserDefinedConversion;
939 }
940 else if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
941 // FIXME. Do we need to check for isLValueReferenceType?
942 DefaultFunctionArrayConversion(From);
943 OwningExprResult InitResult =
Anders Carlssonec8e5ea2009-09-05 07:40:38 +0000944 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
Anders Carlssonf47511a2009-09-07 22:23:31 +0000945 ToType.getNonReferenceType(), CD,
946 MultiExprArg(*this, (void**)&From, 1));
Fariborz Jahanian31976592009-08-29 19:15:16 +0000947 // Take ownership of this expression.
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +0000948 From = InitResult.takeAs<Expr>();
949 CastKind = CastExpr::CK_ConstructorConversion ;
950 }
951 ImpCastExprToType(From, ToType.getNonReferenceType(),
952 CastKind,
953 ToType->isLValueReferenceType());
954 return false;
955 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000956
957 case ImplicitConversionSequence::EllipsisConversion:
958 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000959 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000960
961 case ImplicitConversionSequence::BadConversion:
962 return true;
963 }
964
965 // Everything went well.
966 return false;
967}
968
969/// PerformImplicitConversion - Perform an implicit conversion of the
970/// expression From to the type ToType by following the standard
971/// conversion sequence SCS. Returns true if there was an error, false
972/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000973/// expression. Flavor is the context in which we're performing this
974/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000975bool
976Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000977 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000978 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000979 // Overall FIXME: we are recomputing too many types here and doing far too
980 // much extra work. What this means is that we need to keep track of more
981 // information that is computed when we try the implicit conversion initially,
982 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000983 QualType FromType = From->getType();
984
Douglas Gregor225c41e2008-11-03 19:09:14 +0000985 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +0000986 // FIXME: When can ToType be a reference type?
987 assert(!ToType->isReferenceType());
988
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000989 OwningExprResult FromResult =
Anders Carlssonec8e5ea2009-09-05 07:40:38 +0000990 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
Anders Carlssonf47511a2009-09-07 22:23:31 +0000991 ToType, SCS.CopyConstructor,
992 MultiExprArg(*this, (void**)&From, 1));
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000993
994 if (FromResult.isInvalid())
995 return true;
996
997 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000998 return false;
999 }
1000
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001001 // Perform the first implicit conversion.
1002 switch (SCS.First) {
1003 case ICK_Identity:
1004 case ICK_Lvalue_To_Rvalue:
1005 // Nothing to do.
1006 break;
1007
1008 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001009 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001010 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001011 break;
1012
1013 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001014 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001015 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1016 if (!Fn)
1017 return true;
1018
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001019 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1020 return true;
1021
Douglas Gregor904eed32008-11-10 20:40:00 +00001022 FixOverloadedFunctionReference(From, Fn);
1023 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +00001024 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001025 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001026 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001027 break;
1028
1029 default:
1030 assert(false && "Improper first standard conversion");
1031 break;
1032 }
1033
1034 // Perform the second implicit conversion
1035 switch (SCS.Second) {
1036 case ICK_Identity:
1037 // Nothing to do.
1038 break;
1039
1040 case ICK_Integral_Promotion:
1041 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001042 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001043 case ICK_Integral_Conversion:
1044 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001045 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001046 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001047 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +00001048 case ICK_Compatible_Conversion:
1049 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001050 FromType = ToType.getUnqualifiedType();
1051 ImpCastExprToType(From, FromType);
1052 break;
1053
1054 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +00001055 if (SCS.IncompatibleObjC) {
1056 // Diagnose incompatible Objective-C conversions
1057 Diag(From->getSourceRange().getBegin(),
1058 diag::ext_typecheck_convert_incompatible_pointer)
1059 << From->getType() << ToType << Flavor
1060 << From->getSourceRange();
1061 }
1062
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001063 if (CheckPointerConversion(From, ToType))
1064 return true;
1065 ImpCastExprToType(From, ToType);
1066 break;
1067
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001068 case ICK_Pointer_Member: {
1069 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1070 if (CheckMemberPointerConversion(From, ToType, Kind))
1071 return true;
1072 ImpCastExprToType(From, ToType, Kind);
1073 break;
1074 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001075 case ICK_Boolean_Conversion:
1076 FromType = Context.BoolTy;
1077 ImpCastExprToType(From, FromType);
1078 break;
1079
1080 default:
1081 assert(false && "Improper second standard conversion");
1082 break;
1083 }
1084
1085 switch (SCS.Third) {
1086 case ICK_Identity:
1087 // Nothing to do.
1088 break;
1089
1090 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001091 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1092 // references.
Douglas Gregor66b947f2009-01-16 19:38:23 +00001093 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +00001094 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001095 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001096 break;
1097
1098 default:
1099 assert(false && "Improper second standard conversion");
1100 break;
1101 }
1102
1103 return false;
1104}
1105
Sebastian Redl64b45f72009-01-05 20:52:13 +00001106Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1107 SourceLocation KWLoc,
1108 SourceLocation LParen,
1109 TypeTy *Ty,
1110 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001111 QualType T = GetTypeFromParser(Ty);
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001112
1113 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1114 // all traits except __is_class, __is_enum and __is_union require a the type
1115 // to be complete.
1116 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1117 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001118 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001119 return ExprError();
1120 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001121
1122 // There is no point in eagerly computing the value. The traits are designed
1123 // to be used from type trait templates, so Ty will be a template parameter
1124 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001125 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1126 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001127}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001128
1129QualType Sema::CheckPointerToMemberOperands(
1130 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
1131{
1132 const char *OpSpelling = isIndirect ? "->*" : ".*";
1133 // C++ 5.5p2
1134 // The binary operator .* [p3: ->*] binds its second operand, which shall
1135 // be of type "pointer to member of T" (where T is a completely-defined
1136 // class type) [...]
1137 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001138 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001139 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001140 Diag(Loc, diag::err_bad_memptr_rhs)
1141 << OpSpelling << RType << rex->getSourceRange();
1142 return QualType();
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00001143 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001144
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001145 QualType Class(MemPtr->getClass(), 0);
1146
1147 // C++ 5.5p2
1148 // [...] to its first operand, which shall be of class T or of a class of
1149 // which T is an unambiguous and accessible base class. [p3: a pointer to
1150 // such a class]
1151 QualType LType = lex->getType();
1152 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001153 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001154 LType = Ptr->getPointeeType().getNonReferenceType();
1155 else {
1156 Diag(Loc, diag::err_bad_memptr_lhs)
1157 << OpSpelling << 1 << LType << lex->getSourceRange();
1158 return QualType();
1159 }
1160 }
1161
1162 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1163 Context.getCanonicalType(LType).getUnqualifiedType()) {
1164 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1165 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001166 // FIXME: Would it be useful to print full ambiguity paths, or is that
1167 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001168 if (!IsDerivedFrom(LType, Class, Paths) ||
1169 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1170 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1171 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1172 return QualType();
1173 }
1174 }
1175
1176 // C++ 5.5p2
1177 // The result is an object or a function of the type specified by the
1178 // second operand.
1179 // The cv qualifiers are the union of those in the pointer and the left side,
1180 // in accordance with 5.5p5 and 5.2.5.
1181 // FIXME: This returns a dereferenced member function pointer as a normal
1182 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001183 // calling them. There's also a GCC extension to get a function pointer to the
1184 // thing, which is another complication, because this type - unlike the type
1185 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001186 // argument.
1187 // We probably need a "MemberFunctionClosureType" or something like that.
1188 QualType Result = MemPtr->getPointeeType();
1189 if (LType.isConstQualified())
1190 Result.addConst();
1191 if (LType.isVolatileQualified())
1192 Result.addVolatile();
1193 return Result;
1194}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001195
1196/// \brief Get the target type of a standard or user-defined conversion.
1197static QualType TargetType(const ImplicitConversionSequence &ICS) {
1198 assert((ICS.ConversionKind ==
1199 ImplicitConversionSequence::StandardConversion ||
1200 ICS.ConversionKind ==
1201 ImplicitConversionSequence::UserDefinedConversion) &&
1202 "function only valid for standard or user-defined conversions");
1203 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1204 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1205 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1206}
1207
1208/// \brief Try to convert a type to another according to C++0x 5.16p3.
1209///
1210/// This is part of the parameter validation for the ? operator. If either
1211/// value operand is a class type, the two operands are attempted to be
1212/// converted to each other. This function does the conversion in one direction.
1213/// It emits a diagnostic and returns true only if it finds an ambiguous
1214/// conversion.
1215static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1216 SourceLocation QuestionLoc,
1217 ImplicitConversionSequence &ICS)
1218{
1219 // C++0x 5.16p3
1220 // The process for determining whether an operand expression E1 of type T1
1221 // can be converted to match an operand expression E2 of type T2 is defined
1222 // as follows:
1223 // -- If E2 is an lvalue:
1224 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1225 // E1 can be converted to match E2 if E1 can be implicitly converted to
1226 // type "lvalue reference to T2", subject to the constraint that in the
1227 // conversion the reference must bind directly to E1.
1228 if (!Self.CheckReferenceInit(From,
1229 Self.Context.getLValueReferenceType(To->getType()),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001230 /*SuppressUserConversions=*/false,
1231 /*AllowExplicit=*/false,
1232 /*ForceRValue=*/false,
1233 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001234 {
1235 assert((ICS.ConversionKind ==
1236 ImplicitConversionSequence::StandardConversion ||
1237 ICS.ConversionKind ==
1238 ImplicitConversionSequence::UserDefinedConversion) &&
1239 "expected a definite conversion");
1240 bool DirectBinding =
1241 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1242 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1243 if (DirectBinding)
1244 return false;
1245 }
1246 }
1247 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1248 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1249 // -- if E1 and E2 have class type, and the underlying class types are
1250 // the same or one is a base class of the other:
1251 QualType FTy = From->getType();
1252 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001253 const RecordType *FRec = FTy->getAs<RecordType>();
1254 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001255 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1256 if (FRec && TRec && (FRec == TRec ||
1257 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1258 // E1 can be converted to match E2 if the class of T2 is the
1259 // same type as, or a base class of, the class of T1, and
1260 // [cv2 > cv1].
1261 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1262 // Could still fail if there's no copy constructor.
1263 // FIXME: Is this a hard error then, or just a conversion failure? The
1264 // standard doesn't say.
Anders Carlssond28b4282009-08-27 17:18:13 +00001265 ICS = Self.TryCopyInitialization(From, TTy,
1266 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001267 /*ForceRValue=*/false,
1268 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001269 }
1270 } else {
1271 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1272 // implicitly converted to the type that expression E2 would have
1273 // if E2 were converted to an rvalue.
1274 // First find the decayed type.
1275 if (TTy->isFunctionType())
1276 TTy = Self.Context.getPointerType(TTy);
1277 else if(TTy->isArrayType())
1278 TTy = Self.Context.getArrayDecayedType(TTy);
1279
1280 // Now try the implicit conversion.
1281 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001282 ICS = Self.TryImplicitConversion(From, TTy,
1283 /*SuppressUserConversions=*/false,
1284 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001285 /*ForceRValue=*/false,
1286 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001287 }
1288 return false;
1289}
1290
1291/// \brief Try to find a common type for two according to C++0x 5.16p5.
1292///
1293/// This is part of the parameter validation for the ? operator. If either
1294/// value operand is a class type, overload resolution is used to find a
1295/// conversion to a common type.
1296static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1297 SourceLocation Loc) {
1298 Expr *Args[2] = { LHS, RHS };
1299 OverloadCandidateSet CandidateSet;
1300 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1301
1302 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001303 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001304 case Sema::OR_Success:
1305 // We found a match. Perform the conversions on the arguments and move on.
1306 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1307 Best->Conversions[0], "converting") ||
1308 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1309 Best->Conversions[1], "converting"))
1310 break;
1311 return false;
1312
1313 case Sema::OR_No_Viable_Function:
1314 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1315 << LHS->getType() << RHS->getType()
1316 << LHS->getSourceRange() << RHS->getSourceRange();
1317 return true;
1318
1319 case Sema::OR_Ambiguous:
1320 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1321 << LHS->getType() << RHS->getType()
1322 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001323 // FIXME: Print the possible common types by printing the return types of
1324 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001325 break;
1326
1327 case Sema::OR_Deleted:
1328 assert(false && "Conditional operator has only built-in overloads");
1329 break;
1330 }
1331 return true;
1332}
1333
Sebastian Redl76458502009-04-17 16:30:52 +00001334/// \brief Perform an "extended" implicit conversion as returned by
1335/// TryClassUnification.
1336///
1337/// TryClassUnification generates ICSs that include reference bindings.
1338/// PerformImplicitConversion is not suitable for this; it chokes if the
1339/// second part of a standard conversion is ICK_DerivedToBase. This function
1340/// handles the reference binding specially.
1341static bool ConvertForConditional(Sema &Self, Expr *&E,
1342 const ImplicitConversionSequence &ICS)
1343{
1344 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1345 ICS.Standard.ReferenceBinding) {
1346 assert(ICS.Standard.DirectBinding &&
1347 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001348 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1349 // redoing all the work.
1350 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001351 TargetType(ICS)),
1352 /*SuppressUserConversions=*/false,
1353 /*AllowExplicit=*/false,
1354 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001355 }
1356 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1357 ICS.UserDefined.After.ReferenceBinding) {
1358 assert(ICS.UserDefined.After.DirectBinding &&
1359 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001360 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001361 TargetType(ICS)),
1362 /*SuppressUserConversions=*/false,
1363 /*AllowExplicit=*/false,
1364 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001365 }
1366 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1367 return true;
1368 return false;
1369}
1370
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001371/// \brief Check the operands of ?: under C++ semantics.
1372///
1373/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1374/// extension. In this case, LHS == Cond. (But they're not aliases.)
1375QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1376 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001377 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1378 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001379
1380 // C++0x 5.16p1
1381 // The first expression is contextually converted to bool.
1382 if (!Cond->isTypeDependent()) {
1383 if (CheckCXXBooleanCondition(Cond))
1384 return QualType();
1385 }
1386
1387 // Either of the arguments dependent?
1388 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1389 return Context.DependentTy;
1390
1391 // C++0x 5.16p2
1392 // If either the second or the third operand has type (cv) void, ...
1393 QualType LTy = LHS->getType();
1394 QualType RTy = RHS->getType();
1395 bool LVoid = LTy->isVoidType();
1396 bool RVoid = RTy->isVoidType();
1397 if (LVoid || RVoid) {
1398 // ... then the [l2r] conversions are performed on the second and third
1399 // operands ...
1400 DefaultFunctionArrayConversion(LHS);
1401 DefaultFunctionArrayConversion(RHS);
1402 LTy = LHS->getType();
1403 RTy = RHS->getType();
1404
1405 // ... and one of the following shall hold:
1406 // -- The second or the third operand (but not both) is a throw-
1407 // expression; the result is of the type of the other and is an rvalue.
1408 bool LThrow = isa<CXXThrowExpr>(LHS);
1409 bool RThrow = isa<CXXThrowExpr>(RHS);
1410 if (LThrow && !RThrow)
1411 return RTy;
1412 if (RThrow && !LThrow)
1413 return LTy;
1414
1415 // -- Both the second and third operands have type void; the result is of
1416 // type void and is an rvalue.
1417 if (LVoid && RVoid)
1418 return Context.VoidTy;
1419
1420 // Neither holds, error.
1421 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1422 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1423 << LHS->getSourceRange() << RHS->getSourceRange();
1424 return QualType();
1425 }
1426
1427 // Neither is void.
1428
1429 // C++0x 5.16p3
1430 // Otherwise, if the second and third operand have different types, and
1431 // either has (cv) class type, and attempt is made to convert each of those
1432 // operands to the other.
1433 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1434 (LTy->isRecordType() || RTy->isRecordType())) {
1435 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1436 // These return true if a single direction is already ambiguous.
1437 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1438 return QualType();
1439 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1440 return QualType();
1441
1442 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1443 ImplicitConversionSequence::BadConversion;
1444 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1445 ImplicitConversionSequence::BadConversion;
1446 // If both can be converted, [...] the program is ill-formed.
1447 if (HaveL2R && HaveR2L) {
1448 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1449 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1450 return QualType();
1451 }
1452
1453 // If exactly one conversion is possible, that conversion is applied to
1454 // the chosen operand and the converted operands are used in place of the
1455 // original operands for the remainder of this section.
1456 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001457 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001458 return QualType();
1459 LTy = LHS->getType();
1460 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001461 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001462 return QualType();
1463 RTy = RHS->getType();
1464 }
1465 }
1466
1467 // C++0x 5.16p4
1468 // If the second and third operands are lvalues and have the same type,
1469 // the result is of that type [...]
1470 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1471 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1472 RHS->isLvalue(Context) == Expr::LV_Valid)
1473 return LTy;
1474
1475 // C++0x 5.16p5
1476 // Otherwise, the result is an rvalue. If the second and third operands
1477 // do not have the same type, and either has (cv) class type, ...
1478 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1479 // ... overload resolution is used to determine the conversions (if any)
1480 // to be applied to the operands. If the overload resolution fails, the
1481 // program is ill-formed.
1482 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1483 return QualType();
1484 }
1485
1486 // C++0x 5.16p6
1487 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1488 // conversions are performed on the second and third operands.
1489 DefaultFunctionArrayConversion(LHS);
1490 DefaultFunctionArrayConversion(RHS);
1491 LTy = LHS->getType();
1492 RTy = RHS->getType();
1493
1494 // After those conversions, one of the following shall hold:
1495 // -- The second and third operands have the same type; the result
1496 // is of that type.
1497 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1498 return LTy;
1499
1500 // -- The second and third operands have arithmetic or enumeration type;
1501 // the usual arithmetic conversions are performed to bring them to a
1502 // common type, and the result is of that type.
1503 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1504 UsualArithmeticConversions(LHS, RHS);
1505 return LHS->getType();
1506 }
1507
1508 // -- The second and third operands have pointer type, or one has pointer
1509 // type and the other is a null pointer constant; pointer conversions
1510 // and qualification conversions are performed to bring them to their
1511 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001512 QualType Composite = FindCompositePointerType(LHS, RHS);
1513 if (!Composite.isNull())
1514 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001515
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001516 // Fourth bullet is same for pointers-to-member. However, the possible
1517 // conversions are far more limited: we have null-to-pointer, upcast of
1518 // containing class, and second-level cv-ness.
1519 // cv-ness is not a union, but must match one of the two operands. (Which,
1520 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001521 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1522 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001523 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1524 ImpCastExprToType(RHS, LTy);
1525 return LTy;
1526 }
1527 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1528 ImpCastExprToType(LHS, RTy);
1529 return RTy;
1530 }
1531 if (LMemPtr && RMemPtr) {
1532 QualType LPointee = LMemPtr->getPointeeType();
1533 QualType RPointee = RMemPtr->getPointeeType();
1534 // First, we check that the unqualified pointee type is the same. If it's
1535 // not, there's no conversion that will unify the two pointers.
1536 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1537 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1538 // Second, we take the greater of the two cv qualifications. If neither
1539 // is greater than the other, the conversion is not possible.
1540 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1541 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1542 // Third, we check if either of the container classes is derived from
1543 // the other.
1544 QualType LContainer(LMemPtr->getClass(), 0);
1545 QualType RContainer(RMemPtr->getClass(), 0);
1546 QualType MoreDerived;
1547 if (Context.getCanonicalType(LContainer) ==
1548 Context.getCanonicalType(RContainer))
1549 MoreDerived = LContainer;
1550 else if (IsDerivedFrom(LContainer, RContainer))
1551 MoreDerived = LContainer;
1552 else if (IsDerivedFrom(RContainer, LContainer))
1553 MoreDerived = RContainer;
1554
1555 if (!MoreDerived.isNull()) {
1556 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1557 // We don't use ImpCastExprToType here because this could still fail
1558 // for ambiguous or inaccessible conversions.
1559 QualType Common = Context.getMemberPointerType(
1560 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1561 if (PerformImplicitConversion(LHS, Common, "converting"))
1562 return QualType();
1563 if (PerformImplicitConversion(RHS, Common, "converting"))
1564 return QualType();
1565 return Common;
1566 }
1567 }
1568 }
1569 }
1570
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001571 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1572 << LHS->getType() << RHS->getType()
1573 << LHS->getSourceRange() << RHS->getSourceRange();
1574 return QualType();
1575}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001576
1577/// \brief Find a merged pointer type and convert the two expressions to it.
1578///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001579/// This finds the composite pointer type (or member pointer type) for @p E1
1580/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1581/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001582/// It does not emit diagnostics.
1583QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1584 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1585 QualType T1 = E1->getType(), T2 = E2->getType();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001586
1587 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1588 !T2->isPointerType() && !T2->isMemberPointerType())
1589 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001590
Douglas Gregor20b3e992009-08-24 17:42:35 +00001591 // FIXME: Do we need to work on the canonical types?
1592
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001593 // C++0x 5.9p2
1594 // Pointer conversions and qualification conversions are performed on
1595 // pointer operands to bring them to their composite pointer type. If
1596 // one operand is a null pointer constant, the composite pointer type is
1597 // the type of the other operand.
1598 if (E1->isNullPointerConstant(Context)) {
1599 ImpCastExprToType(E1, T2);
1600 return T2;
1601 }
1602 if (E2->isNullPointerConstant(Context)) {
1603 ImpCastExprToType(E2, T1);
1604 return T1;
1605 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00001606
1607 // Now both have to be pointers or member pointers.
1608 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1609 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001610 return QualType();
1611
1612 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1613 // the other has type "pointer to cv2 T" and the composite pointer type is
1614 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1615 // Otherwise, the composite pointer type is a pointer type similar to the
1616 // type of one of the operands, with a cv-qualification signature that is
1617 // the union of the cv-qualification signatures of the operand types.
1618 // In practice, the first part here is redundant; it's subsumed by the second.
1619 // What we do here is, we build the two possible composite types, and try the
1620 // conversions in both directions. If only one works, or if the two composite
1621 // types are the same, we have succeeded.
1622 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001623 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001624 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001625 do {
1626 const PointerType *Ptr1, *Ptr2;
1627 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1628 (Ptr2 = Composite2->getAs<PointerType>())) {
1629 Composite1 = Ptr1->getPointeeType();
1630 Composite2 = Ptr2->getPointeeType();
1631 QualifierUnion.push_back(
1632 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1633 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1634 continue;
1635 }
1636
1637 const MemberPointerType *MemPtr1, *MemPtr2;
1638 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1639 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1640 Composite1 = MemPtr1->getPointeeType();
1641 Composite2 = MemPtr2->getPointeeType();
1642 QualifierUnion.push_back(
1643 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1644 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1645 MemPtr2->getClass()));
1646 continue;
1647 }
1648
1649 // FIXME: block pointer types?
1650
1651 // Cannot unwrap any more types.
1652 break;
1653 } while (true);
1654
1655 // Rewrap the composites as pointers or member pointers with the union CVRs.
1656 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1657 = MemberOfClass.begin();
1658 for (llvm::SmallVector<unsigned, 4>::iterator
1659 I = QualifierUnion.begin(),
1660 E = QualifierUnion.end();
1661 I != E; (void)++I, ++MOC) {
1662 if (MOC->first && MOC->second) {
1663 // Rebuild member pointer type
1664 Composite1 = Context.getMemberPointerType(Composite1.getQualifiedType(*I),
1665 MOC->first);
1666 Composite2 = Context.getMemberPointerType(Composite2.getQualifiedType(*I),
1667 MOC->second);
1668 } else {
1669 // Rebuild pointer type
1670 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1671 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1672 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001673 }
1674
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001675 ImplicitConversionSequence E1ToC1 =
1676 TryImplicitConversion(E1, Composite1,
1677 /*SuppressUserConversions=*/false,
1678 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001679 /*ForceRValue=*/false,
1680 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001681 ImplicitConversionSequence E2ToC1 =
1682 TryImplicitConversion(E2, Composite1,
1683 /*SuppressUserConversions=*/false,
1684 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001685 /*ForceRValue=*/false,
1686 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001687
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001688 ImplicitConversionSequence E1ToC2, E2ToC2;
1689 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1690 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1691 if (Context.getCanonicalType(Composite1) !=
1692 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001693 E1ToC2 = TryImplicitConversion(E1, Composite2,
1694 /*SuppressUserConversions=*/false,
1695 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001696 /*ForceRValue=*/false,
1697 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001698 E2ToC2 = TryImplicitConversion(E2, Composite2,
1699 /*SuppressUserConversions=*/false,
1700 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001701 /*ForceRValue=*/false,
1702 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001703 }
1704
1705 bool ToC1Viable = E1ToC1.ConversionKind !=
1706 ImplicitConversionSequence::BadConversion
1707 && E2ToC1.ConversionKind !=
1708 ImplicitConversionSequence::BadConversion;
1709 bool ToC2Viable = E1ToC2.ConversionKind !=
1710 ImplicitConversionSequence::BadConversion
1711 && E2ToC2.ConversionKind !=
1712 ImplicitConversionSequence::BadConversion;
1713 if (ToC1Viable && !ToC2Viable) {
1714 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1715 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1716 return Composite1;
1717 }
1718 if (ToC2Viable && !ToC1Viable) {
1719 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1720 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1721 return Composite2;
1722 }
1723 return QualType();
1724}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001725
Anders Carlssondef11992009-05-30 20:36:53 +00001726Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001727 if (!Context.getLangOptions().CPlusPlus)
1728 return Owned(E);
1729
Ted Kremenek6217b802009-07-29 21:53:49 +00001730 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001731 if (!RT)
1732 return Owned(E);
1733
1734 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1735 if (RD->hasTrivialDestructor())
1736 return Owned(E);
1737
1738 CXXTemporary *Temp = CXXTemporary::Create(Context,
1739 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00001740 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00001741 if (CXXDestructorDecl *Destructor =
1742 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1743 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00001744 // FIXME: Add the temporary to the temporaries vector.
1745 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1746}
1747
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001748Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00001749 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001750 assert(SubExpr && "sub expression can't be null!");
1751
1752 if (ExprTemporaries.empty())
1753 return SubExpr;
1754
1755 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1756 &ExprTemporaries[0],
1757 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00001758 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001759 ExprTemporaries.clear();
1760
1761 return E;
1762}
1763
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001764Sema::OwningExprResult
1765Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
1766 tok::TokenKind OpKind, TypeTy *&ObjectType) {
1767 // Since this might be a postfix expression, get rid of ParenListExprs.
1768 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1769
1770 Expr *BaseExpr = (Expr*)Base.get();
1771 assert(BaseExpr && "no record expansion");
1772
1773 QualType BaseType = BaseExpr->getType();
1774 if (BaseType->isDependentType()) {
1775 // FIXME: member of the current instantiation
1776 ObjectType = BaseType.getAsOpaquePtr();
1777 return move(Base);
1778 }
1779
1780 // C++ [over.match.oper]p8:
1781 // [...] When operator->returns, the operator-> is applied to the value
1782 // returned, with the original second operand.
1783 if (OpKind == tok::arrow) {
1784 while (BaseType->isRecordType()) {
1785 Base = BuildOverloadedArrowExpr(S, move(Base), BaseExpr->getExprLoc());
1786 BaseExpr = (Expr*)Base.get();
1787 if (BaseExpr == NULL)
1788 return ExprError();
1789 BaseType = BaseExpr->getType();
1790 }
1791 }
1792
1793 if (BaseType->isPointerType())
1794 BaseType = BaseType->getPointeeType();
1795
1796 // We could end up with various non-record types here, such as extended
1797 // vector types or Objective-C interfaces. Just return early and let
1798 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00001799 if (!BaseType->isRecordType()) {
1800 // C++ [basic.lookup.classref]p2:
1801 // [...] If the type of the object expression is of pointer to scalar
1802 // type, the unqualified-id is looked up in the context of the complete
1803 // postfix-expression.
1804 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001805 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00001806 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001807
Douglas Gregorc68afe22009-09-03 21:38:09 +00001808 // C++ [basic.lookup.classref]p2:
1809 // If the id-expression in a class member access (5.2.5) is an
1810 // unqualified-id, and the type of the object expres- sion is of a class
1811 // type C (or of pointer to a class type C), the unqualified-id is looked
1812 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001813 ObjectType = BaseType.getAsOpaquePtr();
1814 return move(Base);
1815}
1816
Anders Carlssonec773872009-08-25 23:46:41 +00001817Sema::OwningExprResult
Anders Carlsson3aa4ca42009-08-26 17:36:19 +00001818Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
Anders Carlssonec773872009-08-25 23:46:41 +00001819 SourceLocation OpLoc,
1820 tok::TokenKind OpKind,
1821 SourceLocation ClassNameLoc,
1822 IdentifierInfo *ClassName,
Douglas Gregora78c5c32009-09-04 18:29:40 +00001823 const CXXScopeSpec &SS,
1824 bool HasTrailingLParen) {
1825 if (SS.isInvalid())
Anders Carlssonec773872009-08-25 23:46:41 +00001826 return ExprError();
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001827
Douglas Gregora71d8192009-09-04 17:36:40 +00001828 QualType BaseType;
Douglas Gregora78c5c32009-09-04 18:29:40 +00001829 if (isUnknownSpecialization(SS))
1830 BaseType = Context.getTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregora71d8192009-09-04 17:36:40 +00001831 ClassName);
1832 else {
Douglas Gregora78c5c32009-09-04 18:29:40 +00001833 TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, &SS);
Douglas Gregora71d8192009-09-04 17:36:40 +00001834 if (!BaseTy) {
1835 Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
1836 << ClassName;
1837 return ExprError();
1838 }
Anders Carlssonec773872009-08-25 23:46:41 +00001839
Douglas Gregora71d8192009-09-04 17:36:40 +00001840 BaseType = GetTypeFromParser(BaseTy);
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001841 }
Anders Carlssonec773872009-08-25 23:46:41 +00001842
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001843 CanQualType CanBaseType = Context.getCanonicalType(BaseType);
1844 DeclarationName DtorName =
1845 Context.DeclarationNames.getCXXDestructorName(CanBaseType);
1846
Douglas Gregora78c5c32009-09-04 18:29:40 +00001847 OwningExprResult Result
1848 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1849 DtorName, DeclPtrTy(), &SS);
1850 if (Result.isInvalid() || HasTrailingLParen)
1851 return move(Result);
1852
1853 // The only way a reference to a destructor can be used is to
1854 // immediately call them. Since the next token is not a '(', produce a
1855 // diagnostic and build the call now.
1856 Expr *E = (Expr *)Result.get();
1857 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(E->getLocEnd());
1858 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
1859 << isa<CXXPseudoDestructorExpr>(E)
1860 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
1861
1862 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
1863 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlssonec773872009-08-25 23:46:41 +00001864}
1865
Douglas Gregora6f0f9d2009-08-31 19:52:13 +00001866Sema::OwningExprResult
1867Sema::ActOnOverloadedOperatorReferenceExpr(Scope *S, ExprArg Base,
1868 SourceLocation OpLoc,
1869 tok::TokenKind OpKind,
1870 SourceLocation ClassNameLoc,
1871 OverloadedOperatorKind OverOpKind,
1872 const CXXScopeSpec *SS) {
1873 if (SS && SS->isInvalid())
1874 return ExprError();
1875
1876 DeclarationName Name =
1877 Context.DeclarationNames.getCXXOperatorName(OverOpKind);
1878
1879 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1880 Name, DeclPtrTy(), SS);
1881}
1882
1883Sema::OwningExprResult
1884Sema::ActOnConversionOperatorReferenceExpr(Scope *S, ExprArg Base,
1885 SourceLocation OpLoc,
1886 tok::TokenKind OpKind,
1887 SourceLocation ClassNameLoc,
1888 TypeTy *Ty,
1889 const CXXScopeSpec *SS) {
1890 if (SS && SS->isInvalid())
1891 return ExprError();
1892
1893 //FIXME: Preserve type source info.
1894 QualType ConvType = GetTypeFromParser(Ty);
1895 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
1896 DeclarationName ConvName =
1897 Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
1898
1899 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1900 ConvName, DeclPtrTy(), SS);
1901}
1902
Anders Carlsson165a0a02009-05-17 18:41:29 +00001903Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1904 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001905 if (FullExpr)
Anders Carlssonf54741e2009-06-16 03:37:31 +00001906 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
1907 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00001908
Anders Carlssonec773872009-08-25 23:46:41 +00001909
Anders Carlsson165a0a02009-05-17 18:41:29 +00001910 return Owned(FullExpr);
1911}