blob: 3633da89bc04ca5bcc0d4a89664777e1833825c7 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ExprCXX.h"
Steve Naroffac5d4f12007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.h"
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +000017#include "clang/Parse/DeclSpec.h"
Argiris Kirtzidiscf4e8f82008-10-06 23:16:35 +000018#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000019#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020using namespace clang;
21
Douglas Gregor24094772008-11-19 19:09:45 +000022/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregorb0212bd2008-11-17 20:34:05 +000023/// name (e.g., operator void const *) as an expression. This is
24/// very similar to ActOnIdentifierExpr, except that instead of
25/// providing an identifier the parser provides the type of the
26/// conversion function.
Douglas Gregor24094772008-11-19 19:09:45 +000027Sema::ExprResult
28Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
29 TypeTy *Ty, bool HasTrailingLParen,
30 const CXXScopeSpec &SS) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +000031 QualType ConvType = QualType::getFromOpaquePtr(Ty);
32 QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
33 DeclarationName ConvName
34 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Douglas Gregoraee3bf82008-11-18 15:03:34 +000035 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor24094772008-11-19 19:09:45 +000036 &SS);
Douglas Gregorb0212bd2008-11-17 20:34:05 +000037}
Sebastian Redlb93b49c2008-11-11 11:37:55 +000038
Douglas Gregor24094772008-11-19 19:09:45 +000039/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregor96a32dd2008-11-18 14:39:36 +000040/// name (e.g., @c operator+ ) as an expression. This is very
41/// similar to ActOnIdentifierExpr, except that instead of providing
42/// an identifier the parser provides the kind of overloaded
43/// operator that was parsed.
Douglas Gregor24094772008-11-19 19:09:45 +000044Sema::ExprResult
45Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
46 OverloadedOperatorKind Op,
47 bool HasTrailingLParen,
48 const CXXScopeSpec &SS) {
Douglas Gregor96a32dd2008-11-18 14:39:36 +000049 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor24094772008-11-19 19:09:45 +000050 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS);
Douglas Gregor96a32dd2008-11-18 14:39:36 +000051}
52
Sebastian Redlb93b49c2008-11-11 11:37:55 +000053/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
54Action::ExprResult
55Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
56 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
57 const NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattnerc2a5f512008-11-20 05:51:55 +000058 if (!StdNs)
59 return Diag(OpLoc, diag::err_need_header_before_typeid);
60
61 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
62 Decl *TypeInfoDecl = LookupDecl(TypeInfoII,
Sebastian Redlb93b49c2008-11-11 11:37:55 +000063 Decl::IDNS_Tag | Decl::IDNS_Ordinary,
64 0, StdNs, /*createBuiltins=*/false);
65 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattnerc2a5f512008-11-20 05:51:55 +000066 if (!TypeInfoRecordDecl)
67 return Diag(OpLoc, diag::err_need_header_before_typeid);
Sebastian Redlb93b49c2008-11-11 11:37:55 +000068
69 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
70
71 return new CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(),
72 SourceRange(OpLoc, RParenLoc));
73}
74
Steve Naroff5cbb02f2007-09-16 14:56:35 +000075/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Chris Lattner4b009652007-07-25 00:24:17 +000076Action::ExprResult
Steve Naroff5cbb02f2007-09-16 14:56:35 +000077Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregorf8e92702008-10-24 15:36:09 +000078 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Chris Lattner4b009652007-07-25 00:24:17 +000079 "Unknown C++ Boolean value!");
Steve Naroffac5d4f12007-08-25 14:02:58 +000080 return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +000081}
Chris Lattnera7447ba2008-02-26 00:51:44 +000082
83/// ActOnCXXThrow - Parse throw expressions.
84Action::ExprResult
85Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
86 return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
87}
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000088
89Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
90 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
91 /// is a non-lvalue expression whose value is the address of the object for
92 /// which the function is called.
93
94 if (!isa<FunctionDecl>(CurContext)) {
95 Diag(ThisLoc, diag::err_invalid_this_use);
96 return ExprResult(true);
97 }
98
99 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
100 if (MD->isInstance())
Douglas Gregora5b022a2008-11-04 14:32:21 +0000101 return new CXXThisExpr(ThisLoc, MD->getThisType(Context));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000102
103 return Diag(ThisLoc, diag::err_invalid_this_use);
104}
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000105
106/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
107/// Can be interpreted either as function-style casting ("int(x)")
108/// or class type construction ("ClassType(x,y,z)")
109/// or creation of a value-initialized type ("int()").
110Action::ExprResult
111Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
112 SourceLocation LParenLoc,
113 ExprTy **ExprTys, unsigned NumExprs,
114 SourceLocation *CommaLocs,
115 SourceLocation RParenLoc) {
116 assert(TypeRep && "Missing type!");
117 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
118 Expr **Exprs = (Expr**)ExprTys;
119 SourceLocation TyBeginLoc = TypeRange.getBegin();
120 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
121
122 if (const RecordType *RT = Ty->getAsRecordType()) {
123 // C++ 5.2.3p1:
124 // If the simple-type-specifier specifies a class type, the class type shall
125 // be complete.
126 //
127 if (!RT->getDecl()->isDefinition())
Chris Lattner77d52da2008-11-20 06:06:08 +0000128 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000129 << Ty << FullRange;
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000130
Argiris Kirtzidiscf4e8f82008-10-06 23:16:35 +0000131 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
132 "class constructors are not supported yet");
133 return Diag(TyBeginLoc, DiagID);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000134 }
135
136 // C++ 5.2.3p1:
137 // If the expression list is a single expression, the type conversion
138 // expression is equivalent (in definedness, and if defined in meaning) to the
139 // corresponding cast expression.
140 //
141 if (NumExprs == 1) {
142 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
143 return true;
Douglas Gregor21a04f32008-10-27 19:41:14 +0000144 return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc,
145 Exprs[0], RParenLoc);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000146 }
147
148 // C++ 5.2.3p1:
149 // If the expression list specifies more than a single value, the type shall
150 // be a class with a suitably declared constructor.
151 //
152 if (NumExprs > 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000153 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg)
154 << FullRange;
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000155
156 assert(NumExprs == 0 && "Expected 0 expressions");
157
158 // C++ 5.2.3p2:
159 // The expression T(), where T is a simple-type-specifier for a non-array
160 // complete object type or the (possibly cv-qualified) void type, creates an
161 // rvalue of the specified type, which is value-initialized.
162 //
163 if (Ty->isArrayType())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000164 return Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange;
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000165 if (Ty->isIncompleteType() && !Ty->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000166 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000167 << Ty << FullRange;
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000168
169 return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
170}
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000171
172
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000173/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
174/// @code new (memory) int[size][4] @endcode
175/// or
176/// @code ::new Foo(23, "hello") @endcode
177/// For the interpretation of this heap of arguments, consult the base version.
178Action::ExprResult
179Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
180 SourceLocation PlacementLParen,
181 ExprTy **PlacementArgs, unsigned NumPlaceArgs,
182 SourceLocation PlacementRParen, bool ParenTypeId,
183 SourceLocation TyStart, TypeTy *Ty, SourceLocation TyEnd,
184 SourceLocation ConstructorLParen,
185 ExprTy **ConstructorArgs, unsigned NumConsArgs,
186 SourceLocation ConstructorRParen)
187{
188 QualType AllocType = QualType::getFromOpaquePtr(Ty);
189 QualType CheckType = AllocType;
190 // To leverage the existing parser as much as possible, array types are
191 // parsed as VLAs. Unwrap for checking.
Chris Lattner271d4c22008-11-24 05:29:24 +0000192 if (const VariableArrayType *VLA = Context.getAsVariableArrayType(AllocType))
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000193 CheckType = VLA->getElementType();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000194
195 // Validate the type, and unwrap an array if any.
196 if (CheckAllocatedType(CheckType, StartLoc, SourceRange(TyStart, TyEnd)))
197 return true;
198
199 QualType ResultType = Context.getPointerType(CheckType);
200
201 // That every array dimension except the first is constant was already
202 // checked by the type check above.
203 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
204 // or enumeration type with a non-negative value."
205 // This was checked by ActOnTypeName, since C99 has the same restriction on
206 // VLA expressions.
207
208 // --- Choosing an allocation function ---
209 // C++ 5.3.4p8 - 14 & 18
210 // 1) If UseGlobal is true, only look in the global scope. Else, also look
211 // in the scope of the allocated class.
212 // 2) If an array size is given, look for operator new[], else look for
213 // operator new.
214 // 3) The first argument is always size_t. Append the arguments from the
215 // placement form.
216 // FIXME: Find the correct overload of operator new.
217 // FIXME: Also find the corresponding overload of operator delete.
218 FunctionDecl *OperatorNew = 0;
219 FunctionDecl *OperatorDelete = 0;
220 Expr **PlaceArgs = (Expr**)PlacementArgs;
221
222 bool Init = ConstructorLParen.isValid();
223 // --- Choosing a constructor ---
224 // C++ 5.3.4p15
225 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
226 // the object is not initialized. If the object, or any part of it, is
227 // const-qualified, it's an error.
228 // 2) If T is a POD and there's an empty initializer, the object is value-
229 // initialized.
230 // 3) If T is a POD and there's one initializer argument, the object is copy-
231 // constructed.
232 // 4) If T is a POD and there's more initializer arguments, it's an error.
233 // 5) If T is not a POD, the initializer arguments are used as constructor
234 // arguments.
235 //
236 // Or by the C++0x formulation:
237 // 1) If there's no initializer, the object is default-initialized according
238 // to C++0x rules.
239 // 2) Otherwise, the object is direct-initialized.
240 CXXConstructorDecl *Constructor = 0;
241 Expr **ConsArgs = (Expr**)ConstructorArgs;
Chris Lattner271d4c22008-11-24 05:29:24 +0000242 if (const RecordType *RT = CheckType->getAsRecordType()) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000243 // FIXME: This is incorrect for when there is an empty initializer and
244 // no user-defined constructor. Must zero-initialize, not default-construct.
245 Constructor = PerformInitializationByConstructor(
246 CheckType, ConsArgs, NumConsArgs,
247 TyStart, SourceRange(TyStart, ConstructorRParen),
Chris Lattner271d4c22008-11-24 05:29:24 +0000248 RT->getDecl()->getDeclName(),
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000249 NumConsArgs != 0 ? IK_Direct : IK_Default);
250 if (!Constructor)
251 return true;
252 } else {
253 if (!Init) {
254 // FIXME: Check that no subpart is const.
255 if (CheckType.isConstQualified()) {
256 Diag(StartLoc, diag::err_new_uninitialized_const)
257 << SourceRange(StartLoc, TyEnd);
258 return true;
259 }
260 } else if (NumConsArgs == 0) {
261 // Object is value-initialized. Do nothing.
262 } else if (NumConsArgs == 1) {
263 // Object is direct-initialized.
Chris Lattner271d4c22008-11-24 05:29:24 +0000264 // FIXME: WHAT DeclarationName do we pass in here?
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000265 if (CheckInitializerTypes(ConsArgs[0], CheckType, StartLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +0000266 DeclarationName() /*CheckType.getAsString()*/))
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000267 return true;
268 } else {
269 Diag(StartLoc, diag::err_builtin_direct_init_more_than_one_arg)
270 << SourceRange(ConstructorLParen, ConstructorRParen);
271 }
272 }
273
274 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
275
276 return new CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs, NumPlaceArgs,
277 ParenTypeId, AllocType, Constructor, Init,
278 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
279 StartLoc, Init ? ConstructorRParen : TyEnd);
280}
281
282/// CheckAllocatedType - Checks that a type is suitable as the allocated type
283/// in a new-expression.
284/// dimension off and stores the size expression in ArraySize.
285bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation StartLoc,
286 const SourceRange &TyR)
287{
288 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
289 // abstract class type or array thereof.
290 // FIXME: We don't have abstract types yet.
291 // FIXME: Under C++ semantics, an incomplete object type is still an object
292 // type. This code assumes the C semantics, where it's not.
293 if (!AllocType->isObjectType()) {
294 diag::kind msg;
295 if (AllocType->isFunctionType()) {
296 msg = diag::err_new_function;
297 } else if(AllocType->isIncompleteType()) {
298 msg = diag::err_new_incomplete;
299 } else if(AllocType->isReferenceType()) {
300 msg = diag::err_new_reference;
301 } else {
302 assert(false && "Unexpected type class");
303 return true;
304 }
Chris Lattner4bfd2232008-11-24 06:25:27 +0000305 Diag(StartLoc, msg) << AllocType << TyR;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000306 return true;
307 }
308
309 // Every dimension beyond the first shall be of constant size.
310 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
311 if (!Array->isConstantArrayType()) {
312 // FIXME: Might be nice to get a better source range from somewhere.
313 Diag(StartLoc, diag::err_new_array_nonconst) << TyR;
314 return true;
315 }
316 AllocType = Array->getElementType();
317 }
318
319 return false;
320}
321
322/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
323/// @code ::delete ptr; @endcode
324/// or
325/// @code delete [] ptr; @endcode
326Action::ExprResult
327Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
328 bool ArrayForm, ExprTy *Operand)
329{
330 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
331 // having a single conversion function to a pointer type. The result has
332 // type void."
333 // DR599 amends "pointer type" to "pointer to object type" in both cases.
334
335 Expr *Ex = (Expr *)Operand;
336 QualType Type = Ex->getType();
337
338 if (Type->isRecordType()) {
339 // FIXME: Find that one conversion function and amend the type.
340 }
341
342 if (!Type->isPointerType()) {
Chris Lattner4bfd2232008-11-24 06:25:27 +0000343 Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000344 return true;
345 }
346
347 QualType Pointee = Type->getAsPointerType()->getPointeeType();
348 if (Pointee->isIncompleteType() && !Pointee->isVoidType())
349 Diag(StartLoc, diag::warn_delete_incomplete)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000350 << Pointee << Ex->getSourceRange();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000351 else if (!Pointee->isObjectType()) {
352 Diag(StartLoc, diag::err_delete_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000353 << Type << Ex->getSourceRange();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000354 return true;
355 }
356
357 // FIXME: Look up the correct operator delete overload and pass a pointer
358 // along.
359 // FIXME: Check access and ambiguity of operator delete and destructor.
360
361 return new CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 0, Ex,
362 StartLoc);
363}
364
365
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000366/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
367/// C++ if/switch/while/for statement.
368/// e.g: "if (int x = f()) {...}"
369Action::ExprResult
370Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
371 Declarator &D,
372 SourceLocation EqualLoc,
373 ExprTy *AssignExprVal) {
374 assert(AssignExprVal && "Null assignment expression");
375
376 // C++ 6.4p2:
377 // The declarator shall not specify a function or an array.
378 // The type-specifier-seq shall not contain typedef and shall not declare a
379 // new class or enumeration.
380
381 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
382 "Parser allowed 'typedef' as storage class of condition decl.");
383
384 QualType Ty = GetTypeForDeclarator(D, S);
385
386 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
387 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
388 // would be created and CXXConditionDeclExpr wants a VarDecl.
Chris Lattner9d2cf082008-11-19 05:27:50 +0000389 return Diag(StartLoc, diag::err_invalid_use_of_function_type)
390 << SourceRange(StartLoc, EqualLoc);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000391 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattner9d2cf082008-11-19 05:27:50 +0000392 Diag(StartLoc, diag::err_invalid_use_of_array_type)
393 << SourceRange(StartLoc, EqualLoc);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000394 } else if (const RecordType *RT = Ty->getAsRecordType()) {
395 RecordDecl *RD = RT->getDecl();
396 // The type-specifier-seq shall not declare a new class...
397 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
398 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
399 } else if (const EnumType *ET = Ty->getAsEnumType()) {
400 EnumDecl *ED = ET->getDecl();
401 // ...or enumeration.
402 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
403 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
404 }
405
406 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
407 if (!Dcl)
408 return true;
409 AddInitializerToDecl(Dcl, AssignExprVal);
410
411 return new CXXConditionDeclExpr(StartLoc, EqualLoc,
412 cast<VarDecl>(static_cast<Decl *>(Dcl)));
413}
414
415/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
416bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
417 // C++ 6.4p4:
418 // The value of a condition that is an initialized declaration in a statement
419 // other than a switch statement is the value of the declared variable
420 // implicitly converted to type bool. If that conversion is ill-formed, the
421 // program is ill-formed.
422 // The value of a condition that is an expression is the value of the
423 // expression, implicitly converted to bool.
424 //
425 QualType Ty = CondExpr->getType(); // Save the type.
426 AssignConvertType
427 ConvTy = CheckSingleAssignmentConstraints(Context.BoolTy, CondExpr);
428 if (ConvTy == Incompatible)
Chris Lattner77d52da2008-11-20 06:06:08 +0000429 return Diag(CondExpr->getLocStart(), diag::err_typecheck_bool_condition)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000430 << Ty << CondExpr->getSourceRange();
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000431 return false;
432}
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000433
434/// Helper function to determine whether this is the (deprecated) C++
435/// conversion from a string literal to a pointer to non-const char or
436/// non-const wchar_t (for narrow and wide string literals,
437/// respectively).
438bool
439Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
440 // Look inside the implicit cast, if it exists.
441 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
442 From = Cast->getSubExpr();
443
444 // A string literal (2.13.4) that is not a wide string literal can
445 // be converted to an rvalue of type "pointer to char"; a wide
446 // string literal can be converted to an rvalue of type "pointer
447 // to wchar_t" (C++ 4.2p2).
448 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
449 if (const PointerType *ToPtrType = ToType->getAsPointerType())
450 if (const BuiltinType *ToPointeeType
451 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
452 // This conversion is considered only when there is an
453 // explicit appropriate pointer target type (C++ 4.2p2).
454 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
455 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
456 (!StrLit->isWide() &&
457 (ToPointeeType->getKind() == BuiltinType::Char_U ||
458 ToPointeeType->getKind() == BuiltinType::Char_S))))
459 return true;
460 }
461
462 return false;
463}
Douglas Gregorbb461502008-10-24 04:54:22 +0000464
465/// PerformImplicitConversion - Perform an implicit conversion of the
466/// expression From to the type ToType. Returns true if there was an
467/// error, false otherwise. The expression From is replaced with the
468/// converted expression.
469bool
470Sema::PerformImplicitConversion(Expr *&From, QualType ToType)
471{
Douglas Gregor81c29152008-10-29 00:13:59 +0000472 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType);
Douglas Gregorbb461502008-10-24 04:54:22 +0000473 switch (ICS.ConversionKind) {
474 case ImplicitConversionSequence::StandardConversion:
475 if (PerformImplicitConversion(From, ToType, ICS.Standard))
476 return true;
477 break;
478
479 case ImplicitConversionSequence::UserDefinedConversion:
480 // FIXME: This is, of course, wrong. We'll need to actually call
481 // the constructor or conversion operator, and then cope with the
482 // standard conversions.
483 ImpCastExprToType(From, ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000484 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000485
486 case ImplicitConversionSequence::EllipsisConversion:
487 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000488 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000489
490 case ImplicitConversionSequence::BadConversion:
491 return true;
492 }
493
494 // Everything went well.
495 return false;
496}
497
498/// PerformImplicitConversion - Perform an implicit conversion of the
499/// expression From to the type ToType by following the standard
500/// conversion sequence SCS. Returns true if there was an error, false
501/// otherwise. The expression From is replaced with the converted
502/// expression.
503bool
504Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
505 const StandardConversionSequence& SCS)
506{
507 // Overall FIXME: we are recomputing too many types here and doing
508 // far too much extra work. What this means is that we need to keep
509 // track of more information that is computed when we try the
510 // implicit conversion initially, so that we don't need to recompute
511 // anything here.
512 QualType FromType = From->getType();
513
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000514 if (SCS.CopyConstructor) {
515 // FIXME: Create a temporary object by calling the copy
516 // constructor.
517 ImpCastExprToType(From, ToType);
518 return false;
519 }
520
Douglas Gregorbb461502008-10-24 04:54:22 +0000521 // Perform the first implicit conversion.
522 switch (SCS.First) {
523 case ICK_Identity:
524 case ICK_Lvalue_To_Rvalue:
525 // Nothing to do.
526 break;
527
528 case ICK_Array_To_Pointer:
Douglas Gregor45014fd2008-11-10 20:40:00 +0000529 if (FromType->isOverloadType()) {
530 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
531 if (!Fn)
532 return true;
533
534 FixOverloadedFunctionReference(From, Fn);
535 FromType = From->getType();
536 } else {
537 FromType = Context.getArrayDecayedType(FromType);
538 }
Douglas Gregorbb461502008-10-24 04:54:22 +0000539 ImpCastExprToType(From, FromType);
540 break;
541
542 case ICK_Function_To_Pointer:
543 FromType = Context.getPointerType(FromType);
544 ImpCastExprToType(From, FromType);
545 break;
546
547 default:
548 assert(false && "Improper first standard conversion");
549 break;
550 }
551
552 // Perform the second implicit conversion
553 switch (SCS.Second) {
554 case ICK_Identity:
555 // Nothing to do.
556 break;
557
558 case ICK_Integral_Promotion:
559 case ICK_Floating_Promotion:
560 case ICK_Integral_Conversion:
561 case ICK_Floating_Conversion:
562 case ICK_Floating_Integral:
563 FromType = ToType.getUnqualifiedType();
564 ImpCastExprToType(From, FromType);
565 break;
566
567 case ICK_Pointer_Conversion:
568 if (CheckPointerConversion(From, ToType))
569 return true;
570 ImpCastExprToType(From, ToType);
571 break;
572
573 case ICK_Pointer_Member:
574 // FIXME: Implement pointer-to-member conversions.
575 assert(false && "Pointer-to-member conversions are unsupported");
576 break;
577
578 case ICK_Boolean_Conversion:
579 FromType = Context.BoolTy;
580 ImpCastExprToType(From, FromType);
581 break;
582
583 default:
584 assert(false && "Improper second standard conversion");
585 break;
586 }
587
588 switch (SCS.Third) {
589 case ICK_Identity:
590 // Nothing to do.
591 break;
592
593 case ICK_Qualification:
594 ImpCastExprToType(From, ToType);
595 break;
596
597 default:
598 assert(false && "Improper second standard conversion");
599 break;
600 }
601
602 return false;
603}
604