blob: 0539caa712f1fb83f4891ada5218b6d2ffeb6146 [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
88/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +000089Action::OwningExprResult
90Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
91 return Owned(new (Context) CXXThrowExpr((Expr*)E.release(), Context.VoidTy,
92 OpLoc));
Chris Lattner50dd2892008-02-26 00:51:44 +000093}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000094
Sebastian Redlf53597f2009-03-15 17:47:39 +000095Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000096 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
97 /// is a non-lvalue expression whose value is the address of the object for
98 /// which the function is called.
99
Sebastian Redlf53597f2009-03-15 17:47:39 +0000100 if (!isa<FunctionDecl>(CurContext))
101 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000102
103 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
104 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000105 return Owned(new (Context) CXXThisExpr(ThisLoc,
106 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000107
Sebastian Redlf53597f2009-03-15 17:47:39 +0000108 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000109}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000110
111/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
112/// Can be interpreted either as function-style casting ("int(x)")
113/// or class type construction ("ClassType(x,y,z)")
114/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000115Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000116Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
117 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000118 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000119 SourceLocation *CommaLocs,
120 SourceLocation RParenLoc) {
121 assert(TypeRep && "Missing type!");
122 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000123 unsigned NumExprs = exprs.size();
124 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000125 SourceLocation TyBeginLoc = TypeRange.getBegin();
126 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
127
Sebastian Redlf53597f2009-03-15 17:47:39 +0000128 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000129 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000130 exprs.release();
131 return Owned(new (Context) CXXTemporaryObjectExpr(0, Ty, TyBeginLoc,
132 Exprs, NumExprs,
133 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000134 }
135
136
Douglas Gregor506ae412009-01-16 18:33:17 +0000137 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000138 // If the expression list is a single expression, the type conversion
139 // expression is equivalent (in definedness, and if defined in meaning) to the
140 // corresponding cast expression.
141 //
142 if (NumExprs == 1) {
143 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000144 return ExprError();
145 exprs.release();
146 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
147 Ty, TyBeginLoc, Exprs[0],
148 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000149 }
150
Douglas Gregor506ae412009-01-16 18:33:17 +0000151 if (const RecordType *RT = Ty->getAsRecordType()) {
152 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000153
Douglas Gregor506ae412009-01-16 18:33:17 +0000154 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
155 CXXConstructorDecl *Constructor
156 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
157 TypeRange.getBegin(),
158 SourceRange(TypeRange.getBegin(),
159 RParenLoc),
160 DeclarationName(),
161 IK_Direct);
Douglas Gregor506ae412009-01-16 18:33:17 +0000162
Sebastian Redlf53597f2009-03-15 17:47:39 +0000163 if (!Constructor)
164 return ExprError();
165
166 exprs.release();
167 return Owned(new (Context) CXXTemporaryObjectExpr(Constructor, Ty,
168 TyBeginLoc, Exprs,
169 NumExprs, RParenLoc));
Douglas Gregor506ae412009-01-16 18:33:17 +0000170 }
171
172 // Fall through to value-initialize an object of class type that
173 // doesn't have a user-declared default constructor.
174 }
175
176 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000177 // If the expression list specifies more than a single value, the type shall
178 // be a class with a suitably declared constructor.
179 //
180 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000181 return ExprError(Diag(CommaLocs[0],
182 diag::err_builtin_func_cast_more_than_one_arg)
183 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000184
185 assert(NumExprs == 0 && "Expected 0 expressions");
186
Douglas Gregor506ae412009-01-16 18:33:17 +0000187 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000188 // The expression T(), where T is a simple-type-specifier for a non-array
189 // complete object type or the (possibly cv-qualified) void type, creates an
190 // rvalue of the specified type, which is value-initialized.
191 //
192 if (Ty->isArrayType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000193 return ExprError(Diag(TyBeginLoc,
194 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000195 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redlf53597f2009-03-15 17:47:39 +0000196 RequireCompleteType(TyBeginLoc, Ty,
197 diag::err_invalid_incomplete_type_use, FullRange))
198 return ExprError();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000199
Anders Carlsson8211eff2009-03-24 01:19:16 +0000200 if (RequireNonAbstractType(TyBeginLoc, Ty,
201 diag::err_allocation_of_abstract_type))
Anders Carlsson11f21a02009-03-23 19:10:31 +0000202 return ExprError();
203
Sebastian Redlf53597f2009-03-15 17:47:39 +0000204 exprs.release();
205 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000206}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000207
208
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000209/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
210/// @code new (memory) int[size][4] @endcode
211/// or
212/// @code ::new Foo(23, "hello") @endcode
213/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000214Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000215Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000216 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000217 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000218 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000219 MultiExprArg ConstructorArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000220 SourceLocation ConstructorRParen)
221{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000222 Expr *ArraySize = 0;
223 unsigned Skip = 0;
224 // If the specified type is an array, unwrap it and save the expression.
225 if (D.getNumTypeObjects() > 0 &&
226 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
227 DeclaratorChunk &Chunk = D.getTypeObject(0);
228 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000229 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
230 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000231 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000232 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
233 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000234 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
235 Skip = 1;
236 }
237
238 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
239 if (D.getInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000240 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000241
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000242 if (CheckAllocatedType(AllocType, D))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000243 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000244
Sebastian Redl28507842009-02-26 14:39:58 +0000245 QualType ResultType = AllocType->isDependentType()
246 ? Context.DependentTy
247 : Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000248
249 // That every array dimension except the first is constant was already
250 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000251
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000252 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
253 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000254 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000255 QualType SizeType = ArraySize->getType();
256 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000257 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
258 diag::err_array_size_not_integral)
259 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000260 // Let's see if this is a constant < 0. If so, we reject it out of hand.
261 // We don't care about special rules, so we tell the machinery it's not
262 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000263 if (!ArraySize->isValueDependent()) {
264 llvm::APSInt Value;
265 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
266 if (Value < llvm::APSInt(
267 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000268 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
269 diag::err_typecheck_negative_array_size)
270 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000271 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000272 }
273 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000274
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000275 FunctionDecl *OperatorNew = 0;
276 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000277 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
278 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000279 if (!AllocType->isDependentType() &&
280 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
281 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000282 SourceRange(PlacementLParen, PlacementRParen),
283 UseGlobal, AllocType, ArraySize, PlaceArgs,
284 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000285 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000286
287 bool Init = ConstructorLParen.isValid();
288 // --- Choosing a constructor ---
289 // C++ 5.3.4p15
290 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
291 // the object is not initialized. If the object, or any part of it, is
292 // const-qualified, it's an error.
293 // 2) If T is a POD and there's an empty initializer, the object is value-
294 // initialized.
295 // 3) If T is a POD and there's one initializer argument, the object is copy-
296 // constructed.
297 // 4) If T is a POD and there's more initializer arguments, it's an error.
298 // 5) If T is not a POD, the initializer arguments are used as constructor
299 // arguments.
300 //
301 // Or by the C++0x formulation:
302 // 1) If there's no initializer, the object is default-initialized according
303 // to C++0x rules.
304 // 2) Otherwise, the object is direct-initialized.
305 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000306 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
307 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000308 if (AllocType->isDependentType()) {
309 // Skip all the checks.
310 }
Sebastian Redl00e68e22009-02-09 18:24:27 +0000311 // FIXME: Should check for primitive/aggregate here, not record.
Sebastian Redl28507842009-02-26 14:39:58 +0000312 else if (const RecordType *RT = AllocType->getAsRecordType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000313 // FIXME: This is incorrect for when there is an empty initializer and
314 // no user-defined constructor. Must zero-initialize, not default-construct.
315 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000316 AllocType, ConsArgs, NumConsArgs,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000317 D.getSourceRange().getBegin(),
318 SourceRange(D.getSourceRange().getBegin(),
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000319 ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000320 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000321 NumConsArgs != 0 ? IK_Direct : IK_Default);
322 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000323 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000324 } else {
325 if (!Init) {
326 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000327 if (AllocType.isConstQualified())
328 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
329 << D.getSourceRange());
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000330 } else if (NumConsArgs == 0) {
331 // Object is value-initialized. Do nothing.
332 } else if (NumConsArgs == 1) {
333 // Object is direct-initialized.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000334 // FIXME: WHAT DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000335 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000336 DeclarationName() /*AllocType.getAsString()*/,
337 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000338 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000339 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000340 return ExprError(Diag(StartLoc,
341 diag::err_builtin_direct_init_more_than_one_arg)
342 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000343 }
344 }
345
346 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
347
Sebastian Redlf53597f2009-03-15 17:47:39 +0000348 PlacementArgs.release();
349 ConstructorArgs.release();
350 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000351 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000352 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000353 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000354}
355
356/// CheckAllocatedType - Checks that a type is suitable as the allocated type
357/// in a new-expression.
358/// dimension off and stores the size expression in ArraySize.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000359bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000360{
361 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
362 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000363 if (AllocType->isFunctionType())
364 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
365 << AllocType << 0 << D.getSourceRange();
366 else if (AllocType->isReferenceType())
367 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
368 << AllocType << 1 << D.getSourceRange();
369 else if (!AllocType->isDependentType() &&
370 RequireCompleteType(D.getSourceRange().getBegin(), AllocType,
371 diag::err_new_incomplete_type,
372 D.getSourceRange()))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000373 return true;
Douglas Gregore7450f52009-03-24 19:52:54 +0000374 else if (RequireNonAbstractType(D.getSourceRange().getBegin(), AllocType,
375 diag::err_allocation_of_abstract_type))
376 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000377
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000378 // Every dimension shall be of constant size.
379 unsigned i = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000380 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
381 if (!Array->isConstantArrayType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000382 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
383 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000384 return true;
385 }
386 AllocType = Array->getElementType();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000387 ++i;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000388 }
389
390 return false;
391}
392
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000393/// FindAllocationFunctions - Finds the overloads of operator new and delete
394/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000395bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
396 bool UseGlobal, QualType AllocType,
397 bool IsArray, Expr **PlaceArgs,
398 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000399 FunctionDecl *&OperatorNew,
400 FunctionDecl *&OperatorDelete)
401{
402 // --- Choosing an allocation function ---
403 // C++ 5.3.4p8 - 14 & 18
404 // 1) If UseGlobal is true, only look in the global scope. Else, also look
405 // in the scope of the allocated class.
406 // 2) If an array size is given, look for operator new[], else look for
407 // operator new.
408 // 3) The first argument is always size_t. Append the arguments from the
409 // placement form.
410 // FIXME: Also find the appropriate delete operator.
411
412 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
413 // We don't care about the actual value of this argument.
414 // FIXME: Should the Sema create the expression and embed it in the syntax
415 // tree? Or should the consumer just recalculate the value?
Ted Kremenek8189cde2009-02-07 01:47:29 +0000416 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000417 Context.Target.getPointerWidth(0)),
418 Context.getSizeType(),
419 SourceLocation());
420 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
421
422 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
423 IsArray ? OO_Array_New : OO_New);
424 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000425 CXXRecordDecl *Record
426 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000427 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000428 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000429 AllocArgs.size(), Record, /*AllowMissing=*/true,
430 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000431 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000432 }
433 if (!OperatorNew) {
434 // Didn't find a member overload. Look for a global one.
435 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000436 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000437 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000438 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
439 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000440 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000441 }
442
Sebastian Redl7f662392008-12-04 22:20:51 +0000443 // FIXME: This is leaked on error. But so much is currently in Sema that it's
444 // easier to clean it in one go.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000445 AllocArgs[0]->Destroy(Context);
446 return false;
447}
448
Sebastian Redl7f662392008-12-04 22:20:51 +0000449/// FindAllocationOverload - Find an fitting overload for the allocation
450/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000451bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
452 DeclarationName Name, Expr** Args,
453 unsigned NumArgs, DeclContext *Ctx,
454 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redl7f662392008-12-04 22:20:51 +0000455{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000456 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000457 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000458 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000459 if (AllowMissing)
460 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000461 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000462 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000463 }
464
465 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000466 for (; Alloc != AllocEnd; ++Alloc) {
467 // Even member operator new/delete are implicitly treated as
468 // static, so don't use AddMemberCandidate.
469 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
470 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
471 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000472 }
473
474 // Do the resolution.
475 OverloadCandidateSet::iterator Best;
476 switch(BestViableFunction(Candidates, Best)) {
477 case OR_Success: {
478 // Got one!
479 FunctionDecl *FnDecl = Best->Function;
480 // The first argument is size_t, and the first parameter must be size_t,
481 // too. This is checked on declaration and can be assumed. (It can't be
482 // asserted on, though, since invalid decls are left in there.)
483 for (unsigned i = 1; i < NumArgs; ++i) {
484 // FIXME: Passing word to diagnostic.
485 if (PerformCopyInitialization(Args[i-1],
486 FnDecl->getParamDecl(i)->getType(),
487 "passing"))
488 return true;
489 }
490 Operator = FnDecl;
491 return false;
492 }
493
494 case OR_No_Viable_Function:
495 if (AllowMissing)
496 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000497 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000498 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000499 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
500 return true;
501
502 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000503 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000504 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000505 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
506 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000507
508 case OR_Deleted:
509 Diag(StartLoc, diag::err_ovl_deleted_call)
510 << Best->Function->isDeleted()
511 << Name << Range;
512 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
513 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000514 }
515 assert(false && "Unreachable, bad result from BestViableFunction");
516 return true;
517}
518
519
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000520/// DeclareGlobalNewDelete - Declare the global forms of operator new and
521/// delete. These are:
522/// @code
523/// void* operator new(std::size_t) throw(std::bad_alloc);
524/// void* operator new[](std::size_t) throw(std::bad_alloc);
525/// void operator delete(void *) throw();
526/// void operator delete[](void *) throw();
527/// @endcode
528/// Note that the placement and nothrow forms of new are *not* implicitly
529/// declared. Their use requires including \<new\>.
530void Sema::DeclareGlobalNewDelete()
531{
532 if (GlobalNewDeleteDeclared)
533 return;
534 GlobalNewDeleteDeclared = true;
535
536 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
537 QualType SizeT = Context.getSizeType();
538
539 // FIXME: Exception specifications are not added.
540 DeclareGlobalAllocationFunction(
541 Context.DeclarationNames.getCXXOperatorName(OO_New),
542 VoidPtr, SizeT);
543 DeclareGlobalAllocationFunction(
544 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
545 VoidPtr, SizeT);
546 DeclareGlobalAllocationFunction(
547 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
548 Context.VoidTy, VoidPtr);
549 DeclareGlobalAllocationFunction(
550 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
551 Context.VoidTy, VoidPtr);
552}
553
554/// DeclareGlobalAllocationFunction - Declares a single implicit global
555/// allocation function if it doesn't already exist.
556void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
557 QualType Return, QualType Argument)
558{
559 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
560
561 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000562 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000563 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000564 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Context, Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000565 Alloc != AllocEnd; ++Alloc) {
566 // FIXME: Do we need to check for default arguments here?
567 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
568 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000569 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000570 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000571 }
572 }
573
574 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
575 FunctionDecl *Alloc =
576 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor2224f842009-02-25 16:33:18 +0000577 FnType, FunctionDecl::None, false, true,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000578 SourceLocation());
579 Alloc->setImplicit();
580 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000581 0, Argument, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000582 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000583
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000584 // FIXME: Also add this declaration to the IdentifierResolver, but
585 // make sure it is at the end of the chain to coincide with the
586 // global scope.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000587 ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000588}
589
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000590/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
591/// @code ::delete ptr; @endcode
592/// or
593/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000594Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000595Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000596 bool ArrayForm, ExprArg Operand)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000597{
598 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
599 // having a single conversion function to a pointer type. The result has
600 // type void."
601 // DR599 amends "pointer type" to "pointer to object type" in both cases.
602
Sebastian Redlf53597f2009-03-15 17:47:39 +0000603 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000604 if (!Ex->isTypeDependent()) {
605 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000606
Sebastian Redl28507842009-02-26 14:39:58 +0000607 if (Type->isRecordType()) {
608 // FIXME: Find that one conversion function and amend the type.
609 }
610
Sebastian Redlf53597f2009-03-15 17:47:39 +0000611 if (!Type->isPointerType())
612 return ExprError(Diag(StartLoc, diag::err_delete_operand)
613 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000614
615 QualType Pointee = Type->getAsPointerType()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000616 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000617 return ExprError(Diag(StartLoc, diag::err_delete_operand)
618 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000619 else if (!Pointee->isDependentType() &&
620 RequireCompleteType(StartLoc, Pointee,
621 diag::warn_delete_incomplete,
622 Ex->getSourceRange()))
623 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000624
625 // FIXME: Look up the correct operator delete overload and pass a pointer
626 // along.
627 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000628 }
629
Sebastian Redlf53597f2009-03-15 17:47:39 +0000630 Operand.release();
631 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
632 0, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000633}
634
635
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000636/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
637/// C++ if/switch/while/for statement.
638/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000639Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000640Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
641 Declarator &D,
642 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000643 ExprArg AssignExprVal) {
644 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000645
646 // C++ 6.4p2:
647 // The declarator shall not specify a function or an array.
648 // The type-specifier-seq shall not contain typedef and shall not declare a
649 // new class or enumeration.
650
651 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
652 "Parser allowed 'typedef' as storage class of condition decl.");
653
654 QualType Ty = GetTypeForDeclarator(D, S);
655
656 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
657 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
658 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000659 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
660 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000661 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000662 Diag(StartLoc, diag::err_invalid_use_of_array_type)
663 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000664 } else if (const RecordType *RT = Ty->getAsRecordType()) {
665 RecordDecl *RD = RT->getDecl();
666 // The type-specifier-seq shall not declare a new class...
Chris Lattnerb28317a2009-03-28 19:18:32 +0000667 if (RD->isDefinition() &&
668 (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD))))
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000669 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
670 } else if (const EnumType *ET = Ty->getAsEnumType()) {
671 EnumDecl *ED = ET->getDecl();
672 // ...or enumeration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000673 if (ED->isDefinition() &&
674 (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED))))
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000675 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
676 }
677
Chris Lattnerb28317a2009-03-28 19:18:32 +0000678 DeclPtrTy Dcl = ActOnDeclarator(S, D, DeclPtrTy());
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000679 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000680 return ExprError();
681 AddInitializerToDecl(Dcl, move(AssignExprVal));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000682
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000683 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000684 // We know that the decl had to be a VarDecl because that is the only type of
685 // decl that can be assigned and the grammar requires an '='.
686 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
687 VD->setDeclaredInCondition(true);
688 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000689}
690
691/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
692bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
693 // C++ 6.4p4:
694 // The value of a condition that is an initialized declaration in a statement
695 // other than a switch statement is the value of the declared variable
696 // implicitly converted to type bool. If that conversion is ill-formed, the
697 // program is ill-formed.
698 // The value of a condition that is an expression is the value of the
699 // expression, implicitly converted to bool.
700 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000701 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000702}
Douglas Gregor77a52232008-09-12 00:47:35 +0000703
704/// Helper function to determine whether this is the (deprecated) C++
705/// conversion from a string literal to a pointer to non-const char or
706/// non-const wchar_t (for narrow and wide string literals,
707/// respectively).
708bool
709Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
710 // Look inside the implicit cast, if it exists.
711 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
712 From = Cast->getSubExpr();
713
714 // A string literal (2.13.4) that is not a wide string literal can
715 // be converted to an rvalue of type "pointer to char"; a wide
716 // string literal can be converted to an rvalue of type "pointer
717 // to wchar_t" (C++ 4.2p2).
718 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
719 if (const PointerType *ToPtrType = ToType->getAsPointerType())
720 if (const BuiltinType *ToPointeeType
721 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
722 // This conversion is considered only when there is an
723 // explicit appropriate pointer target type (C++ 4.2p2).
724 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
725 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
726 (!StrLit->isWide() &&
727 (ToPointeeType->getKind() == BuiltinType::Char_U ||
728 ToPointeeType->getKind() == BuiltinType::Char_S))))
729 return true;
730 }
731
732 return false;
733}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000734
735/// PerformImplicitConversion - Perform an implicit conversion of the
736/// expression From to the type ToType. Returns true if there was an
737/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000738/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000739/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000740/// explicit user-defined conversions are permitted. @p Elidable should be true
741/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
742/// resolution works differently in that case.
743bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000744Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000745 const char *Flavor, bool AllowExplicit,
746 bool Elidable)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000747{
Sebastian Redle2b68332009-04-12 17:16:29 +0000748 ImplicitConversionSequence ICS;
749 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
750 if (Elidable && getLangOptions().CPlusPlus0x) {
751 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
752 AllowExplicit, /*ForceRValue*/true);
753 }
754 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
755 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
756 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000757 return PerformImplicitConversion(From, ToType, ICS, Flavor);
758}
759
760/// PerformImplicitConversion - Perform an implicit conversion of the
761/// expression From to the type ToType using the pre-computed implicit
762/// conversion sequence ICS. Returns true if there was an error, false
763/// otherwise. The expression From is replaced with the converted
764/// expression. Flavor is the kind of conversion we're performing,
765/// used in the error message.
766bool
767Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
768 const ImplicitConversionSequence &ICS,
769 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000770 switch (ICS.ConversionKind) {
771 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000772 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000773 return true;
774 break;
775
776 case ImplicitConversionSequence::UserDefinedConversion:
777 // FIXME: This is, of course, wrong. We'll need to actually call
778 // the constructor or conversion operator, and then cope with the
779 // standard conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000780 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000781 ToType->isLValueReferenceType());
Douglas Gregor60d62c22008-10-31 16:23:19 +0000782 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000783
784 case ImplicitConversionSequence::EllipsisConversion:
785 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000786 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000787
788 case ImplicitConversionSequence::BadConversion:
789 return true;
790 }
791
792 // Everything went well.
793 return false;
794}
795
796/// PerformImplicitConversion - Perform an implicit conversion of the
797/// expression From to the type ToType by following the standard
798/// conversion sequence SCS. Returns true if there was an error, false
799/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000800/// expression. Flavor is the context in which we're performing this
801/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000802bool
803Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000804 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000805 const char *Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000806 // Overall FIXME: we are recomputing too many types here and doing
807 // far too much extra work. What this means is that we need to keep
808 // track of more information that is computed when we try the
809 // implicit conversion initially, so that we don't need to recompute
810 // anything here.
811 QualType FromType = From->getType();
812
Douglas Gregor225c41e2008-11-03 19:09:14 +0000813 if (SCS.CopyConstructor) {
814 // FIXME: Create a temporary object by calling the copy
815 // constructor.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000816 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000817 ToType->isLValueReferenceType());
Douglas Gregor225c41e2008-11-03 19:09:14 +0000818 return false;
819 }
820
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000821 // Perform the first implicit conversion.
822 switch (SCS.First) {
823 case ICK_Identity:
824 case ICK_Lvalue_To_Rvalue:
825 // Nothing to do.
826 break;
827
828 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000829 FromType = Context.getArrayDecayedType(FromType);
830 ImpCastExprToType(From, FromType);
831 break;
832
833 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +0000834 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +0000835 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
836 if (!Fn)
837 return true;
838
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000839 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
840 return true;
841
Douglas Gregor904eed32008-11-10 20:40:00 +0000842 FixOverloadedFunctionReference(From, Fn);
843 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +0000844 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000845 FromType = Context.getPointerType(FromType);
846 ImpCastExprToType(From, FromType);
847 break;
848
849 default:
850 assert(false && "Improper first standard conversion");
851 break;
852 }
853
854 // Perform the second implicit conversion
855 switch (SCS.Second) {
856 case ICK_Identity:
857 // Nothing to do.
858 break;
859
860 case ICK_Integral_Promotion:
861 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000862 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000863 case ICK_Integral_Conversion:
864 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000865 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000866 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000867 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +0000868 case ICK_Compatible_Conversion:
869 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000870 FromType = ToType.getUnqualifiedType();
871 ImpCastExprToType(From, FromType);
872 break;
873
874 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000875 if (SCS.IncompatibleObjC) {
876 // Diagnose incompatible Objective-C conversions
877 Diag(From->getSourceRange().getBegin(),
878 diag::ext_typecheck_convert_incompatible_pointer)
879 << From->getType() << ToType << Flavor
880 << From->getSourceRange();
881 }
882
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000883 if (CheckPointerConversion(From, ToType))
884 return true;
885 ImpCastExprToType(From, ToType);
886 break;
887
888 case ICK_Pointer_Member:
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000889 if (CheckMemberPointerConversion(From, ToType))
890 return true;
891 ImpCastExprToType(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000892 break;
893
894 case ICK_Boolean_Conversion:
895 FromType = Context.BoolTy;
896 ImpCastExprToType(From, FromType);
897 break;
898
899 default:
900 assert(false && "Improper second standard conversion");
901 break;
902 }
903
904 switch (SCS.Third) {
905 case ICK_Identity:
906 // Nothing to do.
907 break;
908
909 case ICK_Qualification:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000910 // FIXME: Not sure about lvalue vs rvalue here in the presence of
911 // rvalue references.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000912 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000913 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000914 break;
915
916 default:
917 assert(false && "Improper second standard conversion");
918 break;
919 }
920
921 return false;
922}
923
Sebastian Redl64b45f72009-01-05 20:52:13 +0000924Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
925 SourceLocation KWLoc,
926 SourceLocation LParen,
927 TypeTy *Ty,
928 SourceLocation RParen) {
929 // FIXME: Some of the type traits have requirements. Interestingly, only the
930 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed,
931 // G++ accepts __is_pod(Incomplete) without complaints, and claims that the
932 // type is indeed a POD.
933
934 // There is no point in eagerly computing the value. The traits are designed
935 // to be used from type trait templates, so Ty will be a template parameter
936 // 99% of the time.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000937 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
Sebastian Redl64b45f72009-01-05 20:52:13 +0000938 QualType::getFromOpaquePtr(Ty),
939 RParen, Context.BoolTy));
940}
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000941
942QualType Sema::CheckPointerToMemberOperands(
943 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
944{
945 const char *OpSpelling = isIndirect ? "->*" : ".*";
946 // C++ 5.5p2
947 // The binary operator .* [p3: ->*] binds its second operand, which shall
948 // be of type "pointer to member of T" (where T is a completely-defined
949 // class type) [...]
950 QualType RType = rex->getType();
951 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
Douglas Gregore7450f52009-03-24 19:52:54 +0000952 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000953 Diag(Loc, diag::err_bad_memptr_rhs)
954 << OpSpelling << RType << rex->getSourceRange();
955 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +0000956 } else if (RequireCompleteType(Loc, QualType(MemPtr->getClass(), 0),
957 diag::err_memptr_rhs_incomplete,
958 rex->getSourceRange()))
959 return QualType();
960
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000961 QualType Class(MemPtr->getClass(), 0);
962
963 // C++ 5.5p2
964 // [...] to its first operand, which shall be of class T or of a class of
965 // which T is an unambiguous and accessible base class. [p3: a pointer to
966 // such a class]
967 QualType LType = lex->getType();
968 if (isIndirect) {
969 if (const PointerType *Ptr = LType->getAsPointerType())
970 LType = Ptr->getPointeeType().getNonReferenceType();
971 else {
972 Diag(Loc, diag::err_bad_memptr_lhs)
973 << OpSpelling << 1 << LType << lex->getSourceRange();
974 return QualType();
975 }
976 }
977
978 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
979 Context.getCanonicalType(LType).getUnqualifiedType()) {
980 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
981 /*DetectVirtual=*/false);
982 // FIXME: Would it be useful to print full ambiguity paths,
983 // or is that overkill?
984 if (!IsDerivedFrom(LType, Class, Paths) ||
985 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
986 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
987 << (int)isIndirect << lex->getType() << lex->getSourceRange();
988 return QualType();
989 }
990 }
991
992 // C++ 5.5p2
993 // The result is an object or a function of the type specified by the
994 // second operand.
995 // The cv qualifiers are the union of those in the pointer and the left side,
996 // in accordance with 5.5p5 and 5.2.5.
997 // FIXME: This returns a dereferenced member function pointer as a normal
998 // function type. However, the only operation valid on such functions is
999 // calling them. There's also a GCC extension to get a function pointer to
1000 // the thing, which is another complication, because this type - unlike the
1001 // type that is the result of this expression - takes the class as the first
1002 // argument.
1003 // We probably need a "MemberFunctionClosureType" or something like that.
1004 QualType Result = MemPtr->getPointeeType();
1005 if (LType.isConstQualified())
1006 Result.addConst();
1007 if (LType.isVolatileQualified())
1008 Result.addVolatile();
1009 return Result;
1010}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001011
1012/// \brief Get the target type of a standard or user-defined conversion.
1013static QualType TargetType(const ImplicitConversionSequence &ICS) {
1014 assert((ICS.ConversionKind ==
1015 ImplicitConversionSequence::StandardConversion ||
1016 ICS.ConversionKind ==
1017 ImplicitConversionSequence::UserDefinedConversion) &&
1018 "function only valid for standard or user-defined conversions");
1019 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1020 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1021 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1022}
1023
1024/// \brief Try to convert a type to another according to C++0x 5.16p3.
1025///
1026/// This is part of the parameter validation for the ? operator. If either
1027/// value operand is a class type, the two operands are attempted to be
1028/// converted to each other. This function does the conversion in one direction.
1029/// It emits a diagnostic and returns true only if it finds an ambiguous
1030/// conversion.
1031static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1032 SourceLocation QuestionLoc,
1033 ImplicitConversionSequence &ICS)
1034{
1035 // C++0x 5.16p3
1036 // The process for determining whether an operand expression E1 of type T1
1037 // can be converted to match an operand expression E2 of type T2 is defined
1038 // as follows:
1039 // -- If E2 is an lvalue:
1040 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1041 // E1 can be converted to match E2 if E1 can be implicitly converted to
1042 // type "lvalue reference to T2", subject to the constraint that in the
1043 // conversion the reference must bind directly to E1.
1044 if (!Self.CheckReferenceInit(From,
1045 Self.Context.getLValueReferenceType(To->getType()),
1046 &ICS))
1047 {
1048 assert((ICS.ConversionKind ==
1049 ImplicitConversionSequence::StandardConversion ||
1050 ICS.ConversionKind ==
1051 ImplicitConversionSequence::UserDefinedConversion) &&
1052 "expected a definite conversion");
1053 bool DirectBinding =
1054 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1055 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1056 if (DirectBinding)
1057 return false;
1058 }
1059 }
1060 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1061 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1062 // -- if E1 and E2 have class type, and the underlying class types are
1063 // the same or one is a base class of the other:
1064 QualType FTy = From->getType();
1065 QualType TTy = To->getType();
1066 const RecordType *FRec = FTy->getAsRecordType();
1067 const RecordType *TRec = TTy->getAsRecordType();
1068 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1069 if (FRec && TRec && (FRec == TRec ||
1070 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1071 // E1 can be converted to match E2 if the class of T2 is the
1072 // same type as, or a base class of, the class of T1, and
1073 // [cv2 > cv1].
1074 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1075 // Could still fail if there's no copy constructor.
1076 // FIXME: Is this a hard error then, or just a conversion failure? The
1077 // standard doesn't say.
1078 ICS = Self.TryCopyInitialization(From, TTy);
1079 }
1080 } else {
1081 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1082 // implicitly converted to the type that expression E2 would have
1083 // if E2 were converted to an rvalue.
1084 // First find the decayed type.
1085 if (TTy->isFunctionType())
1086 TTy = Self.Context.getPointerType(TTy);
1087 else if(TTy->isArrayType())
1088 TTy = Self.Context.getArrayDecayedType(TTy);
1089
1090 // Now try the implicit conversion.
1091 // FIXME: This doesn't detect ambiguities.
1092 ICS = Self.TryImplicitConversion(From, TTy);
1093 }
1094 return false;
1095}
1096
1097/// \brief Try to find a common type for two according to C++0x 5.16p5.
1098///
1099/// This is part of the parameter validation for the ? operator. If either
1100/// value operand is a class type, overload resolution is used to find a
1101/// conversion to a common type.
1102static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1103 SourceLocation Loc) {
1104 Expr *Args[2] = { LHS, RHS };
1105 OverloadCandidateSet CandidateSet;
1106 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1107
1108 OverloadCandidateSet::iterator Best;
1109 switch (Self.BestViableFunction(CandidateSet, Best)) {
1110 case Sema::OR_Success:
1111 // We found a match. Perform the conversions on the arguments and move on.
1112 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1113 Best->Conversions[0], "converting") ||
1114 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1115 Best->Conversions[1], "converting"))
1116 break;
1117 return false;
1118
1119 case Sema::OR_No_Viable_Function:
1120 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1121 << LHS->getType() << RHS->getType()
1122 << LHS->getSourceRange() << RHS->getSourceRange();
1123 return true;
1124
1125 case Sema::OR_Ambiguous:
1126 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1127 << LHS->getType() << RHS->getType()
1128 << LHS->getSourceRange() << RHS->getSourceRange();
1129 // FIXME: Print the possible common types by printing the return types
1130 // of the viable candidates.
1131 break;
1132
1133 case Sema::OR_Deleted:
1134 assert(false && "Conditional operator has only built-in overloads");
1135 break;
1136 }
1137 return true;
1138}
1139
Sebastian Redl76458502009-04-17 16:30:52 +00001140/// \brief Perform an "extended" implicit conversion as returned by
1141/// TryClassUnification.
1142///
1143/// TryClassUnification generates ICSs that include reference bindings.
1144/// PerformImplicitConversion is not suitable for this; it chokes if the
1145/// second part of a standard conversion is ICK_DerivedToBase. This function
1146/// handles the reference binding specially.
1147static bool ConvertForConditional(Sema &Self, Expr *&E,
1148 const ImplicitConversionSequence &ICS)
1149{
1150 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1151 ICS.Standard.ReferenceBinding) {
1152 assert(ICS.Standard.DirectBinding &&
1153 "TryClassUnification should never generate indirect ref bindings");
1154 Self.ImpCastExprToType(E, TargetType(ICS), true);
1155 return false;
1156 }
1157 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1158 ICS.UserDefined.After.ReferenceBinding) {
1159 assert(ICS.UserDefined.After.DirectBinding &&
1160 "TryClassUnification should never generate indirect ref bindings");
1161 Self.ImpCastExprToType(E, TargetType(ICS), true);
1162 return false;
1163 }
1164 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1165 return true;
1166 return false;
1167}
1168
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001169/// \brief Check the operands of ?: under C++ semantics.
1170///
1171/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1172/// extension. In this case, LHS == Cond. (But they're not aliases.)
1173QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1174 SourceLocation QuestionLoc) {
1175 // FIXME: Handle C99's complex types, vector types, block pointers and
1176 // Obj-C++ interface pointers.
1177
1178 // C++0x 5.16p1
1179 // The first expression is contextually converted to bool.
1180 if (!Cond->isTypeDependent()) {
1181 if (CheckCXXBooleanCondition(Cond))
1182 return QualType();
1183 }
1184
1185 // Either of the arguments dependent?
1186 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1187 return Context.DependentTy;
1188
1189 // C++0x 5.16p2
1190 // If either the second or the third operand has type (cv) void, ...
1191 QualType LTy = LHS->getType();
1192 QualType RTy = RHS->getType();
1193 bool LVoid = LTy->isVoidType();
1194 bool RVoid = RTy->isVoidType();
1195 if (LVoid || RVoid) {
1196 // ... then the [l2r] conversions are performed on the second and third
1197 // operands ...
1198 DefaultFunctionArrayConversion(LHS);
1199 DefaultFunctionArrayConversion(RHS);
1200 LTy = LHS->getType();
1201 RTy = RHS->getType();
1202
1203 // ... and one of the following shall hold:
1204 // -- The second or the third operand (but not both) is a throw-
1205 // expression; the result is of the type of the other and is an rvalue.
1206 bool LThrow = isa<CXXThrowExpr>(LHS);
1207 bool RThrow = isa<CXXThrowExpr>(RHS);
1208 if (LThrow && !RThrow)
1209 return RTy;
1210 if (RThrow && !LThrow)
1211 return LTy;
1212
1213 // -- Both the second and third operands have type void; the result is of
1214 // type void and is an rvalue.
1215 if (LVoid && RVoid)
1216 return Context.VoidTy;
1217
1218 // Neither holds, error.
1219 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1220 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1221 << LHS->getSourceRange() << RHS->getSourceRange();
1222 return QualType();
1223 }
1224
1225 // Neither is void.
1226
1227 // C++0x 5.16p3
1228 // Otherwise, if the second and third operand have different types, and
1229 // either has (cv) class type, and attempt is made to convert each of those
1230 // operands to the other.
1231 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1232 (LTy->isRecordType() || RTy->isRecordType())) {
1233 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1234 // These return true if a single direction is already ambiguous.
1235 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1236 return QualType();
1237 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1238 return QualType();
1239
1240 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1241 ImplicitConversionSequence::BadConversion;
1242 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1243 ImplicitConversionSequence::BadConversion;
1244 // If both can be converted, [...] the program is ill-formed.
1245 if (HaveL2R && HaveR2L) {
1246 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1247 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1248 return QualType();
1249 }
1250
1251 // If exactly one conversion is possible, that conversion is applied to
1252 // the chosen operand and the converted operands are used in place of the
1253 // original operands for the remainder of this section.
1254 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001255 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001256 return QualType();
1257 LTy = LHS->getType();
1258 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001259 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001260 return QualType();
1261 RTy = RHS->getType();
1262 }
1263 }
1264
1265 // C++0x 5.16p4
1266 // If the second and third operands are lvalues and have the same type,
1267 // the result is of that type [...]
1268 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1269 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1270 RHS->isLvalue(Context) == Expr::LV_Valid)
1271 return LTy;
1272
1273 // C++0x 5.16p5
1274 // Otherwise, the result is an rvalue. If the second and third operands
1275 // do not have the same type, and either has (cv) class type, ...
1276 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1277 // ... overload resolution is used to determine the conversions (if any)
1278 // to be applied to the operands. If the overload resolution fails, the
1279 // program is ill-formed.
1280 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1281 return QualType();
1282 }
1283
1284 // C++0x 5.16p6
1285 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1286 // conversions are performed on the second and third operands.
1287 DefaultFunctionArrayConversion(LHS);
1288 DefaultFunctionArrayConversion(RHS);
1289 LTy = LHS->getType();
1290 RTy = RHS->getType();
1291
1292 // After those conversions, one of the following shall hold:
1293 // -- The second and third operands have the same type; the result
1294 // is of that type.
1295 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1296 return LTy;
1297
1298 // -- The second and third operands have arithmetic or enumeration type;
1299 // the usual arithmetic conversions are performed to bring them to a
1300 // common type, and the result is of that type.
1301 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1302 UsualArithmeticConversions(LHS, RHS);
1303 return LHS->getType();
1304 }
1305
1306 // -- The second and third operands have pointer type, or one has pointer
1307 // type and the other is a null pointer constant; pointer conversions
1308 // and qualification conversions are performed to bring them to their
1309 // composite pointer type. The result is of the composite pointer type.
1310 // Fourth bullet is same for pointers-to-member.
1311 if ((LTy->isPointerType() || LTy->isMemberPointerType()) &&
1312 RHS->isNullPointerConstant(Context)) {
1313 ImpCastExprToType(RHS, LTy); // promote the null to a pointer.
1314 return LTy;
1315 }
1316 if ((RTy->isPointerType() || RTy->isMemberPointerType()) &&
1317 LHS->isNullPointerConstant(Context)) {
1318 ImpCastExprToType(LHS, RTy); // promote the null to a pointer.
1319 return RTy;
1320 }
1321
1322 // FIXME: Handle the case where both are pointers.
1323 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1324 << LHS->getType() << RHS->getType()
1325 << LHS->getSourceRange() << RHS->getSourceRange();
1326 return QualType();
1327}