blob: b3d94c372dc77ff9b3e41b06b3354fadd25c5010 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
Sebastian Redl7c8bd602009-02-07 20:10:22 +000014#include "SemaInherit.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "Sema.h"
16#include "clang/AST/ExprCXX.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +000018#include "clang/Parse/DeclSpec.h"
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +000019#include "clang/Lex/Preprocessor.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000020#include "clang/Basic/TargetInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000021#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23
Douglas Gregor487a75a2008-11-19 19:09:45 +000024/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregor2def4832008-11-17 20:34:05 +000025/// name (e.g., operator void const *) as an expression. This is
26/// very similar to ActOnIdentifierExpr, except that instead of
27/// providing an identifier the parser provides the type of the
28/// conversion function.
Sebastian Redlcd965b92009-01-18 18:53:16 +000029Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000030Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
31 TypeTy *Ty, bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000032 const CXXScopeSpec &SS,
33 bool isAddressOfOperand) {
Douglas Gregor2def4832008-11-17 20:34:05 +000034 QualType ConvType = QualType::getFromOpaquePtr(Ty);
35 QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
36 DeclarationName ConvName
37 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd965b92009-01-18 18:53:16 +000038 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +000039 &SS, isAddressOfOperand);
Douglas Gregor2def4832008-11-17 20:34:05 +000040}
Sebastian Redlc42e1182008-11-11 11:37:55 +000041
Douglas Gregor487a75a2008-11-19 19:09:45 +000042/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-11-18 14:39:36 +000043/// name (e.g., @c operator+ ) as an expression. This is very
44/// similar to ActOnIdentifierExpr, except that instead of providing
45/// an identifier the parser provides the kind of overloaded
46/// operator that was parsed.
Sebastian Redlcd965b92009-01-18 18:53:16 +000047Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000048Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
49 OverloadedOperatorKind Op,
50 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000051 const CXXScopeSpec &SS,
52 bool isAddressOfOperand) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000053 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redlebc07d52009-02-03 20:19:35 +000054 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor17330012009-02-04 15:01:18 +000055 isAddressOfOperand);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000056}
57
Sebastian Redlc42e1182008-11-11 11:37:55 +000058/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000059Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000060Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
61 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +000062 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000063 if (!StdNs)
Sebastian Redlf53597f2009-03-15 17:47:39 +000064 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Chris Lattner572af492008-11-20 05:51:55 +000065
66 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor4c921ae2009-01-30 01:04:22 +000067 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlc42e1182008-11-11 11:37:55 +000068 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000069 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000070 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000071
72 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
73
Sebastian Redlf53597f2009-03-15 17:47:39 +000074 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
75 TypeInfoType.withConst(),
76 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +000077}
78
Steve Naroff1b273c42007-09-16 14:56:35 +000079/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +000080Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000081Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000082 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000083 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +000084 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
85 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000086}
Chris Lattner50dd2892008-02-26 00:51:44 +000087
88/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +000089Action::OwningExprResult
90Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
91 return Owned(new (Context) CXXThrowExpr((Expr*)E.release(), Context.VoidTy,
92 OpLoc));
Chris Lattner50dd2892008-02-26 00:51:44 +000093}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000094
Sebastian Redlf53597f2009-03-15 17:47:39 +000095Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000096 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
97 /// is a non-lvalue expression whose value is the address of the object for
98 /// which the function is called.
99
Sebastian Redlf53597f2009-03-15 17:47:39 +0000100 if (!isa<FunctionDecl>(CurContext))
101 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000102
103 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
104 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000105 return Owned(new (Context) CXXThisExpr(ThisLoc,
106 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000107
Sebastian Redlf53597f2009-03-15 17:47:39 +0000108 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000109}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000110
111/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
112/// Can be interpreted either as function-style casting ("int(x)")
113/// or class type construction ("ClassType(x,y,z)")
114/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000115Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000116Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
117 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000118 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000119 SourceLocation *CommaLocs,
120 SourceLocation RParenLoc) {
121 assert(TypeRep && "Missing type!");
122 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000123 unsigned NumExprs = exprs.size();
124 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000125 SourceLocation TyBeginLoc = TypeRange.getBegin();
126 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
127
Sebastian Redlf53597f2009-03-15 17:47:39 +0000128 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000129 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000130 exprs.release();
131 return Owned(new (Context) CXXTemporaryObjectExpr(0, Ty, TyBeginLoc,
132 Exprs, NumExprs,
133 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000134 }
135
136
Douglas Gregor506ae412009-01-16 18:33:17 +0000137 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000138 // If the expression list is a single expression, the type conversion
139 // expression is equivalent (in definedness, and if defined in meaning) to the
140 // corresponding cast expression.
141 //
142 if (NumExprs == 1) {
143 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000144 return ExprError();
145 exprs.release();
146 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
147 Ty, TyBeginLoc, Exprs[0],
148 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000149 }
150
Douglas Gregor506ae412009-01-16 18:33:17 +0000151 if (const RecordType *RT = Ty->getAsRecordType()) {
152 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000153
Douglas Gregor506ae412009-01-16 18:33:17 +0000154 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
155 CXXConstructorDecl *Constructor
156 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
157 TypeRange.getBegin(),
158 SourceRange(TypeRange.getBegin(),
159 RParenLoc),
160 DeclarationName(),
161 IK_Direct);
Douglas Gregor506ae412009-01-16 18:33:17 +0000162
Sebastian Redlf53597f2009-03-15 17:47:39 +0000163 if (!Constructor)
164 return ExprError();
165
166 exprs.release();
167 return Owned(new (Context) CXXTemporaryObjectExpr(Constructor, Ty,
168 TyBeginLoc, Exprs,
169 NumExprs, RParenLoc));
Douglas Gregor506ae412009-01-16 18:33:17 +0000170 }
171
172 // Fall through to value-initialize an object of class type that
173 // doesn't have a user-declared default constructor.
174 }
175
176 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000177 // If the expression list specifies more than a single value, the type shall
178 // be a class with a suitably declared constructor.
179 //
180 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000181 return ExprError(Diag(CommaLocs[0],
182 diag::err_builtin_func_cast_more_than_one_arg)
183 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000184
185 assert(NumExprs == 0 && "Expected 0 expressions");
186
Douglas Gregor506ae412009-01-16 18:33:17 +0000187 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000188 // The expression T(), where T is a simple-type-specifier for a non-array
189 // complete object type or the (possibly cv-qualified) void type, creates an
190 // rvalue of the specified type, which is value-initialized.
191 //
192 if (Ty->isArrayType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000193 return ExprError(Diag(TyBeginLoc,
194 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000195 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redlf53597f2009-03-15 17:47:39 +0000196 RequireCompleteType(TyBeginLoc, Ty,
197 diag::err_invalid_incomplete_type_use, FullRange))
198 return ExprError();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000199
Sebastian Redlf53597f2009-03-15 17:47:39 +0000200 exprs.release();
201 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000202}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000203
204
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000205/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
206/// @code new (memory) int[size][4] @endcode
207/// or
208/// @code ::new Foo(23, "hello") @endcode
209/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000210Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000211Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000212 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000213 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000214 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000215 MultiExprArg ConstructorArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000216 SourceLocation ConstructorRParen)
217{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000218 Expr *ArraySize = 0;
219 unsigned Skip = 0;
220 // If the specified type is an array, unwrap it and save the expression.
221 if (D.getNumTypeObjects() > 0 &&
222 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
223 DeclaratorChunk &Chunk = D.getTypeObject(0);
224 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000225 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
226 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000227 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000228 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
229 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000230 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
231 Skip = 1;
232 }
233
234 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
235 if (D.getInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000236 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000237
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000238 if (CheckAllocatedType(AllocType, D))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000239 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000240
Sebastian Redl28507842009-02-26 14:39:58 +0000241 QualType ResultType = AllocType->isDependentType()
242 ? Context.DependentTy
243 : Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000244
245 // That every array dimension except the first is constant was already
246 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000247
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000248 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
249 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000250 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000251 QualType SizeType = ArraySize->getType();
252 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000253 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
254 diag::err_array_size_not_integral)
255 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000256 // Let's see if this is a constant < 0. If so, we reject it out of hand.
257 // We don't care about special rules, so we tell the machinery it's not
258 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000259 if (!ArraySize->isValueDependent()) {
260 llvm::APSInt Value;
261 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
262 if (Value < llvm::APSInt(
263 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000264 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
265 diag::err_typecheck_negative_array_size)
266 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000267 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000268 }
269 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000270
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000271 FunctionDecl *OperatorNew = 0;
272 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000273 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
274 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000275 if (!AllocType->isDependentType() &&
276 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
277 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000278 SourceRange(PlacementLParen, PlacementRParen),
279 UseGlobal, AllocType, ArraySize, PlaceArgs,
280 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000281 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000282
283 bool Init = ConstructorLParen.isValid();
284 // --- Choosing a constructor ---
285 // C++ 5.3.4p15
286 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
287 // the object is not initialized. If the object, or any part of it, is
288 // const-qualified, it's an error.
289 // 2) If T is a POD and there's an empty initializer, the object is value-
290 // initialized.
291 // 3) If T is a POD and there's one initializer argument, the object is copy-
292 // constructed.
293 // 4) If T is a POD and there's more initializer arguments, it's an error.
294 // 5) If T is not a POD, the initializer arguments are used as constructor
295 // arguments.
296 //
297 // Or by the C++0x formulation:
298 // 1) If there's no initializer, the object is default-initialized according
299 // to C++0x rules.
300 // 2) Otherwise, the object is direct-initialized.
301 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000302 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
303 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000304 if (AllocType->isDependentType()) {
305 // Skip all the checks.
306 }
Sebastian Redl00e68e22009-02-09 18:24:27 +0000307 // FIXME: Should check for primitive/aggregate here, not record.
Sebastian Redl28507842009-02-26 14:39:58 +0000308 else if (const RecordType *RT = AllocType->getAsRecordType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000309 // FIXME: This is incorrect for when there is an empty initializer and
310 // no user-defined constructor. Must zero-initialize, not default-construct.
311 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000312 AllocType, ConsArgs, NumConsArgs,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000313 D.getSourceRange().getBegin(),
314 SourceRange(D.getSourceRange().getBegin(),
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000315 ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000316 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000317 NumConsArgs != 0 ? IK_Direct : IK_Default);
318 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000319 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000320 } else {
321 if (!Init) {
322 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000323 if (AllocType.isConstQualified())
324 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
325 << D.getSourceRange());
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000326 } else if (NumConsArgs == 0) {
327 // Object is value-initialized. Do nothing.
328 } else if (NumConsArgs == 1) {
329 // Object is direct-initialized.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000330 // FIXME: WHAT DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000331 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000332 DeclarationName() /*AllocType.getAsString()*/,
333 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000334 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000335 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000336 return ExprError(Diag(StartLoc,
337 diag::err_builtin_direct_init_more_than_one_arg)
338 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000339 }
340 }
341
342 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
343
Sebastian Redlf53597f2009-03-15 17:47:39 +0000344 PlacementArgs.release();
345 ConstructorArgs.release();
346 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000347 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000348 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000349 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000350}
351
352/// CheckAllocatedType - Checks that a type is suitable as the allocated type
353/// in a new-expression.
354/// dimension off and stores the size expression in ArraySize.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000355bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000356{
357 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
358 // abstract class type or array thereof.
359 // FIXME: We don't have abstract types yet.
360 // FIXME: Under C++ semantics, an incomplete object type is still an object
361 // type. This code assumes the C semantics, where it's not.
362 if (!AllocType->isObjectType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000363 unsigned type; // For the select in the message.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000364 if (AllocType->isFunctionType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000365 type = 0;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000366 } else if(AllocType->isIncompleteType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000367 type = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000368 } else {
Sebastian Redl00e68e22009-02-09 18:24:27 +0000369 assert(AllocType->isReferenceType() && "Unhandled non-object type.");
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000370 type = 2;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000371 }
Sebastian Redl00e68e22009-02-09 18:24:27 +0000372 Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
373 << AllocType << type << D.getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000374 return true;
375 }
376
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000377 // Every dimension shall be of constant size.
378 unsigned i = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000379 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
380 if (!Array->isConstantArrayType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000381 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
382 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000383 return true;
384 }
385 AllocType = Array->getElementType();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000386 ++i;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000387 }
388
389 return false;
390}
391
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000392/// FindAllocationFunctions - Finds the overloads of operator new and delete
393/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000394bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
395 bool UseGlobal, QualType AllocType,
396 bool IsArray, Expr **PlaceArgs,
397 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000398 FunctionDecl *&OperatorNew,
399 FunctionDecl *&OperatorDelete)
400{
401 // --- Choosing an allocation function ---
402 // C++ 5.3.4p8 - 14 & 18
403 // 1) If UseGlobal is true, only look in the global scope. Else, also look
404 // in the scope of the allocated class.
405 // 2) If an array size is given, look for operator new[], else look for
406 // operator new.
407 // 3) The first argument is always size_t. Append the arguments from the
408 // placement form.
409 // FIXME: Also find the appropriate delete operator.
410
411 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
412 // We don't care about the actual value of this argument.
413 // FIXME: Should the Sema create the expression and embed it in the syntax
414 // tree? Or should the consumer just recalculate the value?
Ted Kremenek8189cde2009-02-07 01:47:29 +0000415 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000416 Context.Target.getPointerWidth(0)),
417 Context.getSizeType(),
418 SourceLocation());
419 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
420
421 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
422 IsArray ? OO_Array_New : OO_New);
423 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000424 CXXRecordDecl *Record
425 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000426 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000427 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000428 AllocArgs.size(), Record, /*AllowMissing=*/true,
429 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000430 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000431 }
432 if (!OperatorNew) {
433 // Didn't find a member overload. Look for a global one.
434 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000435 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000436 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000437 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
438 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000439 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000440 }
441
Sebastian Redl7f662392008-12-04 22:20:51 +0000442 // FIXME: This is leaked on error. But so much is currently in Sema that it's
443 // easier to clean it in one go.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000444 AllocArgs[0]->Destroy(Context);
445 return false;
446}
447
Sebastian Redl7f662392008-12-04 22:20:51 +0000448/// FindAllocationOverload - Find an fitting overload for the allocation
449/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000450bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
451 DeclarationName Name, Expr** Args,
452 unsigned NumArgs, DeclContext *Ctx,
453 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redl7f662392008-12-04 22:20:51 +0000454{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000455 DeclContext::lookup_iterator Alloc, AllocEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000456 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000457 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000458 if (AllowMissing)
459 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000460 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000461 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000462 }
463
464 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000465 for (; Alloc != AllocEnd; ++Alloc) {
466 // Even member operator new/delete are implicitly treated as
467 // static, so don't use AddMemberCandidate.
468 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
469 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
470 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000471 }
472
473 // Do the resolution.
474 OverloadCandidateSet::iterator Best;
475 switch(BestViableFunction(Candidates, Best)) {
476 case OR_Success: {
477 // Got one!
478 FunctionDecl *FnDecl = Best->Function;
479 // The first argument is size_t, and the first parameter must be size_t,
480 // too. This is checked on declaration and can be assumed. (It can't be
481 // asserted on, though, since invalid decls are left in there.)
482 for (unsigned i = 1; i < NumArgs; ++i) {
483 // FIXME: Passing word to diagnostic.
484 if (PerformCopyInitialization(Args[i-1],
485 FnDecl->getParamDecl(i)->getType(),
486 "passing"))
487 return true;
488 }
489 Operator = FnDecl;
490 return false;
491 }
492
493 case OR_No_Viable_Function:
494 if (AllowMissing)
495 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000496 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000497 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000498 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
499 return true;
500
501 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000502 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000503 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000504 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
505 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000506
507 case OR_Deleted:
508 Diag(StartLoc, diag::err_ovl_deleted_call)
509 << Best->Function->isDeleted()
510 << Name << Range;
511 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
512 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000513 }
514 assert(false && "Unreachable, bad result from BestViableFunction");
515 return true;
516}
517
518
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000519/// DeclareGlobalNewDelete - Declare the global forms of operator new and
520/// delete. These are:
521/// @code
522/// void* operator new(std::size_t) throw(std::bad_alloc);
523/// void* operator new[](std::size_t) throw(std::bad_alloc);
524/// void operator delete(void *) throw();
525/// void operator delete[](void *) throw();
526/// @endcode
527/// Note that the placement and nothrow forms of new are *not* implicitly
528/// declared. Their use requires including \<new\>.
529void Sema::DeclareGlobalNewDelete()
530{
531 if (GlobalNewDeleteDeclared)
532 return;
533 GlobalNewDeleteDeclared = true;
534
535 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
536 QualType SizeT = Context.getSizeType();
537
538 // FIXME: Exception specifications are not added.
539 DeclareGlobalAllocationFunction(
540 Context.DeclarationNames.getCXXOperatorName(OO_New),
541 VoidPtr, SizeT);
542 DeclareGlobalAllocationFunction(
543 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
544 VoidPtr, SizeT);
545 DeclareGlobalAllocationFunction(
546 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
547 Context.VoidTy, VoidPtr);
548 DeclareGlobalAllocationFunction(
549 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
550 Context.VoidTy, VoidPtr);
551}
552
553/// DeclareGlobalAllocationFunction - Declares a single implicit global
554/// allocation function if it doesn't already exist.
555void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
556 QualType Return, QualType Argument)
557{
558 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
559
560 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000561 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000562 DeclContext::lookup_iterator Alloc, AllocEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000563 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000564 Alloc != AllocEnd; ++Alloc) {
565 // FIXME: Do we need to check for default arguments here?
566 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
567 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000568 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000569 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000570 }
571 }
572
573 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
574 FunctionDecl *Alloc =
575 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor2224f842009-02-25 16:33:18 +0000576 FnType, FunctionDecl::None, false, true,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000577 SourceLocation());
578 Alloc->setImplicit();
579 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000580 0, Argument, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000581 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000582
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000583 // FIXME: Also add this declaration to the IdentifierResolver, but
584 // make sure it is at the end of the chain to coincide with the
585 // global scope.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000586 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000587}
588
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000589/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
590/// @code ::delete ptr; @endcode
591/// or
592/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000593Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000594Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000595 bool ArrayForm, ExprArg Operand)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000596{
597 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
598 // having a single conversion function to a pointer type. The result has
599 // type void."
600 // DR599 amends "pointer type" to "pointer to object type" in both cases.
601
Sebastian Redlf53597f2009-03-15 17:47:39 +0000602 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000603 if (!Ex->isTypeDependent()) {
604 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000605
Sebastian Redl28507842009-02-26 14:39:58 +0000606 if (Type->isRecordType()) {
607 // FIXME: Find that one conversion function and amend the type.
608 }
609
Sebastian Redlf53597f2009-03-15 17:47:39 +0000610 if (!Type->isPointerType())
611 return ExprError(Diag(StartLoc, diag::err_delete_operand)
612 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000613
614 QualType Pointee = Type->getAsPointerType()->getPointeeType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000615 if (!Pointee->isVoidType() &&
Douglas Gregor86447ec2009-03-09 16:13:40 +0000616 RequireCompleteType(StartLoc, Pointee, diag::warn_delete_incomplete,
Sebastian Redl28507842009-02-26 14:39:58 +0000617 Ex->getSourceRange()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000618 return ExprError();
619 else if (!Pointee->isObjectType())
620 return ExprError(Diag(StartLoc, diag::err_delete_operand)
621 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000622
623 // FIXME: Look up the correct operator delete overload and pass a pointer
624 // along.
625 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000626 }
627
Sebastian Redlf53597f2009-03-15 17:47:39 +0000628 Operand.release();
629 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
630 0, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000631}
632
633
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000634/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
635/// C++ if/switch/while/for statement.
636/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000637Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000638Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
639 Declarator &D,
640 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000641 ExprArg AssignExprVal) {
642 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000643
644 // C++ 6.4p2:
645 // The declarator shall not specify a function or an array.
646 // The type-specifier-seq shall not contain typedef and shall not declare a
647 // new class or enumeration.
648
649 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
650 "Parser allowed 'typedef' as storage class of condition decl.");
651
652 QualType Ty = GetTypeForDeclarator(D, S);
653
654 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
655 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
656 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000657 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
658 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000659 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000660 Diag(StartLoc, diag::err_invalid_use_of_array_type)
661 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000662 } else if (const RecordType *RT = Ty->getAsRecordType()) {
663 RecordDecl *RD = RT->getDecl();
664 // The type-specifier-seq shall not declare a new class...
665 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
666 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
667 } else if (const EnumType *ET = Ty->getAsEnumType()) {
668 EnumDecl *ED = ET->getDecl();
669 // ...or enumeration.
670 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
671 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
672 }
673
674 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
675 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000676 return ExprError();
677 AddInitializerToDecl(Dcl, move(AssignExprVal));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000678
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000679 // Mark this variable as one that is declared within a conditional.
680 if (VarDecl *VD = dyn_cast<VarDecl>((Decl *)Dcl))
681 VD->setDeclaredInCondition(true);
682
Sebastian Redlf53597f2009-03-15 17:47:39 +0000683 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc,
684 cast<VarDecl>(static_cast<Decl *>(Dcl))));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000685}
686
687/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
688bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
689 // C++ 6.4p4:
690 // The value of a condition that is an initialized declaration in a statement
691 // other than a switch statement is the value of the declared variable
692 // implicitly converted to type bool. If that conversion is ill-formed, the
693 // program is ill-formed.
694 // The value of a condition that is an expression is the value of the
695 // expression, implicitly converted to bool.
696 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000697 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000698}
Douglas Gregor77a52232008-09-12 00:47:35 +0000699
700/// Helper function to determine whether this is the (deprecated) C++
701/// conversion from a string literal to a pointer to non-const char or
702/// non-const wchar_t (for narrow and wide string literals,
703/// respectively).
704bool
705Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
706 // Look inside the implicit cast, if it exists.
707 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
708 From = Cast->getSubExpr();
709
710 // A string literal (2.13.4) that is not a wide string literal can
711 // be converted to an rvalue of type "pointer to char"; a wide
712 // string literal can be converted to an rvalue of type "pointer
713 // to wchar_t" (C++ 4.2p2).
714 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
715 if (const PointerType *ToPtrType = ToType->getAsPointerType())
716 if (const BuiltinType *ToPointeeType
717 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
718 // This conversion is considered only when there is an
719 // explicit appropriate pointer target type (C++ 4.2p2).
720 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
721 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
722 (!StrLit->isWide() &&
723 (ToPointeeType->getKind() == BuiltinType::Char_U ||
724 ToPointeeType->getKind() == BuiltinType::Char_S))))
725 return true;
726 }
727
728 return false;
729}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000730
731/// PerformImplicitConversion - Perform an implicit conversion of the
732/// expression From to the type ToType. Returns true if there was an
733/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000734/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000735/// performing, used in the error message. If @p AllowExplicit,
736/// explicit user-defined conversions are permitted.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000737bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000738Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000739 const char *Flavor, bool AllowExplicit)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000740{
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000741 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType, false,
742 AllowExplicit);
743 return PerformImplicitConversion(From, ToType, ICS, Flavor);
744}
745
746/// PerformImplicitConversion - Perform an implicit conversion of the
747/// expression From to the type ToType using the pre-computed implicit
748/// conversion sequence ICS. Returns true if there was an error, false
749/// otherwise. The expression From is replaced with the converted
750/// expression. Flavor is the kind of conversion we're performing,
751/// used in the error message.
752bool
753Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
754 const ImplicitConversionSequence &ICS,
755 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000756 switch (ICS.ConversionKind) {
757 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000758 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000759 return true;
760 break;
761
762 case ImplicitConversionSequence::UserDefinedConversion:
763 // FIXME: This is, of course, wrong. We'll need to actually call
764 // the constructor or conversion operator, and then cope with the
765 // standard conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000766 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000767 ToType->isLValueReferenceType());
Douglas Gregor60d62c22008-10-31 16:23:19 +0000768 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000769
770 case ImplicitConversionSequence::EllipsisConversion:
771 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000772 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000773
774 case ImplicitConversionSequence::BadConversion:
775 return true;
776 }
777
778 // Everything went well.
779 return false;
780}
781
782/// PerformImplicitConversion - Perform an implicit conversion of the
783/// expression From to the type ToType by following the standard
784/// conversion sequence SCS. Returns true if there was an error, false
785/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000786/// expression. Flavor is the context in which we're performing this
787/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000788bool
789Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000790 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000791 const char *Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000792 // Overall FIXME: we are recomputing too many types here and doing
793 // far too much extra work. What this means is that we need to keep
794 // track of more information that is computed when we try the
795 // implicit conversion initially, so that we don't need to recompute
796 // anything here.
797 QualType FromType = From->getType();
798
Douglas Gregor225c41e2008-11-03 19:09:14 +0000799 if (SCS.CopyConstructor) {
800 // FIXME: Create a temporary object by calling the copy
801 // constructor.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000802 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000803 ToType->isLValueReferenceType());
Douglas Gregor225c41e2008-11-03 19:09:14 +0000804 return false;
805 }
806
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000807 // Perform the first implicit conversion.
808 switch (SCS.First) {
809 case ICK_Identity:
810 case ICK_Lvalue_To_Rvalue:
811 // Nothing to do.
812 break;
813
814 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000815 FromType = Context.getArrayDecayedType(FromType);
816 ImpCastExprToType(From, FromType);
817 break;
818
819 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +0000820 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +0000821 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
822 if (!Fn)
823 return true;
824
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000825 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
826 return true;
827
Douglas Gregor904eed32008-11-10 20:40:00 +0000828 FixOverloadedFunctionReference(From, Fn);
829 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +0000830 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000831 FromType = Context.getPointerType(FromType);
832 ImpCastExprToType(From, FromType);
833 break;
834
835 default:
836 assert(false && "Improper first standard conversion");
837 break;
838 }
839
840 // Perform the second implicit conversion
841 switch (SCS.Second) {
842 case ICK_Identity:
843 // Nothing to do.
844 break;
845
846 case ICK_Integral_Promotion:
847 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000848 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000849 case ICK_Integral_Conversion:
850 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000851 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000852 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000853 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +0000854 case ICK_Compatible_Conversion:
855 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000856 FromType = ToType.getUnqualifiedType();
857 ImpCastExprToType(From, FromType);
858 break;
859
860 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000861 if (SCS.IncompatibleObjC) {
862 // Diagnose incompatible Objective-C conversions
863 Diag(From->getSourceRange().getBegin(),
864 diag::ext_typecheck_convert_incompatible_pointer)
865 << From->getType() << ToType << Flavor
866 << From->getSourceRange();
867 }
868
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000869 if (CheckPointerConversion(From, ToType))
870 return true;
871 ImpCastExprToType(From, ToType);
872 break;
873
874 case ICK_Pointer_Member:
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000875 if (CheckMemberPointerConversion(From, ToType))
876 return true;
877 ImpCastExprToType(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000878 break;
879
880 case ICK_Boolean_Conversion:
881 FromType = Context.BoolTy;
882 ImpCastExprToType(From, FromType);
883 break;
884
885 default:
886 assert(false && "Improper second standard conversion");
887 break;
888 }
889
890 switch (SCS.Third) {
891 case ICK_Identity:
892 // Nothing to do.
893 break;
894
895 case ICK_Qualification:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000896 // FIXME: Not sure about lvalue vs rvalue here in the presence of
897 // rvalue references.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000898 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000899 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000900 break;
901
902 default:
903 assert(false && "Improper second standard conversion");
904 break;
905 }
906
907 return false;
908}
909
Sebastian Redl64b45f72009-01-05 20:52:13 +0000910Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
911 SourceLocation KWLoc,
912 SourceLocation LParen,
913 TypeTy *Ty,
914 SourceLocation RParen) {
915 // FIXME: Some of the type traits have requirements. Interestingly, only the
916 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed,
917 // G++ accepts __is_pod(Incomplete) without complaints, and claims that the
918 // type is indeed a POD.
919
920 // There is no point in eagerly computing the value. The traits are designed
921 // to be used from type trait templates, so Ty will be a template parameter
922 // 99% of the time.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000923 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
Sebastian Redl64b45f72009-01-05 20:52:13 +0000924 QualType::getFromOpaquePtr(Ty),
925 RParen, Context.BoolTy));
926}
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000927
928QualType Sema::CheckPointerToMemberOperands(
929 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
930{
931 const char *OpSpelling = isIndirect ? "->*" : ".*";
932 // C++ 5.5p2
933 // The binary operator .* [p3: ->*] binds its second operand, which shall
934 // be of type "pointer to member of T" (where T is a completely-defined
935 // class type) [...]
936 QualType RType = rex->getType();
937 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
938 if (!MemPtr || MemPtr->getClass()->isIncompleteType()) {
939 Diag(Loc, diag::err_bad_memptr_rhs)
940 << OpSpelling << RType << rex->getSourceRange();
941 return QualType();
942 }
943 QualType Class(MemPtr->getClass(), 0);
944
945 // C++ 5.5p2
946 // [...] to its first operand, which shall be of class T or of a class of
947 // which T is an unambiguous and accessible base class. [p3: a pointer to
948 // such a class]
949 QualType LType = lex->getType();
950 if (isIndirect) {
951 if (const PointerType *Ptr = LType->getAsPointerType())
952 LType = Ptr->getPointeeType().getNonReferenceType();
953 else {
954 Diag(Loc, diag::err_bad_memptr_lhs)
955 << OpSpelling << 1 << LType << lex->getSourceRange();
956 return QualType();
957 }
958 }
959
960 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
961 Context.getCanonicalType(LType).getUnqualifiedType()) {
962 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
963 /*DetectVirtual=*/false);
964 // FIXME: Would it be useful to print full ambiguity paths,
965 // or is that overkill?
966 if (!IsDerivedFrom(LType, Class, Paths) ||
967 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
968 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
969 << (int)isIndirect << lex->getType() << lex->getSourceRange();
970 return QualType();
971 }
972 }
973
974 // C++ 5.5p2
975 // The result is an object or a function of the type specified by the
976 // second operand.
977 // The cv qualifiers are the union of those in the pointer and the left side,
978 // in accordance with 5.5p5 and 5.2.5.
979 // FIXME: This returns a dereferenced member function pointer as a normal
980 // function type. However, the only operation valid on such functions is
981 // calling them. There's also a GCC extension to get a function pointer to
982 // the thing, which is another complication, because this type - unlike the
983 // type that is the result of this expression - takes the class as the first
984 // argument.
985 // We probably need a "MemberFunctionClosureType" or something like that.
986 QualType Result = MemPtr->getPointeeType();
987 if (LType.isConstQualified())
988 Result.addConst();
989 if (LType.isVolatileQualified())
990 Result.addVolatile();
991 return Result;
992}