blob: bec595ca9cf989448a618bc3a8ce64f292d722dd [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"
16#include "clang/AST/ExprCXX.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +000018#include "clang/Parse/DeclSpec.h"
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +000019#include "clang/Lex/Preprocessor.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000020#include "clang/Basic/TargetInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000021#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23
Douglas Gregor487a75a2008-11-19 19:09:45 +000024/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregor2def4832008-11-17 20:34:05 +000025/// name (e.g., operator void const *) as an expression. This is
26/// very similar to ActOnIdentifierExpr, except that instead of
27/// providing an identifier the parser provides the type of the
28/// conversion function.
Sebastian Redlcd965b92009-01-18 18:53:16 +000029Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000030Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
31 TypeTy *Ty, bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000032 const CXXScopeSpec &SS,
33 bool isAddressOfOperand) {
Douglas Gregor2def4832008-11-17 20:34:05 +000034 QualType ConvType = QualType::getFromOpaquePtr(Ty);
35 QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
36 DeclarationName ConvName
37 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd965b92009-01-18 18:53:16 +000038 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +000039 &SS, isAddressOfOperand);
Douglas Gregor2def4832008-11-17 20:34:05 +000040}
Sebastian Redlc42e1182008-11-11 11:37:55 +000041
Douglas Gregor487a75a2008-11-19 19:09:45 +000042/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-11-18 14:39:36 +000043/// name (e.g., @c operator+ ) as an expression. This is very
44/// similar to ActOnIdentifierExpr, except that instead of providing
45/// an identifier the parser provides the kind of overloaded
46/// operator that was parsed.
Sebastian Redlcd965b92009-01-18 18:53:16 +000047Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000048Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
49 OverloadedOperatorKind Op,
50 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000051 const CXXScopeSpec &SS,
52 bool isAddressOfOperand) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000053 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redlebc07d52009-02-03 20:19:35 +000054 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor17330012009-02-04 15:01:18 +000055 isAddressOfOperand);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000056}
57
Sebastian Redlc42e1182008-11-11 11:37:55 +000058/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000059Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000060Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
61 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +000062 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000063 if (!StdNs)
Sebastian Redlf53597f2009-03-15 17:47:39 +000064 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Chris Lattner572af492008-11-20 05:51:55 +000065
66 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor4c921ae2009-01-30 01:04:22 +000067 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlc42e1182008-11-11 11:37:55 +000068 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000069 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000070 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000071
72 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
73
Sebastian Redlf53597f2009-03-15 17:47:39 +000074 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
75 TypeInfoType.withConst(),
76 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +000077}
78
Steve Naroff1b273c42007-09-16 14:56:35 +000079/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +000080Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000081Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000082 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000083 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +000084 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
85 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000086}
Chris Lattner50dd2892008-02-26 00:51:44 +000087
Sebastian Redl6e8ed162009-05-10 18:38:11 +000088/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
89Action::OwningExprResult
90Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
91 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
92}
93
Chris Lattner50dd2892008-02-26 00:51:44 +000094/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +000095Action::OwningExprResult
96Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +000097 Expr *Ex = E.takeAs<Expr>();
98 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
99 return ExprError();
100 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
101}
102
103/// CheckCXXThrowOperand - Validate the operand of a throw.
104bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
105 // C++ [except.throw]p3:
106 // [...] adjusting the type from "array of T" or "function returning T"
107 // to "pointer to T" or "pointer to function returning T", [...]
108 DefaultFunctionArrayConversion(E);
109
110 // If the type of the exception would be an incomplete type or a pointer
111 // to an incomplete type other than (cv) void the program is ill-formed.
112 QualType Ty = E->getType();
113 int isPointer = 0;
114 if (const PointerType* Ptr = Ty->getAsPointerType()) {
115 Ty = Ptr->getPointeeType();
116 isPointer = 1;
117 }
118 if (!isPointer || !Ty->isVoidType()) {
119 if (RequireCompleteType(ThrowLoc, Ty,
120 isPointer ? diag::err_throw_incomplete_ptr
121 : diag::err_throw_incomplete,
122 E->getSourceRange(), SourceRange(), QualType()))
123 return true;
124 }
125
126 // FIXME: Construct a temporary here.
127 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000128}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000129
Sebastian Redlf53597f2009-03-15 17:47:39 +0000130Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000131 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
132 /// is a non-lvalue expression whose value is the address of the object for
133 /// which the function is called.
134
Sebastian Redlf53597f2009-03-15 17:47:39 +0000135 if (!isa<FunctionDecl>(CurContext))
136 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000137
138 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
139 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000140 return Owned(new (Context) CXXThisExpr(ThisLoc,
141 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000142
Sebastian Redlf53597f2009-03-15 17:47:39 +0000143 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000144}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000145
146/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
147/// Can be interpreted either as function-style casting ("int(x)")
148/// or class type construction ("ClassType(x,y,z)")
149/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000150Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000151Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
152 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000153 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000154 SourceLocation *CommaLocs,
155 SourceLocation RParenLoc) {
156 assert(TypeRep && "Missing type!");
157 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000158 unsigned NumExprs = exprs.size();
159 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000160 SourceLocation TyBeginLoc = TypeRange.getBegin();
161 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
162
Sebastian Redlf53597f2009-03-15 17:47:39 +0000163 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000164 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000165 exprs.release();
Anders Carlsson26de5492009-04-24 05:23:13 +0000166
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000167 return Owned(CXXUnresolvedConstructExpr::Create(Context,
168 TypeRange.getBegin(), Ty,
169 LParenLoc,
170 Exprs, NumExprs,
171 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000172 }
173
174
Douglas Gregor506ae412009-01-16 18:33:17 +0000175 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000176 // If the expression list is a single expression, the type conversion
177 // expression is equivalent (in definedness, and if defined in meaning) to the
178 // corresponding cast expression.
179 //
180 if (NumExprs == 1) {
181 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000182 return ExprError();
183 exprs.release();
184 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
185 Ty, TyBeginLoc, Exprs[0],
186 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000187 }
188
Douglas Gregor506ae412009-01-16 18:33:17 +0000189 if (const RecordType *RT = Ty->getAsRecordType()) {
190 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000191
Anders Carlsson165a0a02009-05-17 18:41:29 +0000192 // FIXME: We should always create a CXXTemporaryObjectExpr here unless
193 // both the ctor and dtor are trivial.
Douglas Gregor506ae412009-01-16 18:33:17 +0000194 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
195 CXXConstructorDecl *Constructor
196 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
197 TypeRange.getBegin(),
198 SourceRange(TypeRange.getBegin(),
199 RParenLoc),
200 DeclarationName(),
201 IK_Direct);
Douglas Gregor506ae412009-01-16 18:33:17 +0000202
Sebastian Redlf53597f2009-03-15 17:47:39 +0000203 if (!Constructor)
204 return ExprError();
205
206 exprs.release();
Anders Carlsson8e587a12009-05-30 20:56:46 +0000207 Expr *E = new (Context) CXXTemporaryObjectExpr(Context, Constructor,
Anders Carlssondef11992009-05-30 20:36:53 +0000208 Ty, TyBeginLoc, Exprs,
209 NumExprs, RParenLoc);
210 return MaybeBindToTemporary(E);
Douglas Gregor506ae412009-01-16 18:33:17 +0000211 }
212
213 // Fall through to value-initialize an object of class type that
214 // doesn't have a user-declared default constructor.
215 }
216
217 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000218 // If the expression list specifies more than a single value, the type shall
219 // be a class with a suitably declared constructor.
220 //
221 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000222 return ExprError(Diag(CommaLocs[0],
223 diag::err_builtin_func_cast_more_than_one_arg)
224 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000225
226 assert(NumExprs == 0 && "Expected 0 expressions");
227
Douglas Gregor506ae412009-01-16 18:33:17 +0000228 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000229 // The expression T(), where T is a simple-type-specifier for a non-array
230 // complete object type or the (possibly cv-qualified) void type, creates an
231 // rvalue of the specified type, which is value-initialized.
232 //
233 if (Ty->isArrayType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000234 return ExprError(Diag(TyBeginLoc,
235 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000236 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redlf53597f2009-03-15 17:47:39 +0000237 RequireCompleteType(TyBeginLoc, Ty,
238 diag::err_invalid_incomplete_type_use, FullRange))
239 return ExprError();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000240
Anders Carlsson8211eff2009-03-24 01:19:16 +0000241 if (RequireNonAbstractType(TyBeginLoc, Ty,
242 diag::err_allocation_of_abstract_type))
Anders Carlsson11f21a02009-03-23 19:10:31 +0000243 return ExprError();
244
Sebastian Redlf53597f2009-03-15 17:47:39 +0000245 exprs.release();
246 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000247}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000248
249
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000250/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
251/// @code new (memory) int[size][4] @endcode
252/// or
253/// @code ::new Foo(23, "hello") @endcode
254/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000255Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000256Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000257 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000258 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000259 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000260 MultiExprArg ConstructorArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000261 SourceLocation ConstructorRParen)
262{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000263 Expr *ArraySize = 0;
264 unsigned Skip = 0;
265 // If the specified type is an array, unwrap it and save the expression.
266 if (D.getNumTypeObjects() > 0 &&
267 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
268 DeclaratorChunk &Chunk = D.getTypeObject(0);
269 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000270 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
271 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000272 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000273 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
274 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000275 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
276 Skip = 1;
277 }
278
279 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000280 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000281 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000282
Douglas Gregor3433cf72009-05-21 00:00:09 +0000283 // Every dimension shall be of constant size.
284 unsigned i = 1;
285 QualType ElementType = AllocType;
286 while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
287 if (!Array->isConstantArrayType()) {
288 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
289 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
290 return ExprError();
291 }
292 ElementType = Array->getElementType();
293 ++i;
294 }
295
296 return BuildCXXNew(StartLoc, UseGlobal,
297 PlacementLParen,
298 move(PlacementArgs),
299 PlacementRParen,
300 ParenTypeId,
301 AllocType,
302 D.getSourceRange().getBegin(),
303 D.getSourceRange(),
304 Owned(ArraySize),
305 ConstructorLParen,
306 move(ConstructorArgs),
307 ConstructorRParen);
308}
309
310Sema::OwningExprResult
311Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
312 SourceLocation PlacementLParen,
313 MultiExprArg PlacementArgs,
314 SourceLocation PlacementRParen,
315 bool ParenTypeId,
316 QualType AllocType,
317 SourceLocation TypeLoc,
318 SourceRange TypeRange,
319 ExprArg ArraySizeE,
320 SourceLocation ConstructorLParen,
321 MultiExprArg ConstructorArgs,
322 SourceLocation ConstructorRParen) {
323 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000324 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000325
Douglas Gregor3433cf72009-05-21 00:00:09 +0000326 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000327
328 // That every array dimension except the first is constant was already
329 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000330
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000331 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
332 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000333 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000334 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000335 QualType SizeType = ArraySize->getType();
336 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000337 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
338 diag::err_array_size_not_integral)
339 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000340 // Let's see if this is a constant < 0. If so, we reject it out of hand.
341 // We don't care about special rules, so we tell the machinery it's not
342 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000343 if (!ArraySize->isValueDependent()) {
344 llvm::APSInt Value;
345 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
346 if (Value < llvm::APSInt(
347 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000348 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
349 diag::err_typecheck_negative_array_size)
350 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000351 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000352 }
353 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000354
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000355 FunctionDecl *OperatorNew = 0;
356 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000357 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
358 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000359 if (!AllocType->isDependentType() &&
360 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
361 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000362 SourceRange(PlacementLParen, PlacementRParen),
363 UseGlobal, AllocType, ArraySize, PlaceArgs,
364 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000365 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000366
367 bool Init = ConstructorLParen.isValid();
368 // --- Choosing a constructor ---
369 // C++ 5.3.4p15
370 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
371 // the object is not initialized. If the object, or any part of it, is
372 // const-qualified, it's an error.
373 // 2) If T is a POD and there's an empty initializer, the object is value-
374 // initialized.
375 // 3) If T is a POD and there's one initializer argument, the object is copy-
376 // constructed.
377 // 4) If T is a POD and there's more initializer arguments, it's an error.
378 // 5) If T is not a POD, the initializer arguments are used as constructor
379 // arguments.
380 //
381 // Or by the C++0x formulation:
382 // 1) If there's no initializer, the object is default-initialized according
383 // to C++0x rules.
384 // 2) Otherwise, the object is direct-initialized.
385 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000386 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000387 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000388 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000389 if (AllocType->isDependentType()) {
390 // Skip all the checks.
391 }
Sebastian Redl4f149632009-05-07 16:14:23 +0000392 else if ((RT = AllocType->getAsRecordType()) &&
393 !AllocType->isAggregateType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000394 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000395 AllocType, ConsArgs, NumConsArgs,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000396 TypeLoc,
397 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000398 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000399 NumConsArgs != 0 ? IK_Direct : IK_Default);
400 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000401 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000402 } else {
403 if (!Init) {
404 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000405 if (AllocType.isConstQualified())
406 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000407 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000408 } else if (NumConsArgs == 0) {
409 // Object is value-initialized. Do nothing.
410 } else if (NumConsArgs == 1) {
411 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000412 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000413 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000414 DeclarationName() /*AllocType.getAsString()*/,
415 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000416 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000417 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000418 return ExprError(Diag(StartLoc,
419 diag::err_builtin_direct_init_more_than_one_arg)
420 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000421 }
422 }
423
424 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
425
Sebastian Redlf53597f2009-03-15 17:47:39 +0000426 PlacementArgs.release();
427 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000428 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000429 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000430 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000431 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000432 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000433}
434
435/// CheckAllocatedType - Checks that a type is suitable as the allocated type
436/// in a new-expression.
437/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000438bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
439 SourceRange R)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000440{
441 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
442 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000443 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000444 return Diag(Loc, diag::err_bad_new_type)
445 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000446 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000447 return Diag(Loc, diag::err_bad_new_type)
448 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000449 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000450 RequireCompleteType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000451 diag::err_new_incomplete_type,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000452 R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000453 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000454 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000455 diag::err_allocation_of_abstract_type))
456 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000457
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000458 return false;
459}
460
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000461/// FindAllocationFunctions - Finds the overloads of operator new and delete
462/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000463bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
464 bool UseGlobal, QualType AllocType,
465 bool IsArray, Expr **PlaceArgs,
466 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000467 FunctionDecl *&OperatorNew,
468 FunctionDecl *&OperatorDelete)
469{
470 // --- Choosing an allocation function ---
471 // C++ 5.3.4p8 - 14 & 18
472 // 1) If UseGlobal is true, only look in the global scope. Else, also look
473 // in the scope of the allocated class.
474 // 2) If an array size is given, look for operator new[], else look for
475 // operator new.
476 // 3) The first argument is always size_t. Append the arguments from the
477 // placement form.
478 // FIXME: Also find the appropriate delete operator.
479
480 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
481 // We don't care about the actual value of this argument.
482 // FIXME: Should the Sema create the expression and embed it in the syntax
483 // tree? Or should the consumer just recalculate the value?
Ted Kremenek8189cde2009-02-07 01:47:29 +0000484 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000485 Context.Target.getPointerWidth(0)),
486 Context.getSizeType(),
487 SourceLocation());
488 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
489
490 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
491 IsArray ? OO_Array_New : OO_New);
492 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000493 CXXRecordDecl *Record
494 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000495 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000496 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000497 AllocArgs.size(), Record, /*AllowMissing=*/true,
498 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000499 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000500 }
501 if (!OperatorNew) {
502 // Didn't find a member overload. Look for a global one.
503 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000504 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000505 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000506 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
507 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000508 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000509 }
510
Anders Carlssond9583892009-05-31 20:26:12 +0000511 // FindAllocationOverload can change the passed in arguments, so we need to
512 // copy them back.
513 if (NumPlaceArgs > 0)
514 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
515
Sebastian Redl7f662392008-12-04 22:20:51 +0000516 // FIXME: This is leaked on error. But so much is currently in Sema that it's
517 // easier to clean it in one go.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000518 AllocArgs[0]->Destroy(Context);
519 return false;
520}
521
Sebastian Redl7f662392008-12-04 22:20:51 +0000522/// FindAllocationOverload - Find an fitting overload for the allocation
523/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000524bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
525 DeclarationName Name, Expr** Args,
526 unsigned NumArgs, DeclContext *Ctx,
527 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redl7f662392008-12-04 22:20:51 +0000528{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000529 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000530 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000531 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000532 if (AllowMissing)
533 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000534 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000535 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000536 }
537
538 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000539 for (; Alloc != AllocEnd; ++Alloc) {
540 // Even member operator new/delete are implicitly treated as
541 // static, so don't use AddMemberCandidate.
542 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
543 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
544 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000545 }
546
547 // Do the resolution.
548 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000549 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000550 case OR_Success: {
551 // Got one!
552 FunctionDecl *FnDecl = Best->Function;
553 // The first argument is size_t, and the first parameter must be size_t,
554 // too. This is checked on declaration and can be assumed. (It can't be
555 // asserted on, though, since invalid decls are left in there.)
556 for (unsigned i = 1; i < NumArgs; ++i) {
557 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000558 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000559 FnDecl->getParamDecl(i)->getType(),
560 "passing"))
561 return true;
562 }
563 Operator = FnDecl;
564 return false;
565 }
566
567 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000568 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000569 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000570 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
571 return true;
572
573 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000574 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000575 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000576 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
577 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000578
579 case OR_Deleted:
580 Diag(StartLoc, diag::err_ovl_deleted_call)
581 << Best->Function->isDeleted()
582 << Name << Range;
583 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
584 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000585 }
586 assert(false && "Unreachable, bad result from BestViableFunction");
587 return true;
588}
589
590
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000591/// DeclareGlobalNewDelete - Declare the global forms of operator new and
592/// delete. These are:
593/// @code
594/// void* operator new(std::size_t) throw(std::bad_alloc);
595/// void* operator new[](std::size_t) throw(std::bad_alloc);
596/// void operator delete(void *) throw();
597/// void operator delete[](void *) throw();
598/// @endcode
599/// Note that the placement and nothrow forms of new are *not* implicitly
600/// declared. Their use requires including \<new\>.
601void Sema::DeclareGlobalNewDelete()
602{
603 if (GlobalNewDeleteDeclared)
604 return;
605 GlobalNewDeleteDeclared = true;
606
607 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
608 QualType SizeT = Context.getSizeType();
609
610 // FIXME: Exception specifications are not added.
611 DeclareGlobalAllocationFunction(
612 Context.DeclarationNames.getCXXOperatorName(OO_New),
613 VoidPtr, SizeT);
614 DeclareGlobalAllocationFunction(
615 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
616 VoidPtr, SizeT);
617 DeclareGlobalAllocationFunction(
618 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
619 Context.VoidTy, VoidPtr);
620 DeclareGlobalAllocationFunction(
621 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
622 Context.VoidTy, VoidPtr);
623}
624
625/// DeclareGlobalAllocationFunction - Declares a single implicit global
626/// allocation function if it doesn't already exist.
627void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
628 QualType Return, QualType Argument)
629{
630 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
631
632 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000633 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000634 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000635 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Context, Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000636 Alloc != AllocEnd; ++Alloc) {
637 // FIXME: Do we need to check for default arguments here?
638 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
639 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000640 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000641 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000642 }
643 }
644
645 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
646 FunctionDecl *Alloc =
647 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor2224f842009-02-25 16:33:18 +0000648 FnType, FunctionDecl::None, false, true,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000649 SourceLocation());
650 Alloc->setImplicit();
651 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000652 0, Argument, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000653 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000654
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000655 // FIXME: Also add this declaration to the IdentifierResolver, but
656 // make sure it is at the end of the chain to coincide with the
657 // global scope.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000658 ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000659}
660
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000661/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
662/// @code ::delete ptr; @endcode
663/// or
664/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000665Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000666Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000667 bool ArrayForm, ExprArg Operand)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000668{
669 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
670 // having a single conversion function to a pointer type. The result has
671 // type void."
672 // DR599 amends "pointer type" to "pointer to object type" in both cases.
673
Sebastian Redlf53597f2009-03-15 17:47:39 +0000674 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000675 if (!Ex->isTypeDependent()) {
676 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000677
Sebastian Redl28507842009-02-26 14:39:58 +0000678 if (Type->isRecordType()) {
679 // FIXME: Find that one conversion function and amend the type.
680 }
681
Sebastian Redlf53597f2009-03-15 17:47:39 +0000682 if (!Type->isPointerType())
683 return ExprError(Diag(StartLoc, diag::err_delete_operand)
684 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000685
686 QualType Pointee = Type->getAsPointerType()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000687 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000688 return ExprError(Diag(StartLoc, diag::err_delete_operand)
689 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000690 else if (!Pointee->isDependentType() &&
691 RequireCompleteType(StartLoc, Pointee,
692 diag::warn_delete_incomplete,
693 Ex->getSourceRange()))
694 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000695
696 // FIXME: Look up the correct operator delete overload and pass a pointer
697 // along.
698 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000699 }
700
Sebastian Redlf53597f2009-03-15 17:47:39 +0000701 Operand.release();
702 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
703 0, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000704}
705
706
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000707/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
708/// C++ if/switch/while/for statement.
709/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000710Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000711Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
712 Declarator &D,
713 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000714 ExprArg AssignExprVal) {
715 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000716
717 // C++ 6.4p2:
718 // The declarator shall not specify a function or an array.
719 // The type-specifier-seq shall not contain typedef and shall not declare a
720 // new class or enumeration.
721
722 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
723 "Parser allowed 'typedef' as storage class of condition decl.");
724
725 QualType Ty = GetTypeForDeclarator(D, S);
726
727 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
728 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
729 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000730 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
731 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000732 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000733 Diag(StartLoc, diag::err_invalid_use_of_array_type)
734 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000735 } else if (const RecordType *RT = Ty->getAsRecordType()) {
736 RecordDecl *RD = RT->getDecl();
737 // The type-specifier-seq shall not declare a new class...
Chris Lattnerb28317a2009-03-28 19:18:32 +0000738 if (RD->isDefinition() &&
739 (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD))))
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000740 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
741 } else if (const EnumType *ET = Ty->getAsEnumType()) {
742 EnumDecl *ED = ET->getDecl();
743 // ...or enumeration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000744 if (ED->isDefinition() &&
745 (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED))))
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000746 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
747 }
748
Chris Lattnerb28317a2009-03-28 19:18:32 +0000749 DeclPtrTy Dcl = ActOnDeclarator(S, D, DeclPtrTy());
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000750 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000751 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000752 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000753
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000754 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000755 // We know that the decl had to be a VarDecl because that is the only type of
756 // decl that can be assigned and the grammar requires an '='.
757 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
758 VD->setDeclaredInCondition(true);
759 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000760}
761
762/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
763bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
764 // C++ 6.4p4:
765 // The value of a condition that is an initialized declaration in a statement
766 // other than a switch statement is the value of the declared variable
767 // implicitly converted to type bool. If that conversion is ill-formed, the
768 // program is ill-formed.
769 // The value of a condition that is an expression is the value of the
770 // expression, implicitly converted to bool.
771 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000772 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000773}
Douglas Gregor77a52232008-09-12 00:47:35 +0000774
775/// Helper function to determine whether this is the (deprecated) C++
776/// conversion from a string literal to a pointer to non-const char or
777/// non-const wchar_t (for narrow and wide string literals,
778/// respectively).
779bool
780Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
781 // Look inside the implicit cast, if it exists.
782 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
783 From = Cast->getSubExpr();
784
785 // A string literal (2.13.4) that is not a wide string literal can
786 // be converted to an rvalue of type "pointer to char"; a wide
787 // string literal can be converted to an rvalue of type "pointer
788 // to wchar_t" (C++ 4.2p2).
789 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
790 if (const PointerType *ToPtrType = ToType->getAsPointerType())
791 if (const BuiltinType *ToPointeeType
792 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
793 // This conversion is considered only when there is an
794 // explicit appropriate pointer target type (C++ 4.2p2).
795 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
796 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
797 (!StrLit->isWide() &&
798 (ToPointeeType->getKind() == BuiltinType::Char_U ||
799 ToPointeeType->getKind() == BuiltinType::Char_S))))
800 return true;
801 }
802
803 return false;
804}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000805
806/// PerformImplicitConversion - Perform an implicit conversion of the
807/// expression From to the type ToType. Returns true if there was an
808/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000809/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000810/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000811/// explicit user-defined conversions are permitted. @p Elidable should be true
812/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
813/// resolution works differently in that case.
814bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000815Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000816 const char *Flavor, bool AllowExplicit,
817 bool Elidable)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000818{
Sebastian Redle2b68332009-04-12 17:16:29 +0000819 ImplicitConversionSequence ICS;
820 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
821 if (Elidable && getLangOptions().CPlusPlus0x) {
822 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
823 AllowExplicit, /*ForceRValue*/true);
824 }
825 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
826 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
827 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000828 return PerformImplicitConversion(From, ToType, ICS, Flavor);
829}
830
831/// PerformImplicitConversion - Perform an implicit conversion of the
832/// expression From to the type ToType using the pre-computed implicit
833/// conversion sequence ICS. Returns true if there was an error, false
834/// otherwise. The expression From is replaced with the converted
835/// expression. Flavor is the kind of conversion we're performing,
836/// used in the error message.
837bool
838Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
839 const ImplicitConversionSequence &ICS,
840 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000841 switch (ICS.ConversionKind) {
842 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000843 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000844 return true;
845 break;
846
847 case ImplicitConversionSequence::UserDefinedConversion:
Mike Stump390b4cc2009-05-16 07:39:55 +0000848 // FIXME: This is, of course, wrong. We'll need to actually call the
849 // constructor or conversion operator, and then cope with the standard
850 // conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000851 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000852 ToType->isLValueReferenceType());
Douglas Gregor60d62c22008-10-31 16:23:19 +0000853 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000854
855 case ImplicitConversionSequence::EllipsisConversion:
856 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000857 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000858
859 case ImplicitConversionSequence::BadConversion:
860 return true;
861 }
862
863 // Everything went well.
864 return false;
865}
866
867/// PerformImplicitConversion - Perform an implicit conversion of the
868/// expression From to the type ToType by following the standard
869/// conversion sequence SCS. Returns true if there was an error, false
870/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000871/// expression. Flavor is the context in which we're performing this
872/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000873bool
874Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000875 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000876 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000877 // Overall FIXME: we are recomputing too many types here and doing far too
878 // much extra work. What this means is that we need to keep track of more
879 // information that is computed when we try the implicit conversion initially,
880 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000881 QualType FromType = From->getType();
882
Douglas Gregor225c41e2008-11-03 19:09:14 +0000883 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +0000884 // FIXME: When can ToType be a reference type?
885 assert(!ToType->isReferenceType());
886
Anders Carlsson7c3e8a12009-05-19 04:45:15 +0000887 // FIXME: Keep track of whether the copy constructor is elidable or not.
Anders Carlsson8e587a12009-05-30 20:56:46 +0000888 From = CXXConstructExpr::Create(Context, ToType,
Anders Carlsson7c3e8a12009-05-19 04:45:15 +0000889 SCS.CopyConstructor, false, &From, 1);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000890 return false;
891 }
892
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000893 // Perform the first implicit conversion.
894 switch (SCS.First) {
895 case ICK_Identity:
896 case ICK_Lvalue_To_Rvalue:
897 // Nothing to do.
898 break;
899
900 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000901 FromType = Context.getArrayDecayedType(FromType);
902 ImpCastExprToType(From, FromType);
903 break;
904
905 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +0000906 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +0000907 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
908 if (!Fn)
909 return true;
910
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000911 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
912 return true;
913
Douglas Gregor904eed32008-11-10 20:40:00 +0000914 FixOverloadedFunctionReference(From, Fn);
915 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +0000916 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000917 FromType = Context.getPointerType(FromType);
918 ImpCastExprToType(From, FromType);
919 break;
920
921 default:
922 assert(false && "Improper first standard conversion");
923 break;
924 }
925
926 // Perform the second implicit conversion
927 switch (SCS.Second) {
928 case ICK_Identity:
929 // Nothing to do.
930 break;
931
932 case ICK_Integral_Promotion:
933 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000934 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000935 case ICK_Integral_Conversion:
936 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000937 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000938 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000939 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +0000940 case ICK_Compatible_Conversion:
941 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000942 FromType = ToType.getUnqualifiedType();
943 ImpCastExprToType(From, FromType);
944 break;
945
946 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000947 if (SCS.IncompatibleObjC) {
948 // Diagnose incompatible Objective-C conversions
949 Diag(From->getSourceRange().getBegin(),
950 diag::ext_typecheck_convert_incompatible_pointer)
951 << From->getType() << ToType << Flavor
952 << From->getSourceRange();
953 }
954
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000955 if (CheckPointerConversion(From, ToType))
956 return true;
957 ImpCastExprToType(From, ToType);
958 break;
959
960 case ICK_Pointer_Member:
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000961 if (CheckMemberPointerConversion(From, ToType))
962 return true;
963 ImpCastExprToType(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000964 break;
965
966 case ICK_Boolean_Conversion:
967 FromType = Context.BoolTy;
968 ImpCastExprToType(From, FromType);
969 break;
970
971 default:
972 assert(false && "Improper second standard conversion");
973 break;
974 }
975
976 switch (SCS.Third) {
977 case ICK_Identity:
978 // Nothing to do.
979 break;
980
981 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +0000982 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
983 // references.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000984 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000985 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000986 break;
987
988 default:
989 assert(false && "Improper second standard conversion");
990 break;
991 }
992
993 return false;
994}
995
Sebastian Redl64b45f72009-01-05 20:52:13 +0000996Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
997 SourceLocation KWLoc,
998 SourceLocation LParen,
999 TypeTy *Ty,
1000 SourceLocation RParen) {
1001 // FIXME: Some of the type traits have requirements. Interestingly, only the
Mike Stump390b4cc2009-05-16 07:39:55 +00001002 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed, G++
1003 // accepts __is_pod(Incomplete) without complaints, and claims that the type
1004 // is indeed a POD.
Sebastian Redl64b45f72009-01-05 20:52:13 +00001005
1006 // There is no point in eagerly computing the value. The traits are designed
1007 // to be used from type trait templates, so Ty will be a template parameter
1008 // 99% of the time.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001009 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
Sebastian Redl64b45f72009-01-05 20:52:13 +00001010 QualType::getFromOpaquePtr(Ty),
1011 RParen, Context.BoolTy));
1012}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001013
1014QualType Sema::CheckPointerToMemberOperands(
1015 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
1016{
1017 const char *OpSpelling = isIndirect ? "->*" : ".*";
1018 // C++ 5.5p2
1019 // The binary operator .* [p3: ->*] binds its second operand, which shall
1020 // be of type "pointer to member of T" (where T is a completely-defined
1021 // class type) [...]
1022 QualType RType = rex->getType();
1023 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
Douglas Gregore7450f52009-03-24 19:52:54 +00001024 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001025 Diag(Loc, diag::err_bad_memptr_rhs)
1026 << OpSpelling << RType << rex->getSourceRange();
1027 return QualType();
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00001028 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001029
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001030 QualType Class(MemPtr->getClass(), 0);
1031
1032 // C++ 5.5p2
1033 // [...] to its first operand, which shall be of class T or of a class of
1034 // which T is an unambiguous and accessible base class. [p3: a pointer to
1035 // such a class]
1036 QualType LType = lex->getType();
1037 if (isIndirect) {
1038 if (const PointerType *Ptr = LType->getAsPointerType())
1039 LType = Ptr->getPointeeType().getNonReferenceType();
1040 else {
1041 Diag(Loc, diag::err_bad_memptr_lhs)
1042 << OpSpelling << 1 << LType << lex->getSourceRange();
1043 return QualType();
1044 }
1045 }
1046
1047 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1048 Context.getCanonicalType(LType).getUnqualifiedType()) {
1049 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1050 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001051 // FIXME: Would it be useful to print full ambiguity paths, or is that
1052 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001053 if (!IsDerivedFrom(LType, Class, Paths) ||
1054 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1055 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1056 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1057 return QualType();
1058 }
1059 }
1060
1061 // C++ 5.5p2
1062 // The result is an object or a function of the type specified by the
1063 // second operand.
1064 // The cv qualifiers are the union of those in the pointer and the left side,
1065 // in accordance with 5.5p5 and 5.2.5.
1066 // FIXME: This returns a dereferenced member function pointer as a normal
1067 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001068 // calling them. There's also a GCC extension to get a function pointer to the
1069 // thing, which is another complication, because this type - unlike the type
1070 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001071 // argument.
1072 // We probably need a "MemberFunctionClosureType" or something like that.
1073 QualType Result = MemPtr->getPointeeType();
1074 if (LType.isConstQualified())
1075 Result.addConst();
1076 if (LType.isVolatileQualified())
1077 Result.addVolatile();
1078 return Result;
1079}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001080
1081/// \brief Get the target type of a standard or user-defined conversion.
1082static QualType TargetType(const ImplicitConversionSequence &ICS) {
1083 assert((ICS.ConversionKind ==
1084 ImplicitConversionSequence::StandardConversion ||
1085 ICS.ConversionKind ==
1086 ImplicitConversionSequence::UserDefinedConversion) &&
1087 "function only valid for standard or user-defined conversions");
1088 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1089 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1090 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1091}
1092
1093/// \brief Try to convert a type to another according to C++0x 5.16p3.
1094///
1095/// This is part of the parameter validation for the ? operator. If either
1096/// value operand is a class type, the two operands are attempted to be
1097/// converted to each other. This function does the conversion in one direction.
1098/// It emits a diagnostic and returns true only if it finds an ambiguous
1099/// conversion.
1100static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1101 SourceLocation QuestionLoc,
1102 ImplicitConversionSequence &ICS)
1103{
1104 // C++0x 5.16p3
1105 // The process for determining whether an operand expression E1 of type T1
1106 // can be converted to match an operand expression E2 of type T2 is defined
1107 // as follows:
1108 // -- If E2 is an lvalue:
1109 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1110 // E1 can be converted to match E2 if E1 can be implicitly converted to
1111 // type "lvalue reference to T2", subject to the constraint that in the
1112 // conversion the reference must bind directly to E1.
1113 if (!Self.CheckReferenceInit(From,
1114 Self.Context.getLValueReferenceType(To->getType()),
1115 &ICS))
1116 {
1117 assert((ICS.ConversionKind ==
1118 ImplicitConversionSequence::StandardConversion ||
1119 ICS.ConversionKind ==
1120 ImplicitConversionSequence::UserDefinedConversion) &&
1121 "expected a definite conversion");
1122 bool DirectBinding =
1123 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1124 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1125 if (DirectBinding)
1126 return false;
1127 }
1128 }
1129 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1130 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1131 // -- if E1 and E2 have class type, and the underlying class types are
1132 // the same or one is a base class of the other:
1133 QualType FTy = From->getType();
1134 QualType TTy = To->getType();
1135 const RecordType *FRec = FTy->getAsRecordType();
1136 const RecordType *TRec = TTy->getAsRecordType();
1137 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1138 if (FRec && TRec && (FRec == TRec ||
1139 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1140 // E1 can be converted to match E2 if the class of T2 is the
1141 // same type as, or a base class of, the class of T1, and
1142 // [cv2 > cv1].
1143 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1144 // Could still fail if there's no copy constructor.
1145 // FIXME: Is this a hard error then, or just a conversion failure? The
1146 // standard doesn't say.
1147 ICS = Self.TryCopyInitialization(From, TTy);
1148 }
1149 } else {
1150 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1151 // implicitly converted to the type that expression E2 would have
1152 // if E2 were converted to an rvalue.
1153 // First find the decayed type.
1154 if (TTy->isFunctionType())
1155 TTy = Self.Context.getPointerType(TTy);
1156 else if(TTy->isArrayType())
1157 TTy = Self.Context.getArrayDecayedType(TTy);
1158
1159 // Now try the implicit conversion.
1160 // FIXME: This doesn't detect ambiguities.
1161 ICS = Self.TryImplicitConversion(From, TTy);
1162 }
1163 return false;
1164}
1165
1166/// \brief Try to find a common type for two according to C++0x 5.16p5.
1167///
1168/// This is part of the parameter validation for the ? operator. If either
1169/// value operand is a class type, overload resolution is used to find a
1170/// conversion to a common type.
1171static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1172 SourceLocation Loc) {
1173 Expr *Args[2] = { LHS, RHS };
1174 OverloadCandidateSet CandidateSet;
1175 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1176
1177 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001178 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001179 case Sema::OR_Success:
1180 // We found a match. Perform the conversions on the arguments and move on.
1181 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1182 Best->Conversions[0], "converting") ||
1183 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1184 Best->Conversions[1], "converting"))
1185 break;
1186 return false;
1187
1188 case Sema::OR_No_Viable_Function:
1189 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1190 << LHS->getType() << RHS->getType()
1191 << LHS->getSourceRange() << RHS->getSourceRange();
1192 return true;
1193
1194 case Sema::OR_Ambiguous:
1195 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1196 << LHS->getType() << RHS->getType()
1197 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001198 // FIXME: Print the possible common types by printing the return types of
1199 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001200 break;
1201
1202 case Sema::OR_Deleted:
1203 assert(false && "Conditional operator has only built-in overloads");
1204 break;
1205 }
1206 return true;
1207}
1208
Sebastian Redl76458502009-04-17 16:30:52 +00001209/// \brief Perform an "extended" implicit conversion as returned by
1210/// TryClassUnification.
1211///
1212/// TryClassUnification generates ICSs that include reference bindings.
1213/// PerformImplicitConversion is not suitable for this; it chokes if the
1214/// second part of a standard conversion is ICK_DerivedToBase. This function
1215/// handles the reference binding specially.
1216static bool ConvertForConditional(Sema &Self, Expr *&E,
1217 const ImplicitConversionSequence &ICS)
1218{
1219 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1220 ICS.Standard.ReferenceBinding) {
1221 assert(ICS.Standard.DirectBinding &&
1222 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001223 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1224 // redoing all the work.
1225 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1226 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001227 }
1228 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1229 ICS.UserDefined.After.ReferenceBinding) {
1230 assert(ICS.UserDefined.After.DirectBinding &&
1231 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001232 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1233 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001234 }
1235 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1236 return true;
1237 return false;
1238}
1239
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001240/// \brief Check the operands of ?: under C++ semantics.
1241///
1242/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1243/// extension. In this case, LHS == Cond. (But they're not aliases.)
1244QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1245 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001246 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1247 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001248
1249 // C++0x 5.16p1
1250 // The first expression is contextually converted to bool.
1251 if (!Cond->isTypeDependent()) {
1252 if (CheckCXXBooleanCondition(Cond))
1253 return QualType();
1254 }
1255
1256 // Either of the arguments dependent?
1257 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1258 return Context.DependentTy;
1259
1260 // C++0x 5.16p2
1261 // If either the second or the third operand has type (cv) void, ...
1262 QualType LTy = LHS->getType();
1263 QualType RTy = RHS->getType();
1264 bool LVoid = LTy->isVoidType();
1265 bool RVoid = RTy->isVoidType();
1266 if (LVoid || RVoid) {
1267 // ... then the [l2r] conversions are performed on the second and third
1268 // operands ...
1269 DefaultFunctionArrayConversion(LHS);
1270 DefaultFunctionArrayConversion(RHS);
1271 LTy = LHS->getType();
1272 RTy = RHS->getType();
1273
1274 // ... and one of the following shall hold:
1275 // -- The second or the third operand (but not both) is a throw-
1276 // expression; the result is of the type of the other and is an rvalue.
1277 bool LThrow = isa<CXXThrowExpr>(LHS);
1278 bool RThrow = isa<CXXThrowExpr>(RHS);
1279 if (LThrow && !RThrow)
1280 return RTy;
1281 if (RThrow && !LThrow)
1282 return LTy;
1283
1284 // -- Both the second and third operands have type void; the result is of
1285 // type void and is an rvalue.
1286 if (LVoid && RVoid)
1287 return Context.VoidTy;
1288
1289 // Neither holds, error.
1290 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1291 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1292 << LHS->getSourceRange() << RHS->getSourceRange();
1293 return QualType();
1294 }
1295
1296 // Neither is void.
1297
1298 // C++0x 5.16p3
1299 // Otherwise, if the second and third operand have different types, and
1300 // either has (cv) class type, and attempt is made to convert each of those
1301 // operands to the other.
1302 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1303 (LTy->isRecordType() || RTy->isRecordType())) {
1304 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1305 // These return true if a single direction is already ambiguous.
1306 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1307 return QualType();
1308 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1309 return QualType();
1310
1311 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1312 ImplicitConversionSequence::BadConversion;
1313 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1314 ImplicitConversionSequence::BadConversion;
1315 // If both can be converted, [...] the program is ill-formed.
1316 if (HaveL2R && HaveR2L) {
1317 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1318 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1319 return QualType();
1320 }
1321
1322 // If exactly one conversion is possible, that conversion is applied to
1323 // the chosen operand and the converted operands are used in place of the
1324 // original operands for the remainder of this section.
1325 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001326 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001327 return QualType();
1328 LTy = LHS->getType();
1329 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001330 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001331 return QualType();
1332 RTy = RHS->getType();
1333 }
1334 }
1335
1336 // C++0x 5.16p4
1337 // If the second and third operands are lvalues and have the same type,
1338 // the result is of that type [...]
1339 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1340 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1341 RHS->isLvalue(Context) == Expr::LV_Valid)
1342 return LTy;
1343
1344 // C++0x 5.16p5
1345 // Otherwise, the result is an rvalue. If the second and third operands
1346 // do not have the same type, and either has (cv) class type, ...
1347 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1348 // ... overload resolution is used to determine the conversions (if any)
1349 // to be applied to the operands. If the overload resolution fails, the
1350 // program is ill-formed.
1351 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1352 return QualType();
1353 }
1354
1355 // C++0x 5.16p6
1356 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1357 // conversions are performed on the second and third operands.
1358 DefaultFunctionArrayConversion(LHS);
1359 DefaultFunctionArrayConversion(RHS);
1360 LTy = LHS->getType();
1361 RTy = RHS->getType();
1362
1363 // After those conversions, one of the following shall hold:
1364 // -- The second and third operands have the same type; the result
1365 // is of that type.
1366 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1367 return LTy;
1368
1369 // -- The second and third operands have arithmetic or enumeration type;
1370 // the usual arithmetic conversions are performed to bring them to a
1371 // common type, and the result is of that type.
1372 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1373 UsualArithmeticConversions(LHS, RHS);
1374 return LHS->getType();
1375 }
1376
1377 // -- The second and third operands have pointer type, or one has pointer
1378 // type and the other is a null pointer constant; pointer conversions
1379 // and qualification conversions are performed to bring them to their
1380 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001381 QualType Composite = FindCompositePointerType(LHS, RHS);
1382 if (!Composite.isNull())
1383 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001384
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001385 // Fourth bullet is same for pointers-to-member. However, the possible
1386 // conversions are far more limited: we have null-to-pointer, upcast of
1387 // containing class, and second-level cv-ness.
1388 // cv-ness is not a union, but must match one of the two operands. (Which,
1389 // frankly, is stupid.)
1390 const MemberPointerType *LMemPtr = LTy->getAsMemberPointerType();
1391 const MemberPointerType *RMemPtr = RTy->getAsMemberPointerType();
1392 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1393 ImpCastExprToType(RHS, LTy);
1394 return LTy;
1395 }
1396 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1397 ImpCastExprToType(LHS, RTy);
1398 return RTy;
1399 }
1400 if (LMemPtr && RMemPtr) {
1401 QualType LPointee = LMemPtr->getPointeeType();
1402 QualType RPointee = RMemPtr->getPointeeType();
1403 // First, we check that the unqualified pointee type is the same. If it's
1404 // not, there's no conversion that will unify the two pointers.
1405 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1406 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1407 // Second, we take the greater of the two cv qualifications. If neither
1408 // is greater than the other, the conversion is not possible.
1409 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1410 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1411 // Third, we check if either of the container classes is derived from
1412 // the other.
1413 QualType LContainer(LMemPtr->getClass(), 0);
1414 QualType RContainer(RMemPtr->getClass(), 0);
1415 QualType MoreDerived;
1416 if (Context.getCanonicalType(LContainer) ==
1417 Context.getCanonicalType(RContainer))
1418 MoreDerived = LContainer;
1419 else if (IsDerivedFrom(LContainer, RContainer))
1420 MoreDerived = LContainer;
1421 else if (IsDerivedFrom(RContainer, LContainer))
1422 MoreDerived = RContainer;
1423
1424 if (!MoreDerived.isNull()) {
1425 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1426 // We don't use ImpCastExprToType here because this could still fail
1427 // for ambiguous or inaccessible conversions.
1428 QualType Common = Context.getMemberPointerType(
1429 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1430 if (PerformImplicitConversion(LHS, Common, "converting"))
1431 return QualType();
1432 if (PerformImplicitConversion(RHS, Common, "converting"))
1433 return QualType();
1434 return Common;
1435 }
1436 }
1437 }
1438 }
1439
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001440 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1441 << LHS->getType() << RHS->getType()
1442 << LHS->getSourceRange() << RHS->getSourceRange();
1443 return QualType();
1444}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001445
1446/// \brief Find a merged pointer type and convert the two expressions to it.
1447///
1448/// This finds the composite pointer type for @p E1 and @p E2 according to
1449/// C++0x 5.9p2. It converts both expressions to this type and returns it.
1450/// It does not emit diagnostics.
1451QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1452 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1453 QualType T1 = E1->getType(), T2 = E2->getType();
1454 if(!T1->isPointerType() && !T2->isPointerType())
1455 return QualType();
1456
1457 // C++0x 5.9p2
1458 // Pointer conversions and qualification conversions are performed on
1459 // pointer operands to bring them to their composite pointer type. If
1460 // one operand is a null pointer constant, the composite pointer type is
1461 // the type of the other operand.
1462 if (E1->isNullPointerConstant(Context)) {
1463 ImpCastExprToType(E1, T2);
1464 return T2;
1465 }
1466 if (E2->isNullPointerConstant(Context)) {
1467 ImpCastExprToType(E2, T1);
1468 return T1;
1469 }
1470 // Now both have to be pointers.
1471 if(!T1->isPointerType() || !T2->isPointerType())
1472 return QualType();
1473
1474 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1475 // the other has type "pointer to cv2 T" and the composite pointer type is
1476 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1477 // Otherwise, the composite pointer type is a pointer type similar to the
1478 // type of one of the operands, with a cv-qualification signature that is
1479 // the union of the cv-qualification signatures of the operand types.
1480 // In practice, the first part here is redundant; it's subsumed by the second.
1481 // What we do here is, we build the two possible composite types, and try the
1482 // conversions in both directions. If only one works, or if the two composite
1483 // types are the same, we have succeeded.
1484 llvm::SmallVector<unsigned, 4> QualifierUnion;
1485 QualType Composite1 = T1, Composite2 = T2;
1486 const PointerType *Ptr1, *Ptr2;
1487 while ((Ptr1 = Composite1->getAsPointerType()) &&
1488 (Ptr2 = Composite2->getAsPointerType())) {
1489 Composite1 = Ptr1->getPointeeType();
1490 Composite2 = Ptr2->getPointeeType();
1491 QualifierUnion.push_back(
1492 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1493 }
1494 // Rewrap the composites as pointers with the union CVRs.
1495 for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(),
1496 E = QualifierUnion.end(); I != E; ++I) {
1497 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1498 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1499 }
1500
1501 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1502 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1503 ImplicitConversionSequence E1ToC2, E2ToC2;
1504 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1505 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1506 if (Context.getCanonicalType(Composite1) !=
1507 Context.getCanonicalType(Composite2)) {
1508 E1ToC2 = TryImplicitConversion(E1, Composite2);
1509 E2ToC2 = TryImplicitConversion(E2, Composite2);
1510 }
1511
1512 bool ToC1Viable = E1ToC1.ConversionKind !=
1513 ImplicitConversionSequence::BadConversion
1514 && E2ToC1.ConversionKind !=
1515 ImplicitConversionSequence::BadConversion;
1516 bool ToC2Viable = E1ToC2.ConversionKind !=
1517 ImplicitConversionSequence::BadConversion
1518 && E2ToC2.ConversionKind !=
1519 ImplicitConversionSequence::BadConversion;
1520 if (ToC1Viable && !ToC2Viable) {
1521 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1522 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1523 return Composite1;
1524 }
1525 if (ToC2Viable && !ToC1Viable) {
1526 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1527 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1528 return Composite2;
1529 }
1530 return QualType();
1531}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001532
Anders Carlssondef11992009-05-30 20:36:53 +00001533Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
1534 const RecordType *RT = E->getType()->getAsRecordType();
1535 if (!RT)
1536 return Owned(E);
1537
1538 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1539 if (RD->hasTrivialDestructor())
1540 return Owned(E);
1541
1542 CXXTemporary *Temp = CXXTemporary::Create(Context,
1543 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00001544 ExprTemporaries.push_back(Temp);
1545
Anders Carlssondef11992009-05-30 20:36:53 +00001546 // FIXME: Add the temporary to the temporaries vector.
1547 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1548}
1549
Anders Carlsson75bbb972009-05-30 22:51:20 +00001550// FIXME: This doesn't handle casts yet.
1551Expr *Sema::RemoveOutermostTemporaryBinding(Expr *E) {
1552 const RecordType *RT = E->getType()->getAsRecordType();
1553 if (!RT)
1554 return E;
1555
1556 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1557 if (RD->hasTrivialDestructor())
1558 return E;
1559
1560 /// The expr passed in must be a CXXExprWithTemporaries.
1561 CXXExprWithTemporaries *TempExpr = dyn_cast<CXXExprWithTemporaries>(E);
1562 if (!TempExpr)
1563 return E;
1564
1565 Expr *SubExpr = TempExpr->getSubExpr();
1566 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) {
1567 assert(BE->getTemporary() ==
1568 TempExpr->getTemporary(TempExpr->getNumTemporaries() - 1) &&
1569 "Found temporary is not last in list!");
1570
1571 Expr *BindSubExpr = BE->getSubExpr();
1572 BE->setSubExpr(0);
1573
1574 if (TempExpr->getNumTemporaries() == 1) {
1575 // There's just one temporary left, so we don't need the TempExpr node.
1576 TempExpr->Destroy(Context);
1577 return BindSubExpr;
1578 } else {
1579 TempExpr->removeLastTemporary();
1580 TempExpr->setSubExpr(BindSubExpr);
1581 BE->Destroy(Context);
1582 }
1583
1584 return E;
1585 }
1586
1587 // FIXME: We might need to handle other expressions here.
1588 return E;
1589}
1590
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001591Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00001592 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001593 assert(SubExpr && "sub expression can't be null!");
1594
1595 if (ExprTemporaries.empty())
1596 return SubExpr;
1597
1598 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1599 &ExprTemporaries[0],
1600 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00001601 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001602 ExprTemporaries.clear();
1603
1604 return E;
1605}
1606
Anders Carlsson165a0a02009-05-17 18:41:29 +00001607Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1608 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001609 if (FullExpr)
Anders Carlssonf54741e2009-06-16 03:37:31 +00001610 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
1611 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00001612
1613 return Owned(FullExpr);
1614}