SemaExprCXX.cpp revision cd965b97cfac7b7a53a835810ec2bc2ac7a9dd1a
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/Diagnostic.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 QualType ConvType = QualType::getFromOpaquePtr(Ty); 34 QualType ConvTypeCanon = Context.getCanonicalType(ConvType); 35 DeclarationName ConvName 36 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon); 37 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen, 38 &SS); 39} 40 41/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator 42/// name (e.g., @c operator+ ) as an expression. This is very 43/// similar to ActOnIdentifierExpr, except that instead of providing 44/// an identifier the parser provides the kind of overloaded 45/// operator that was parsed. 46Sema::OwningExprResult 47Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc, 48 OverloadedOperatorKind Op, 49 bool HasTrailingLParen, 50 const CXXScopeSpec &SS) { 51 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op); 52 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS); 53} 54 55/// ActOnCXXTypeidOfType - Parse typeid( type-id ). 56Action::ExprResult 57Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 58 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 59 const NamespaceDecl *StdNs = GetStdNamespace(); 60 if (!StdNs) 61 return Diag(OpLoc, diag::err_need_header_before_typeid); 62 63 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 64 Decl *TypeInfoDecl = LookupDecl(TypeInfoII, Decl::IDNS_Tag, 65 0, StdNs, /*createBuiltins=*/false); 66 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl); 67 if (!TypeInfoRecordDecl) 68 return Diag(OpLoc, diag::err_need_header_before_typeid); 69 70 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl); 71 72 return new CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(), 73 SourceRange(OpLoc, RParenLoc)); 74} 75 76/// ActOnCXXBoolLiteral - Parse {true,false} literals. 77Action::ExprResult 78Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 79 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 80 "Unknown C++ Boolean value!"); 81 return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); 82} 83 84/// ActOnCXXThrow - Parse throw expressions. 85Action::ExprResult 86Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) { 87 return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc); 88} 89 90Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { 91 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 92 /// is a non-lvalue expression whose value is the address of the object for 93 /// which the function is called. 94 95 if (!isa<FunctionDecl>(CurContext)) { 96 Diag(ThisLoc, diag::err_invalid_this_use); 97 return ExprResult(true); 98 } 99 100 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) 101 if (MD->isInstance()) 102 return new CXXThisExpr(ThisLoc, MD->getThisType(Context)); 103 104 return Diag(ThisLoc, diag::err_invalid_this_use); 105} 106 107/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 108/// Can be interpreted either as function-style casting ("int(x)") 109/// or class type construction ("ClassType(x,y,z)") 110/// or creation of a value-initialized type ("int()"). 111Action::ExprResult 112Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep, 113 SourceLocation LParenLoc, 114 ExprTy **ExprTys, unsigned NumExprs, 115 SourceLocation *CommaLocs, 116 SourceLocation RParenLoc) { 117 assert(TypeRep && "Missing type!"); 118 QualType Ty = QualType::getFromOpaquePtr(TypeRep); 119 Expr **Exprs = (Expr**)ExprTys; 120 SourceLocation TyBeginLoc = TypeRange.getBegin(); 121 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); 122 123 // C++ [expr.type.conv]p1: 124 // If the expression list is a single expression, the type conversion 125 // expression is equivalent (in definedness, and if defined in meaning) to the 126 // corresponding cast expression. 127 // 128 if (NumExprs == 1) { 129 if (CheckCastTypes(TypeRange, Ty, Exprs[0])) 130 return true; 131 return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc, 132 Exprs[0], RParenLoc); 133 } 134 135 if (const RecordType *RT = Ty->getAsRecordType()) { 136 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 137 138 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) { 139 CXXConstructorDecl *Constructor 140 = PerformInitializationByConstructor(Ty, Exprs, NumExprs, 141 TypeRange.getBegin(), 142 SourceRange(TypeRange.getBegin(), 143 RParenLoc), 144 DeclarationName(), 145 IK_Direct); 146 147 if (!Constructor) 148 return true; 149 150 return new CXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc, 151 Exprs, NumExprs, RParenLoc); 152 } 153 154 // Fall through to value-initialize an object of class type that 155 // doesn't have a user-declared default constructor. 156 } 157 158 // C++ [expr.type.conv]p1: 159 // If the expression list specifies more than a single value, the type shall 160 // be a class with a suitably declared constructor. 161 // 162 if (NumExprs > 1) 163 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg) 164 << FullRange; 165 166 assert(NumExprs == 0 && "Expected 0 expressions"); 167 168 // C++ [expr.type.conv]p2: 169 // The expression T(), where T is a simple-type-specifier for a non-array 170 // complete object type or the (possibly cv-qualified) void type, creates an 171 // rvalue of the specified type, which is value-initialized. 172 // 173 if (Ty->isArrayType()) 174 return Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange; 175 if (!Ty->isDependentType() && Ty->isIncompleteType() && !Ty->isVoidType()) 176 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use) 177 << Ty << FullRange; 178 179 return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc); 180} 181 182 183/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: 184/// @code new (memory) int[size][4] @endcode 185/// or 186/// @code ::new Foo(23, "hello") @endcode 187/// For the interpretation of this heap of arguments, consult the base version. 188Action::ExprResult 189Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 190 SourceLocation PlacementLParen, 191 ExprTy **PlacementArgs, unsigned NumPlaceArgs, 192 SourceLocation PlacementRParen, bool ParenTypeId, 193 Declarator &D, SourceLocation ConstructorLParen, 194 ExprTy **ConstructorArgs, unsigned NumConsArgs, 195 SourceLocation ConstructorRParen) 196{ 197 // FIXME: Throughout this function, we have rather bad location information. 198 // Implementing Declarator::getSourceRange() would go a long way toward 199 // fixing that. 200 201 Expr *ArraySize = 0; 202 unsigned Skip = 0; 203 // If the specified type is an array, unwrap it and save the expression. 204 if (D.getNumTypeObjects() > 0 && 205 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 206 DeclaratorChunk &Chunk = D.getTypeObject(0); 207 if (Chunk.Arr.hasStatic) 208 return Diag(Chunk.Loc, diag::err_static_illegal_in_new); 209 if (!Chunk.Arr.NumElts) 210 return Diag(Chunk.Loc, diag::err_array_new_needs_size); 211 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 212 Skip = 1; 213 } 214 215 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip); 216 if (D.getInvalidType()) 217 return true; 218 219 if (CheckAllocatedType(AllocType, D)) 220 return true; 221 222 QualType ResultType = Context.getPointerType(AllocType); 223 224 // That every array dimension except the first is constant was already 225 // checked by the type check above. 226 227 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral 228 // or enumeration type with a non-negative value." 229 if (ArraySize) { 230 QualType SizeType = ArraySize->getType(); 231 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType()) 232 return Diag(ArraySize->getSourceRange().getBegin(), 233 diag::err_array_size_not_integral) 234 << SizeType << ArraySize->getSourceRange(); 235 // Let's see if this is a constant < 0. If so, we reject it out of hand. 236 // We don't care about special rules, so we tell the machinery it's not 237 // evaluated - it gives us a result in more cases. 238 llvm::APSInt Value; 239 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) { 240 if (Value < llvm::APSInt( 241 llvm::APInt::getNullValue(Value.getBitWidth()), false)) 242 return Diag(ArraySize->getSourceRange().getBegin(), 243 diag::err_typecheck_negative_array_size) 244 << ArraySize->getSourceRange(); 245 } 246 } 247 248 FunctionDecl *OperatorNew = 0; 249 FunctionDecl *OperatorDelete = 0; 250 Expr **PlaceArgs = (Expr**)PlacementArgs; 251 if (FindAllocationFunctions(StartLoc, UseGlobal, AllocType, ArraySize, 252 PlaceArgs, NumPlaceArgs, OperatorNew, 253 OperatorDelete)) 254 return true; 255 256 bool Init = ConstructorLParen.isValid(); 257 // --- Choosing a constructor --- 258 // C++ 5.3.4p15 259 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid) 260 // the object is not initialized. If the object, or any part of it, is 261 // const-qualified, it's an error. 262 // 2) If T is a POD and there's an empty initializer, the object is value- 263 // initialized. 264 // 3) If T is a POD and there's one initializer argument, the object is copy- 265 // constructed. 266 // 4) If T is a POD and there's more initializer arguments, it's an error. 267 // 5) If T is not a POD, the initializer arguments are used as constructor 268 // arguments. 269 // 270 // Or by the C++0x formulation: 271 // 1) If there's no initializer, the object is default-initialized according 272 // to C++0x rules. 273 // 2) Otherwise, the object is direct-initialized. 274 CXXConstructorDecl *Constructor = 0; 275 Expr **ConsArgs = (Expr**)ConstructorArgs; 276 if (const RecordType *RT = AllocType->getAsRecordType()) { 277 // FIXME: This is incorrect for when there is an empty initializer and 278 // no user-defined constructor. Must zero-initialize, not default-construct. 279 Constructor = PerformInitializationByConstructor( 280 AllocType, ConsArgs, NumConsArgs, 281 D.getDeclSpec().getSourceRange().getBegin(), 282 SourceRange(D.getDeclSpec().getSourceRange().getBegin(), 283 ConstructorRParen), 284 RT->getDecl()->getDeclName(), 285 NumConsArgs != 0 ? IK_Direct : IK_Default); 286 if (!Constructor) 287 return true; 288 } else { 289 if (!Init) { 290 // FIXME: Check that no subpart is const. 291 if (AllocType.isConstQualified()) { 292 Diag(StartLoc, diag::err_new_uninitialized_const) 293 << D.getSourceRange(); 294 return true; 295 } 296 } else if (NumConsArgs == 0) { 297 // Object is value-initialized. Do nothing. 298 } else if (NumConsArgs == 1) { 299 // Object is direct-initialized. 300 // FIXME: WHAT DeclarationName do we pass in here? 301 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc, 302 DeclarationName() /*AllocType.getAsString()*/, 303 /*DirectInit=*/true)) 304 return true; 305 } else { 306 Diag(StartLoc, diag::err_builtin_direct_init_more_than_one_arg) 307 << SourceRange(ConstructorLParen, ConstructorRParen); 308 } 309 } 310 311 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) 312 313 return new CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs, NumPlaceArgs, 314 ParenTypeId, ArraySize, Constructor, Init, 315 ConsArgs, NumConsArgs, OperatorDelete, ResultType, 316 StartLoc, Init ? ConstructorRParen : SourceLocation()); 317} 318 319/// CheckAllocatedType - Checks that a type is suitable as the allocated type 320/// in a new-expression. 321/// dimension off and stores the size expression in ArraySize. 322bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D) 323{ 324 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 325 // abstract class type or array thereof. 326 // FIXME: We don't have abstract types yet. 327 // FIXME: Under C++ semantics, an incomplete object type is still an object 328 // type. This code assumes the C semantics, where it's not. 329 if (!AllocType->isObjectType()) { 330 unsigned type; // For the select in the message. 331 if (AllocType->isFunctionType()) { 332 type = 0; 333 } else if(AllocType->isIncompleteType()) { 334 type = 1; 335 } else { 336 assert(AllocType->isReferenceType() && "What else could it be?"); 337 type = 2; 338 } 339 SourceRange TyR = D.getDeclSpec().getSourceRange(); 340 // FIXME: This is very much a guess and won't work for, e.g., pointers. 341 if (D.getNumTypeObjects() > 0) 342 TyR.setEnd(D.getTypeObject(0).Loc); 343 Diag(TyR.getBegin(), diag::err_bad_new_type) 344 << AllocType.getAsString() << type << TyR; 345 return true; 346 } 347 348 // Every dimension shall be of constant size. 349 unsigned i = 1; 350 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) { 351 if (!Array->isConstantArrayType()) { 352 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst) 353 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange(); 354 return true; 355 } 356 AllocType = Array->getElementType(); 357 ++i; 358 } 359 360 return false; 361} 362 363/// FindAllocationFunctions - Finds the overloads of operator new and delete 364/// that are appropriate for the allocation. 365bool Sema::FindAllocationFunctions(SourceLocation StartLoc, bool UseGlobal, 366 QualType AllocType, bool IsArray, 367 Expr **PlaceArgs, unsigned NumPlaceArgs, 368 FunctionDecl *&OperatorNew, 369 FunctionDecl *&OperatorDelete) 370{ 371 // --- Choosing an allocation function --- 372 // C++ 5.3.4p8 - 14 & 18 373 // 1) If UseGlobal is true, only look in the global scope. Else, also look 374 // in the scope of the allocated class. 375 // 2) If an array size is given, look for operator new[], else look for 376 // operator new. 377 // 3) The first argument is always size_t. Append the arguments from the 378 // placement form. 379 // FIXME: Also find the appropriate delete operator. 380 381 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); 382 // We don't care about the actual value of this argument. 383 // FIXME: Should the Sema create the expression and embed it in the syntax 384 // tree? Or should the consumer just recalculate the value? 385 AllocArgs[0] = new IntegerLiteral(llvm::APInt::getNullValue( 386 Context.Target.getPointerWidth(0)), 387 Context.getSizeType(), 388 SourceLocation()); 389 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); 390 391 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 392 IsArray ? OO_Array_New : OO_New); 393 if (AllocType->isRecordType() && !UseGlobal) { 394 CXXRecordDecl *Record = cast<CXXRecordType>(AllocType->getAsRecordType()) 395 ->getDecl(); 396 // FIXME: We fail to find inherited overloads. 397 if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0], 398 AllocArgs.size(), Record, /*AllowMissing=*/true, 399 OperatorNew)) 400 return true; 401 } 402 if (!OperatorNew) { 403 // Didn't find a member overload. Look for a global one. 404 DeclareGlobalNewDelete(); 405 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 406 if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0], 407 AllocArgs.size(), TUDecl, /*AllowMissing=*/false, 408 OperatorNew)) 409 return true; 410 } 411 412 // FIXME: This is leaked on error. But so much is currently in Sema that it's 413 // easier to clean it in one go. 414 AllocArgs[0]->Destroy(Context); 415 return false; 416} 417 418/// FindAllocationOverload - Find an fitting overload for the allocation 419/// function in the specified scope. 420bool Sema::FindAllocationOverload(SourceLocation StartLoc, DeclarationName Name, 421 Expr** Args, unsigned NumArgs, 422 DeclContext *Ctx, bool AllowMissing, 423 FunctionDecl *&Operator) 424{ 425 DeclContext::lookup_iterator Alloc, AllocEnd; 426 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name); 427 if (Alloc == AllocEnd) { 428 if (AllowMissing) 429 return false; 430 // FIXME: Bad location information. 431 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 432 << Name << 0; 433 } 434 435 OverloadCandidateSet Candidates; 436 for (; Alloc != AllocEnd; ++Alloc) { 437 // Even member operator new/delete are implicitly treated as 438 // static, so don't use AddMemberCandidate. 439 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) 440 AddOverloadCandidate(Fn, Args, NumArgs, Candidates, 441 /*SuppressUserConversions=*/false); 442 } 443 444 // Do the resolution. 445 OverloadCandidateSet::iterator Best; 446 switch(BestViableFunction(Candidates, Best)) { 447 case OR_Success: { 448 // Got one! 449 FunctionDecl *FnDecl = Best->Function; 450 // The first argument is size_t, and the first parameter must be size_t, 451 // too. This is checked on declaration and can be assumed. (It can't be 452 // asserted on, though, since invalid decls are left in there.) 453 for (unsigned i = 1; i < NumArgs; ++i) { 454 // FIXME: Passing word to diagnostic. 455 if (PerformCopyInitialization(Args[i-1], 456 FnDecl->getParamDecl(i)->getType(), 457 "passing")) 458 return true; 459 } 460 Operator = FnDecl; 461 return false; 462 } 463 464 case OR_No_Viable_Function: 465 if (AllowMissing) 466 return false; 467 // FIXME: Bad location information. 468 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 469 << Name << (unsigned)Candidates.size(); 470 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false); 471 return true; 472 473 case OR_Ambiguous: 474 // FIXME: Bad location information. 475 Diag(StartLoc, diag::err_ovl_ambiguous_call) 476 << Name; 477 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true); 478 return true; 479 } 480 assert(false && "Unreachable, bad result from BestViableFunction"); 481 return true; 482} 483 484 485/// DeclareGlobalNewDelete - Declare the global forms of operator new and 486/// delete. These are: 487/// @code 488/// void* operator new(std::size_t) throw(std::bad_alloc); 489/// void* operator new[](std::size_t) throw(std::bad_alloc); 490/// void operator delete(void *) throw(); 491/// void operator delete[](void *) throw(); 492/// @endcode 493/// Note that the placement and nothrow forms of new are *not* implicitly 494/// declared. Their use requires including \<new\>. 495void Sema::DeclareGlobalNewDelete() 496{ 497 if (GlobalNewDeleteDeclared) 498 return; 499 GlobalNewDeleteDeclared = true; 500 501 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 502 QualType SizeT = Context.getSizeType(); 503 504 // FIXME: Exception specifications are not added. 505 DeclareGlobalAllocationFunction( 506 Context.DeclarationNames.getCXXOperatorName(OO_New), 507 VoidPtr, SizeT); 508 DeclareGlobalAllocationFunction( 509 Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 510 VoidPtr, SizeT); 511 DeclareGlobalAllocationFunction( 512 Context.DeclarationNames.getCXXOperatorName(OO_Delete), 513 Context.VoidTy, VoidPtr); 514 DeclareGlobalAllocationFunction( 515 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 516 Context.VoidTy, VoidPtr); 517} 518 519/// DeclareGlobalAllocationFunction - Declares a single implicit global 520/// allocation function if it doesn't already exist. 521void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 522 QualType Return, QualType Argument) 523{ 524 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 525 526 // Check if this function is already declared. 527 { 528 DeclContext::lookup_iterator Alloc, AllocEnd; 529 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); 530 Alloc != AllocEnd; ++Alloc) { 531 // FIXME: Do we need to check for default arguments here? 532 FunctionDecl *Func = cast<FunctionDecl>(*Alloc); 533 if (Func->getNumParams() == 1 && 534 Context.getCanonicalType(Func->getParamDecl(0)->getType()) == Argument) 535 return; 536 } 537 } 538 539 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0); 540 FunctionDecl *Alloc = 541 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, 542 FnType, FunctionDecl::None, false, 0, 543 SourceLocation()); 544 Alloc->setImplicit(); 545 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 546 0, Argument, VarDecl::None, 0, 0); 547 Alloc->setParams(Context, &Param, 1); 548 549 // FIXME: Also add this declaration to the IdentifierResolver, but 550 // make sure it is at the end of the chain to coincide with the 551 // global scope. 552 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc); 553} 554 555/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 556/// @code ::delete ptr; @endcode 557/// or 558/// @code delete [] ptr; @endcode 559Action::ExprResult 560Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 561 bool ArrayForm, ExprTy *Operand) 562{ 563 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type 564 // having a single conversion function to a pointer type. The result has 565 // type void." 566 // DR599 amends "pointer type" to "pointer to object type" in both cases. 567 568 Expr *Ex = (Expr *)Operand; 569 QualType Type = Ex->getType(); 570 571 if (Type->isRecordType()) { 572 // FIXME: Find that one conversion function and amend the type. 573 } 574 575 if (!Type->isPointerType()) { 576 Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange(); 577 return true; 578 } 579 580 QualType Pointee = Type->getAsPointerType()->getPointeeType(); 581 if (Pointee->isIncompleteType() && !Pointee->isVoidType()) 582 Diag(StartLoc, diag::warn_delete_incomplete) 583 << Pointee << Ex->getSourceRange(); 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 // FIXME: Implement pointer-to-member conversions. 834 assert(false && "Pointer-to-member conversions are unsupported"); 835 break; 836 837 case ICK_Boolean_Conversion: 838 FromType = Context.BoolTy; 839 ImpCastExprToType(From, FromType); 840 break; 841 842 default: 843 assert(false && "Improper second standard conversion"); 844 break; 845 } 846 847 switch (SCS.Third) { 848 case ICK_Identity: 849 // Nothing to do. 850 break; 851 852 case ICK_Qualification: 853 ImpCastExprToType(From, ToType.getNonReferenceType(), 854 ToType->isReferenceType()); 855 break; 856 857 default: 858 assert(false && "Improper second standard conversion"); 859 break; 860 } 861 862 return false; 863} 864 865Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 866 SourceLocation KWLoc, 867 SourceLocation LParen, 868 TypeTy *Ty, 869 SourceLocation RParen) { 870 // FIXME: Some of the type traits have requirements. Interestingly, only the 871 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed, 872 // G++ accepts __is_pod(Incomplete) without complaints, and claims that the 873 // type is indeed a POD. 874 875 // There is no point in eagerly computing the value. The traits are designed 876 // to be used from type trait templates, so Ty will be a template parameter 877 // 99% of the time. 878 return Owned(new UnaryTypeTraitExpr(KWLoc, OTT, 879 QualType::getFromOpaquePtr(Ty), 880 RParen, Context.BoolTy)); 881} 882