blob: f6ee0927da85f308f285b565da0f33333f4e75f8 [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
167 // FIXME: Is this correct?
168 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty);
Anders Carlsson09c4abb2009-04-24 05:44:25 +0000169 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Temp, 0, Ty,
170 TyBeginLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000171 Exprs, NumExprs,
172 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000173 }
174
175
Douglas Gregor506ae412009-01-16 18:33:17 +0000176 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000177 // If the expression list is a single expression, the type conversion
178 // expression is equivalent (in definedness, and if defined in meaning) to the
179 // corresponding cast expression.
180 //
181 if (NumExprs == 1) {
182 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000183 return ExprError();
184 exprs.release();
185 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
186 Ty, TyBeginLoc, Exprs[0],
187 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000188 }
189
Douglas Gregor506ae412009-01-16 18:33:17 +0000190 if (const RecordType *RT = Ty->getAsRecordType()) {
191 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000192
Douglas Gregor506ae412009-01-16 18:33:17 +0000193 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
194 CXXConstructorDecl *Constructor
195 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
196 TypeRange.getBegin(),
197 SourceRange(TypeRange.getBegin(),
198 RParenLoc),
199 DeclarationName(),
200 IK_Direct);
Douglas Gregor506ae412009-01-16 18:33:17 +0000201
Sebastian Redlf53597f2009-03-15 17:47:39 +0000202 if (!Constructor)
203 return ExprError();
204
Anders Carlsson26de5492009-04-24 05:23:13 +0000205 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty);
206
Sebastian Redlf53597f2009-03-15 17:47:39 +0000207 exprs.release();
Anders Carlsson09c4abb2009-04-24 05:44:25 +0000208 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Temp,
209 Constructor, Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000210 TyBeginLoc, Exprs,
211 NumExprs, RParenLoc));
Douglas Gregor506ae412009-01-16 18:33:17 +0000212 }
213
214 // Fall through to value-initialize an object of class type that
215 // doesn't have a user-declared default constructor.
216 }
217
218 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000219 // If the expression list specifies more than a single value, the type shall
220 // be a class with a suitably declared constructor.
221 //
222 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000223 return ExprError(Diag(CommaLocs[0],
224 diag::err_builtin_func_cast_more_than_one_arg)
225 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000226
227 assert(NumExprs == 0 && "Expected 0 expressions");
228
Douglas Gregor506ae412009-01-16 18:33:17 +0000229 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000230 // The expression T(), where T is a simple-type-specifier for a non-array
231 // complete object type or the (possibly cv-qualified) void type, creates an
232 // rvalue of the specified type, which is value-initialized.
233 //
234 if (Ty->isArrayType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000235 return ExprError(Diag(TyBeginLoc,
236 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000237 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redlf53597f2009-03-15 17:47:39 +0000238 RequireCompleteType(TyBeginLoc, Ty,
239 diag::err_invalid_incomplete_type_use, FullRange))
240 return ExprError();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000241
Anders Carlsson8211eff2009-03-24 01:19:16 +0000242 if (RequireNonAbstractType(TyBeginLoc, Ty,
243 diag::err_allocation_of_abstract_type))
Anders Carlsson11f21a02009-03-23 19:10:31 +0000244 return ExprError();
245
Sebastian Redlf53597f2009-03-15 17:47:39 +0000246 exprs.release();
247 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000248}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000249
250
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000251/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
252/// @code new (memory) int[size][4] @endcode
253/// or
254/// @code ::new Foo(23, "hello") @endcode
255/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000256Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000257Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000258 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000259 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000260 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000261 MultiExprArg ConstructorArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000262 SourceLocation ConstructorRParen)
263{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000264 Expr *ArraySize = 0;
265 unsigned Skip = 0;
266 // If the specified type is an array, unwrap it and save the expression.
267 if (D.getNumTypeObjects() > 0 &&
268 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
269 DeclaratorChunk &Chunk = D.getTypeObject(0);
270 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000271 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
272 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000273 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000274 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
275 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000276 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
277 Skip = 1;
278 }
279
280 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000281 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000282 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000283
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000284 if (CheckAllocatedType(AllocType, D))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000285 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000286
Sebastian Redl28507842009-02-26 14:39:58 +0000287 QualType ResultType = AllocType->isDependentType()
288 ? Context.DependentTy
289 : Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000290
291 // That every array dimension except the first is constant was already
292 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000293
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000294 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
295 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000296 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000297 QualType SizeType = ArraySize->getType();
298 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000299 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
300 diag::err_array_size_not_integral)
301 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000302 // Let's see if this is a constant < 0. If so, we reject it out of hand.
303 // We don't care about special rules, so we tell the machinery it's not
304 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000305 if (!ArraySize->isValueDependent()) {
306 llvm::APSInt Value;
307 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
308 if (Value < llvm::APSInt(
309 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000310 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
311 diag::err_typecheck_negative_array_size)
312 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000313 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000314 }
315 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000316
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000317 FunctionDecl *OperatorNew = 0;
318 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000319 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
320 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000321 if (!AllocType->isDependentType() &&
322 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
323 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000324 SourceRange(PlacementLParen, PlacementRParen),
325 UseGlobal, AllocType, ArraySize, PlaceArgs,
326 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000327 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000328
329 bool Init = ConstructorLParen.isValid();
330 // --- Choosing a constructor ---
331 // C++ 5.3.4p15
332 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
333 // the object is not initialized. If the object, or any part of it, is
334 // const-qualified, it's an error.
335 // 2) If T is a POD and there's an empty initializer, the object is value-
336 // initialized.
337 // 3) If T is a POD and there's one initializer argument, the object is copy-
338 // constructed.
339 // 4) If T is a POD and there's more initializer arguments, it's an error.
340 // 5) If T is not a POD, the initializer arguments are used as constructor
341 // arguments.
342 //
343 // Or by the C++0x formulation:
344 // 1) If there's no initializer, the object is default-initialized according
345 // to C++0x rules.
346 // 2) Otherwise, the object is direct-initialized.
347 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000348 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000349 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000350 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000351 if (AllocType->isDependentType()) {
352 // Skip all the checks.
353 }
Sebastian Redl4f149632009-05-07 16:14:23 +0000354 else if ((RT = AllocType->getAsRecordType()) &&
355 !AllocType->isAggregateType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000356 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000357 AllocType, ConsArgs, NumConsArgs,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000358 D.getSourceRange().getBegin(),
359 SourceRange(D.getSourceRange().getBegin(),
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000360 ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000361 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000362 NumConsArgs != 0 ? IK_Direct : IK_Default);
363 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000364 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000365 } else {
366 if (!Init) {
367 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000368 if (AllocType.isConstQualified())
369 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
370 << D.getSourceRange());
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000371 } else if (NumConsArgs == 0) {
372 // Object is value-initialized. Do nothing.
373 } else if (NumConsArgs == 1) {
374 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000375 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000376 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000377 DeclarationName() /*AllocType.getAsString()*/,
378 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000379 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000380 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000381 return ExprError(Diag(StartLoc,
382 diag::err_builtin_direct_init_more_than_one_arg)
383 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000384 }
385 }
386
387 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
388
Sebastian Redlf53597f2009-03-15 17:47:39 +0000389 PlacementArgs.release();
390 ConstructorArgs.release();
391 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000392 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000393 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000394 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000395}
396
397/// CheckAllocatedType - Checks that a type is suitable as the allocated type
398/// in a new-expression.
399/// dimension off and stores the size expression in ArraySize.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000400bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000401{
402 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
403 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000404 if (AllocType->isFunctionType())
405 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
406 << AllocType << 0 << D.getSourceRange();
407 else if (AllocType->isReferenceType())
408 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
409 << AllocType << 1 << D.getSourceRange();
410 else if (!AllocType->isDependentType() &&
411 RequireCompleteType(D.getSourceRange().getBegin(), AllocType,
412 diag::err_new_incomplete_type,
413 D.getSourceRange()))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000414 return true;
Douglas Gregore7450f52009-03-24 19:52:54 +0000415 else if (RequireNonAbstractType(D.getSourceRange().getBegin(), AllocType,
416 diag::err_allocation_of_abstract_type))
417 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000418
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000419 // Every dimension shall be of constant size.
420 unsigned i = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000421 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
422 if (!Array->isConstantArrayType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000423 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
424 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000425 return true;
426 }
427 AllocType = Array->getElementType();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000428 ++i;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000429 }
430
431 return false;
432}
433
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000434/// FindAllocationFunctions - Finds the overloads of operator new and delete
435/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000436bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
437 bool UseGlobal, QualType AllocType,
438 bool IsArray, Expr **PlaceArgs,
439 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000440 FunctionDecl *&OperatorNew,
441 FunctionDecl *&OperatorDelete)
442{
443 // --- Choosing an allocation function ---
444 // C++ 5.3.4p8 - 14 & 18
445 // 1) If UseGlobal is true, only look in the global scope. Else, also look
446 // in the scope of the allocated class.
447 // 2) If an array size is given, look for operator new[], else look for
448 // operator new.
449 // 3) The first argument is always size_t. Append the arguments from the
450 // placement form.
451 // FIXME: Also find the appropriate delete operator.
452
453 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
454 // We don't care about the actual value of this argument.
455 // FIXME: Should the Sema create the expression and embed it in the syntax
456 // tree? Or should the consumer just recalculate the value?
Ted Kremenek8189cde2009-02-07 01:47:29 +0000457 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000458 Context.Target.getPointerWidth(0)),
459 Context.getSizeType(),
460 SourceLocation());
461 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
462
463 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
464 IsArray ? OO_Array_New : OO_New);
465 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000466 CXXRecordDecl *Record
467 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000468 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000469 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000470 AllocArgs.size(), Record, /*AllowMissing=*/true,
471 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000472 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000473 }
474 if (!OperatorNew) {
475 // Didn't find a member overload. Look for a global one.
476 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000477 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000478 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000479 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
480 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000481 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000482 }
483
Sebastian Redl7f662392008-12-04 22:20:51 +0000484 // FIXME: This is leaked on error. But so much is currently in Sema that it's
485 // easier to clean it in one go.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000486 AllocArgs[0]->Destroy(Context);
487 return false;
488}
489
Sebastian Redl7f662392008-12-04 22:20:51 +0000490/// FindAllocationOverload - Find an fitting overload for the allocation
491/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000492bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
493 DeclarationName Name, Expr** Args,
494 unsigned NumArgs, DeclContext *Ctx,
495 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redl7f662392008-12-04 22:20:51 +0000496{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000497 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000498 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000499 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000500 if (AllowMissing)
501 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000502 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000503 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000504 }
505
506 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000507 for (; Alloc != AllocEnd; ++Alloc) {
508 // Even member operator new/delete are implicitly treated as
509 // static, so don't use AddMemberCandidate.
510 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
511 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
512 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000513 }
514
515 // Do the resolution.
516 OverloadCandidateSet::iterator Best;
517 switch(BestViableFunction(Candidates, Best)) {
518 case OR_Success: {
519 // Got one!
520 FunctionDecl *FnDecl = Best->Function;
521 // The first argument is size_t, and the first parameter must be size_t,
522 // too. This is checked on declaration and can be assumed. (It can't be
523 // asserted on, though, since invalid decls are left in there.)
524 for (unsigned i = 1; i < NumArgs; ++i) {
525 // FIXME: Passing word to diagnostic.
526 if (PerformCopyInitialization(Args[i-1],
527 FnDecl->getParamDecl(i)->getType(),
528 "passing"))
529 return true;
530 }
531 Operator = FnDecl;
532 return false;
533 }
534
535 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000536 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000537 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000538 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
539 return true;
540
541 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000542 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000543 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000544 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
545 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000546
547 case OR_Deleted:
548 Diag(StartLoc, diag::err_ovl_deleted_call)
549 << Best->Function->isDeleted()
550 << Name << Range;
551 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
552 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000553 }
554 assert(false && "Unreachable, bad result from BestViableFunction");
555 return true;
556}
557
558
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000559/// DeclareGlobalNewDelete - Declare the global forms of operator new and
560/// delete. These are:
561/// @code
562/// void* operator new(std::size_t) throw(std::bad_alloc);
563/// void* operator new[](std::size_t) throw(std::bad_alloc);
564/// void operator delete(void *) throw();
565/// void operator delete[](void *) throw();
566/// @endcode
567/// Note that the placement and nothrow forms of new are *not* implicitly
568/// declared. Their use requires including \<new\>.
569void Sema::DeclareGlobalNewDelete()
570{
571 if (GlobalNewDeleteDeclared)
572 return;
573 GlobalNewDeleteDeclared = true;
574
575 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
576 QualType SizeT = Context.getSizeType();
577
578 // FIXME: Exception specifications are not added.
579 DeclareGlobalAllocationFunction(
580 Context.DeclarationNames.getCXXOperatorName(OO_New),
581 VoidPtr, SizeT);
582 DeclareGlobalAllocationFunction(
583 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
584 VoidPtr, SizeT);
585 DeclareGlobalAllocationFunction(
586 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
587 Context.VoidTy, VoidPtr);
588 DeclareGlobalAllocationFunction(
589 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
590 Context.VoidTy, VoidPtr);
591}
592
593/// DeclareGlobalAllocationFunction - Declares a single implicit global
594/// allocation function if it doesn't already exist.
595void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
596 QualType Return, QualType Argument)
597{
598 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
599
600 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000601 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000602 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000603 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Context, Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000604 Alloc != AllocEnd; ++Alloc) {
605 // FIXME: Do we need to check for default arguments here?
606 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
607 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000608 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000609 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000610 }
611 }
612
613 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
614 FunctionDecl *Alloc =
615 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor2224f842009-02-25 16:33:18 +0000616 FnType, FunctionDecl::None, false, true,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000617 SourceLocation());
618 Alloc->setImplicit();
619 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000620 0, Argument, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000621 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000622
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000623 // FIXME: Also add this declaration to the IdentifierResolver, but
624 // make sure it is at the end of the chain to coincide with the
625 // global scope.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000626 ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000627}
628
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000629/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
630/// @code ::delete ptr; @endcode
631/// or
632/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000633Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000634Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000635 bool ArrayForm, ExprArg Operand)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000636{
637 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
638 // having a single conversion function to a pointer type. The result has
639 // type void."
640 // DR599 amends "pointer type" to "pointer to object type" in both cases.
641
Sebastian Redlf53597f2009-03-15 17:47:39 +0000642 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000643 if (!Ex->isTypeDependent()) {
644 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000645
Sebastian Redl28507842009-02-26 14:39:58 +0000646 if (Type->isRecordType()) {
647 // FIXME: Find that one conversion function and amend the type.
648 }
649
Sebastian Redlf53597f2009-03-15 17:47:39 +0000650 if (!Type->isPointerType())
651 return ExprError(Diag(StartLoc, diag::err_delete_operand)
652 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000653
654 QualType Pointee = Type->getAsPointerType()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000655 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000656 return ExprError(Diag(StartLoc, diag::err_delete_operand)
657 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000658 else if (!Pointee->isDependentType() &&
659 RequireCompleteType(StartLoc, Pointee,
660 diag::warn_delete_incomplete,
661 Ex->getSourceRange()))
662 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000663
664 // FIXME: Look up the correct operator delete overload and pass a pointer
665 // along.
666 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000667 }
668
Sebastian Redlf53597f2009-03-15 17:47:39 +0000669 Operand.release();
670 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
671 0, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000672}
673
674
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000675/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
676/// C++ if/switch/while/for statement.
677/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000678Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000679Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
680 Declarator &D,
681 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000682 ExprArg AssignExprVal) {
683 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000684
685 // C++ 6.4p2:
686 // The declarator shall not specify a function or an array.
687 // The type-specifier-seq shall not contain typedef and shall not declare a
688 // new class or enumeration.
689
690 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
691 "Parser allowed 'typedef' as storage class of condition decl.");
692
693 QualType Ty = GetTypeForDeclarator(D, S);
694
695 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
696 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
697 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000698 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
699 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000700 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000701 Diag(StartLoc, diag::err_invalid_use_of_array_type)
702 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000703 } else if (const RecordType *RT = Ty->getAsRecordType()) {
704 RecordDecl *RD = RT->getDecl();
705 // The type-specifier-seq shall not declare a new class...
Chris Lattnerb28317a2009-03-28 19:18:32 +0000706 if (RD->isDefinition() &&
707 (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD))))
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000708 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
709 } else if (const EnumType *ET = Ty->getAsEnumType()) {
710 EnumDecl *ED = ET->getDecl();
711 // ...or enumeration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000712 if (ED->isDefinition() &&
713 (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED))))
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000714 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
715 }
716
Chris Lattnerb28317a2009-03-28 19:18:32 +0000717 DeclPtrTy Dcl = ActOnDeclarator(S, D, DeclPtrTy());
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000718 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000719 return ExprError();
720 AddInitializerToDecl(Dcl, move(AssignExprVal));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000721
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000722 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000723 // We know that the decl had to be a VarDecl because that is the only type of
724 // decl that can be assigned and the grammar requires an '='.
725 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
726 VD->setDeclaredInCondition(true);
727 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000728}
729
730/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
731bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
732 // C++ 6.4p4:
733 // The value of a condition that is an initialized declaration in a statement
734 // other than a switch statement is the value of the declared variable
735 // implicitly converted to type bool. If that conversion is ill-formed, the
736 // program is ill-formed.
737 // The value of a condition that is an expression is the value of the
738 // expression, implicitly converted to bool.
739 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000740 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000741}
Douglas Gregor77a52232008-09-12 00:47:35 +0000742
743/// Helper function to determine whether this is the (deprecated) C++
744/// conversion from a string literal to a pointer to non-const char or
745/// non-const wchar_t (for narrow and wide string literals,
746/// respectively).
747bool
748Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
749 // Look inside the implicit cast, if it exists.
750 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
751 From = Cast->getSubExpr();
752
753 // A string literal (2.13.4) that is not a wide string literal can
754 // be converted to an rvalue of type "pointer to char"; a wide
755 // string literal can be converted to an rvalue of type "pointer
756 // to wchar_t" (C++ 4.2p2).
757 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
758 if (const PointerType *ToPtrType = ToType->getAsPointerType())
759 if (const BuiltinType *ToPointeeType
760 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
761 // This conversion is considered only when there is an
762 // explicit appropriate pointer target type (C++ 4.2p2).
763 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
764 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
765 (!StrLit->isWide() &&
766 (ToPointeeType->getKind() == BuiltinType::Char_U ||
767 ToPointeeType->getKind() == BuiltinType::Char_S))))
768 return true;
769 }
770
771 return false;
772}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000773
774/// PerformImplicitConversion - Perform an implicit conversion of the
775/// expression From to the type ToType. Returns true if there was an
776/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000777/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000778/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000779/// explicit user-defined conversions are permitted. @p Elidable should be true
780/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
781/// resolution works differently in that case.
782bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000783Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000784 const char *Flavor, bool AllowExplicit,
785 bool Elidable)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000786{
Sebastian Redle2b68332009-04-12 17:16:29 +0000787 ImplicitConversionSequence ICS;
788 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
789 if (Elidable && getLangOptions().CPlusPlus0x) {
790 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
791 AllowExplicit, /*ForceRValue*/true);
792 }
793 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
794 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
795 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000796 return PerformImplicitConversion(From, ToType, ICS, Flavor);
797}
798
799/// PerformImplicitConversion - Perform an implicit conversion of the
800/// expression From to the type ToType using the pre-computed implicit
801/// conversion sequence ICS. Returns true if there was an error, false
802/// otherwise. The expression From is replaced with the converted
803/// expression. Flavor is the kind of conversion we're performing,
804/// used in the error message.
805bool
806Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
807 const ImplicitConversionSequence &ICS,
808 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000809 switch (ICS.ConversionKind) {
810 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000811 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000812 return true;
813 break;
814
815 case ImplicitConversionSequence::UserDefinedConversion:
Mike Stump390b4cc2009-05-16 07:39:55 +0000816 // FIXME: This is, of course, wrong. We'll need to actually call the
817 // constructor or conversion operator, and then cope with the standard
818 // conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000819 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000820 ToType->isLValueReferenceType());
Douglas Gregor60d62c22008-10-31 16:23:19 +0000821 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000822
823 case ImplicitConversionSequence::EllipsisConversion:
824 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000825 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000826
827 case ImplicitConversionSequence::BadConversion:
828 return true;
829 }
830
831 // Everything went well.
832 return false;
833}
834
835/// PerformImplicitConversion - Perform an implicit conversion of the
836/// expression From to the type ToType by following the standard
837/// conversion sequence SCS. Returns true if there was an error, false
838/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000839/// expression. Flavor is the context in which we're performing this
840/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000841bool
842Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000843 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000844 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000845 // Overall FIXME: we are recomputing too many types here and doing far too
846 // much extra work. What this means is that we need to keep track of more
847 // information that is computed when we try the implicit conversion initially,
848 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000849 QualType FromType = From->getType();
850
Douglas Gregor225c41e2008-11-03 19:09:14 +0000851 if (SCS.CopyConstructor) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000852 // FIXME: Create a temporary object by calling the copy constructor.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000853 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000854 ToType->isLValueReferenceType());
Douglas Gregor225c41e2008-11-03 19:09:14 +0000855 return false;
856 }
857
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000858 // Perform the first implicit conversion.
859 switch (SCS.First) {
860 case ICK_Identity:
861 case ICK_Lvalue_To_Rvalue:
862 // Nothing to do.
863 break;
864
865 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000866 FromType = Context.getArrayDecayedType(FromType);
867 ImpCastExprToType(From, FromType);
868 break;
869
870 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +0000871 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +0000872 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
873 if (!Fn)
874 return true;
875
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000876 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
877 return true;
878
Douglas Gregor904eed32008-11-10 20:40:00 +0000879 FixOverloadedFunctionReference(From, Fn);
880 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +0000881 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000882 FromType = Context.getPointerType(FromType);
883 ImpCastExprToType(From, FromType);
884 break;
885
886 default:
887 assert(false && "Improper first standard conversion");
888 break;
889 }
890
891 // Perform the second implicit conversion
892 switch (SCS.Second) {
893 case ICK_Identity:
894 // Nothing to do.
895 break;
896
897 case ICK_Integral_Promotion:
898 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000899 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000900 case ICK_Integral_Conversion:
901 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000902 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000903 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000904 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +0000905 case ICK_Compatible_Conversion:
906 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000907 FromType = ToType.getUnqualifiedType();
908 ImpCastExprToType(From, FromType);
909 break;
910
911 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000912 if (SCS.IncompatibleObjC) {
913 // Diagnose incompatible Objective-C conversions
914 Diag(From->getSourceRange().getBegin(),
915 diag::ext_typecheck_convert_incompatible_pointer)
916 << From->getType() << ToType << Flavor
917 << From->getSourceRange();
918 }
919
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000920 if (CheckPointerConversion(From, ToType))
921 return true;
922 ImpCastExprToType(From, ToType);
923 break;
924
925 case ICK_Pointer_Member:
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000926 if (CheckMemberPointerConversion(From, ToType))
927 return true;
928 ImpCastExprToType(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000929 break;
930
931 case ICK_Boolean_Conversion:
932 FromType = Context.BoolTy;
933 ImpCastExprToType(From, FromType);
934 break;
935
936 default:
937 assert(false && "Improper second standard conversion");
938 break;
939 }
940
941 switch (SCS.Third) {
942 case ICK_Identity:
943 // Nothing to do.
944 break;
945
946 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +0000947 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
948 // references.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000949 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000950 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000951 break;
952
953 default:
954 assert(false && "Improper second standard conversion");
955 break;
956 }
957
958 return false;
959}
960
Sebastian Redl64b45f72009-01-05 20:52:13 +0000961Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
962 SourceLocation KWLoc,
963 SourceLocation LParen,
964 TypeTy *Ty,
965 SourceLocation RParen) {
966 // FIXME: Some of the type traits have requirements. Interestingly, only the
Mike Stump390b4cc2009-05-16 07:39:55 +0000967 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed, G++
968 // accepts __is_pod(Incomplete) without complaints, and claims that the type
969 // is indeed a POD.
Sebastian Redl64b45f72009-01-05 20:52:13 +0000970
971 // There is no point in eagerly computing the value. The traits are designed
972 // to be used from type trait templates, so Ty will be a template parameter
973 // 99% of the time.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000974 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
Sebastian Redl64b45f72009-01-05 20:52:13 +0000975 QualType::getFromOpaquePtr(Ty),
976 RParen, Context.BoolTy));
977}
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000978
979QualType Sema::CheckPointerToMemberOperands(
980 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
981{
982 const char *OpSpelling = isIndirect ? "->*" : ".*";
983 // C++ 5.5p2
984 // The binary operator .* [p3: ->*] binds its second operand, which shall
985 // be of type "pointer to member of T" (where T is a completely-defined
986 // class type) [...]
987 QualType RType = rex->getType();
988 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
Douglas Gregore7450f52009-03-24 19:52:54 +0000989 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000990 Diag(Loc, diag::err_bad_memptr_rhs)
991 << OpSpelling << RType << rex->getSourceRange();
992 return QualType();
Douglas Gregor3f5b61c2009-05-14 00:28:11 +0000993 }
Douglas Gregore7450f52009-03-24 19:52:54 +0000994
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000995 QualType Class(MemPtr->getClass(), 0);
996
997 // C++ 5.5p2
998 // [...] to its first operand, which shall be of class T or of a class of
999 // which T is an unambiguous and accessible base class. [p3: a pointer to
1000 // such a class]
1001 QualType LType = lex->getType();
1002 if (isIndirect) {
1003 if (const PointerType *Ptr = LType->getAsPointerType())
1004 LType = Ptr->getPointeeType().getNonReferenceType();
1005 else {
1006 Diag(Loc, diag::err_bad_memptr_lhs)
1007 << OpSpelling << 1 << LType << lex->getSourceRange();
1008 return QualType();
1009 }
1010 }
1011
1012 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1013 Context.getCanonicalType(LType).getUnqualifiedType()) {
1014 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1015 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001016 // FIXME: Would it be useful to print full ambiguity paths, or is that
1017 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001018 if (!IsDerivedFrom(LType, Class, Paths) ||
1019 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1020 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1021 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1022 return QualType();
1023 }
1024 }
1025
1026 // C++ 5.5p2
1027 // The result is an object or a function of the type specified by the
1028 // second operand.
1029 // The cv qualifiers are the union of those in the pointer and the left side,
1030 // in accordance with 5.5p5 and 5.2.5.
1031 // FIXME: This returns a dereferenced member function pointer as a normal
1032 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001033 // calling them. There's also a GCC extension to get a function pointer to the
1034 // thing, which is another complication, because this type - unlike the type
1035 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001036 // argument.
1037 // We probably need a "MemberFunctionClosureType" or something like that.
1038 QualType Result = MemPtr->getPointeeType();
1039 if (LType.isConstQualified())
1040 Result.addConst();
1041 if (LType.isVolatileQualified())
1042 Result.addVolatile();
1043 return Result;
1044}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001045
1046/// \brief Get the target type of a standard or user-defined conversion.
1047static QualType TargetType(const ImplicitConversionSequence &ICS) {
1048 assert((ICS.ConversionKind ==
1049 ImplicitConversionSequence::StandardConversion ||
1050 ICS.ConversionKind ==
1051 ImplicitConversionSequence::UserDefinedConversion) &&
1052 "function only valid for standard or user-defined conversions");
1053 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1054 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1055 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1056}
1057
1058/// \brief Try to convert a type to another according to C++0x 5.16p3.
1059///
1060/// This is part of the parameter validation for the ? operator. If either
1061/// value operand is a class type, the two operands are attempted to be
1062/// converted to each other. This function does the conversion in one direction.
1063/// It emits a diagnostic and returns true only if it finds an ambiguous
1064/// conversion.
1065static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1066 SourceLocation QuestionLoc,
1067 ImplicitConversionSequence &ICS)
1068{
1069 // C++0x 5.16p3
1070 // The process for determining whether an operand expression E1 of type T1
1071 // can be converted to match an operand expression E2 of type T2 is defined
1072 // as follows:
1073 // -- If E2 is an lvalue:
1074 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1075 // E1 can be converted to match E2 if E1 can be implicitly converted to
1076 // type "lvalue reference to T2", subject to the constraint that in the
1077 // conversion the reference must bind directly to E1.
1078 if (!Self.CheckReferenceInit(From,
1079 Self.Context.getLValueReferenceType(To->getType()),
1080 &ICS))
1081 {
1082 assert((ICS.ConversionKind ==
1083 ImplicitConversionSequence::StandardConversion ||
1084 ICS.ConversionKind ==
1085 ImplicitConversionSequence::UserDefinedConversion) &&
1086 "expected a definite conversion");
1087 bool DirectBinding =
1088 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1089 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1090 if (DirectBinding)
1091 return false;
1092 }
1093 }
1094 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1095 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1096 // -- if E1 and E2 have class type, and the underlying class types are
1097 // the same or one is a base class of the other:
1098 QualType FTy = From->getType();
1099 QualType TTy = To->getType();
1100 const RecordType *FRec = FTy->getAsRecordType();
1101 const RecordType *TRec = TTy->getAsRecordType();
1102 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1103 if (FRec && TRec && (FRec == TRec ||
1104 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1105 // E1 can be converted to match E2 if the class of T2 is the
1106 // same type as, or a base class of, the class of T1, and
1107 // [cv2 > cv1].
1108 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1109 // Could still fail if there's no copy constructor.
1110 // FIXME: Is this a hard error then, or just a conversion failure? The
1111 // standard doesn't say.
1112 ICS = Self.TryCopyInitialization(From, TTy);
1113 }
1114 } else {
1115 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1116 // implicitly converted to the type that expression E2 would have
1117 // if E2 were converted to an rvalue.
1118 // First find the decayed type.
1119 if (TTy->isFunctionType())
1120 TTy = Self.Context.getPointerType(TTy);
1121 else if(TTy->isArrayType())
1122 TTy = Self.Context.getArrayDecayedType(TTy);
1123
1124 // Now try the implicit conversion.
1125 // FIXME: This doesn't detect ambiguities.
1126 ICS = Self.TryImplicitConversion(From, TTy);
1127 }
1128 return false;
1129}
1130
1131/// \brief Try to find a common type for two according to C++0x 5.16p5.
1132///
1133/// This is part of the parameter validation for the ? operator. If either
1134/// value operand is a class type, overload resolution is used to find a
1135/// conversion to a common type.
1136static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1137 SourceLocation Loc) {
1138 Expr *Args[2] = { LHS, RHS };
1139 OverloadCandidateSet CandidateSet;
1140 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1141
1142 OverloadCandidateSet::iterator Best;
1143 switch (Self.BestViableFunction(CandidateSet, Best)) {
1144 case Sema::OR_Success:
1145 // We found a match. Perform the conversions on the arguments and move on.
1146 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1147 Best->Conversions[0], "converting") ||
1148 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1149 Best->Conversions[1], "converting"))
1150 break;
1151 return false;
1152
1153 case Sema::OR_No_Viable_Function:
1154 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1155 << LHS->getType() << RHS->getType()
1156 << LHS->getSourceRange() << RHS->getSourceRange();
1157 return true;
1158
1159 case Sema::OR_Ambiguous:
1160 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1161 << LHS->getType() << RHS->getType()
1162 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001163 // FIXME: Print the possible common types by printing the return types of
1164 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001165 break;
1166
1167 case Sema::OR_Deleted:
1168 assert(false && "Conditional operator has only built-in overloads");
1169 break;
1170 }
1171 return true;
1172}
1173
Sebastian Redl76458502009-04-17 16:30:52 +00001174/// \brief Perform an "extended" implicit conversion as returned by
1175/// TryClassUnification.
1176///
1177/// TryClassUnification generates ICSs that include reference bindings.
1178/// PerformImplicitConversion is not suitable for this; it chokes if the
1179/// second part of a standard conversion is ICK_DerivedToBase. This function
1180/// handles the reference binding specially.
1181static bool ConvertForConditional(Sema &Self, Expr *&E,
1182 const ImplicitConversionSequence &ICS)
1183{
1184 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1185 ICS.Standard.ReferenceBinding) {
1186 assert(ICS.Standard.DirectBinding &&
1187 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001188 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1189 // redoing all the work.
1190 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1191 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001192 }
1193 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1194 ICS.UserDefined.After.ReferenceBinding) {
1195 assert(ICS.UserDefined.After.DirectBinding &&
1196 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001197 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1198 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001199 }
1200 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1201 return true;
1202 return false;
1203}
1204
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001205/// \brief Check the operands of ?: under C++ semantics.
1206///
1207/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1208/// extension. In this case, LHS == Cond. (But they're not aliases.)
1209QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1210 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001211 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1212 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001213
1214 // C++0x 5.16p1
1215 // The first expression is contextually converted to bool.
1216 if (!Cond->isTypeDependent()) {
1217 if (CheckCXXBooleanCondition(Cond))
1218 return QualType();
1219 }
1220
1221 // Either of the arguments dependent?
1222 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1223 return Context.DependentTy;
1224
1225 // C++0x 5.16p2
1226 // If either the second or the third operand has type (cv) void, ...
1227 QualType LTy = LHS->getType();
1228 QualType RTy = RHS->getType();
1229 bool LVoid = LTy->isVoidType();
1230 bool RVoid = RTy->isVoidType();
1231 if (LVoid || RVoid) {
1232 // ... then the [l2r] conversions are performed on the second and third
1233 // operands ...
1234 DefaultFunctionArrayConversion(LHS);
1235 DefaultFunctionArrayConversion(RHS);
1236 LTy = LHS->getType();
1237 RTy = RHS->getType();
1238
1239 // ... and one of the following shall hold:
1240 // -- The second or the third operand (but not both) is a throw-
1241 // expression; the result is of the type of the other and is an rvalue.
1242 bool LThrow = isa<CXXThrowExpr>(LHS);
1243 bool RThrow = isa<CXXThrowExpr>(RHS);
1244 if (LThrow && !RThrow)
1245 return RTy;
1246 if (RThrow && !LThrow)
1247 return LTy;
1248
1249 // -- Both the second and third operands have type void; the result is of
1250 // type void and is an rvalue.
1251 if (LVoid && RVoid)
1252 return Context.VoidTy;
1253
1254 // Neither holds, error.
1255 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1256 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1257 << LHS->getSourceRange() << RHS->getSourceRange();
1258 return QualType();
1259 }
1260
1261 // Neither is void.
1262
1263 // C++0x 5.16p3
1264 // Otherwise, if the second and third operand have different types, and
1265 // either has (cv) class type, and attempt is made to convert each of those
1266 // operands to the other.
1267 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1268 (LTy->isRecordType() || RTy->isRecordType())) {
1269 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1270 // These return true if a single direction is already ambiguous.
1271 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1272 return QualType();
1273 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1274 return QualType();
1275
1276 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1277 ImplicitConversionSequence::BadConversion;
1278 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1279 ImplicitConversionSequence::BadConversion;
1280 // If both can be converted, [...] the program is ill-formed.
1281 if (HaveL2R && HaveR2L) {
1282 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1283 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1284 return QualType();
1285 }
1286
1287 // If exactly one conversion is possible, that conversion is applied to
1288 // the chosen operand and the converted operands are used in place of the
1289 // original operands for the remainder of this section.
1290 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001291 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001292 return QualType();
1293 LTy = LHS->getType();
1294 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001295 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001296 return QualType();
1297 RTy = RHS->getType();
1298 }
1299 }
1300
1301 // C++0x 5.16p4
1302 // If the second and third operands are lvalues and have the same type,
1303 // the result is of that type [...]
1304 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1305 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1306 RHS->isLvalue(Context) == Expr::LV_Valid)
1307 return LTy;
1308
1309 // C++0x 5.16p5
1310 // Otherwise, the result is an rvalue. If the second and third operands
1311 // do not have the same type, and either has (cv) class type, ...
1312 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1313 // ... overload resolution is used to determine the conversions (if any)
1314 // to be applied to the operands. If the overload resolution fails, the
1315 // program is ill-formed.
1316 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1317 return QualType();
1318 }
1319
1320 // C++0x 5.16p6
1321 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1322 // conversions are performed on the second and third operands.
1323 DefaultFunctionArrayConversion(LHS);
1324 DefaultFunctionArrayConversion(RHS);
1325 LTy = LHS->getType();
1326 RTy = RHS->getType();
1327
1328 // After those conversions, one of the following shall hold:
1329 // -- The second and third operands have the same type; the result
1330 // is of that type.
1331 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1332 return LTy;
1333
1334 // -- The second and third operands have arithmetic or enumeration type;
1335 // the usual arithmetic conversions are performed to bring them to a
1336 // common type, and the result is of that type.
1337 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1338 UsualArithmeticConversions(LHS, RHS);
1339 return LHS->getType();
1340 }
1341
1342 // -- The second and third operands have pointer type, or one has pointer
1343 // type and the other is a null pointer constant; pointer conversions
1344 // and qualification conversions are performed to bring them to their
1345 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001346 QualType Composite = FindCompositePointerType(LHS, RHS);
1347 if (!Composite.isNull())
1348 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001349
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001350 // Fourth bullet is same for pointers-to-member. However, the possible
1351 // conversions are far more limited: we have null-to-pointer, upcast of
1352 // containing class, and second-level cv-ness.
1353 // cv-ness is not a union, but must match one of the two operands. (Which,
1354 // frankly, is stupid.)
1355 const MemberPointerType *LMemPtr = LTy->getAsMemberPointerType();
1356 const MemberPointerType *RMemPtr = RTy->getAsMemberPointerType();
1357 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1358 ImpCastExprToType(RHS, LTy);
1359 return LTy;
1360 }
1361 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1362 ImpCastExprToType(LHS, RTy);
1363 return RTy;
1364 }
1365 if (LMemPtr && RMemPtr) {
1366 QualType LPointee = LMemPtr->getPointeeType();
1367 QualType RPointee = RMemPtr->getPointeeType();
1368 // First, we check that the unqualified pointee type is the same. If it's
1369 // not, there's no conversion that will unify the two pointers.
1370 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1371 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1372 // Second, we take the greater of the two cv qualifications. If neither
1373 // is greater than the other, the conversion is not possible.
1374 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1375 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1376 // Third, we check if either of the container classes is derived from
1377 // the other.
1378 QualType LContainer(LMemPtr->getClass(), 0);
1379 QualType RContainer(RMemPtr->getClass(), 0);
1380 QualType MoreDerived;
1381 if (Context.getCanonicalType(LContainer) ==
1382 Context.getCanonicalType(RContainer))
1383 MoreDerived = LContainer;
1384 else if (IsDerivedFrom(LContainer, RContainer))
1385 MoreDerived = LContainer;
1386 else if (IsDerivedFrom(RContainer, LContainer))
1387 MoreDerived = RContainer;
1388
1389 if (!MoreDerived.isNull()) {
1390 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1391 // We don't use ImpCastExprToType here because this could still fail
1392 // for ambiguous or inaccessible conversions.
1393 QualType Common = Context.getMemberPointerType(
1394 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1395 if (PerformImplicitConversion(LHS, Common, "converting"))
1396 return QualType();
1397 if (PerformImplicitConversion(RHS, Common, "converting"))
1398 return QualType();
1399 return Common;
1400 }
1401 }
1402 }
1403 }
1404
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001405 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1406 << LHS->getType() << RHS->getType()
1407 << LHS->getSourceRange() << RHS->getSourceRange();
1408 return QualType();
1409}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001410
1411/// \brief Find a merged pointer type and convert the two expressions to it.
1412///
1413/// This finds the composite pointer type for @p E1 and @p E2 according to
1414/// C++0x 5.9p2. It converts both expressions to this type and returns it.
1415/// It does not emit diagnostics.
1416QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1417 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1418 QualType T1 = E1->getType(), T2 = E2->getType();
1419 if(!T1->isPointerType() && !T2->isPointerType())
1420 return QualType();
1421
1422 // C++0x 5.9p2
1423 // Pointer conversions and qualification conversions are performed on
1424 // pointer operands to bring them to their composite pointer type. If
1425 // one operand is a null pointer constant, the composite pointer type is
1426 // the type of the other operand.
1427 if (E1->isNullPointerConstant(Context)) {
1428 ImpCastExprToType(E1, T2);
1429 return T2;
1430 }
1431 if (E2->isNullPointerConstant(Context)) {
1432 ImpCastExprToType(E2, T1);
1433 return T1;
1434 }
1435 // Now both have to be pointers.
1436 if(!T1->isPointerType() || !T2->isPointerType())
1437 return QualType();
1438
1439 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1440 // the other has type "pointer to cv2 T" and the composite pointer type is
1441 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1442 // Otherwise, the composite pointer type is a pointer type similar to the
1443 // type of one of the operands, with a cv-qualification signature that is
1444 // the union of the cv-qualification signatures of the operand types.
1445 // In practice, the first part here is redundant; it's subsumed by the second.
1446 // What we do here is, we build the two possible composite types, and try the
1447 // conversions in both directions. If only one works, or if the two composite
1448 // types are the same, we have succeeded.
1449 llvm::SmallVector<unsigned, 4> QualifierUnion;
1450 QualType Composite1 = T1, Composite2 = T2;
1451 const PointerType *Ptr1, *Ptr2;
1452 while ((Ptr1 = Composite1->getAsPointerType()) &&
1453 (Ptr2 = Composite2->getAsPointerType())) {
1454 Composite1 = Ptr1->getPointeeType();
1455 Composite2 = Ptr2->getPointeeType();
1456 QualifierUnion.push_back(
1457 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1458 }
1459 // Rewrap the composites as pointers with the union CVRs.
1460 for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(),
1461 E = QualifierUnion.end(); I != E; ++I) {
1462 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1463 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1464 }
1465
1466 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1467 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1468 ImplicitConversionSequence E1ToC2, E2ToC2;
1469 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1470 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1471 if (Context.getCanonicalType(Composite1) !=
1472 Context.getCanonicalType(Composite2)) {
1473 E1ToC2 = TryImplicitConversion(E1, Composite2);
1474 E2ToC2 = TryImplicitConversion(E2, Composite2);
1475 }
1476
1477 bool ToC1Viable = E1ToC1.ConversionKind !=
1478 ImplicitConversionSequence::BadConversion
1479 && E2ToC1.ConversionKind !=
1480 ImplicitConversionSequence::BadConversion;
1481 bool ToC2Viable = E1ToC2.ConversionKind !=
1482 ImplicitConversionSequence::BadConversion
1483 && E2ToC2.ConversionKind !=
1484 ImplicitConversionSequence::BadConversion;
1485 if (ToC1Viable && !ToC2Viable) {
1486 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1487 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1488 return Composite1;
1489 }
1490 if (ToC2Viable && !ToC1Viable) {
1491 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1492 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1493 return Composite2;
1494 }
1495 return QualType();
1496}