blob: 4c3c85bbf5558fc84dc467681cf0b9dde7f24579 [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) {
Sebastian Redl972041f2009-04-27 20:27:31 +000091 Expr *Ex = E.takeAs<Expr>();
92 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
93 return ExprError();
94 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
95}
96
97/// CheckCXXThrowOperand - Validate the operand of a throw.
98bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
99 // C++ [except.throw]p3:
100 // [...] adjusting the type from "array of T" or "function returning T"
101 // to "pointer to T" or "pointer to function returning T", [...]
102 DefaultFunctionArrayConversion(E);
103
104 // If the type of the exception would be an incomplete type or a pointer
105 // to an incomplete type other than (cv) void the program is ill-formed.
106 QualType Ty = E->getType();
107 int isPointer = 0;
108 if (const PointerType* Ptr = Ty->getAsPointerType()) {
109 Ty = Ptr->getPointeeType();
110 isPointer = 1;
111 }
112 if (!isPointer || !Ty->isVoidType()) {
113 if (RequireCompleteType(ThrowLoc, Ty,
114 isPointer ? diag::err_throw_incomplete_ptr
115 : diag::err_throw_incomplete,
116 E->getSourceRange(), SourceRange(), QualType()))
117 return true;
118 }
119
120 // FIXME: Construct a temporary here.
121 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000122}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000123
Sebastian Redlf53597f2009-03-15 17:47:39 +0000124Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000125 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
126 /// is a non-lvalue expression whose value is the address of the object for
127 /// which the function is called.
128
Sebastian Redlf53597f2009-03-15 17:47:39 +0000129 if (!isa<FunctionDecl>(CurContext))
130 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000131
132 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
133 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000134 return Owned(new (Context) CXXThisExpr(ThisLoc,
135 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000136
Sebastian Redlf53597f2009-03-15 17:47:39 +0000137 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000138}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000139
140/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
141/// Can be interpreted either as function-style casting ("int(x)")
142/// or class type construction ("ClassType(x,y,z)")
143/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000144Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000145Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
146 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000147 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000148 SourceLocation *CommaLocs,
149 SourceLocation RParenLoc) {
150 assert(TypeRep && "Missing type!");
151 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000152 unsigned NumExprs = exprs.size();
153 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000154 SourceLocation TyBeginLoc = TypeRange.getBegin();
155 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
156
Sebastian Redlf53597f2009-03-15 17:47:39 +0000157 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000158 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000159 exprs.release();
Anders Carlsson26de5492009-04-24 05:23:13 +0000160
161 // FIXME: Is this correct?
162 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty);
Anders Carlsson09c4abb2009-04-24 05:44:25 +0000163 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Temp, 0, Ty,
164 TyBeginLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000165 Exprs, NumExprs,
166 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000167 }
168
169
Douglas Gregor506ae412009-01-16 18:33:17 +0000170 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000171 // If the expression list is a single expression, the type conversion
172 // expression is equivalent (in definedness, and if defined in meaning) to the
173 // corresponding cast expression.
174 //
175 if (NumExprs == 1) {
176 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000177 return ExprError();
178 exprs.release();
179 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
180 Ty, TyBeginLoc, Exprs[0],
181 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000182 }
183
Douglas Gregor506ae412009-01-16 18:33:17 +0000184 if (const RecordType *RT = Ty->getAsRecordType()) {
185 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000186
Douglas Gregor506ae412009-01-16 18:33:17 +0000187 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
188 CXXConstructorDecl *Constructor
189 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
190 TypeRange.getBegin(),
191 SourceRange(TypeRange.getBegin(),
192 RParenLoc),
193 DeclarationName(),
194 IK_Direct);
Douglas Gregor506ae412009-01-16 18:33:17 +0000195
Sebastian Redlf53597f2009-03-15 17:47:39 +0000196 if (!Constructor)
197 return ExprError();
198
Anders Carlsson26de5492009-04-24 05:23:13 +0000199 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty);
200
Sebastian Redlf53597f2009-03-15 17:47:39 +0000201 exprs.release();
Anders Carlsson09c4abb2009-04-24 05:44:25 +0000202 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Temp,
203 Constructor, Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000204 TyBeginLoc, Exprs,
205 NumExprs, RParenLoc));
Douglas Gregor506ae412009-01-16 18:33:17 +0000206 }
207
208 // Fall through to value-initialize an object of class type that
209 // doesn't have a user-declared default constructor.
210 }
211
212 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000213 // If the expression list specifies more than a single value, the type shall
214 // be a class with a suitably declared constructor.
215 //
216 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000217 return ExprError(Diag(CommaLocs[0],
218 diag::err_builtin_func_cast_more_than_one_arg)
219 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000220
221 assert(NumExprs == 0 && "Expected 0 expressions");
222
Douglas Gregor506ae412009-01-16 18:33:17 +0000223 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000224 // The expression T(), where T is a simple-type-specifier for a non-array
225 // complete object type or the (possibly cv-qualified) void type, creates an
226 // rvalue of the specified type, which is value-initialized.
227 //
228 if (Ty->isArrayType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000229 return ExprError(Diag(TyBeginLoc,
230 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000231 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redlf53597f2009-03-15 17:47:39 +0000232 RequireCompleteType(TyBeginLoc, Ty,
233 diag::err_invalid_incomplete_type_use, FullRange))
234 return ExprError();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000235
Anders Carlsson8211eff2009-03-24 01:19:16 +0000236 if (RequireNonAbstractType(TyBeginLoc, Ty,
237 diag::err_allocation_of_abstract_type))
Anders Carlsson11f21a02009-03-23 19:10:31 +0000238 return ExprError();
239
Sebastian Redlf53597f2009-03-15 17:47:39 +0000240 exprs.release();
241 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000242}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000243
244
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000245/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
246/// @code new (memory) int[size][4] @endcode
247/// or
248/// @code ::new Foo(23, "hello") @endcode
249/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000250Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000251Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000252 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000253 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000254 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000255 MultiExprArg ConstructorArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000256 SourceLocation ConstructorRParen)
257{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000258 Expr *ArraySize = 0;
259 unsigned Skip = 0;
260 // If the specified type is an array, unwrap it and save the expression.
261 if (D.getNumTypeObjects() > 0 &&
262 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
263 DeclaratorChunk &Chunk = D.getTypeObject(0);
264 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000265 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
266 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000267 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000268 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
269 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000270 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
271 Skip = 1;
272 }
273
274 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000275 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000276 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000277
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000278 if (CheckAllocatedType(AllocType, D))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000279 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000280
Sebastian Redl28507842009-02-26 14:39:58 +0000281 QualType ResultType = AllocType->isDependentType()
282 ? Context.DependentTy
283 : Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000284
285 // That every array dimension except the first is constant was already
286 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000287
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000288 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
289 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000290 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000291 QualType SizeType = ArraySize->getType();
292 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000293 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
294 diag::err_array_size_not_integral)
295 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000296 // Let's see if this is a constant < 0. If so, we reject it out of hand.
297 // We don't care about special rules, so we tell the machinery it's not
298 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000299 if (!ArraySize->isValueDependent()) {
300 llvm::APSInt Value;
301 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
302 if (Value < llvm::APSInt(
303 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000304 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
305 diag::err_typecheck_negative_array_size)
306 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000307 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000308 }
309 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000310
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000311 FunctionDecl *OperatorNew = 0;
312 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000313 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
314 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000315 if (!AllocType->isDependentType() &&
316 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
317 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000318 SourceRange(PlacementLParen, PlacementRParen),
319 UseGlobal, AllocType, ArraySize, PlaceArgs,
320 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000321 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000322
323 bool Init = ConstructorLParen.isValid();
324 // --- Choosing a constructor ---
325 // C++ 5.3.4p15
326 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
327 // the object is not initialized. If the object, or any part of it, is
328 // const-qualified, it's an error.
329 // 2) If T is a POD and there's an empty initializer, the object is value-
330 // initialized.
331 // 3) If T is a POD and there's one initializer argument, the object is copy-
332 // constructed.
333 // 4) If T is a POD and there's more initializer arguments, it's an error.
334 // 5) If T is not a POD, the initializer arguments are used as constructor
335 // arguments.
336 //
337 // Or by the C++0x formulation:
338 // 1) If there's no initializer, the object is default-initialized according
339 // to C++0x rules.
340 // 2) Otherwise, the object is direct-initialized.
341 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000342 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
343 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000344 if (AllocType->isDependentType()) {
345 // Skip all the checks.
346 }
Sebastian Redl00e68e22009-02-09 18:24:27 +0000347 // FIXME: Should check for primitive/aggregate here, not record.
Sebastian Redl28507842009-02-26 14:39:58 +0000348 else if (const RecordType *RT = AllocType->getAsRecordType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000349 // FIXME: This is incorrect for when there is an empty initializer and
350 // no user-defined constructor. Must zero-initialize, not default-construct.
351 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000352 AllocType, ConsArgs, NumConsArgs,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000353 D.getSourceRange().getBegin(),
354 SourceRange(D.getSourceRange().getBegin(),
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000355 ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000356 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000357 NumConsArgs != 0 ? IK_Direct : IK_Default);
358 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000359 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000360 } else {
361 if (!Init) {
362 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000363 if (AllocType.isConstQualified())
364 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
365 << D.getSourceRange());
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000366 } else if (NumConsArgs == 0) {
367 // Object is value-initialized. Do nothing.
368 } else if (NumConsArgs == 1) {
369 // Object is direct-initialized.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000370 // FIXME: WHAT DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000371 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000372 DeclarationName() /*AllocType.getAsString()*/,
373 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000374 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000375 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000376 return ExprError(Diag(StartLoc,
377 diag::err_builtin_direct_init_more_than_one_arg)
378 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000379 }
380 }
381
382 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
383
Sebastian Redlf53597f2009-03-15 17:47:39 +0000384 PlacementArgs.release();
385 ConstructorArgs.release();
386 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000387 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000388 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000389 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000390}
391
392/// CheckAllocatedType - Checks that a type is suitable as the allocated type
393/// in a new-expression.
394/// dimension off and stores the size expression in ArraySize.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000395bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000396{
397 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
398 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000399 if (AllocType->isFunctionType())
400 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
401 << AllocType << 0 << D.getSourceRange();
402 else if (AllocType->isReferenceType())
403 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
404 << AllocType << 1 << D.getSourceRange();
405 else if (!AllocType->isDependentType() &&
406 RequireCompleteType(D.getSourceRange().getBegin(), AllocType,
407 diag::err_new_incomplete_type,
408 D.getSourceRange()))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000409 return true;
Douglas Gregore7450f52009-03-24 19:52:54 +0000410 else if (RequireNonAbstractType(D.getSourceRange().getBegin(), AllocType,
411 diag::err_allocation_of_abstract_type))
412 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000413
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000414 // Every dimension shall be of constant size.
415 unsigned i = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000416 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
417 if (!Array->isConstantArrayType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000418 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
419 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000420 return true;
421 }
422 AllocType = Array->getElementType();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000423 ++i;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000424 }
425
426 return false;
427}
428
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000429/// FindAllocationFunctions - Finds the overloads of operator new and delete
430/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000431bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
432 bool UseGlobal, QualType AllocType,
433 bool IsArray, Expr **PlaceArgs,
434 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000435 FunctionDecl *&OperatorNew,
436 FunctionDecl *&OperatorDelete)
437{
438 // --- Choosing an allocation function ---
439 // C++ 5.3.4p8 - 14 & 18
440 // 1) If UseGlobal is true, only look in the global scope. Else, also look
441 // in the scope of the allocated class.
442 // 2) If an array size is given, look for operator new[], else look for
443 // operator new.
444 // 3) The first argument is always size_t. Append the arguments from the
445 // placement form.
446 // FIXME: Also find the appropriate delete operator.
447
448 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
449 // We don't care about the actual value of this argument.
450 // FIXME: Should the Sema create the expression and embed it in the syntax
451 // tree? Or should the consumer just recalculate the value?
Ted Kremenek8189cde2009-02-07 01:47:29 +0000452 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000453 Context.Target.getPointerWidth(0)),
454 Context.getSizeType(),
455 SourceLocation());
456 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
457
458 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
459 IsArray ? OO_Array_New : OO_New);
460 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000461 CXXRecordDecl *Record
462 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000463 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000464 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000465 AllocArgs.size(), Record, /*AllowMissing=*/true,
466 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000467 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000468 }
469 if (!OperatorNew) {
470 // Didn't find a member overload. Look for a global one.
471 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000472 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000473 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000474 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
475 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000476 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000477 }
478
Sebastian Redl7f662392008-12-04 22:20:51 +0000479 // FIXME: This is leaked on error. But so much is currently in Sema that it's
480 // easier to clean it in one go.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000481 AllocArgs[0]->Destroy(Context);
482 return false;
483}
484
Sebastian Redl7f662392008-12-04 22:20:51 +0000485/// FindAllocationOverload - Find an fitting overload for the allocation
486/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000487bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
488 DeclarationName Name, Expr** Args,
489 unsigned NumArgs, DeclContext *Ctx,
490 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redl7f662392008-12-04 22:20:51 +0000491{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000492 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000493 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000494 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000495 if (AllowMissing)
496 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000497 return 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 }
500
501 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000502 for (; Alloc != AllocEnd; ++Alloc) {
503 // Even member operator new/delete are implicitly treated as
504 // static, so don't use AddMemberCandidate.
505 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
506 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
507 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000508 }
509
510 // Do the resolution.
511 OverloadCandidateSet::iterator Best;
512 switch(BestViableFunction(Candidates, Best)) {
513 case OR_Success: {
514 // Got one!
515 FunctionDecl *FnDecl = Best->Function;
516 // The first argument is size_t, and the first parameter must be size_t,
517 // too. This is checked on declaration and can be assumed. (It can't be
518 // asserted on, though, since invalid decls are left in there.)
519 for (unsigned i = 1; i < NumArgs; ++i) {
520 // FIXME: Passing word to diagnostic.
521 if (PerformCopyInitialization(Args[i-1],
522 FnDecl->getParamDecl(i)->getType(),
523 "passing"))
524 return true;
525 }
526 Operator = FnDecl;
527 return false;
528 }
529
530 case OR_No_Viable_Function:
531 if (AllowMissing)
532 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000533 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000534 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000535 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
536 return true;
537
538 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000539 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000540 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000541 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
542 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000543
544 case OR_Deleted:
545 Diag(StartLoc, diag::err_ovl_deleted_call)
546 << Best->Function->isDeleted()
547 << Name << Range;
548 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
549 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000550 }
551 assert(false && "Unreachable, bad result from BestViableFunction");
552 return true;
553}
554
555
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000556/// DeclareGlobalNewDelete - Declare the global forms of operator new and
557/// delete. These are:
558/// @code
559/// void* operator new(std::size_t) throw(std::bad_alloc);
560/// void* operator new[](std::size_t) throw(std::bad_alloc);
561/// void operator delete(void *) throw();
562/// void operator delete[](void *) throw();
563/// @endcode
564/// Note that the placement and nothrow forms of new are *not* implicitly
565/// declared. Their use requires including \<new\>.
566void Sema::DeclareGlobalNewDelete()
567{
568 if (GlobalNewDeleteDeclared)
569 return;
570 GlobalNewDeleteDeclared = true;
571
572 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
573 QualType SizeT = Context.getSizeType();
574
575 // FIXME: Exception specifications are not added.
576 DeclareGlobalAllocationFunction(
577 Context.DeclarationNames.getCXXOperatorName(OO_New),
578 VoidPtr, SizeT);
579 DeclareGlobalAllocationFunction(
580 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
581 VoidPtr, SizeT);
582 DeclareGlobalAllocationFunction(
583 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
584 Context.VoidTy, VoidPtr);
585 DeclareGlobalAllocationFunction(
586 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
587 Context.VoidTy, VoidPtr);
588}
589
590/// DeclareGlobalAllocationFunction - Declares a single implicit global
591/// allocation function if it doesn't already exist.
592void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
593 QualType Return, QualType Argument)
594{
595 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
596
597 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000598 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000599 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000600 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Context, Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000601 Alloc != AllocEnd; ++Alloc) {
602 // FIXME: Do we need to check for default arguments here?
603 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
604 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000605 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000606 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000607 }
608 }
609
610 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
611 FunctionDecl *Alloc =
612 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor2224f842009-02-25 16:33:18 +0000613 FnType, FunctionDecl::None, false, true,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000614 SourceLocation());
615 Alloc->setImplicit();
616 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000617 0, Argument, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000618 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000619
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000620 // FIXME: Also add this declaration to the IdentifierResolver, but
621 // make sure it is at the end of the chain to coincide with the
622 // global scope.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000623 ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000624}
625
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000626/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
627/// @code ::delete ptr; @endcode
628/// or
629/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000630Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000631Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000632 bool ArrayForm, ExprArg Operand)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000633{
634 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
635 // having a single conversion function to a pointer type. The result has
636 // type void."
637 // DR599 amends "pointer type" to "pointer to object type" in both cases.
638
Sebastian Redlf53597f2009-03-15 17:47:39 +0000639 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000640 if (!Ex->isTypeDependent()) {
641 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000642
Sebastian Redl28507842009-02-26 14:39:58 +0000643 if (Type->isRecordType()) {
644 // FIXME: Find that one conversion function and amend the type.
645 }
646
Sebastian Redlf53597f2009-03-15 17:47:39 +0000647 if (!Type->isPointerType())
648 return ExprError(Diag(StartLoc, diag::err_delete_operand)
649 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000650
651 QualType Pointee = Type->getAsPointerType()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000652 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000653 return ExprError(Diag(StartLoc, diag::err_delete_operand)
654 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000655 else if (!Pointee->isDependentType() &&
656 RequireCompleteType(StartLoc, Pointee,
657 diag::warn_delete_incomplete,
658 Ex->getSourceRange()))
659 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000660
661 // FIXME: Look up the correct operator delete overload and pass a pointer
662 // along.
663 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000664 }
665
Sebastian Redlf53597f2009-03-15 17:47:39 +0000666 Operand.release();
667 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
668 0, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000669}
670
671
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000672/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
673/// C++ if/switch/while/for statement.
674/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000675Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000676Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
677 Declarator &D,
678 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000679 ExprArg AssignExprVal) {
680 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000681
682 // C++ 6.4p2:
683 // The declarator shall not specify a function or an array.
684 // The type-specifier-seq shall not contain typedef and shall not declare a
685 // new class or enumeration.
686
687 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
688 "Parser allowed 'typedef' as storage class of condition decl.");
689
690 QualType Ty = GetTypeForDeclarator(D, S);
691
692 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
693 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
694 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000695 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
696 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000697 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000698 Diag(StartLoc, diag::err_invalid_use_of_array_type)
699 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000700 } else if (const RecordType *RT = Ty->getAsRecordType()) {
701 RecordDecl *RD = RT->getDecl();
702 // The type-specifier-seq shall not declare a new class...
Chris Lattnerb28317a2009-03-28 19:18:32 +0000703 if (RD->isDefinition() &&
704 (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD))))
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000705 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
706 } else if (const EnumType *ET = Ty->getAsEnumType()) {
707 EnumDecl *ED = ET->getDecl();
708 // ...or enumeration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000709 if (ED->isDefinition() &&
710 (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED))))
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000711 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
712 }
713
Chris Lattnerb28317a2009-03-28 19:18:32 +0000714 DeclPtrTy Dcl = ActOnDeclarator(S, D, DeclPtrTy());
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000715 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000716 return ExprError();
717 AddInitializerToDecl(Dcl, move(AssignExprVal));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000718
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000719 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000720 // We know that the decl had to be a VarDecl because that is the only type of
721 // decl that can be assigned and the grammar requires an '='.
722 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
723 VD->setDeclaredInCondition(true);
724 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000725}
726
727/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
728bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
729 // C++ 6.4p4:
730 // The value of a condition that is an initialized declaration in a statement
731 // other than a switch statement is the value of the declared variable
732 // implicitly converted to type bool. If that conversion is ill-formed, the
733 // program is ill-formed.
734 // The value of a condition that is an expression is the value of the
735 // expression, implicitly converted to bool.
736 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000737 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000738}
Douglas Gregor77a52232008-09-12 00:47:35 +0000739
740/// Helper function to determine whether this is the (deprecated) C++
741/// conversion from a string literal to a pointer to non-const char or
742/// non-const wchar_t (for narrow and wide string literals,
743/// respectively).
744bool
745Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
746 // Look inside the implicit cast, if it exists.
747 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
748 From = Cast->getSubExpr();
749
750 // A string literal (2.13.4) that is not a wide string literal can
751 // be converted to an rvalue of type "pointer to char"; a wide
752 // string literal can be converted to an rvalue of type "pointer
753 // to wchar_t" (C++ 4.2p2).
754 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
755 if (const PointerType *ToPtrType = ToType->getAsPointerType())
756 if (const BuiltinType *ToPointeeType
757 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
758 // This conversion is considered only when there is an
759 // explicit appropriate pointer target type (C++ 4.2p2).
760 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
761 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
762 (!StrLit->isWide() &&
763 (ToPointeeType->getKind() == BuiltinType::Char_U ||
764 ToPointeeType->getKind() == BuiltinType::Char_S))))
765 return true;
766 }
767
768 return false;
769}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000770
771/// PerformImplicitConversion - Perform an implicit conversion of the
772/// expression From to the type ToType. Returns true if there was an
773/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000774/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000775/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000776/// explicit user-defined conversions are permitted. @p Elidable should be true
777/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
778/// resolution works differently in that case.
779bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000780Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000781 const char *Flavor, bool AllowExplicit,
782 bool Elidable)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000783{
Sebastian Redle2b68332009-04-12 17:16:29 +0000784 ImplicitConversionSequence ICS;
785 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
786 if (Elidable && getLangOptions().CPlusPlus0x) {
787 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
788 AllowExplicit, /*ForceRValue*/true);
789 }
790 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
791 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
792 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000793 return PerformImplicitConversion(From, ToType, ICS, Flavor);
794}
795
796/// PerformImplicitConversion - Perform an implicit conversion of the
797/// expression From to the type ToType using the pre-computed implicit
798/// conversion sequence ICS. Returns true if there was an error, false
799/// otherwise. The expression From is replaced with the converted
800/// expression. Flavor is the kind of conversion we're performing,
801/// used in the error message.
802bool
803Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
804 const ImplicitConversionSequence &ICS,
805 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000806 switch (ICS.ConversionKind) {
807 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000808 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000809 return true;
810 break;
811
812 case ImplicitConversionSequence::UserDefinedConversion:
813 // FIXME: This is, of course, wrong. We'll need to actually call
814 // the constructor or conversion operator, and then cope with the
815 // standard conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000816 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000817 ToType->isLValueReferenceType());
Douglas Gregor60d62c22008-10-31 16:23:19 +0000818 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000819
820 case ImplicitConversionSequence::EllipsisConversion:
821 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000822 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000823
824 case ImplicitConversionSequence::BadConversion:
825 return true;
826 }
827
828 // Everything went well.
829 return false;
830}
831
832/// PerformImplicitConversion - Perform an implicit conversion of the
833/// expression From to the type ToType by following the standard
834/// conversion sequence SCS. Returns true if there was an error, false
835/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000836/// expression. Flavor is the context in which we're performing this
837/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000838bool
839Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000840 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000841 const char *Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000842 // Overall FIXME: we are recomputing too many types here and doing
843 // far too much extra work. What this means is that we need to keep
844 // track of more information that is computed when we try the
845 // implicit conversion initially, so that we don't need to recompute
846 // anything here.
847 QualType FromType = From->getType();
848
Douglas Gregor225c41e2008-11-03 19:09:14 +0000849 if (SCS.CopyConstructor) {
850 // FIXME: Create a temporary object by calling the copy
851 // constructor.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000852 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000853 ToType->isLValueReferenceType());
Douglas Gregor225c41e2008-11-03 19:09:14 +0000854 return false;
855 }
856
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000857 // Perform the first implicit conversion.
858 switch (SCS.First) {
859 case ICK_Identity:
860 case ICK_Lvalue_To_Rvalue:
861 // Nothing to do.
862 break;
863
864 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000865 FromType = Context.getArrayDecayedType(FromType);
866 ImpCastExprToType(From, FromType);
867 break;
868
869 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +0000870 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +0000871 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
872 if (!Fn)
873 return true;
874
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000875 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
876 return true;
877
Douglas Gregor904eed32008-11-10 20:40:00 +0000878 FixOverloadedFunctionReference(From, Fn);
879 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +0000880 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000881 FromType = Context.getPointerType(FromType);
882 ImpCastExprToType(From, FromType);
883 break;
884
885 default:
886 assert(false && "Improper first standard conversion");
887 break;
888 }
889
890 // Perform the second implicit conversion
891 switch (SCS.Second) {
892 case ICK_Identity:
893 // Nothing to do.
894 break;
895
896 case ICK_Integral_Promotion:
897 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000898 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000899 case ICK_Integral_Conversion:
900 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000901 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000902 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000903 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +0000904 case ICK_Compatible_Conversion:
905 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000906 FromType = ToType.getUnqualifiedType();
907 ImpCastExprToType(From, FromType);
908 break;
909
910 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000911 if (SCS.IncompatibleObjC) {
912 // Diagnose incompatible Objective-C conversions
913 Diag(From->getSourceRange().getBegin(),
914 diag::ext_typecheck_convert_incompatible_pointer)
915 << From->getType() << ToType << Flavor
916 << From->getSourceRange();
917 }
918
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000919 if (CheckPointerConversion(From, ToType))
920 return true;
921 ImpCastExprToType(From, ToType);
922 break;
923
924 case ICK_Pointer_Member:
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000925 if (CheckMemberPointerConversion(From, ToType))
926 return true;
927 ImpCastExprToType(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000928 break;
929
930 case ICK_Boolean_Conversion:
931 FromType = Context.BoolTy;
932 ImpCastExprToType(From, FromType);
933 break;
934
935 default:
936 assert(false && "Improper second standard conversion");
937 break;
938 }
939
940 switch (SCS.Third) {
941 case ICK_Identity:
942 // Nothing to do.
943 break;
944
945 case ICK_Qualification:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000946 // FIXME: Not sure about lvalue vs rvalue here in the presence of
947 // rvalue references.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000948 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000949 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000950 break;
951
952 default:
953 assert(false && "Improper second standard conversion");
954 break;
955 }
956
957 return false;
958}
959
Sebastian Redl64b45f72009-01-05 20:52:13 +0000960Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
961 SourceLocation KWLoc,
962 SourceLocation LParen,
963 TypeTy *Ty,
964 SourceLocation RParen) {
965 // FIXME: Some of the type traits have requirements. Interestingly, only the
966 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed,
967 // G++ accepts __is_pod(Incomplete) without complaints, and claims that the
968 // type is indeed a POD.
969
970 // There is no point in eagerly computing the value. The traits are designed
971 // to be used from type trait templates, so Ty will be a template parameter
972 // 99% of the time.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000973 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
Sebastian Redl64b45f72009-01-05 20:52:13 +0000974 QualType::getFromOpaquePtr(Ty),
975 RParen, Context.BoolTy));
976}
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000977
978QualType Sema::CheckPointerToMemberOperands(
979 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
980{
981 const char *OpSpelling = isIndirect ? "->*" : ".*";
982 // C++ 5.5p2
983 // The binary operator .* [p3: ->*] binds its second operand, which shall
984 // be of type "pointer to member of T" (where T is a completely-defined
985 // class type) [...]
986 QualType RType = rex->getType();
987 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
Douglas Gregore7450f52009-03-24 19:52:54 +0000988 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000989 Diag(Loc, diag::err_bad_memptr_rhs)
990 << OpSpelling << RType << rex->getSourceRange();
991 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +0000992 } else if (RequireCompleteType(Loc, QualType(MemPtr->getClass(), 0),
993 diag::err_memptr_rhs_incomplete,
994 rex->getSourceRange()))
995 return QualType();
996
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000997 QualType Class(MemPtr->getClass(), 0);
998
999 // C++ 5.5p2
1000 // [...] to its first operand, which shall be of class T or of a class of
1001 // which T is an unambiguous and accessible base class. [p3: a pointer to
1002 // such a class]
1003 QualType LType = lex->getType();
1004 if (isIndirect) {
1005 if (const PointerType *Ptr = LType->getAsPointerType())
1006 LType = Ptr->getPointeeType().getNonReferenceType();
1007 else {
1008 Diag(Loc, diag::err_bad_memptr_lhs)
1009 << OpSpelling << 1 << LType << lex->getSourceRange();
1010 return QualType();
1011 }
1012 }
1013
1014 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1015 Context.getCanonicalType(LType).getUnqualifiedType()) {
1016 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1017 /*DetectVirtual=*/false);
1018 // FIXME: Would it be useful to print full ambiguity paths,
1019 // or is that overkill?
1020 if (!IsDerivedFrom(LType, Class, Paths) ||
1021 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1022 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1023 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1024 return QualType();
1025 }
1026 }
1027
1028 // C++ 5.5p2
1029 // The result is an object or a function of the type specified by the
1030 // second operand.
1031 // The cv qualifiers are the union of those in the pointer and the left side,
1032 // in accordance with 5.5p5 and 5.2.5.
1033 // FIXME: This returns a dereferenced member function pointer as a normal
1034 // function type. However, the only operation valid on such functions is
1035 // calling them. There's also a GCC extension to get a function pointer to
1036 // the thing, which is another complication, because this type - unlike the
1037 // type that is the result of this expression - takes the class as the first
1038 // argument.
1039 // We probably need a "MemberFunctionClosureType" or something like that.
1040 QualType Result = MemPtr->getPointeeType();
1041 if (LType.isConstQualified())
1042 Result.addConst();
1043 if (LType.isVolatileQualified())
1044 Result.addVolatile();
1045 return Result;
1046}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001047
1048/// \brief Get the target type of a standard or user-defined conversion.
1049static QualType TargetType(const ImplicitConversionSequence &ICS) {
1050 assert((ICS.ConversionKind ==
1051 ImplicitConversionSequence::StandardConversion ||
1052 ICS.ConversionKind ==
1053 ImplicitConversionSequence::UserDefinedConversion) &&
1054 "function only valid for standard or user-defined conversions");
1055 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1056 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1057 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1058}
1059
1060/// \brief Try to convert a type to another according to C++0x 5.16p3.
1061///
1062/// This is part of the parameter validation for the ? operator. If either
1063/// value operand is a class type, the two operands are attempted to be
1064/// converted to each other. This function does the conversion in one direction.
1065/// It emits a diagnostic and returns true only if it finds an ambiguous
1066/// conversion.
1067static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1068 SourceLocation QuestionLoc,
1069 ImplicitConversionSequence &ICS)
1070{
1071 // C++0x 5.16p3
1072 // The process for determining whether an operand expression E1 of type T1
1073 // can be converted to match an operand expression E2 of type T2 is defined
1074 // as follows:
1075 // -- If E2 is an lvalue:
1076 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1077 // E1 can be converted to match E2 if E1 can be implicitly converted to
1078 // type "lvalue reference to T2", subject to the constraint that in the
1079 // conversion the reference must bind directly to E1.
1080 if (!Self.CheckReferenceInit(From,
1081 Self.Context.getLValueReferenceType(To->getType()),
1082 &ICS))
1083 {
1084 assert((ICS.ConversionKind ==
1085 ImplicitConversionSequence::StandardConversion ||
1086 ICS.ConversionKind ==
1087 ImplicitConversionSequence::UserDefinedConversion) &&
1088 "expected a definite conversion");
1089 bool DirectBinding =
1090 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1091 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1092 if (DirectBinding)
1093 return false;
1094 }
1095 }
1096 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1097 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1098 // -- if E1 and E2 have class type, and the underlying class types are
1099 // the same or one is a base class of the other:
1100 QualType FTy = From->getType();
1101 QualType TTy = To->getType();
1102 const RecordType *FRec = FTy->getAsRecordType();
1103 const RecordType *TRec = TTy->getAsRecordType();
1104 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1105 if (FRec && TRec && (FRec == TRec ||
1106 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1107 // E1 can be converted to match E2 if the class of T2 is the
1108 // same type as, or a base class of, the class of T1, and
1109 // [cv2 > cv1].
1110 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1111 // Could still fail if there's no copy constructor.
1112 // FIXME: Is this a hard error then, or just a conversion failure? The
1113 // standard doesn't say.
1114 ICS = Self.TryCopyInitialization(From, TTy);
1115 }
1116 } else {
1117 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1118 // implicitly converted to the type that expression E2 would have
1119 // if E2 were converted to an rvalue.
1120 // First find the decayed type.
1121 if (TTy->isFunctionType())
1122 TTy = Self.Context.getPointerType(TTy);
1123 else if(TTy->isArrayType())
1124 TTy = Self.Context.getArrayDecayedType(TTy);
1125
1126 // Now try the implicit conversion.
1127 // FIXME: This doesn't detect ambiguities.
1128 ICS = Self.TryImplicitConversion(From, TTy);
1129 }
1130 return false;
1131}
1132
1133/// \brief Try to find a common type for two according to C++0x 5.16p5.
1134///
1135/// This is part of the parameter validation for the ? operator. If either
1136/// value operand is a class type, overload resolution is used to find a
1137/// conversion to a common type.
1138static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1139 SourceLocation Loc) {
1140 Expr *Args[2] = { LHS, RHS };
1141 OverloadCandidateSet CandidateSet;
1142 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1143
1144 OverloadCandidateSet::iterator Best;
1145 switch (Self.BestViableFunction(CandidateSet, Best)) {
1146 case Sema::OR_Success:
1147 // We found a match. Perform the conversions on the arguments and move on.
1148 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1149 Best->Conversions[0], "converting") ||
1150 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1151 Best->Conversions[1], "converting"))
1152 break;
1153 return false;
1154
1155 case Sema::OR_No_Viable_Function:
1156 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1157 << LHS->getType() << RHS->getType()
1158 << LHS->getSourceRange() << RHS->getSourceRange();
1159 return true;
1160
1161 case Sema::OR_Ambiguous:
1162 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1163 << LHS->getType() << RHS->getType()
1164 << LHS->getSourceRange() << RHS->getSourceRange();
1165 // FIXME: Print the possible common types by printing the return types
1166 // of the viable candidates.
1167 break;
1168
1169 case Sema::OR_Deleted:
1170 assert(false && "Conditional operator has only built-in overloads");
1171 break;
1172 }
1173 return true;
1174}
1175
Sebastian Redl76458502009-04-17 16:30:52 +00001176/// \brief Perform an "extended" implicit conversion as returned by
1177/// TryClassUnification.
1178///
1179/// TryClassUnification generates ICSs that include reference bindings.
1180/// PerformImplicitConversion is not suitable for this; it chokes if the
1181/// second part of a standard conversion is ICK_DerivedToBase. This function
1182/// handles the reference binding specially.
1183static bool ConvertForConditional(Sema &Self, Expr *&E,
1184 const ImplicitConversionSequence &ICS)
1185{
1186 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1187 ICS.Standard.ReferenceBinding) {
1188 assert(ICS.Standard.DirectBinding &&
1189 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001190 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1191 // redoing all the work.
1192 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1193 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001194 }
1195 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1196 ICS.UserDefined.After.ReferenceBinding) {
1197 assert(ICS.UserDefined.After.DirectBinding &&
1198 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001199 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1200 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001201 }
1202 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1203 return true;
1204 return false;
1205}
1206
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001207/// \brief Check the operands of ?: under C++ semantics.
1208///
1209/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1210/// extension. In this case, LHS == Cond. (But they're not aliases.)
1211QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1212 SourceLocation QuestionLoc) {
1213 // FIXME: Handle C99's complex types, vector types, block pointers and
1214 // Obj-C++ interface pointers.
1215
1216 // C++0x 5.16p1
1217 // The first expression is contextually converted to bool.
1218 if (!Cond->isTypeDependent()) {
1219 if (CheckCXXBooleanCondition(Cond))
1220 return QualType();
1221 }
1222
1223 // Either of the arguments dependent?
1224 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1225 return Context.DependentTy;
1226
1227 // C++0x 5.16p2
1228 // If either the second or the third operand has type (cv) void, ...
1229 QualType LTy = LHS->getType();
1230 QualType RTy = RHS->getType();
1231 bool LVoid = LTy->isVoidType();
1232 bool RVoid = RTy->isVoidType();
1233 if (LVoid || RVoid) {
1234 // ... then the [l2r] conversions are performed on the second and third
1235 // operands ...
1236 DefaultFunctionArrayConversion(LHS);
1237 DefaultFunctionArrayConversion(RHS);
1238 LTy = LHS->getType();
1239 RTy = RHS->getType();
1240
1241 // ... and one of the following shall hold:
1242 // -- The second or the third operand (but not both) is a throw-
1243 // expression; the result is of the type of the other and is an rvalue.
1244 bool LThrow = isa<CXXThrowExpr>(LHS);
1245 bool RThrow = isa<CXXThrowExpr>(RHS);
1246 if (LThrow && !RThrow)
1247 return RTy;
1248 if (RThrow && !LThrow)
1249 return LTy;
1250
1251 // -- Both the second and third operands have type void; the result is of
1252 // type void and is an rvalue.
1253 if (LVoid && RVoid)
1254 return Context.VoidTy;
1255
1256 // Neither holds, error.
1257 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1258 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1259 << LHS->getSourceRange() << RHS->getSourceRange();
1260 return QualType();
1261 }
1262
1263 // Neither is void.
1264
1265 // C++0x 5.16p3
1266 // Otherwise, if the second and third operand have different types, and
1267 // either has (cv) class type, and attempt is made to convert each of those
1268 // operands to the other.
1269 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1270 (LTy->isRecordType() || RTy->isRecordType())) {
1271 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1272 // These return true if a single direction is already ambiguous.
1273 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1274 return QualType();
1275 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1276 return QualType();
1277
1278 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1279 ImplicitConversionSequence::BadConversion;
1280 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1281 ImplicitConversionSequence::BadConversion;
1282 // If both can be converted, [...] the program is ill-formed.
1283 if (HaveL2R && HaveR2L) {
1284 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1285 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1286 return QualType();
1287 }
1288
1289 // If exactly one conversion is possible, that conversion is applied to
1290 // the chosen operand and the converted operands are used in place of the
1291 // original operands for the remainder of this section.
1292 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001293 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001294 return QualType();
1295 LTy = LHS->getType();
1296 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001297 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001298 return QualType();
1299 RTy = RHS->getType();
1300 }
1301 }
1302
1303 // C++0x 5.16p4
1304 // If the second and third operands are lvalues and have the same type,
1305 // the result is of that type [...]
1306 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1307 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1308 RHS->isLvalue(Context) == Expr::LV_Valid)
1309 return LTy;
1310
1311 // C++0x 5.16p5
1312 // Otherwise, the result is an rvalue. If the second and third operands
1313 // do not have the same type, and either has (cv) class type, ...
1314 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1315 // ... overload resolution is used to determine the conversions (if any)
1316 // to be applied to the operands. If the overload resolution fails, the
1317 // program is ill-formed.
1318 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1319 return QualType();
1320 }
1321
1322 // C++0x 5.16p6
1323 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1324 // conversions are performed on the second and third operands.
1325 DefaultFunctionArrayConversion(LHS);
1326 DefaultFunctionArrayConversion(RHS);
1327 LTy = LHS->getType();
1328 RTy = RHS->getType();
1329
1330 // After those conversions, one of the following shall hold:
1331 // -- The second and third operands have the same type; the result
1332 // is of that type.
1333 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1334 return LTy;
1335
1336 // -- The second and third operands have arithmetic or enumeration type;
1337 // the usual arithmetic conversions are performed to bring them to a
1338 // common type, and the result is of that type.
1339 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1340 UsualArithmeticConversions(LHS, RHS);
1341 return LHS->getType();
1342 }
1343
1344 // -- The second and third operands have pointer type, or one has pointer
1345 // type and the other is a null pointer constant; pointer conversions
1346 // and qualification conversions are performed to bring them to their
1347 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001348 QualType Composite = FindCompositePointerType(LHS, RHS);
1349 if (!Composite.isNull())
1350 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001351
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001352 // Fourth bullet is same for pointers-to-member. However, the possible
1353 // conversions are far more limited: we have null-to-pointer, upcast of
1354 // containing class, and second-level cv-ness.
1355 // cv-ness is not a union, but must match one of the two operands. (Which,
1356 // frankly, is stupid.)
1357 const MemberPointerType *LMemPtr = LTy->getAsMemberPointerType();
1358 const MemberPointerType *RMemPtr = RTy->getAsMemberPointerType();
1359 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1360 ImpCastExprToType(RHS, LTy);
1361 return LTy;
1362 }
1363 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1364 ImpCastExprToType(LHS, RTy);
1365 return RTy;
1366 }
1367 if (LMemPtr && RMemPtr) {
1368 QualType LPointee = LMemPtr->getPointeeType();
1369 QualType RPointee = RMemPtr->getPointeeType();
1370 // First, we check that the unqualified pointee type is the same. If it's
1371 // not, there's no conversion that will unify the two pointers.
1372 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1373 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1374 // Second, we take the greater of the two cv qualifications. If neither
1375 // is greater than the other, the conversion is not possible.
1376 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1377 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1378 // Third, we check if either of the container classes is derived from
1379 // the other.
1380 QualType LContainer(LMemPtr->getClass(), 0);
1381 QualType RContainer(RMemPtr->getClass(), 0);
1382 QualType MoreDerived;
1383 if (Context.getCanonicalType(LContainer) ==
1384 Context.getCanonicalType(RContainer))
1385 MoreDerived = LContainer;
1386 else if (IsDerivedFrom(LContainer, RContainer))
1387 MoreDerived = LContainer;
1388 else if (IsDerivedFrom(RContainer, LContainer))
1389 MoreDerived = RContainer;
1390
1391 if (!MoreDerived.isNull()) {
1392 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1393 // We don't use ImpCastExprToType here because this could still fail
1394 // for ambiguous or inaccessible conversions.
1395 QualType Common = Context.getMemberPointerType(
1396 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1397 if (PerformImplicitConversion(LHS, Common, "converting"))
1398 return QualType();
1399 if (PerformImplicitConversion(RHS, Common, "converting"))
1400 return QualType();
1401 return Common;
1402 }
1403 }
1404 }
1405 }
1406
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001407 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1408 << LHS->getType() << RHS->getType()
1409 << LHS->getSourceRange() << RHS->getSourceRange();
1410 return QualType();
1411}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001412
1413/// \brief Find a merged pointer type and convert the two expressions to it.
1414///
1415/// This finds the composite pointer type for @p E1 and @p E2 according to
1416/// C++0x 5.9p2. It converts both expressions to this type and returns it.
1417/// It does not emit diagnostics.
1418QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1419 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1420 QualType T1 = E1->getType(), T2 = E2->getType();
1421 if(!T1->isPointerType() && !T2->isPointerType())
1422 return QualType();
1423
1424 // C++0x 5.9p2
1425 // Pointer conversions and qualification conversions are performed on
1426 // pointer operands to bring them to their composite pointer type. If
1427 // one operand is a null pointer constant, the composite pointer type is
1428 // the type of the other operand.
1429 if (E1->isNullPointerConstant(Context)) {
1430 ImpCastExprToType(E1, T2);
1431 return T2;
1432 }
1433 if (E2->isNullPointerConstant(Context)) {
1434 ImpCastExprToType(E2, T1);
1435 return T1;
1436 }
1437 // Now both have to be pointers.
1438 if(!T1->isPointerType() || !T2->isPointerType())
1439 return QualType();
1440
1441 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1442 // the other has type "pointer to cv2 T" and the composite pointer type is
1443 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1444 // Otherwise, the composite pointer type is a pointer type similar to the
1445 // type of one of the operands, with a cv-qualification signature that is
1446 // the union of the cv-qualification signatures of the operand types.
1447 // In practice, the first part here is redundant; it's subsumed by the second.
1448 // What we do here is, we build the two possible composite types, and try the
1449 // conversions in both directions. If only one works, or if the two composite
1450 // types are the same, we have succeeded.
1451 llvm::SmallVector<unsigned, 4> QualifierUnion;
1452 QualType Composite1 = T1, Composite2 = T2;
1453 const PointerType *Ptr1, *Ptr2;
1454 while ((Ptr1 = Composite1->getAsPointerType()) &&
1455 (Ptr2 = Composite2->getAsPointerType())) {
1456 Composite1 = Ptr1->getPointeeType();
1457 Composite2 = Ptr2->getPointeeType();
1458 QualifierUnion.push_back(
1459 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1460 }
1461 // Rewrap the composites as pointers with the union CVRs.
1462 for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(),
1463 E = QualifierUnion.end(); I != E; ++I) {
1464 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1465 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1466 }
1467
1468 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1469 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1470 ImplicitConversionSequence E1ToC2, E2ToC2;
1471 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1472 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1473 if (Context.getCanonicalType(Composite1) !=
1474 Context.getCanonicalType(Composite2)) {
1475 E1ToC2 = TryImplicitConversion(E1, Composite2);
1476 E2ToC2 = TryImplicitConversion(E2, Composite2);
1477 }
1478
1479 bool ToC1Viable = E1ToC1.ConversionKind !=
1480 ImplicitConversionSequence::BadConversion
1481 && E2ToC1.ConversionKind !=
1482 ImplicitConversionSequence::BadConversion;
1483 bool ToC2Viable = E1ToC2.ConversionKind !=
1484 ImplicitConversionSequence::BadConversion
1485 && E2ToC2.ConversionKind !=
1486 ImplicitConversionSequence::BadConversion;
1487 if (ToC1Viable && !ToC2Viable) {
1488 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1489 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1490 return Composite1;
1491 }
1492 if (ToC2Viable && !ToC1Viable) {
1493 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1494 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1495 return Composite2;
1496 }
1497 return QualType();
1498}