SemaExprCXX.cpp revision 4c921ae760cbdd9270c16d48417d7d527eb0ceb8
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for C++ expressions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "Sema.h" 15#include "clang/AST/ExprCXX.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/Parse/DeclSpec.h" 18#include "clang/Lex/Preprocessor.h" 19#include "clang/Basic/TargetInfo.h" 20#include "llvm/ADT/STLExtras.h" 21using namespace clang; 22 23/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function 24/// name (e.g., operator void const *) as an expression. This is 25/// very similar to ActOnIdentifierExpr, except that instead of 26/// providing an identifier the parser provides the type of the 27/// conversion function. 28Sema::OwningExprResult 29Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc, 30 TypeTy *Ty, bool HasTrailingLParen, 31 const CXXScopeSpec &SS) { 32 QualType ConvType = QualType::getFromOpaquePtr(Ty); 33 QualType ConvTypeCanon = Context.getCanonicalType(ConvType); 34 DeclarationName ConvName 35 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon); 36 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen, 37 &SS); 38} 39 40/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator 41/// name (e.g., @c operator+ ) as an expression. This is very 42/// similar to ActOnIdentifierExpr, except that instead of providing 43/// an identifier the parser provides the kind of overloaded 44/// operator that was parsed. 45Sema::OwningExprResult 46Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc, 47 OverloadedOperatorKind Op, 48 bool HasTrailingLParen, 49 const CXXScopeSpec &SS) { 50 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op); 51 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS); 52} 53 54/// ActOnCXXTypeidOfType - Parse typeid( type-id ). 55Action::ExprResult 56Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 57 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 58 NamespaceDecl *StdNs = GetStdNamespace(); 59 if (!StdNs) 60 return Diag(OpLoc, diag::err_need_header_before_typeid); 61 62 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 63 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName); 64 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl); 65 if (!TypeInfoRecordDecl) 66 return Diag(OpLoc, diag::err_need_header_before_typeid); 67 68 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl); 69 70 return new CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(), 71 SourceRange(OpLoc, RParenLoc)); 72} 73 74/// ActOnCXXBoolLiteral - Parse {true,false} literals. 75Action::ExprResult 76Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 77 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 78 "Unknown C++ Boolean value!"); 79 return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); 80} 81 82/// ActOnCXXThrow - Parse throw expressions. 83Action::ExprResult 84Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) { 85 return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc); 86} 87 88Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { 89 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 90 /// is a non-lvalue expression whose value is the address of the object for 91 /// which the function is called. 92 93 if (!isa<FunctionDecl>(CurContext)) { 94 Diag(ThisLoc, diag::err_invalid_this_use); 95 return ExprResult(true); 96 } 97 98 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) 99 if (MD->isInstance()) 100 return new CXXThisExpr(ThisLoc, MD->getThisType(Context)); 101 102 return Diag(ThisLoc, diag::err_invalid_this_use); 103} 104 105/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 106/// Can be interpreted either as function-style casting ("int(x)") 107/// or class type construction ("ClassType(x,y,z)") 108/// or creation of a value-initialized type ("int()"). 109Action::ExprResult 110Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep, 111 SourceLocation LParenLoc, 112 ExprTy **ExprTys, unsigned NumExprs, 113 SourceLocation *CommaLocs, 114 SourceLocation RParenLoc) { 115 assert(TypeRep && "Missing type!"); 116 QualType Ty = QualType::getFromOpaquePtr(TypeRep); 117 Expr **Exprs = (Expr**)ExprTys; 118 SourceLocation TyBeginLoc = TypeRange.getBegin(); 119 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); 120 121 // C++ [expr.type.conv]p1: 122 // If the expression list is a single expression, the type conversion 123 // expression is equivalent (in definedness, and if defined in meaning) to the 124 // corresponding cast expression. 125 // 126 if (NumExprs == 1) { 127 if (CheckCastTypes(TypeRange, Ty, Exprs[0])) 128 return true; 129 return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc, 130 Exprs[0], RParenLoc); 131 } 132 133 if (const RecordType *RT = Ty->getAsRecordType()) { 134 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 135 136 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) { 137 CXXConstructorDecl *Constructor 138 = PerformInitializationByConstructor(Ty, Exprs, NumExprs, 139 TypeRange.getBegin(), 140 SourceRange(TypeRange.getBegin(), 141 RParenLoc), 142 DeclarationName(), 143 IK_Direct); 144 145 if (!Constructor) 146 return true; 147 148 return new CXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc, 149 Exprs, NumExprs, RParenLoc); 150 } 151 152 // Fall through to value-initialize an object of class type that 153 // doesn't have a user-declared default constructor. 154 } 155 156 // C++ [expr.type.conv]p1: 157 // If the expression list specifies more than a single value, the type shall 158 // be a class with a suitably declared constructor. 159 // 160 if (NumExprs > 1) 161 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg) 162 << FullRange; 163 164 assert(NumExprs == 0 && "Expected 0 expressions"); 165 166 // C++ [expr.type.conv]p2: 167 // The expression T(), where T is a simple-type-specifier for a non-array 168 // complete object type or the (possibly cv-qualified) void type, creates an 169 // rvalue of the specified type, which is value-initialized. 170 // 171 if (Ty->isArrayType()) 172 return Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange; 173 if (!Ty->isDependentType() && !Ty->isVoidType() && 174 DiagnoseIncompleteType(TyBeginLoc, Ty, 175 diag::err_invalid_incomplete_type_use, FullRange)) 176 return true; 177 178 return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc); 179} 180 181 182/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: 183/// @code new (memory) int[size][4] @endcode 184/// or 185/// @code ::new Foo(23, "hello") @endcode 186/// For the interpretation of this heap of arguments, consult the base version. 187Action::ExprResult 188Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 189 SourceLocation PlacementLParen, 190 ExprTy **PlacementArgs, unsigned NumPlaceArgs, 191 SourceLocation PlacementRParen, bool ParenTypeId, 192 Declarator &D, SourceLocation ConstructorLParen, 193 ExprTy **ConstructorArgs, unsigned NumConsArgs, 194 SourceLocation ConstructorRParen) 195{ 196 // FIXME: Throughout this function, we have rather bad location information. 197 // Implementing Declarator::getSourceRange() would go a long way toward 198 // fixing that. 199 200 Expr *ArraySize = 0; 201 unsigned Skip = 0; 202 // If the specified type is an array, unwrap it and save the expression. 203 if (D.getNumTypeObjects() > 0 && 204 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 205 DeclaratorChunk &Chunk = D.getTypeObject(0); 206 if (Chunk.Arr.hasStatic) 207 return Diag(Chunk.Loc, diag::err_static_illegal_in_new); 208 if (!Chunk.Arr.NumElts) 209 return Diag(Chunk.Loc, diag::err_array_new_needs_size); 210 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 211 Skip = 1; 212 } 213 214 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip); 215 if (D.getInvalidType()) 216 return true; 217 218 if (CheckAllocatedType(AllocType, D)) 219 return true; 220 221 QualType ResultType = Context.getPointerType(AllocType); 222 223 // That every array dimension except the first is constant was already 224 // checked by the type check above. 225 226 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral 227 // or enumeration type with a non-negative value." 228 if (ArraySize) { 229 QualType SizeType = ArraySize->getType(); 230 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType()) 231 return Diag(ArraySize->getSourceRange().getBegin(), 232 diag::err_array_size_not_integral) 233 << SizeType << ArraySize->getSourceRange(); 234 // Let's see if this is a constant < 0. If so, we reject it out of hand. 235 // We don't care about special rules, so we tell the machinery it's not 236 // evaluated - it gives us a result in more cases. 237 llvm::APSInt Value; 238 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) { 239 if (Value < llvm::APSInt( 240 llvm::APInt::getNullValue(Value.getBitWidth()), false)) 241 return Diag(ArraySize->getSourceRange().getBegin(), 242 diag::err_typecheck_negative_array_size) 243 << ArraySize->getSourceRange(); 244 } 245 } 246 247 FunctionDecl *OperatorNew = 0; 248 FunctionDecl *OperatorDelete = 0; 249 Expr **PlaceArgs = (Expr**)PlacementArgs; 250 if (FindAllocationFunctions(StartLoc, UseGlobal, AllocType, ArraySize, 251 PlaceArgs, NumPlaceArgs, OperatorNew, 252 OperatorDelete)) 253 return true; 254 255 bool Init = ConstructorLParen.isValid(); 256 // --- Choosing a constructor --- 257 // C++ 5.3.4p15 258 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid) 259 // the object is not initialized. If the object, or any part of it, is 260 // const-qualified, it's an error. 261 // 2) If T is a POD and there's an empty initializer, the object is value- 262 // initialized. 263 // 3) If T is a POD and there's one initializer argument, the object is copy- 264 // constructed. 265 // 4) If T is a POD and there's more initializer arguments, it's an error. 266 // 5) If T is not a POD, the initializer arguments are used as constructor 267 // arguments. 268 // 269 // Or by the C++0x formulation: 270 // 1) If there's no initializer, the object is default-initialized according 271 // to C++0x rules. 272 // 2) Otherwise, the object is direct-initialized. 273 CXXConstructorDecl *Constructor = 0; 274 Expr **ConsArgs = (Expr**)ConstructorArgs; 275 if (const RecordType *RT = AllocType->getAsRecordType()) { 276 // FIXME: This is incorrect for when there is an empty initializer and 277 // no user-defined constructor. Must zero-initialize, not default-construct. 278 Constructor = PerformInitializationByConstructor( 279 AllocType, ConsArgs, NumConsArgs, 280 D.getDeclSpec().getSourceRange().getBegin(), 281 SourceRange(D.getDeclSpec().getSourceRange().getBegin(), 282 ConstructorRParen), 283 RT->getDecl()->getDeclName(), 284 NumConsArgs != 0 ? IK_Direct : IK_Default); 285 if (!Constructor) 286 return true; 287 } else { 288 if (!Init) { 289 // FIXME: Check that no subpart is const. 290 if (AllocType.isConstQualified()) { 291 Diag(StartLoc, diag::err_new_uninitialized_const) 292 << D.getSourceRange(); 293 return true; 294 } 295 } else if (NumConsArgs == 0) { 296 // Object is value-initialized. Do nothing. 297 } else if (NumConsArgs == 1) { 298 // Object is direct-initialized. 299 // FIXME: WHAT DeclarationName do we pass in here? 300 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc, 301 DeclarationName() /*AllocType.getAsString()*/, 302 /*DirectInit=*/true)) 303 return true; 304 } else { 305 Diag(StartLoc, diag::err_builtin_direct_init_more_than_one_arg) 306 << SourceRange(ConstructorLParen, ConstructorRParen); 307 } 308 } 309 310 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) 311 312 return new CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs, NumPlaceArgs, 313 ParenTypeId, ArraySize, Constructor, Init, 314 ConsArgs, NumConsArgs, OperatorDelete, ResultType, 315 StartLoc, Init ? ConstructorRParen : SourceLocation()); 316} 317 318/// CheckAllocatedType - Checks that a type is suitable as the allocated type 319/// in a new-expression. 320/// dimension off and stores the size expression in ArraySize. 321bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D) 322{ 323 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 324 // abstract class type or array thereof. 325 // FIXME: We don't have abstract types yet. 326 // FIXME: Under C++ semantics, an incomplete object type is still an object 327 // type. This code assumes the C semantics, where it's not. 328 if (!AllocType->isObjectType()) { 329 unsigned type; // For the select in the message. 330 if (AllocType->isFunctionType()) { 331 type = 0; 332 } else if(AllocType->isIncompleteType()) { 333 type = 1; 334 } else { 335 assert(AllocType->isReferenceType() && "What else could it be?"); 336 type = 2; 337 } 338 SourceRange TyR = D.getDeclSpec().getSourceRange(); 339 // FIXME: This is very much a guess and won't work for, e.g., pointers. 340 if (D.getNumTypeObjects() > 0) 341 TyR.setEnd(D.getTypeObject(0).Loc); 342 Diag(TyR.getBegin(), diag::err_bad_new_type) 343 << AllocType.getAsString() << type << TyR; 344 return true; 345 } 346 347 // Every dimension shall be of constant size. 348 unsigned i = 1; 349 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) { 350 if (!Array->isConstantArrayType()) { 351 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst) 352 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange(); 353 return true; 354 } 355 AllocType = Array->getElementType(); 356 ++i; 357 } 358 359 return false; 360} 361 362/// FindAllocationFunctions - Finds the overloads of operator new and delete 363/// that are appropriate for the allocation. 364bool Sema::FindAllocationFunctions(SourceLocation StartLoc, bool UseGlobal, 365 QualType AllocType, bool IsArray, 366 Expr **PlaceArgs, unsigned NumPlaceArgs, 367 FunctionDecl *&OperatorNew, 368 FunctionDecl *&OperatorDelete) 369{ 370 // --- Choosing an allocation function --- 371 // C++ 5.3.4p8 - 14 & 18 372 // 1) If UseGlobal is true, only look in the global scope. Else, also look 373 // in the scope of the allocated class. 374 // 2) If an array size is given, look for operator new[], else look for 375 // operator new. 376 // 3) The first argument is always size_t. Append the arguments from the 377 // placement form. 378 // FIXME: Also find the appropriate delete operator. 379 380 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); 381 // We don't care about the actual value of this argument. 382 // FIXME: Should the Sema create the expression and embed it in the syntax 383 // tree? Or should the consumer just recalculate the value? 384 AllocArgs[0] = new IntegerLiteral(llvm::APInt::getNullValue( 385 Context.Target.getPointerWidth(0)), 386 Context.getSizeType(), 387 SourceLocation()); 388 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); 389 390 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 391 IsArray ? OO_Array_New : OO_New); 392 if (AllocType->isRecordType() && !UseGlobal) { 393 CXXRecordDecl *Record = cast<CXXRecordType>(AllocType->getAsRecordType()) 394 ->getDecl(); 395 // FIXME: We fail to find inherited overloads. 396 if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0], 397 AllocArgs.size(), Record, /*AllowMissing=*/true, 398 OperatorNew)) 399 return true; 400 } 401 if (!OperatorNew) { 402 // Didn't find a member overload. Look for a global one. 403 DeclareGlobalNewDelete(); 404 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 405 if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0], 406 AllocArgs.size(), TUDecl, /*AllowMissing=*/false, 407 OperatorNew)) 408 return true; 409 } 410 411 // FIXME: This is leaked on error. But so much is currently in Sema that it's 412 // easier to clean it in one go. 413 AllocArgs[0]->Destroy(Context); 414 return false; 415} 416 417/// FindAllocationOverload - Find an fitting overload for the allocation 418/// function in the specified scope. 419bool Sema::FindAllocationOverload(SourceLocation StartLoc, DeclarationName Name, 420 Expr** Args, unsigned NumArgs, 421 DeclContext *Ctx, bool AllowMissing, 422 FunctionDecl *&Operator) 423{ 424 DeclContext::lookup_iterator Alloc, AllocEnd; 425 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name); 426 if (Alloc == AllocEnd) { 427 if (AllowMissing) 428 return false; 429 // FIXME: Bad location information. 430 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 431 << Name << 0; 432 } 433 434 OverloadCandidateSet Candidates; 435 for (; Alloc != AllocEnd; ++Alloc) { 436 // Even member operator new/delete are implicitly treated as 437 // static, so don't use AddMemberCandidate. 438 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) 439 AddOverloadCandidate(Fn, Args, NumArgs, Candidates, 440 /*SuppressUserConversions=*/false); 441 } 442 443 // Do the resolution. 444 OverloadCandidateSet::iterator Best; 445 switch(BestViableFunction(Candidates, Best)) { 446 case OR_Success: { 447 // Got one! 448 FunctionDecl *FnDecl = Best->Function; 449 // The first argument is size_t, and the first parameter must be size_t, 450 // too. This is checked on declaration and can be assumed. (It can't be 451 // asserted on, though, since invalid decls are left in there.) 452 for (unsigned i = 1; i < NumArgs; ++i) { 453 // FIXME: Passing word to diagnostic. 454 if (PerformCopyInitialization(Args[i-1], 455 FnDecl->getParamDecl(i)->getType(), 456 "passing")) 457 return true; 458 } 459 Operator = FnDecl; 460 return false; 461 } 462 463 case OR_No_Viable_Function: 464 if (AllowMissing) 465 return false; 466 // FIXME: Bad location information. 467 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 468 << Name << (unsigned)Candidates.size(); 469 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false); 470 return true; 471 472 case OR_Ambiguous: 473 // FIXME: Bad location information. 474 Diag(StartLoc, diag::err_ovl_ambiguous_call) 475 << Name; 476 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true); 477 return true; 478 } 479 assert(false && "Unreachable, bad result from BestViableFunction"); 480 return true; 481} 482 483 484/// DeclareGlobalNewDelete - Declare the global forms of operator new and 485/// delete. These are: 486/// @code 487/// void* operator new(std::size_t) throw(std::bad_alloc); 488/// void* operator new[](std::size_t) throw(std::bad_alloc); 489/// void operator delete(void *) throw(); 490/// void operator delete[](void *) throw(); 491/// @endcode 492/// Note that the placement and nothrow forms of new are *not* implicitly 493/// declared. Their use requires including \<new\>. 494void Sema::DeclareGlobalNewDelete() 495{ 496 if (GlobalNewDeleteDeclared) 497 return; 498 GlobalNewDeleteDeclared = true; 499 500 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 501 QualType SizeT = Context.getSizeType(); 502 503 // FIXME: Exception specifications are not added. 504 DeclareGlobalAllocationFunction( 505 Context.DeclarationNames.getCXXOperatorName(OO_New), 506 VoidPtr, SizeT); 507 DeclareGlobalAllocationFunction( 508 Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 509 VoidPtr, SizeT); 510 DeclareGlobalAllocationFunction( 511 Context.DeclarationNames.getCXXOperatorName(OO_Delete), 512 Context.VoidTy, VoidPtr); 513 DeclareGlobalAllocationFunction( 514 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 515 Context.VoidTy, VoidPtr); 516} 517 518/// DeclareGlobalAllocationFunction - Declares a single implicit global 519/// allocation function if it doesn't already exist. 520void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 521 QualType Return, QualType Argument) 522{ 523 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 524 525 // Check if this function is already declared. 526 { 527 DeclContext::lookup_iterator Alloc, AllocEnd; 528 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); 529 Alloc != AllocEnd; ++Alloc) { 530 // FIXME: Do we need to check for default arguments here? 531 FunctionDecl *Func = cast<FunctionDecl>(*Alloc); 532 if (Func->getNumParams() == 1 && 533 Context.getCanonicalType(Func->getParamDecl(0)->getType()) == Argument) 534 return; 535 } 536 } 537 538 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0); 539 FunctionDecl *Alloc = 540 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, 541 FnType, FunctionDecl::None, false, 542 SourceLocation()); 543 Alloc->setImplicit(); 544 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 545 0, Argument, VarDecl::None, 0); 546 Alloc->setParams(Context, &Param, 1); 547 548 // FIXME: Also add this declaration to the IdentifierResolver, but 549 // make sure it is at the end of the chain to coincide with the 550 // global scope. 551 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc); 552} 553 554/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 555/// @code ::delete ptr; @endcode 556/// or 557/// @code delete [] ptr; @endcode 558Action::ExprResult 559Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 560 bool ArrayForm, ExprTy *Operand) 561{ 562 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type 563 // having a single conversion function to a pointer type. The result has 564 // type void." 565 // DR599 amends "pointer type" to "pointer to object type" in both cases. 566 567 Expr *Ex = (Expr *)Operand; 568 QualType Type = Ex->getType(); 569 570 if (Type->isRecordType()) { 571 // FIXME: Find that one conversion function and amend the type. 572 } 573 574 if (!Type->isPointerType()) { 575 Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange(); 576 return true; 577 } 578 579 QualType Pointee = Type->getAsPointerType()->getPointeeType(); 580 if (!Pointee->isVoidType() && 581 DiagnoseIncompleteType(StartLoc, Pointee, diag::warn_delete_incomplete, 582 Ex->getSourceRange())) 583 return true; 584 else if (!Pointee->isObjectType()) { 585 Diag(StartLoc, diag::err_delete_operand) 586 << Type << Ex->getSourceRange(); 587 return true; 588 } 589 590 // FIXME: Look up the correct operator delete overload and pass a pointer 591 // along. 592 // FIXME: Check access and ambiguity of operator delete and destructor. 593 594 return new CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 0, Ex, 595 StartLoc); 596} 597 598 599/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 600/// C++ if/switch/while/for statement. 601/// e.g: "if (int x = f()) {...}" 602Action::ExprResult 603Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc, 604 Declarator &D, 605 SourceLocation EqualLoc, 606 ExprTy *AssignExprVal) { 607 assert(AssignExprVal && "Null assignment expression"); 608 609 // C++ 6.4p2: 610 // The declarator shall not specify a function or an array. 611 // The type-specifier-seq shall not contain typedef and shall not declare a 612 // new class or enumeration. 613 614 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 615 "Parser allowed 'typedef' as storage class of condition decl."); 616 617 QualType Ty = GetTypeForDeclarator(D, S); 618 619 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 620 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 621 // would be created and CXXConditionDeclExpr wants a VarDecl. 622 return Diag(StartLoc, diag::err_invalid_use_of_function_type) 623 << SourceRange(StartLoc, EqualLoc); 624 } else if (Ty->isArrayType()) { // ...or an array. 625 Diag(StartLoc, diag::err_invalid_use_of_array_type) 626 << SourceRange(StartLoc, EqualLoc); 627 } else if (const RecordType *RT = Ty->getAsRecordType()) { 628 RecordDecl *RD = RT->getDecl(); 629 // The type-specifier-seq shall not declare a new class... 630 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD))) 631 Diag(RD->getLocation(), diag::err_type_defined_in_condition); 632 } else if (const EnumType *ET = Ty->getAsEnumType()) { 633 EnumDecl *ED = ET->getDecl(); 634 // ...or enumeration. 635 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED))) 636 Diag(ED->getLocation(), diag::err_type_defined_in_condition); 637 } 638 639 DeclTy *Dcl = ActOnDeclarator(S, D, 0); 640 if (!Dcl) 641 return true; 642 AddInitializerToDecl(Dcl, ExprArg(*this, AssignExprVal)); 643 644 // Mark this variable as one that is declared within a conditional. 645 if (VarDecl *VD = dyn_cast<VarDecl>((Decl *)Dcl)) 646 VD->setDeclaredInCondition(true); 647 648 return new CXXConditionDeclExpr(StartLoc, EqualLoc, 649 cast<VarDecl>(static_cast<Decl *>(Dcl))); 650} 651 652/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 653bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { 654 // C++ 6.4p4: 655 // The value of a condition that is an initialized declaration in a statement 656 // other than a switch statement is the value of the declared variable 657 // implicitly converted to type bool. If that conversion is ill-formed, the 658 // program is ill-formed. 659 // The value of a condition that is an expression is the value of the 660 // expression, implicitly converted to bool. 661 // 662 return PerformContextuallyConvertToBool(CondExpr); 663} 664 665/// Helper function to determine whether this is the (deprecated) C++ 666/// conversion from a string literal to a pointer to non-const char or 667/// non-const wchar_t (for narrow and wide string literals, 668/// respectively). 669bool 670Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 671 // Look inside the implicit cast, if it exists. 672 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 673 From = Cast->getSubExpr(); 674 675 // A string literal (2.13.4) that is not a wide string literal can 676 // be converted to an rvalue of type "pointer to char"; a wide 677 // string literal can be converted to an rvalue of type "pointer 678 // to wchar_t" (C++ 4.2p2). 679 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From)) 680 if (const PointerType *ToPtrType = ToType->getAsPointerType()) 681 if (const BuiltinType *ToPointeeType 682 = ToPtrType->getPointeeType()->getAsBuiltinType()) { 683 // This conversion is considered only when there is an 684 // explicit appropriate pointer target type (C++ 4.2p2). 685 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 && 686 ((StrLit->isWide() && ToPointeeType->isWideCharType()) || 687 (!StrLit->isWide() && 688 (ToPointeeType->getKind() == BuiltinType::Char_U || 689 ToPointeeType->getKind() == BuiltinType::Char_S)))) 690 return true; 691 } 692 693 return false; 694} 695 696/// PerformImplicitConversion - Perform an implicit conversion of the 697/// expression From to the type ToType. Returns true if there was an 698/// error, false otherwise. The expression From is replaced with the 699/// converted expression. Flavor is the kind of conversion we're 700/// performing, used in the error message. If @p AllowExplicit, 701/// explicit user-defined conversions are permitted. 702bool 703Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 704 const char *Flavor, bool AllowExplicit) 705{ 706 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType, false, 707 AllowExplicit); 708 return PerformImplicitConversion(From, ToType, ICS, Flavor); 709} 710 711/// PerformImplicitConversion - Perform an implicit conversion of the 712/// expression From to the type ToType using the pre-computed implicit 713/// conversion sequence ICS. Returns true if there was an error, false 714/// otherwise. The expression From is replaced with the converted 715/// expression. Flavor is the kind of conversion we're performing, 716/// used in the error message. 717bool 718Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 719 const ImplicitConversionSequence &ICS, 720 const char* Flavor) { 721 switch (ICS.ConversionKind) { 722 case ImplicitConversionSequence::StandardConversion: 723 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor)) 724 return true; 725 break; 726 727 case ImplicitConversionSequence::UserDefinedConversion: 728 // FIXME: This is, of course, wrong. We'll need to actually call 729 // the constructor or conversion operator, and then cope with the 730 // standard conversions. 731 ImpCastExprToType(From, ToType.getNonReferenceType(), 732 ToType->isReferenceType()); 733 return false; 734 735 case ImplicitConversionSequence::EllipsisConversion: 736 assert(false && "Cannot perform an ellipsis conversion"); 737 return false; 738 739 case ImplicitConversionSequence::BadConversion: 740 return true; 741 } 742 743 // Everything went well. 744 return false; 745} 746 747/// PerformImplicitConversion - Perform an implicit conversion of the 748/// expression From to the type ToType by following the standard 749/// conversion sequence SCS. Returns true if there was an error, false 750/// otherwise. The expression From is replaced with the converted 751/// expression. Flavor is the context in which we're performing this 752/// conversion, for use in error messages. 753bool 754Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 755 const StandardConversionSequence& SCS, 756 const char *Flavor) { 757 // Overall FIXME: we are recomputing too many types here and doing 758 // far too much extra work. What this means is that we need to keep 759 // track of more information that is computed when we try the 760 // implicit conversion initially, so that we don't need to recompute 761 // anything here. 762 QualType FromType = From->getType(); 763 764 if (SCS.CopyConstructor) { 765 // FIXME: Create a temporary object by calling the copy 766 // constructor. 767 ImpCastExprToType(From, ToType.getNonReferenceType(), 768 ToType->isReferenceType()); 769 return false; 770 } 771 772 // Perform the first implicit conversion. 773 switch (SCS.First) { 774 case ICK_Identity: 775 case ICK_Lvalue_To_Rvalue: 776 // Nothing to do. 777 break; 778 779 case ICK_Array_To_Pointer: 780 if (FromType->isOverloadType()) { 781 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true); 782 if (!Fn) 783 return true; 784 785 FixOverloadedFunctionReference(From, Fn); 786 FromType = From->getType(); 787 } else { 788 FromType = Context.getArrayDecayedType(FromType); 789 } 790 ImpCastExprToType(From, FromType); 791 break; 792 793 case ICK_Function_To_Pointer: 794 FromType = Context.getPointerType(FromType); 795 ImpCastExprToType(From, FromType); 796 break; 797 798 default: 799 assert(false && "Improper first standard conversion"); 800 break; 801 } 802 803 // Perform the second implicit conversion 804 switch (SCS.Second) { 805 case ICK_Identity: 806 // Nothing to do. 807 break; 808 809 case ICK_Integral_Promotion: 810 case ICK_Floating_Promotion: 811 case ICK_Integral_Conversion: 812 case ICK_Floating_Conversion: 813 case ICK_Floating_Integral: 814 FromType = ToType.getUnqualifiedType(); 815 ImpCastExprToType(From, FromType); 816 break; 817 818 case ICK_Pointer_Conversion: 819 if (SCS.IncompatibleObjC) { 820 // Diagnose incompatible Objective-C conversions 821 Diag(From->getSourceRange().getBegin(), 822 diag::ext_typecheck_convert_incompatible_pointer) 823 << From->getType() << ToType << Flavor 824 << From->getSourceRange(); 825 } 826 827 if (CheckPointerConversion(From, ToType)) 828 return true; 829 ImpCastExprToType(From, ToType); 830 break; 831 832 case ICK_Pointer_Member: 833 if (CheckMemberPointerConversion(From, ToType)) 834 return true; 835 ImpCastExprToType(From, ToType); 836 break; 837 838 case ICK_Boolean_Conversion: 839 FromType = Context.BoolTy; 840 ImpCastExprToType(From, FromType); 841 break; 842 843 default: 844 assert(false && "Improper second standard conversion"); 845 break; 846 } 847 848 switch (SCS.Third) { 849 case ICK_Identity: 850 // Nothing to do. 851 break; 852 853 case ICK_Qualification: 854 ImpCastExprToType(From, ToType.getNonReferenceType(), 855 ToType->isReferenceType()); 856 break; 857 858 default: 859 assert(false && "Improper second standard conversion"); 860 break; 861 } 862 863 return false; 864} 865 866Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 867 SourceLocation KWLoc, 868 SourceLocation LParen, 869 TypeTy *Ty, 870 SourceLocation RParen) { 871 // FIXME: Some of the type traits have requirements. Interestingly, only the 872 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed, 873 // G++ accepts __is_pod(Incomplete) without complaints, and claims that the 874 // type is indeed a POD. 875 876 // There is no point in eagerly computing the value. The traits are designed 877 // to be used from type trait templates, so Ty will be a template parameter 878 // 99% of the time. 879 return Owned(new UnaryTypeTraitExpr(KWLoc, OTT, 880 QualType::getFromOpaquePtr(Ty), 881 RParen, Context.BoolTy)); 882} 883