blob: 501eda74438bdc9e95ec129cde7a7bdc6ef5554b [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 ).
59Action::ExprResult
60Sema::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)
64 return Diag(OpLoc, diag::err_need_header_before_typeid);
65
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)
70 return Diag(OpLoc, diag::err_need_header_before_typeid);
Sebastian Redlc42e1182008-11-11 11:37:55 +000071
72 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
73
Ted Kremenek8189cde2009-02-07 01:47:29 +000074 return new (Context) CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(),
75 SourceRange(OpLoc, RParenLoc));
Sebastian Redlc42e1182008-11-11 11:37:55 +000076}
77
Steve Naroff1b273c42007-09-16 14:56:35 +000078/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Reid Spencer5f016e22007-07-11 17:01:13 +000079Action::ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000080Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000081 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000082 "Unknown C++ Boolean value!");
Ted Kremenek8189cde2009-02-07 01:47:29 +000083 return new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +000084}
Chris Lattner50dd2892008-02-26 00:51:44 +000085
86/// ActOnCXXThrow - Parse throw expressions.
87Action::ExprResult
88Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
Ted Kremenek8189cde2009-02-07 01:47:29 +000089 return new (Context) CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
Chris Lattner50dd2892008-02-26 00:51:44 +000090}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000091
92Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
93 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
94 /// is a non-lvalue expression whose value is the address of the object for
95 /// which the function is called.
96
97 if (!isa<FunctionDecl>(CurContext)) {
98 Diag(ThisLoc, diag::err_invalid_this_use);
99 return ExprResult(true);
100 }
101
102 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
103 if (MD->isInstance())
Ted Kremenek8189cde2009-02-07 01:47:29 +0000104 return new (Context) CXXThisExpr(ThisLoc, MD->getThisType(Context));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000105
106 return Diag(ThisLoc, diag::err_invalid_this_use);
107}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000108
109/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
110/// Can be interpreted either as function-style casting ("int(x)")
111/// or class type construction ("ClassType(x,y,z)")
112/// or creation of a value-initialized type ("int()").
113Action::ExprResult
114Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
115 SourceLocation LParenLoc,
116 ExprTy **ExprTys, unsigned NumExprs,
117 SourceLocation *CommaLocs,
118 SourceLocation RParenLoc) {
119 assert(TypeRep && "Missing type!");
120 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
121 Expr **Exprs = (Expr**)ExprTys;
122 SourceLocation TyBeginLoc = TypeRange.getBegin();
123 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
124
Douglas Gregor506ae412009-01-16 18:33:17 +0000125 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000126 // If the expression list is a single expression, the type conversion
127 // expression is equivalent (in definedness, and if defined in meaning) to the
128 // corresponding cast expression.
129 //
130 if (NumExprs == 1) {
131 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
132 return true;
Ted Kremenek8189cde2009-02-07 01:47:29 +0000133 return new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty,
134 TyBeginLoc, Exprs[0], RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000135 }
136
Sebastian Redl28507842009-02-26 14:39:58 +0000137 // FIXME: What AST node to create when the type is dependent?
138
Douglas Gregor506ae412009-01-16 18:33:17 +0000139 if (const RecordType *RT = Ty->getAsRecordType()) {
140 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
141
142 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
143 CXXConstructorDecl *Constructor
144 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
145 TypeRange.getBegin(),
146 SourceRange(TypeRange.getBegin(),
147 RParenLoc),
148 DeclarationName(),
149 IK_Direct);
150
151 if (!Constructor)
152 return true;
153
Ted Kremenek8189cde2009-02-07 01:47:29 +0000154 return new (Context) CXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor506ae412009-01-16 18:33:17 +0000155 Exprs, NumExprs, RParenLoc);
156 }
157
158 // Fall through to value-initialize an object of class type that
159 // doesn't have a user-declared default constructor.
160 }
161
162 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000163 // If the expression list specifies more than a single value, the type shall
164 // be a class with a suitably declared constructor.
165 //
166 if (NumExprs > 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000167 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg)
168 << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000169
170 assert(NumExprs == 0 && "Expected 0 expressions");
171
Douglas Gregor506ae412009-01-16 18:33:17 +0000172 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000173 // The expression T(), where T is a simple-type-specifier for a non-array
174 // complete object type or the (possibly cv-qualified) void type, creates an
175 // rvalue of the specified type, which is value-initialized.
176 //
177 if (Ty->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000178 return Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange;
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000179 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Douglas Gregor86447ec2009-03-09 16:13:40 +0000180 RequireCompleteType(TyBeginLoc, Ty,
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000181 diag::err_invalid_incomplete_type_use, FullRange))
182 return true;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000183
Ted Kremenek8189cde2009-02-07 01:47:29 +0000184 return new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000185}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000186
187
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000188/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
189/// @code new (memory) int[size][4] @endcode
190/// or
191/// @code ::new Foo(23, "hello") @endcode
192/// For the interpretation of this heap of arguments, consult the base version.
193Action::ExprResult
194Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
195 SourceLocation PlacementLParen,
196 ExprTy **PlacementArgs, unsigned NumPlaceArgs,
197 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000198 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000199 ExprTy **ConstructorArgs, unsigned NumConsArgs,
200 SourceLocation ConstructorRParen)
201{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000202 Expr *ArraySize = 0;
203 unsigned Skip = 0;
204 // If the specified type is an array, unwrap it and save the expression.
205 if (D.getNumTypeObjects() > 0 &&
206 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
207 DeclaratorChunk &Chunk = D.getTypeObject(0);
208 if (Chunk.Arr.hasStatic)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000209 return Diag(Chunk.Loc, diag::err_static_illegal_in_new)
210 << D.getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000211 if (!Chunk.Arr.NumElts)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000212 return Diag(Chunk.Loc, diag::err_array_new_needs_size)
213 << D.getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000214 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
215 Skip = 1;
216 }
217
218 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
219 if (D.getInvalidType())
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000220 return true;
221
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000222 if (CheckAllocatedType(AllocType, D))
223 return true;
224
Sebastian Redl28507842009-02-26 14:39:58 +0000225 QualType ResultType = AllocType->isDependentType()
226 ? Context.DependentTy
227 : Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000228
229 // That every array dimension except the first is constant was already
230 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000231
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000232 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
233 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000234 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000235 QualType SizeType = ArraySize->getType();
236 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
237 return Diag(ArraySize->getSourceRange().getBegin(),
238 diag::err_array_size_not_integral)
239 << SizeType << ArraySize->getSourceRange();
240 // Let's see if this is a constant < 0. If so, we reject it out of hand.
241 // We don't care about special rules, so we tell the machinery it's not
242 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000243 if (!ArraySize->isValueDependent()) {
244 llvm::APSInt Value;
245 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
246 if (Value < llvm::APSInt(
247 llvm::APInt::getNullValue(Value.getBitWidth()), false))
248 return Diag(ArraySize->getSourceRange().getBegin(),
249 diag::err_typecheck_negative_array_size)
250 << ArraySize->getSourceRange();
251 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000252 }
253 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000254
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000255 FunctionDecl *OperatorNew = 0;
256 FunctionDecl *OperatorDelete = 0;
257 Expr **PlaceArgs = (Expr**)PlacementArgs;
Sebastian Redl28507842009-02-26 14:39:58 +0000258 if (!AllocType->isDependentType() &&
259 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
260 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000261 SourceRange(PlacementLParen, PlacementRParen),
262 UseGlobal, AllocType, ArraySize, PlaceArgs,
263 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000264 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000265
266 bool Init = ConstructorLParen.isValid();
267 // --- Choosing a constructor ---
268 // C++ 5.3.4p15
269 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
270 // the object is not initialized. If the object, or any part of it, is
271 // const-qualified, it's an error.
272 // 2) If T is a POD and there's an empty initializer, the object is value-
273 // initialized.
274 // 3) If T is a POD and there's one initializer argument, the object is copy-
275 // constructed.
276 // 4) If T is a POD and there's more initializer arguments, it's an error.
277 // 5) If T is not a POD, the initializer arguments are used as constructor
278 // arguments.
279 //
280 // Or by the C++0x formulation:
281 // 1) If there's no initializer, the object is default-initialized according
282 // to C++0x rules.
283 // 2) Otherwise, the object is direct-initialized.
284 CXXConstructorDecl *Constructor = 0;
285 Expr **ConsArgs = (Expr**)ConstructorArgs;
Sebastian Redl28507842009-02-26 14:39:58 +0000286 if (AllocType->isDependentType()) {
287 // Skip all the checks.
288 }
Sebastian Redl00e68e22009-02-09 18:24:27 +0000289 // FIXME: Should check for primitive/aggregate here, not record.
Sebastian Redl28507842009-02-26 14:39:58 +0000290 else if (const RecordType *RT = AllocType->getAsRecordType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000291 // FIXME: This is incorrect for when there is an empty initializer and
292 // no user-defined constructor. Must zero-initialize, not default-construct.
293 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000294 AllocType, ConsArgs, NumConsArgs,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000295 D.getSourceRange().getBegin(),
296 SourceRange(D.getSourceRange().getBegin(),
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000297 ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000298 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000299 NumConsArgs != 0 ? IK_Direct : IK_Default);
300 if (!Constructor)
301 return true;
302 } else {
303 if (!Init) {
304 // FIXME: Check that no subpart is const.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000305 if (AllocType.isConstQualified()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000306 Diag(StartLoc, diag::err_new_uninitialized_const)
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000307 << D.getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000308 return true;
309 }
310 } else if (NumConsArgs == 0) {
311 // Object is value-initialized. Do nothing.
312 } else if (NumConsArgs == 1) {
313 // Object is direct-initialized.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000314 // FIXME: WHAT DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000315 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000316 DeclarationName() /*AllocType.getAsString()*/,
317 /*DirectInit=*/true))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000318 return true;
319 } else {
320 Diag(StartLoc, diag::err_builtin_direct_init_more_than_one_arg)
321 << SourceRange(ConstructorLParen, ConstructorRParen);
322 }
323 }
324
325 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
326
Ted Kremenek8189cde2009-02-07 01:47:29 +0000327 return new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
328 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000329 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000330 StartLoc, Init ? ConstructorRParen : SourceLocation());
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000331}
332
333/// CheckAllocatedType - Checks that a type is suitable as the allocated type
334/// in a new-expression.
335/// dimension off and stores the size expression in ArraySize.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000336bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000337{
338 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
339 // abstract class type or array thereof.
340 // FIXME: We don't have abstract types yet.
341 // FIXME: Under C++ semantics, an incomplete object type is still an object
342 // type. This code assumes the C semantics, where it's not.
343 if (!AllocType->isObjectType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000344 unsigned type; // For the select in the message.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000345 if (AllocType->isFunctionType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000346 type = 0;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000347 } else if(AllocType->isIncompleteType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000348 type = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000349 } else {
Sebastian Redl00e68e22009-02-09 18:24:27 +0000350 assert(AllocType->isReferenceType() && "Unhandled non-object type.");
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000351 type = 2;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000352 }
Sebastian Redl00e68e22009-02-09 18:24:27 +0000353 Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
354 << AllocType << type << D.getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000355 return true;
356 }
357
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000358 // Every dimension shall be of constant size.
359 unsigned i = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000360 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
361 if (!Array->isConstantArrayType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000362 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
363 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000364 return true;
365 }
366 AllocType = Array->getElementType();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000367 ++i;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000368 }
369
370 return false;
371}
372
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000373/// FindAllocationFunctions - Finds the overloads of operator new and delete
374/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000375bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
376 bool UseGlobal, QualType AllocType,
377 bool IsArray, Expr **PlaceArgs,
378 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000379 FunctionDecl *&OperatorNew,
380 FunctionDecl *&OperatorDelete)
381{
382 // --- Choosing an allocation function ---
383 // C++ 5.3.4p8 - 14 & 18
384 // 1) If UseGlobal is true, only look in the global scope. Else, also look
385 // in the scope of the allocated class.
386 // 2) If an array size is given, look for operator new[], else look for
387 // operator new.
388 // 3) The first argument is always size_t. Append the arguments from the
389 // placement form.
390 // FIXME: Also find the appropriate delete operator.
391
392 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
393 // We don't care about the actual value of this argument.
394 // FIXME: Should the Sema create the expression and embed it in the syntax
395 // tree? Or should the consumer just recalculate the value?
Ted Kremenek8189cde2009-02-07 01:47:29 +0000396 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000397 Context.Target.getPointerWidth(0)),
398 Context.getSizeType(),
399 SourceLocation());
400 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
401
402 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
403 IsArray ? OO_Array_New : OO_New);
404 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000405 CXXRecordDecl *Record
406 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000407 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000408 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000409 AllocArgs.size(), Record, /*AllowMissing=*/true,
410 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000411 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000412 }
413 if (!OperatorNew) {
414 // Didn't find a member overload. Look for a global one.
415 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000416 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000417 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000418 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
419 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000420 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000421 }
422
Sebastian Redl7f662392008-12-04 22:20:51 +0000423 // FIXME: This is leaked on error. But so much is currently in Sema that it's
424 // easier to clean it in one go.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000425 AllocArgs[0]->Destroy(Context);
426 return false;
427}
428
Sebastian Redl7f662392008-12-04 22:20:51 +0000429/// FindAllocationOverload - Find an fitting overload for the allocation
430/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000431bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
432 DeclarationName Name, Expr** Args,
433 unsigned NumArgs, DeclContext *Ctx,
434 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redl7f662392008-12-04 22:20:51 +0000435{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000436 DeclContext::lookup_iterator Alloc, AllocEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000437 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000438 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000439 if (AllowMissing)
440 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000441 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000442 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000443 }
444
445 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000446 for (; Alloc != AllocEnd; ++Alloc) {
447 // Even member operator new/delete are implicitly treated as
448 // static, so don't use AddMemberCandidate.
449 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
450 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
451 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000452 }
453
454 // Do the resolution.
455 OverloadCandidateSet::iterator Best;
456 switch(BestViableFunction(Candidates, Best)) {
457 case OR_Success: {
458 // Got one!
459 FunctionDecl *FnDecl = Best->Function;
460 // The first argument is size_t, and the first parameter must be size_t,
461 // too. This is checked on declaration and can be assumed. (It can't be
462 // asserted on, though, since invalid decls are left in there.)
463 for (unsigned i = 1; i < NumArgs; ++i) {
464 // FIXME: Passing word to diagnostic.
465 if (PerformCopyInitialization(Args[i-1],
466 FnDecl->getParamDecl(i)->getType(),
467 "passing"))
468 return true;
469 }
470 Operator = FnDecl;
471 return false;
472 }
473
474 case OR_No_Viable_Function:
475 if (AllowMissing)
476 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000477 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000478 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000479 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
480 return true;
481
482 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000483 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000484 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000485 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
486 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000487
488 case OR_Deleted:
489 Diag(StartLoc, diag::err_ovl_deleted_call)
490 << Best->Function->isDeleted()
491 << Name << Range;
492 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
493 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000494 }
495 assert(false && "Unreachable, bad result from BestViableFunction");
496 return true;
497}
498
499
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000500/// DeclareGlobalNewDelete - Declare the global forms of operator new and
501/// delete. These are:
502/// @code
503/// void* operator new(std::size_t) throw(std::bad_alloc);
504/// void* operator new[](std::size_t) throw(std::bad_alloc);
505/// void operator delete(void *) throw();
506/// void operator delete[](void *) throw();
507/// @endcode
508/// Note that the placement and nothrow forms of new are *not* implicitly
509/// declared. Their use requires including \<new\>.
510void Sema::DeclareGlobalNewDelete()
511{
512 if (GlobalNewDeleteDeclared)
513 return;
514 GlobalNewDeleteDeclared = true;
515
516 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
517 QualType SizeT = Context.getSizeType();
518
519 // FIXME: Exception specifications are not added.
520 DeclareGlobalAllocationFunction(
521 Context.DeclarationNames.getCXXOperatorName(OO_New),
522 VoidPtr, SizeT);
523 DeclareGlobalAllocationFunction(
524 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
525 VoidPtr, SizeT);
526 DeclareGlobalAllocationFunction(
527 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
528 Context.VoidTy, VoidPtr);
529 DeclareGlobalAllocationFunction(
530 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
531 Context.VoidTy, VoidPtr);
532}
533
534/// DeclareGlobalAllocationFunction - Declares a single implicit global
535/// allocation function if it doesn't already exist.
536void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
537 QualType Return, QualType Argument)
538{
539 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
540
541 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000542 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000543 DeclContext::lookup_iterator Alloc, AllocEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000544 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000545 Alloc != AllocEnd; ++Alloc) {
546 // FIXME: Do we need to check for default arguments here?
547 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
548 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000549 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000550 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000551 }
552 }
553
554 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
555 FunctionDecl *Alloc =
556 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor2224f842009-02-25 16:33:18 +0000557 FnType, FunctionDecl::None, false, true,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000558 SourceLocation());
559 Alloc->setImplicit();
560 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000561 0, Argument, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000562 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000563
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000564 // FIXME: Also add this declaration to the IdentifierResolver, but
565 // make sure it is at the end of the chain to coincide with the
566 // global scope.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000567 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000568}
569
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000570/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
571/// @code ::delete ptr; @endcode
572/// or
573/// @code delete [] ptr; @endcode
574Action::ExprResult
575Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
576 bool ArrayForm, ExprTy *Operand)
577{
578 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
579 // having a single conversion function to a pointer type. The result has
580 // type void."
581 // DR599 amends "pointer type" to "pointer to object type" in both cases.
582
583 Expr *Ex = (Expr *)Operand;
Sebastian Redl28507842009-02-26 14:39:58 +0000584 if (!Ex->isTypeDependent()) {
585 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000586
Sebastian Redl28507842009-02-26 14:39:58 +0000587 if (Type->isRecordType()) {
588 // FIXME: Find that one conversion function and amend the type.
589 }
590
591 if (!Type->isPointerType()) {
592 Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange();
593 return true;
594 }
595
596 QualType Pointee = Type->getAsPointerType()->getPointeeType();
597 if (!Pointee->isVoidType() &&
Douglas Gregor86447ec2009-03-09 16:13:40 +0000598 RequireCompleteType(StartLoc, Pointee, diag::warn_delete_incomplete,
Sebastian Redl28507842009-02-26 14:39:58 +0000599 Ex->getSourceRange()))
600 return true;
601 else if (!Pointee->isObjectType()) {
602 Diag(StartLoc, diag::err_delete_operand)
603 << Type << Ex->getSourceRange();
604 return true;
605 }
606
607 // FIXME: Look up the correct operator delete overload and pass a pointer
608 // along.
609 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000610 }
611
Ted Kremenek8189cde2009-02-07 01:47:29 +0000612 return new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 0,
613 Ex, StartLoc);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000614}
615
616
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000617/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
618/// C++ if/switch/while/for statement.
619/// e.g: "if (int x = f()) {...}"
620Action::ExprResult
621Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
622 Declarator &D,
623 SourceLocation EqualLoc,
624 ExprTy *AssignExprVal) {
625 assert(AssignExprVal && "Null assignment expression");
626
627 // C++ 6.4p2:
628 // The declarator shall not specify a function or an array.
629 // The type-specifier-seq shall not contain typedef and shall not declare a
630 // new class or enumeration.
631
632 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
633 "Parser allowed 'typedef' as storage class of condition decl.");
634
635 QualType Ty = GetTypeForDeclarator(D, S);
636
637 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
638 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
639 // would be created and CXXConditionDeclExpr wants a VarDecl.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000640 return Diag(StartLoc, diag::err_invalid_use_of_function_type)
641 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000642 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000643 Diag(StartLoc, diag::err_invalid_use_of_array_type)
644 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000645 } else if (const RecordType *RT = Ty->getAsRecordType()) {
646 RecordDecl *RD = RT->getDecl();
647 // The type-specifier-seq shall not declare a new class...
648 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
649 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
650 } else if (const EnumType *ET = Ty->getAsEnumType()) {
651 EnumDecl *ED = ET->getDecl();
652 // ...or enumeration.
653 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
654 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
655 }
656
657 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
658 if (!Dcl)
659 return true;
Sebastian Redl798d1192008-12-13 16:23:55 +0000660 AddInitializerToDecl(Dcl, ExprArg(*this, AssignExprVal));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000661
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000662 // Mark this variable as one that is declared within a conditional.
663 if (VarDecl *VD = dyn_cast<VarDecl>((Decl *)Dcl))
664 VD->setDeclaredInCondition(true);
665
Ted Kremenek8189cde2009-02-07 01:47:29 +0000666 return new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc,
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000667 cast<VarDecl>(static_cast<Decl *>(Dcl)));
668}
669
670/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
671bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
672 // C++ 6.4p4:
673 // The value of a condition that is an initialized declaration in a statement
674 // other than a switch statement is the value of the declared variable
675 // implicitly converted to type bool. If that conversion is ill-formed, the
676 // program is ill-formed.
677 // The value of a condition that is an expression is the value of the
678 // expression, implicitly converted to bool.
679 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000680 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000681}
Douglas Gregor77a52232008-09-12 00:47:35 +0000682
683/// Helper function to determine whether this is the (deprecated) C++
684/// conversion from a string literal to a pointer to non-const char or
685/// non-const wchar_t (for narrow and wide string literals,
686/// respectively).
687bool
688Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
689 // Look inside the implicit cast, if it exists.
690 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
691 From = Cast->getSubExpr();
692
693 // A string literal (2.13.4) that is not a wide string literal can
694 // be converted to an rvalue of type "pointer to char"; a wide
695 // string literal can be converted to an rvalue of type "pointer
696 // to wchar_t" (C++ 4.2p2).
697 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
698 if (const PointerType *ToPtrType = ToType->getAsPointerType())
699 if (const BuiltinType *ToPointeeType
700 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
701 // This conversion is considered only when there is an
702 // explicit appropriate pointer target type (C++ 4.2p2).
703 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
704 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
705 (!StrLit->isWide() &&
706 (ToPointeeType->getKind() == BuiltinType::Char_U ||
707 ToPointeeType->getKind() == BuiltinType::Char_S))))
708 return true;
709 }
710
711 return false;
712}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000713
714/// PerformImplicitConversion - Perform an implicit conversion of the
715/// expression From to the type ToType. Returns true if there was an
716/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000717/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000718/// performing, used in the error message. If @p AllowExplicit,
719/// explicit user-defined conversions are permitted.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000720bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000721Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000722 const char *Flavor, bool AllowExplicit)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000723{
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000724 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType, false,
725 AllowExplicit);
726 return PerformImplicitConversion(From, ToType, ICS, Flavor);
727}
728
729/// PerformImplicitConversion - Perform an implicit conversion of the
730/// expression From to the type ToType using the pre-computed implicit
731/// conversion sequence ICS. Returns true if there was an error, false
732/// otherwise. The expression From is replaced with the converted
733/// expression. Flavor is the kind of conversion we're performing,
734/// used in the error message.
735bool
736Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
737 const ImplicitConversionSequence &ICS,
738 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000739 switch (ICS.ConversionKind) {
740 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000741 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000742 return true;
743 break;
744
745 case ImplicitConversionSequence::UserDefinedConversion:
746 // FIXME: This is, of course, wrong. We'll need to actually call
747 // the constructor or conversion operator, and then cope with the
748 // standard conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000749 ImpCastExprToType(From, ToType.getNonReferenceType(),
750 ToType->isReferenceType());
Douglas Gregor60d62c22008-10-31 16:23:19 +0000751 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000752
753 case ImplicitConversionSequence::EllipsisConversion:
754 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000755 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000756
757 case ImplicitConversionSequence::BadConversion:
758 return true;
759 }
760
761 // Everything went well.
762 return false;
763}
764
765/// PerformImplicitConversion - Perform an implicit conversion of the
766/// expression From to the type ToType by following the standard
767/// conversion sequence SCS. Returns true if there was an error, false
768/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000769/// expression. Flavor is the context in which we're performing this
770/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000771bool
772Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000773 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000774 const char *Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000775 // Overall FIXME: we are recomputing too many types here and doing
776 // far too much extra work. What this means is that we need to keep
777 // track of more information that is computed when we try the
778 // implicit conversion initially, so that we don't need to recompute
779 // anything here.
780 QualType FromType = From->getType();
781
Douglas Gregor225c41e2008-11-03 19:09:14 +0000782 if (SCS.CopyConstructor) {
783 // FIXME: Create a temporary object by calling the copy
784 // constructor.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000785 ImpCastExprToType(From, ToType.getNonReferenceType(),
786 ToType->isReferenceType());
Douglas Gregor225c41e2008-11-03 19:09:14 +0000787 return false;
788 }
789
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000790 // Perform the first implicit conversion.
791 switch (SCS.First) {
792 case ICK_Identity:
793 case ICK_Lvalue_To_Rvalue:
794 // Nothing to do.
795 break;
796
797 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000798 FromType = Context.getArrayDecayedType(FromType);
799 ImpCastExprToType(From, FromType);
800 break;
801
802 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +0000803 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +0000804 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
805 if (!Fn)
806 return true;
807
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000808 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
809 return true;
810
Douglas Gregor904eed32008-11-10 20:40:00 +0000811 FixOverloadedFunctionReference(From, Fn);
812 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +0000813 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000814 FromType = Context.getPointerType(FromType);
815 ImpCastExprToType(From, FromType);
816 break;
817
818 default:
819 assert(false && "Improper first standard conversion");
820 break;
821 }
822
823 // Perform the second implicit conversion
824 switch (SCS.Second) {
825 case ICK_Identity:
826 // Nothing to do.
827 break;
828
829 case ICK_Integral_Promotion:
830 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000831 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000832 case ICK_Integral_Conversion:
833 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000834 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000835 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000836 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +0000837 case ICK_Compatible_Conversion:
838 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000839 FromType = ToType.getUnqualifiedType();
840 ImpCastExprToType(From, FromType);
841 break;
842
843 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000844 if (SCS.IncompatibleObjC) {
845 // Diagnose incompatible Objective-C conversions
846 Diag(From->getSourceRange().getBegin(),
847 diag::ext_typecheck_convert_incompatible_pointer)
848 << From->getType() << ToType << Flavor
849 << From->getSourceRange();
850 }
851
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000852 if (CheckPointerConversion(From, ToType))
853 return true;
854 ImpCastExprToType(From, ToType);
855 break;
856
857 case ICK_Pointer_Member:
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000858 if (CheckMemberPointerConversion(From, ToType))
859 return true;
860 ImpCastExprToType(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000861 break;
862
863 case ICK_Boolean_Conversion:
864 FromType = Context.BoolTy;
865 ImpCastExprToType(From, FromType);
866 break;
867
868 default:
869 assert(false && "Improper second standard conversion");
870 break;
871 }
872
873 switch (SCS.Third) {
874 case ICK_Identity:
875 // Nothing to do.
876 break;
877
878 case ICK_Qualification:
Douglas Gregor66b947f2009-01-16 19:38:23 +0000879 ImpCastExprToType(From, ToType.getNonReferenceType(),
880 ToType->isReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000881 break;
882
883 default:
884 assert(false && "Improper second standard conversion");
885 break;
886 }
887
888 return false;
889}
890
Sebastian Redl64b45f72009-01-05 20:52:13 +0000891Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
892 SourceLocation KWLoc,
893 SourceLocation LParen,
894 TypeTy *Ty,
895 SourceLocation RParen) {
896 // FIXME: Some of the type traits have requirements. Interestingly, only the
897 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed,
898 // G++ accepts __is_pod(Incomplete) without complaints, and claims that the
899 // type is indeed a POD.
900
901 // There is no point in eagerly computing the value. The traits are designed
902 // to be used from type trait templates, so Ty will be a template parameter
903 // 99% of the time.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000904 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
Sebastian Redl64b45f72009-01-05 20:52:13 +0000905 QualType::getFromOpaquePtr(Ty),
906 RParen, Context.BoolTy));
907}
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000908
909QualType Sema::CheckPointerToMemberOperands(
910 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
911{
912 const char *OpSpelling = isIndirect ? "->*" : ".*";
913 // C++ 5.5p2
914 // The binary operator .* [p3: ->*] binds its second operand, which shall
915 // be of type "pointer to member of T" (where T is a completely-defined
916 // class type) [...]
917 QualType RType = rex->getType();
918 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
919 if (!MemPtr || MemPtr->getClass()->isIncompleteType()) {
920 Diag(Loc, diag::err_bad_memptr_rhs)
921 << OpSpelling << RType << rex->getSourceRange();
922 return QualType();
923 }
924 QualType Class(MemPtr->getClass(), 0);
925
926 // C++ 5.5p2
927 // [...] to its first operand, which shall be of class T or of a class of
928 // which T is an unambiguous and accessible base class. [p3: a pointer to
929 // such a class]
930 QualType LType = lex->getType();
931 if (isIndirect) {
932 if (const PointerType *Ptr = LType->getAsPointerType())
933 LType = Ptr->getPointeeType().getNonReferenceType();
934 else {
935 Diag(Loc, diag::err_bad_memptr_lhs)
936 << OpSpelling << 1 << LType << lex->getSourceRange();
937 return QualType();
938 }
939 }
940
941 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
942 Context.getCanonicalType(LType).getUnqualifiedType()) {
943 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
944 /*DetectVirtual=*/false);
945 // FIXME: Would it be useful to print full ambiguity paths,
946 // or is that overkill?
947 if (!IsDerivedFrom(LType, Class, Paths) ||
948 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
949 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
950 << (int)isIndirect << lex->getType() << lex->getSourceRange();
951 return QualType();
952 }
953 }
954
955 // C++ 5.5p2
956 // The result is an object or a function of the type specified by the
957 // second operand.
958 // The cv qualifiers are the union of those in the pointer and the left side,
959 // in accordance with 5.5p5 and 5.2.5.
960 // FIXME: This returns a dereferenced member function pointer as a normal
961 // function type. However, the only operation valid on such functions is
962 // calling them. There's also a GCC extension to get a function pointer to
963 // the thing, which is another complication, because this type - unlike the
964 // type that is the result of this expression - takes the class as the first
965 // argument.
966 // We probably need a "MemberFunctionClosureType" or something like that.
967 QualType Result = MemPtr->getPointeeType();
968 if (LType.isConstQualified())
969 Result.addConst();
970 if (LType.isVolatileQualified())
971 Result.addVolatile();
972 return Result;
973}