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