blob: b9575101b0ae2747ec7e1804c51095208fe241f5 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
Sebastian Redl7c8bd602009-02-07 20:10:22 +000014#include "SemaInherit.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "Sema.h"
16#include "clang/AST/ExprCXX.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +000018#include "clang/Parse/DeclSpec.h"
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +000019#include "clang/Lex/Preprocessor.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000020#include "clang/Basic/TargetInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000021#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23
Douglas Gregor487a75a2008-11-19 19:09:45 +000024/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregor2def4832008-11-17 20:34:05 +000025/// name (e.g., operator void const *) as an expression. This is
26/// very similar to ActOnIdentifierExpr, except that instead of
27/// providing an identifier the parser provides the type of the
28/// conversion function.
Sebastian Redlcd965b92009-01-18 18:53:16 +000029Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000030Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
31 TypeTy *Ty, bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000032 const CXXScopeSpec &SS,
33 bool isAddressOfOperand) {
Douglas Gregor2def4832008-11-17 20:34:05 +000034 QualType ConvType = QualType::getFromOpaquePtr(Ty);
35 QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
36 DeclarationName ConvName
37 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd965b92009-01-18 18:53:16 +000038 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +000039 &SS, isAddressOfOperand);
Douglas Gregor2def4832008-11-17 20:34:05 +000040}
Sebastian Redlc42e1182008-11-11 11:37:55 +000041
Douglas Gregor487a75a2008-11-19 19:09:45 +000042/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-11-18 14:39:36 +000043/// name (e.g., @c operator+ ) as an expression. This is very
44/// similar to ActOnIdentifierExpr, except that instead of providing
45/// an identifier the parser provides the kind of overloaded
46/// operator that was parsed.
Sebastian Redlcd965b92009-01-18 18:53:16 +000047Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000048Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
49 OverloadedOperatorKind Op,
50 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000051 const CXXScopeSpec &SS,
52 bool isAddressOfOperand) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000053 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redlebc07d52009-02-03 20:19:35 +000054 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor17330012009-02-04 15:01:18 +000055 isAddressOfOperand);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000056}
57
Sebastian Redlc42e1182008-11-11 11:37:55 +000058/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000059Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000060Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
61 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +000062 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000063 if (!StdNs)
Sebastian Redlf53597f2009-03-15 17:47:39 +000064 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Chris Lattner572af492008-11-20 05:51:55 +000065
66 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor4c921ae2009-01-30 01:04:22 +000067 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlc42e1182008-11-11 11:37:55 +000068 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000069 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000070 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000071
72 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
73
Sebastian Redlf53597f2009-03-15 17:47:39 +000074 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
75 TypeInfoType.withConst(),
76 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +000077}
78
Steve Naroff1b273c42007-09-16 14:56:35 +000079/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +000080Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000081Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000082 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000083 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +000084 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
85 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000086}
Chris Lattner50dd2892008-02-26 00:51:44 +000087
Sebastian Redl6e8ed162009-05-10 18:38:11 +000088/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
89Action::OwningExprResult
90Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
91 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
92}
93
Chris Lattner50dd2892008-02-26 00:51:44 +000094/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +000095Action::OwningExprResult
96Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +000097 Expr *Ex = E.takeAs<Expr>();
98 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
99 return ExprError();
100 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
101}
102
103/// CheckCXXThrowOperand - Validate the operand of a throw.
104bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
105 // C++ [except.throw]p3:
106 // [...] adjusting the type from "array of T" or "function returning T"
107 // to "pointer to T" or "pointer to function returning T", [...]
108 DefaultFunctionArrayConversion(E);
109
110 // If the type of the exception would be an incomplete type or a pointer
111 // to an incomplete type other than (cv) void the program is ill-formed.
112 QualType Ty = E->getType();
113 int isPointer = 0;
114 if (const PointerType* Ptr = Ty->getAsPointerType()) {
115 Ty = Ptr->getPointeeType();
116 isPointer = 1;
117 }
118 if (!isPointer || !Ty->isVoidType()) {
119 if (RequireCompleteType(ThrowLoc, Ty,
120 isPointer ? diag::err_throw_incomplete_ptr
121 : diag::err_throw_incomplete,
122 E->getSourceRange(), SourceRange(), QualType()))
123 return true;
124 }
125
126 // FIXME: Construct a temporary here.
127 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000128}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000129
Sebastian Redlf53597f2009-03-15 17:47:39 +0000130Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000131 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
132 /// is a non-lvalue expression whose value is the address of the object for
133 /// which the function is called.
134
Sebastian Redlf53597f2009-03-15 17:47:39 +0000135 if (!isa<FunctionDecl>(CurContext))
136 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000137
138 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
139 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000140 return Owned(new (Context) CXXThisExpr(ThisLoc,
141 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000142
Sebastian Redlf53597f2009-03-15 17:47:39 +0000143 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000144}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000145
146/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
147/// Can be interpreted either as function-style casting ("int(x)")
148/// or class type construction ("ClassType(x,y,z)")
149/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000150Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000151Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
152 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000153 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000154 SourceLocation *CommaLocs,
155 SourceLocation RParenLoc) {
156 assert(TypeRep && "Missing type!");
157 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000158 unsigned NumExprs = exprs.size();
159 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000160 SourceLocation TyBeginLoc = TypeRange.getBegin();
161 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
162
Sebastian Redlf53597f2009-03-15 17:47:39 +0000163 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000164 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000165 exprs.release();
Anders Carlsson26de5492009-04-24 05:23:13 +0000166
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000167 return Owned(CXXUnresolvedConstructExpr::Create(Context,
168 TypeRange.getBegin(), Ty,
169 LParenLoc,
170 Exprs, NumExprs,
171 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000172 }
173
174
Douglas Gregor506ae412009-01-16 18:33:17 +0000175 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000176 // If the expression list is a single expression, the type conversion
177 // expression is equivalent (in definedness, and if defined in meaning) to the
178 // corresponding cast expression.
179 //
180 if (NumExprs == 1) {
181 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000182 return ExprError();
183 exprs.release();
184 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
185 Ty, TyBeginLoc, Exprs[0],
186 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000187 }
188
Douglas Gregor506ae412009-01-16 18:33:17 +0000189 if (const RecordType *RT = Ty->getAsRecordType()) {
190 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000191
Anders Carlsson165a0a02009-05-17 18:41:29 +0000192 // FIXME: We should always create a CXXTemporaryObjectExpr here unless
193 // both the ctor and dtor are trivial.
Douglas Gregor506ae412009-01-16 18:33:17 +0000194 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
195 CXXConstructorDecl *Constructor
196 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
197 TypeRange.getBegin(),
198 SourceRange(TypeRange.getBegin(),
199 RParenLoc),
200 DeclarationName(),
201 IK_Direct);
Douglas Gregor506ae412009-01-16 18:33:17 +0000202
Sebastian Redlf53597f2009-03-15 17:47:39 +0000203 if (!Constructor)
204 return ExprError();
205
Anders Carlsson26de5492009-04-24 05:23:13 +0000206 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty);
Anders Carlsson165a0a02009-05-17 18:41:29 +0000207 ExprTemporaries.push_back(Temp);
208
Sebastian Redlf53597f2009-03-15 17:47:39 +0000209 exprs.release();
Anders Carlsson09c4abb2009-04-24 05:44:25 +0000210 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Temp,
211 Constructor, Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000212 TyBeginLoc, Exprs,
213 NumExprs, RParenLoc));
Douglas Gregor506ae412009-01-16 18:33:17 +0000214 }
215
216 // Fall through to value-initialize an object of class type that
217 // doesn't have a user-declared default constructor.
218 }
219
220 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000221 // If the expression list specifies more than a single value, the type shall
222 // be a class with a suitably declared constructor.
223 //
224 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000225 return ExprError(Diag(CommaLocs[0],
226 diag::err_builtin_func_cast_more_than_one_arg)
227 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000228
229 assert(NumExprs == 0 && "Expected 0 expressions");
230
Douglas Gregor506ae412009-01-16 18:33:17 +0000231 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000232 // The expression T(), where T is a simple-type-specifier for a non-array
233 // complete object type or the (possibly cv-qualified) void type, creates an
234 // rvalue of the specified type, which is value-initialized.
235 //
236 if (Ty->isArrayType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000237 return ExprError(Diag(TyBeginLoc,
238 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000239 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redlf53597f2009-03-15 17:47:39 +0000240 RequireCompleteType(TyBeginLoc, Ty,
241 diag::err_invalid_incomplete_type_use, FullRange))
242 return ExprError();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000243
Anders Carlsson8211eff2009-03-24 01:19:16 +0000244 if (RequireNonAbstractType(TyBeginLoc, Ty,
245 diag::err_allocation_of_abstract_type))
Anders Carlsson11f21a02009-03-23 19:10:31 +0000246 return ExprError();
247
Sebastian Redlf53597f2009-03-15 17:47:39 +0000248 exprs.release();
249 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000250}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000251
252
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000253/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
254/// @code new (memory) int[size][4] @endcode
255/// or
256/// @code ::new Foo(23, "hello") @endcode
257/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000258Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000259Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000260 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000261 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000262 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000263 MultiExprArg ConstructorArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000264 SourceLocation ConstructorRParen)
265{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000266 Expr *ArraySize = 0;
267 unsigned Skip = 0;
268 // If the specified type is an array, unwrap it and save the expression.
269 if (D.getNumTypeObjects() > 0 &&
270 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
271 DeclaratorChunk &Chunk = D.getTypeObject(0);
272 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000273 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
274 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000275 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000276 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
277 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000278 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
279 Skip = 1;
280 }
281
282 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000283 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000284 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000285
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000286 if (CheckAllocatedType(AllocType, D))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000287 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000288
Sebastian Redl28507842009-02-26 14:39:58 +0000289 QualType ResultType = AllocType->isDependentType()
290 ? Context.DependentTy
291 : Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000292
293 // That every array dimension except the first is constant was already
294 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000295
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000296 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
297 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000298 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000299 QualType SizeType = ArraySize->getType();
300 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000301 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
302 diag::err_array_size_not_integral)
303 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000304 // Let's see if this is a constant < 0. If so, we reject it out of hand.
305 // We don't care about special rules, so we tell the machinery it's not
306 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000307 if (!ArraySize->isValueDependent()) {
308 llvm::APSInt Value;
309 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
310 if (Value < llvm::APSInt(
311 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000312 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
313 diag::err_typecheck_negative_array_size)
314 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000315 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000316 }
317 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000318
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000319 FunctionDecl *OperatorNew = 0;
320 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000321 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
322 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000323 if (!AllocType->isDependentType() &&
324 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
325 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000326 SourceRange(PlacementLParen, PlacementRParen),
327 UseGlobal, AllocType, ArraySize, PlaceArgs,
328 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000329 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000330
331 bool Init = ConstructorLParen.isValid();
332 // --- Choosing a constructor ---
333 // C++ 5.3.4p15
334 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
335 // the object is not initialized. If the object, or any part of it, is
336 // const-qualified, it's an error.
337 // 2) If T is a POD and there's an empty initializer, the object is value-
338 // initialized.
339 // 3) If T is a POD and there's one initializer argument, the object is copy-
340 // constructed.
341 // 4) If T is a POD and there's more initializer arguments, it's an error.
342 // 5) If T is not a POD, the initializer arguments are used as constructor
343 // arguments.
344 //
345 // Or by the C++0x formulation:
346 // 1) If there's no initializer, the object is default-initialized according
347 // to C++0x rules.
348 // 2) Otherwise, the object is direct-initialized.
349 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000350 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000351 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000352 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000353 if (AllocType->isDependentType()) {
354 // Skip all the checks.
355 }
Sebastian Redl4f149632009-05-07 16:14:23 +0000356 else if ((RT = AllocType->getAsRecordType()) &&
357 !AllocType->isAggregateType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000358 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000359 AllocType, ConsArgs, NumConsArgs,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000360 D.getSourceRange().getBegin(),
361 SourceRange(D.getSourceRange().getBegin(),
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000362 ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000363 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000364 NumConsArgs != 0 ? IK_Direct : IK_Default);
365 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000366 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000367 } else {
368 if (!Init) {
369 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000370 if (AllocType.isConstQualified())
371 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
372 << D.getSourceRange());
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000373 } else if (NumConsArgs == 0) {
374 // Object is value-initialized. Do nothing.
375 } else if (NumConsArgs == 1) {
376 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000377 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000378 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000379 DeclarationName() /*AllocType.getAsString()*/,
380 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000381 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000382 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000383 return ExprError(Diag(StartLoc,
384 diag::err_builtin_direct_init_more_than_one_arg)
385 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000386 }
387 }
388
389 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
390
Sebastian Redlf53597f2009-03-15 17:47:39 +0000391 PlacementArgs.release();
392 ConstructorArgs.release();
393 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000394 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000395 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000396 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000397}
398
399/// CheckAllocatedType - Checks that a type is suitable as the allocated type
400/// in a new-expression.
401/// dimension off and stores the size expression in ArraySize.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000402bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000403{
404 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
405 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000406 if (AllocType->isFunctionType())
407 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
408 << AllocType << 0 << D.getSourceRange();
409 else if (AllocType->isReferenceType())
410 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
411 << AllocType << 1 << D.getSourceRange();
412 else if (!AllocType->isDependentType() &&
413 RequireCompleteType(D.getSourceRange().getBegin(), AllocType,
414 diag::err_new_incomplete_type,
415 D.getSourceRange()))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000416 return true;
Douglas Gregore7450f52009-03-24 19:52:54 +0000417 else if (RequireNonAbstractType(D.getSourceRange().getBegin(), AllocType,
418 diag::err_allocation_of_abstract_type))
419 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000420
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000421 // Every dimension shall be of constant size.
422 unsigned i = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000423 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
424 if (!Array->isConstantArrayType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000425 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
426 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000427 return true;
428 }
429 AllocType = Array->getElementType();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000430 ++i;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000431 }
432
433 return false;
434}
435
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000436/// FindAllocationFunctions - Finds the overloads of operator new and delete
437/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000438bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
439 bool UseGlobal, QualType AllocType,
440 bool IsArray, Expr **PlaceArgs,
441 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000442 FunctionDecl *&OperatorNew,
443 FunctionDecl *&OperatorDelete)
444{
445 // --- Choosing an allocation function ---
446 // C++ 5.3.4p8 - 14 & 18
447 // 1) If UseGlobal is true, only look in the global scope. Else, also look
448 // in the scope of the allocated class.
449 // 2) If an array size is given, look for operator new[], else look for
450 // operator new.
451 // 3) The first argument is always size_t. Append the arguments from the
452 // placement form.
453 // FIXME: Also find the appropriate delete operator.
454
455 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
456 // We don't care about the actual value of this argument.
457 // FIXME: Should the Sema create the expression and embed it in the syntax
458 // tree? Or should the consumer just recalculate the value?
Ted Kremenek8189cde2009-02-07 01:47:29 +0000459 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000460 Context.Target.getPointerWidth(0)),
461 Context.getSizeType(),
462 SourceLocation());
463 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
464
465 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
466 IsArray ? OO_Array_New : OO_New);
467 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000468 CXXRecordDecl *Record
469 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000470 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000471 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000472 AllocArgs.size(), Record, /*AllowMissing=*/true,
473 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000474 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000475 }
476 if (!OperatorNew) {
477 // Didn't find a member overload. Look for a global one.
478 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000479 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000480 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000481 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
482 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000483 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000484 }
485
Sebastian Redl7f662392008-12-04 22:20:51 +0000486 // FIXME: This is leaked on error. But so much is currently in Sema that it's
487 // easier to clean it in one go.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000488 AllocArgs[0]->Destroy(Context);
489 return false;
490}
491
Sebastian Redl7f662392008-12-04 22:20:51 +0000492/// FindAllocationOverload - Find an fitting overload for the allocation
493/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000494bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
495 DeclarationName Name, Expr** Args,
496 unsigned NumArgs, DeclContext *Ctx,
497 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redl7f662392008-12-04 22:20:51 +0000498{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000499 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000500 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000501 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000502 if (AllowMissing)
503 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000504 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000505 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000506 }
507
508 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000509 for (; Alloc != AllocEnd; ++Alloc) {
510 // Even member operator new/delete are implicitly treated as
511 // static, so don't use AddMemberCandidate.
512 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
513 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
514 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000515 }
516
517 // Do the resolution.
518 OverloadCandidateSet::iterator Best;
519 switch(BestViableFunction(Candidates, Best)) {
520 case OR_Success: {
521 // Got one!
522 FunctionDecl *FnDecl = Best->Function;
523 // The first argument is size_t, and the first parameter must be size_t,
524 // too. This is checked on declaration and can be assumed. (It can't be
525 // asserted on, though, since invalid decls are left in there.)
526 for (unsigned i = 1; i < NumArgs; ++i) {
527 // FIXME: Passing word to diagnostic.
528 if (PerformCopyInitialization(Args[i-1],
529 FnDecl->getParamDecl(i)->getType(),
530 "passing"))
531 return true;
532 }
533 Operator = FnDecl;
534 return false;
535 }
536
537 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000538 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000539 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000540 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
541 return true;
542
543 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000544 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000545 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000546 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
547 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000548
549 case OR_Deleted:
550 Diag(StartLoc, diag::err_ovl_deleted_call)
551 << Best->Function->isDeleted()
552 << Name << Range;
553 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
554 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000555 }
556 assert(false && "Unreachable, bad result from BestViableFunction");
557 return true;
558}
559
560
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000561/// DeclareGlobalNewDelete - Declare the global forms of operator new and
562/// delete. These are:
563/// @code
564/// void* operator new(std::size_t) throw(std::bad_alloc);
565/// void* operator new[](std::size_t) throw(std::bad_alloc);
566/// void operator delete(void *) throw();
567/// void operator delete[](void *) throw();
568/// @endcode
569/// Note that the placement and nothrow forms of new are *not* implicitly
570/// declared. Their use requires including \<new\>.
571void Sema::DeclareGlobalNewDelete()
572{
573 if (GlobalNewDeleteDeclared)
574 return;
575 GlobalNewDeleteDeclared = true;
576
577 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
578 QualType SizeT = Context.getSizeType();
579
580 // FIXME: Exception specifications are not added.
581 DeclareGlobalAllocationFunction(
582 Context.DeclarationNames.getCXXOperatorName(OO_New),
583 VoidPtr, SizeT);
584 DeclareGlobalAllocationFunction(
585 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
586 VoidPtr, SizeT);
587 DeclareGlobalAllocationFunction(
588 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
589 Context.VoidTy, VoidPtr);
590 DeclareGlobalAllocationFunction(
591 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
592 Context.VoidTy, VoidPtr);
593}
594
595/// DeclareGlobalAllocationFunction - Declares a single implicit global
596/// allocation function if it doesn't already exist.
597void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
598 QualType Return, QualType Argument)
599{
600 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
601
602 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000603 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000604 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000605 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Context, Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000606 Alloc != AllocEnd; ++Alloc) {
607 // FIXME: Do we need to check for default arguments here?
608 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
609 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000610 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000611 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000612 }
613 }
614
615 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
616 FunctionDecl *Alloc =
617 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor2224f842009-02-25 16:33:18 +0000618 FnType, FunctionDecl::None, false, true,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000619 SourceLocation());
620 Alloc->setImplicit();
621 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000622 0, Argument, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000623 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000624
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000625 // FIXME: Also add this declaration to the IdentifierResolver, but
626 // make sure it is at the end of the chain to coincide with the
627 // global scope.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000628 ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000629}
630
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000631/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
632/// @code ::delete ptr; @endcode
633/// or
634/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000635Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000636Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000637 bool ArrayForm, ExprArg Operand)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000638{
639 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
640 // having a single conversion function to a pointer type. The result has
641 // type void."
642 // DR599 amends "pointer type" to "pointer to object type" in both cases.
643
Sebastian Redlf53597f2009-03-15 17:47:39 +0000644 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000645 if (!Ex->isTypeDependent()) {
646 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000647
Sebastian Redl28507842009-02-26 14:39:58 +0000648 if (Type->isRecordType()) {
649 // FIXME: Find that one conversion function and amend the type.
650 }
651
Sebastian Redlf53597f2009-03-15 17:47:39 +0000652 if (!Type->isPointerType())
653 return ExprError(Diag(StartLoc, diag::err_delete_operand)
654 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000655
656 QualType Pointee = Type->getAsPointerType()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000657 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000658 return ExprError(Diag(StartLoc, diag::err_delete_operand)
659 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000660 else if (!Pointee->isDependentType() &&
661 RequireCompleteType(StartLoc, Pointee,
662 diag::warn_delete_incomplete,
663 Ex->getSourceRange()))
664 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000665
666 // FIXME: Look up the correct operator delete overload and pass a pointer
667 // along.
668 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000669 }
670
Sebastian Redlf53597f2009-03-15 17:47:39 +0000671 Operand.release();
672 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
673 0, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000674}
675
676
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000677/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
678/// C++ if/switch/while/for statement.
679/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000680Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000681Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
682 Declarator &D,
683 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000684 ExprArg AssignExprVal) {
685 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000686
687 // C++ 6.4p2:
688 // The declarator shall not specify a function or an array.
689 // The type-specifier-seq shall not contain typedef and shall not declare a
690 // new class or enumeration.
691
692 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
693 "Parser allowed 'typedef' as storage class of condition decl.");
694
695 QualType Ty = GetTypeForDeclarator(D, S);
696
697 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
698 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
699 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000700 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
701 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000702 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000703 Diag(StartLoc, diag::err_invalid_use_of_array_type)
704 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000705 } else if (const RecordType *RT = Ty->getAsRecordType()) {
706 RecordDecl *RD = RT->getDecl();
707 // The type-specifier-seq shall not declare a new class...
Chris Lattnerb28317a2009-03-28 19:18:32 +0000708 if (RD->isDefinition() &&
709 (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD))))
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000710 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
711 } else if (const EnumType *ET = Ty->getAsEnumType()) {
712 EnumDecl *ED = ET->getDecl();
713 // ...or enumeration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000714 if (ED->isDefinition() &&
715 (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED))))
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000716 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
717 }
718
Chris Lattnerb28317a2009-03-28 19:18:32 +0000719 DeclPtrTy Dcl = ActOnDeclarator(S, D, DeclPtrTy());
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000720 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000721 return ExprError();
722 AddInitializerToDecl(Dcl, move(AssignExprVal));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000723
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000724 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000725 // We know that the decl had to be a VarDecl because that is the only type of
726 // decl that can be assigned and the grammar requires an '='.
727 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
728 VD->setDeclaredInCondition(true);
729 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000730}
731
732/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
733bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
734 // C++ 6.4p4:
735 // The value of a condition that is an initialized declaration in a statement
736 // other than a switch statement is the value of the declared variable
737 // implicitly converted to type bool. If that conversion is ill-formed, the
738 // program is ill-formed.
739 // The value of a condition that is an expression is the value of the
740 // expression, implicitly converted to bool.
741 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000742 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000743}
Douglas Gregor77a52232008-09-12 00:47:35 +0000744
745/// Helper function to determine whether this is the (deprecated) C++
746/// conversion from a string literal to a pointer to non-const char or
747/// non-const wchar_t (for narrow and wide string literals,
748/// respectively).
749bool
750Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
751 // Look inside the implicit cast, if it exists.
752 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
753 From = Cast->getSubExpr();
754
755 // A string literal (2.13.4) that is not a wide string literal can
756 // be converted to an rvalue of type "pointer to char"; a wide
757 // string literal can be converted to an rvalue of type "pointer
758 // to wchar_t" (C++ 4.2p2).
759 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
760 if (const PointerType *ToPtrType = ToType->getAsPointerType())
761 if (const BuiltinType *ToPointeeType
762 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
763 // This conversion is considered only when there is an
764 // explicit appropriate pointer target type (C++ 4.2p2).
765 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
766 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
767 (!StrLit->isWide() &&
768 (ToPointeeType->getKind() == BuiltinType::Char_U ||
769 ToPointeeType->getKind() == BuiltinType::Char_S))))
770 return true;
771 }
772
773 return false;
774}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000775
776/// PerformImplicitConversion - Perform an implicit conversion of the
777/// expression From to the type ToType. Returns true if there was an
778/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000779/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000780/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000781/// explicit user-defined conversions are permitted. @p Elidable should be true
782/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
783/// resolution works differently in that case.
784bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000785Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000786 const char *Flavor, bool AllowExplicit,
787 bool Elidable)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000788{
Sebastian Redle2b68332009-04-12 17:16:29 +0000789 ImplicitConversionSequence ICS;
790 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
791 if (Elidable && getLangOptions().CPlusPlus0x) {
792 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
793 AllowExplicit, /*ForceRValue*/true);
794 }
795 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
796 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
797 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000798 return PerformImplicitConversion(From, ToType, ICS, Flavor);
799}
800
801/// PerformImplicitConversion - Perform an implicit conversion of the
802/// expression From to the type ToType using the pre-computed implicit
803/// conversion sequence ICS. Returns true if there was an error, false
804/// otherwise. The expression From is replaced with the converted
805/// expression. Flavor is the kind of conversion we're performing,
806/// used in the error message.
807bool
808Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
809 const ImplicitConversionSequence &ICS,
810 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000811 switch (ICS.ConversionKind) {
812 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000813 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000814 return true;
815 break;
816
817 case ImplicitConversionSequence::UserDefinedConversion:
Mike Stump390b4cc2009-05-16 07:39:55 +0000818 // FIXME: This is, of course, wrong. We'll need to actually call the
819 // constructor or conversion operator, and then cope with the standard
820 // conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000821 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000822 ToType->isLValueReferenceType());
Douglas Gregor60d62c22008-10-31 16:23:19 +0000823 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000824
825 case ImplicitConversionSequence::EllipsisConversion:
826 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000827 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000828
829 case ImplicitConversionSequence::BadConversion:
830 return true;
831 }
832
833 // Everything went well.
834 return false;
835}
836
837/// PerformImplicitConversion - Perform an implicit conversion of the
838/// expression From to the type ToType by following the standard
839/// conversion sequence SCS. Returns true if there was an error, false
840/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000841/// expression. Flavor is the context in which we're performing this
842/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000843bool
844Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000845 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000846 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000847 // Overall FIXME: we are recomputing too many types here and doing far too
848 // much extra work. What this means is that we need to keep track of more
849 // information that is computed when we try the implicit conversion initially,
850 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000851 QualType FromType = From->getType();
852
Douglas Gregor225c41e2008-11-03 19:09:14 +0000853 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +0000854 // FIXME: When can ToType be a reference type?
855 assert(!ToType->isReferenceType());
856
857 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, ToType);
858 // FIXME: Keep track of whether the copy constructor is elidable or not.
859 From = CXXConstructExpr::Create(Context, Temp, ToType,
860 SCS.CopyConstructor, false, &From, 1);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000861 return false;
862 }
863
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000864 // Perform the first implicit conversion.
865 switch (SCS.First) {
866 case ICK_Identity:
867 case ICK_Lvalue_To_Rvalue:
868 // Nothing to do.
869 break;
870
871 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000872 FromType = Context.getArrayDecayedType(FromType);
873 ImpCastExprToType(From, FromType);
874 break;
875
876 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +0000877 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +0000878 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
879 if (!Fn)
880 return true;
881
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000882 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
883 return true;
884
Douglas Gregor904eed32008-11-10 20:40:00 +0000885 FixOverloadedFunctionReference(From, Fn);
886 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +0000887 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000888 FromType = Context.getPointerType(FromType);
889 ImpCastExprToType(From, FromType);
890 break;
891
892 default:
893 assert(false && "Improper first standard conversion");
894 break;
895 }
896
897 // Perform the second implicit conversion
898 switch (SCS.Second) {
899 case ICK_Identity:
900 // Nothing to do.
901 break;
902
903 case ICK_Integral_Promotion:
904 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000905 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000906 case ICK_Integral_Conversion:
907 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000908 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000909 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000910 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +0000911 case ICK_Compatible_Conversion:
912 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000913 FromType = ToType.getUnqualifiedType();
914 ImpCastExprToType(From, FromType);
915 break;
916
917 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000918 if (SCS.IncompatibleObjC) {
919 // Diagnose incompatible Objective-C conversions
920 Diag(From->getSourceRange().getBegin(),
921 diag::ext_typecheck_convert_incompatible_pointer)
922 << From->getType() << ToType << Flavor
923 << From->getSourceRange();
924 }
925
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000926 if (CheckPointerConversion(From, ToType))
927 return true;
928 ImpCastExprToType(From, ToType);
929 break;
930
931 case ICK_Pointer_Member:
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000932 if (CheckMemberPointerConversion(From, ToType))
933 return true;
934 ImpCastExprToType(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000935 break;
936
937 case ICK_Boolean_Conversion:
938 FromType = Context.BoolTy;
939 ImpCastExprToType(From, FromType);
940 break;
941
942 default:
943 assert(false && "Improper second standard conversion");
944 break;
945 }
946
947 switch (SCS.Third) {
948 case ICK_Identity:
949 // Nothing to do.
950 break;
951
952 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +0000953 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
954 // references.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000955 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000956 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000957 break;
958
959 default:
960 assert(false && "Improper second standard conversion");
961 break;
962 }
963
964 return false;
965}
966
Sebastian Redl64b45f72009-01-05 20:52:13 +0000967Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
968 SourceLocation KWLoc,
969 SourceLocation LParen,
970 TypeTy *Ty,
971 SourceLocation RParen) {
972 // FIXME: Some of the type traits have requirements. Interestingly, only the
Mike Stump390b4cc2009-05-16 07:39:55 +0000973 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed, G++
974 // accepts __is_pod(Incomplete) without complaints, and claims that the type
975 // is indeed a POD.
Sebastian Redl64b45f72009-01-05 20:52:13 +0000976
977 // There is no point in eagerly computing the value. The traits are designed
978 // to be used from type trait templates, so Ty will be a template parameter
979 // 99% of the time.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000980 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
Sebastian Redl64b45f72009-01-05 20:52:13 +0000981 QualType::getFromOpaquePtr(Ty),
982 RParen, Context.BoolTy));
983}
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000984
985QualType Sema::CheckPointerToMemberOperands(
986 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
987{
988 const char *OpSpelling = isIndirect ? "->*" : ".*";
989 // C++ 5.5p2
990 // The binary operator .* [p3: ->*] binds its second operand, which shall
991 // be of type "pointer to member of T" (where T is a completely-defined
992 // class type) [...]
993 QualType RType = rex->getType();
994 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
Douglas Gregore7450f52009-03-24 19:52:54 +0000995 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000996 Diag(Loc, diag::err_bad_memptr_rhs)
997 << OpSpelling << RType << rex->getSourceRange();
998 return QualType();
Douglas Gregor3f5b61c2009-05-14 00:28:11 +0000999 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001000
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001001 QualType Class(MemPtr->getClass(), 0);
1002
1003 // C++ 5.5p2
1004 // [...] to its first operand, which shall be of class T or of a class of
1005 // which T is an unambiguous and accessible base class. [p3: a pointer to
1006 // such a class]
1007 QualType LType = lex->getType();
1008 if (isIndirect) {
1009 if (const PointerType *Ptr = LType->getAsPointerType())
1010 LType = Ptr->getPointeeType().getNonReferenceType();
1011 else {
1012 Diag(Loc, diag::err_bad_memptr_lhs)
1013 << OpSpelling << 1 << LType << lex->getSourceRange();
1014 return QualType();
1015 }
1016 }
1017
1018 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1019 Context.getCanonicalType(LType).getUnqualifiedType()) {
1020 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1021 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001022 // FIXME: Would it be useful to print full ambiguity paths, or is that
1023 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001024 if (!IsDerivedFrom(LType, Class, Paths) ||
1025 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1026 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1027 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1028 return QualType();
1029 }
1030 }
1031
1032 // C++ 5.5p2
1033 // The result is an object or a function of the type specified by the
1034 // second operand.
1035 // The cv qualifiers are the union of those in the pointer and the left side,
1036 // in accordance with 5.5p5 and 5.2.5.
1037 // FIXME: This returns a dereferenced member function pointer as a normal
1038 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001039 // calling them. There's also a GCC extension to get a function pointer to the
1040 // thing, which is another complication, because this type - unlike the type
1041 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001042 // argument.
1043 // We probably need a "MemberFunctionClosureType" or something like that.
1044 QualType Result = MemPtr->getPointeeType();
1045 if (LType.isConstQualified())
1046 Result.addConst();
1047 if (LType.isVolatileQualified())
1048 Result.addVolatile();
1049 return Result;
1050}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001051
1052/// \brief Get the target type of a standard or user-defined conversion.
1053static QualType TargetType(const ImplicitConversionSequence &ICS) {
1054 assert((ICS.ConversionKind ==
1055 ImplicitConversionSequence::StandardConversion ||
1056 ICS.ConversionKind ==
1057 ImplicitConversionSequence::UserDefinedConversion) &&
1058 "function only valid for standard or user-defined conversions");
1059 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1060 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1061 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1062}
1063
1064/// \brief Try to convert a type to another according to C++0x 5.16p3.
1065///
1066/// This is part of the parameter validation for the ? operator. If either
1067/// value operand is a class type, the two operands are attempted to be
1068/// converted to each other. This function does the conversion in one direction.
1069/// It emits a diagnostic and returns true only if it finds an ambiguous
1070/// conversion.
1071static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1072 SourceLocation QuestionLoc,
1073 ImplicitConversionSequence &ICS)
1074{
1075 // C++0x 5.16p3
1076 // The process for determining whether an operand expression E1 of type T1
1077 // can be converted to match an operand expression E2 of type T2 is defined
1078 // as follows:
1079 // -- If E2 is an lvalue:
1080 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1081 // E1 can be converted to match E2 if E1 can be implicitly converted to
1082 // type "lvalue reference to T2", subject to the constraint that in the
1083 // conversion the reference must bind directly to E1.
1084 if (!Self.CheckReferenceInit(From,
1085 Self.Context.getLValueReferenceType(To->getType()),
1086 &ICS))
1087 {
1088 assert((ICS.ConversionKind ==
1089 ImplicitConversionSequence::StandardConversion ||
1090 ICS.ConversionKind ==
1091 ImplicitConversionSequence::UserDefinedConversion) &&
1092 "expected a definite conversion");
1093 bool DirectBinding =
1094 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1095 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1096 if (DirectBinding)
1097 return false;
1098 }
1099 }
1100 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1101 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1102 // -- if E1 and E2 have class type, and the underlying class types are
1103 // the same or one is a base class of the other:
1104 QualType FTy = From->getType();
1105 QualType TTy = To->getType();
1106 const RecordType *FRec = FTy->getAsRecordType();
1107 const RecordType *TRec = TTy->getAsRecordType();
1108 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1109 if (FRec && TRec && (FRec == TRec ||
1110 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1111 // E1 can be converted to match E2 if the class of T2 is the
1112 // same type as, or a base class of, the class of T1, and
1113 // [cv2 > cv1].
1114 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1115 // Could still fail if there's no copy constructor.
1116 // FIXME: Is this a hard error then, or just a conversion failure? The
1117 // standard doesn't say.
1118 ICS = Self.TryCopyInitialization(From, TTy);
1119 }
1120 } else {
1121 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1122 // implicitly converted to the type that expression E2 would have
1123 // if E2 were converted to an rvalue.
1124 // First find the decayed type.
1125 if (TTy->isFunctionType())
1126 TTy = Self.Context.getPointerType(TTy);
1127 else if(TTy->isArrayType())
1128 TTy = Self.Context.getArrayDecayedType(TTy);
1129
1130 // Now try the implicit conversion.
1131 // FIXME: This doesn't detect ambiguities.
1132 ICS = Self.TryImplicitConversion(From, TTy);
1133 }
1134 return false;
1135}
1136
1137/// \brief Try to find a common type for two according to C++0x 5.16p5.
1138///
1139/// This is part of the parameter validation for the ? operator. If either
1140/// value operand is a class type, overload resolution is used to find a
1141/// conversion to a common type.
1142static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1143 SourceLocation Loc) {
1144 Expr *Args[2] = { LHS, RHS };
1145 OverloadCandidateSet CandidateSet;
1146 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1147
1148 OverloadCandidateSet::iterator Best;
1149 switch (Self.BestViableFunction(CandidateSet, Best)) {
1150 case Sema::OR_Success:
1151 // We found a match. Perform the conversions on the arguments and move on.
1152 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1153 Best->Conversions[0], "converting") ||
1154 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1155 Best->Conversions[1], "converting"))
1156 break;
1157 return false;
1158
1159 case Sema::OR_No_Viable_Function:
1160 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1161 << LHS->getType() << RHS->getType()
1162 << LHS->getSourceRange() << RHS->getSourceRange();
1163 return true;
1164
1165 case Sema::OR_Ambiguous:
1166 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1167 << LHS->getType() << RHS->getType()
1168 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001169 // FIXME: Print the possible common types by printing the return types of
1170 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001171 break;
1172
1173 case Sema::OR_Deleted:
1174 assert(false && "Conditional operator has only built-in overloads");
1175 break;
1176 }
1177 return true;
1178}
1179
Sebastian Redl76458502009-04-17 16:30:52 +00001180/// \brief Perform an "extended" implicit conversion as returned by
1181/// TryClassUnification.
1182///
1183/// TryClassUnification generates ICSs that include reference bindings.
1184/// PerformImplicitConversion is not suitable for this; it chokes if the
1185/// second part of a standard conversion is ICK_DerivedToBase. This function
1186/// handles the reference binding specially.
1187static bool ConvertForConditional(Sema &Self, Expr *&E,
1188 const ImplicitConversionSequence &ICS)
1189{
1190 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1191 ICS.Standard.ReferenceBinding) {
1192 assert(ICS.Standard.DirectBinding &&
1193 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001194 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1195 // redoing all the work.
1196 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1197 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001198 }
1199 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1200 ICS.UserDefined.After.ReferenceBinding) {
1201 assert(ICS.UserDefined.After.DirectBinding &&
1202 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001203 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1204 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001205 }
1206 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1207 return true;
1208 return false;
1209}
1210
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001211/// \brief Check the operands of ?: under C++ semantics.
1212///
1213/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1214/// extension. In this case, LHS == Cond. (But they're not aliases.)
1215QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1216 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001217 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1218 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001219
1220 // C++0x 5.16p1
1221 // The first expression is contextually converted to bool.
1222 if (!Cond->isTypeDependent()) {
1223 if (CheckCXXBooleanCondition(Cond))
1224 return QualType();
1225 }
1226
1227 // Either of the arguments dependent?
1228 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1229 return Context.DependentTy;
1230
1231 // C++0x 5.16p2
1232 // If either the second or the third operand has type (cv) void, ...
1233 QualType LTy = LHS->getType();
1234 QualType RTy = RHS->getType();
1235 bool LVoid = LTy->isVoidType();
1236 bool RVoid = RTy->isVoidType();
1237 if (LVoid || RVoid) {
1238 // ... then the [l2r] conversions are performed on the second and third
1239 // operands ...
1240 DefaultFunctionArrayConversion(LHS);
1241 DefaultFunctionArrayConversion(RHS);
1242 LTy = LHS->getType();
1243 RTy = RHS->getType();
1244
1245 // ... and one of the following shall hold:
1246 // -- The second or the third operand (but not both) is a throw-
1247 // expression; the result is of the type of the other and is an rvalue.
1248 bool LThrow = isa<CXXThrowExpr>(LHS);
1249 bool RThrow = isa<CXXThrowExpr>(RHS);
1250 if (LThrow && !RThrow)
1251 return RTy;
1252 if (RThrow && !LThrow)
1253 return LTy;
1254
1255 // -- Both the second and third operands have type void; the result is of
1256 // type void and is an rvalue.
1257 if (LVoid && RVoid)
1258 return Context.VoidTy;
1259
1260 // Neither holds, error.
1261 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1262 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1263 << LHS->getSourceRange() << RHS->getSourceRange();
1264 return QualType();
1265 }
1266
1267 // Neither is void.
1268
1269 // C++0x 5.16p3
1270 // Otherwise, if the second and third operand have different types, and
1271 // either has (cv) class type, and attempt is made to convert each of those
1272 // operands to the other.
1273 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1274 (LTy->isRecordType() || RTy->isRecordType())) {
1275 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1276 // These return true if a single direction is already ambiguous.
1277 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1278 return QualType();
1279 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1280 return QualType();
1281
1282 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1283 ImplicitConversionSequence::BadConversion;
1284 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1285 ImplicitConversionSequence::BadConversion;
1286 // If both can be converted, [...] the program is ill-formed.
1287 if (HaveL2R && HaveR2L) {
1288 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1289 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1290 return QualType();
1291 }
1292
1293 // If exactly one conversion is possible, that conversion is applied to
1294 // the chosen operand and the converted operands are used in place of the
1295 // original operands for the remainder of this section.
1296 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001297 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001298 return QualType();
1299 LTy = LHS->getType();
1300 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001301 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001302 return QualType();
1303 RTy = RHS->getType();
1304 }
1305 }
1306
1307 // C++0x 5.16p4
1308 // If the second and third operands are lvalues and have the same type,
1309 // the result is of that type [...]
1310 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1311 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1312 RHS->isLvalue(Context) == Expr::LV_Valid)
1313 return LTy;
1314
1315 // C++0x 5.16p5
1316 // Otherwise, the result is an rvalue. If the second and third operands
1317 // do not have the same type, and either has (cv) class type, ...
1318 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1319 // ... overload resolution is used to determine the conversions (if any)
1320 // to be applied to the operands. If the overload resolution fails, the
1321 // program is ill-formed.
1322 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1323 return QualType();
1324 }
1325
1326 // C++0x 5.16p6
1327 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1328 // conversions are performed on the second and third operands.
1329 DefaultFunctionArrayConversion(LHS);
1330 DefaultFunctionArrayConversion(RHS);
1331 LTy = LHS->getType();
1332 RTy = RHS->getType();
1333
1334 // After those conversions, one of the following shall hold:
1335 // -- The second and third operands have the same type; the result
1336 // is of that type.
1337 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1338 return LTy;
1339
1340 // -- The second and third operands have arithmetic or enumeration type;
1341 // the usual arithmetic conversions are performed to bring them to a
1342 // common type, and the result is of that type.
1343 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1344 UsualArithmeticConversions(LHS, RHS);
1345 return LHS->getType();
1346 }
1347
1348 // -- The second and third operands have pointer type, or one has pointer
1349 // type and the other is a null pointer constant; pointer conversions
1350 // and qualification conversions are performed to bring them to their
1351 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001352 QualType Composite = FindCompositePointerType(LHS, RHS);
1353 if (!Composite.isNull())
1354 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001355
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001356 // Fourth bullet is same for pointers-to-member. However, the possible
1357 // conversions are far more limited: we have null-to-pointer, upcast of
1358 // containing class, and second-level cv-ness.
1359 // cv-ness is not a union, but must match one of the two operands. (Which,
1360 // frankly, is stupid.)
1361 const MemberPointerType *LMemPtr = LTy->getAsMemberPointerType();
1362 const MemberPointerType *RMemPtr = RTy->getAsMemberPointerType();
1363 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1364 ImpCastExprToType(RHS, LTy);
1365 return LTy;
1366 }
1367 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1368 ImpCastExprToType(LHS, RTy);
1369 return RTy;
1370 }
1371 if (LMemPtr && RMemPtr) {
1372 QualType LPointee = LMemPtr->getPointeeType();
1373 QualType RPointee = RMemPtr->getPointeeType();
1374 // First, we check that the unqualified pointee type is the same. If it's
1375 // not, there's no conversion that will unify the two pointers.
1376 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1377 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1378 // Second, we take the greater of the two cv qualifications. If neither
1379 // is greater than the other, the conversion is not possible.
1380 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1381 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1382 // Third, we check if either of the container classes is derived from
1383 // the other.
1384 QualType LContainer(LMemPtr->getClass(), 0);
1385 QualType RContainer(RMemPtr->getClass(), 0);
1386 QualType MoreDerived;
1387 if (Context.getCanonicalType(LContainer) ==
1388 Context.getCanonicalType(RContainer))
1389 MoreDerived = LContainer;
1390 else if (IsDerivedFrom(LContainer, RContainer))
1391 MoreDerived = LContainer;
1392 else if (IsDerivedFrom(RContainer, LContainer))
1393 MoreDerived = RContainer;
1394
1395 if (!MoreDerived.isNull()) {
1396 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1397 // We don't use ImpCastExprToType here because this could still fail
1398 // for ambiguous or inaccessible conversions.
1399 QualType Common = Context.getMemberPointerType(
1400 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1401 if (PerformImplicitConversion(LHS, Common, "converting"))
1402 return QualType();
1403 if (PerformImplicitConversion(RHS, Common, "converting"))
1404 return QualType();
1405 return Common;
1406 }
1407 }
1408 }
1409 }
1410
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001411 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1412 << LHS->getType() << RHS->getType()
1413 << LHS->getSourceRange() << RHS->getSourceRange();
1414 return QualType();
1415}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001416
1417/// \brief Find a merged pointer type and convert the two expressions to it.
1418///
1419/// This finds the composite pointer type for @p E1 and @p E2 according to
1420/// C++0x 5.9p2. It converts both expressions to this type and returns it.
1421/// It does not emit diagnostics.
1422QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1423 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1424 QualType T1 = E1->getType(), T2 = E2->getType();
1425 if(!T1->isPointerType() && !T2->isPointerType())
1426 return QualType();
1427
1428 // C++0x 5.9p2
1429 // Pointer conversions and qualification conversions are performed on
1430 // pointer operands to bring them to their composite pointer type. If
1431 // one operand is a null pointer constant, the composite pointer type is
1432 // the type of the other operand.
1433 if (E1->isNullPointerConstant(Context)) {
1434 ImpCastExprToType(E1, T2);
1435 return T2;
1436 }
1437 if (E2->isNullPointerConstant(Context)) {
1438 ImpCastExprToType(E2, T1);
1439 return T1;
1440 }
1441 // Now both have to be pointers.
1442 if(!T1->isPointerType() || !T2->isPointerType())
1443 return QualType();
1444
1445 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1446 // the other has type "pointer to cv2 T" and the composite pointer type is
1447 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1448 // Otherwise, the composite pointer type is a pointer type similar to the
1449 // type of one of the operands, with a cv-qualification signature that is
1450 // the union of the cv-qualification signatures of the operand types.
1451 // In practice, the first part here is redundant; it's subsumed by the second.
1452 // What we do here is, we build the two possible composite types, and try the
1453 // conversions in both directions. If only one works, or if the two composite
1454 // types are the same, we have succeeded.
1455 llvm::SmallVector<unsigned, 4> QualifierUnion;
1456 QualType Composite1 = T1, Composite2 = T2;
1457 const PointerType *Ptr1, *Ptr2;
1458 while ((Ptr1 = Composite1->getAsPointerType()) &&
1459 (Ptr2 = Composite2->getAsPointerType())) {
1460 Composite1 = Ptr1->getPointeeType();
1461 Composite2 = Ptr2->getPointeeType();
1462 QualifierUnion.push_back(
1463 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1464 }
1465 // Rewrap the composites as pointers with the union CVRs.
1466 for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(),
1467 E = QualifierUnion.end(); I != E; ++I) {
1468 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1469 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1470 }
1471
1472 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1473 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1474 ImplicitConversionSequence E1ToC2, E2ToC2;
1475 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1476 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1477 if (Context.getCanonicalType(Composite1) !=
1478 Context.getCanonicalType(Composite2)) {
1479 E1ToC2 = TryImplicitConversion(E1, Composite2);
1480 E2ToC2 = TryImplicitConversion(E2, Composite2);
1481 }
1482
1483 bool ToC1Viable = E1ToC1.ConversionKind !=
1484 ImplicitConversionSequence::BadConversion
1485 && E2ToC1.ConversionKind !=
1486 ImplicitConversionSequence::BadConversion;
1487 bool ToC2Viable = E1ToC2.ConversionKind !=
1488 ImplicitConversionSequence::BadConversion
1489 && E2ToC2.ConversionKind !=
1490 ImplicitConversionSequence::BadConversion;
1491 if (ToC1Viable && !ToC2Viable) {
1492 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1493 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1494 return Composite1;
1495 }
1496 if (ToC2Viable && !ToC1Viable) {
1497 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1498 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1499 return Composite2;
1500 }
1501 return QualType();
1502}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001503
1504Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1505 Expr *FullExpr = Arg.takeAs<Expr>();
1506 assert(FullExpr && "Null full expr!");
1507
1508 if (!ExprTemporaries.empty()) {
1509 // Create a cleanup expr.
1510 FullExpr =
1511 new (Context) CXXExprWithTemporaries(FullExpr, &ExprTemporaries[0],
1512 ExprTemporaries.size());
1513 ExprTemporaries.clear();
1514 }
1515
1516 return Owned(FullExpr);
1517}