SemaExprCXX.cpp revision 7498e50aea92276fdd8aceb7076b4156ee6dbab4
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/ASTContext.h" 17#include "clang/AST/ExprCXX.h" 18#include "clang/Basic/PartialDiagnostic.h" 19#include "clang/Basic/TargetInfo.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/Parse/DeclSpec.h" 22#include "llvm/ADT/STLExtras.h" 23using namespace clang; 24 25/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function 26/// name (e.g., operator void const *) as an expression. This is 27/// very similar to ActOnIdentifierExpr, except that instead of 28/// providing an identifier the parser provides the type of the 29/// conversion function. 30Sema::OwningExprResult 31Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc, 32 TypeTy *Ty, bool HasTrailingLParen, 33 const CXXScopeSpec &SS, 34 bool isAddressOfOperand) { 35 //FIXME: Preserve type source info. 36 QualType ConvType = GetTypeFromParser(Ty); 37 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType); 38 DeclarationName ConvName 39 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon); 40 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen, 41 &SS, isAddressOfOperand); 42} 43 44/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator 45/// name (e.g., @c operator+ ) as an expression. This is very 46/// similar to ActOnIdentifierExpr, except that instead of providing 47/// an identifier the parser provides the kind of overloaded 48/// operator that was parsed. 49Sema::OwningExprResult 50Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc, 51 OverloadedOperatorKind Op, 52 bool HasTrailingLParen, 53 const CXXScopeSpec &SS, 54 bool isAddressOfOperand) { 55 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op); 56 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS, 57 isAddressOfOperand); 58} 59 60/// ActOnCXXTypeidOfType - Parse typeid( type-id ). 61Action::OwningExprResult 62Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 63 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 64 if (!StdNamespace) 65 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 66 67 if (isType) 68 // FIXME: Preserve type source info. 69 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr(); 70 71 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 72 Decl *TypeInfoDecl = LookupQualifiedName(StdNamespace, TypeInfoII, 73 LookupTagName); 74 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl); 75 if (!TypeInfoRecordDecl) 76 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 77 78 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl); 79 80 if (!isType) { 81 // C++0x [expr.typeid]p3: 82 // When typeid is applied to an expression other than an lvalue of a 83 // polymorphic class type [...] [the] expression is an unevaluated 84 // operand. 85 86 // FIXME: if the type of the expression is a class type, the class 87 // shall be completely defined. 88 bool isUnevaluatedOperand = true; 89 Expr *E = static_cast<Expr *>(TyOrExpr); 90 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) { 91 QualType T = E->getType(); 92 if (const RecordType *RecordT = T->getAs<RecordType>()) { 93 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 94 if (RecordD->isPolymorphic()) 95 isUnevaluatedOperand = false; 96 } 97 } 98 99 // If this is an unevaluated operand, clear out the set of declaration 100 // references we have been computing. 101 if (isUnevaluatedOperand) 102 PotentiallyReferencedDeclStack.back().clear(); 103 } 104 105 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr, 106 TypeInfoType.withConst(), 107 SourceRange(OpLoc, RParenLoc))); 108} 109 110/// ActOnCXXBoolLiteral - Parse {true,false} literals. 111Action::OwningExprResult 112Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 113 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 114 "Unknown C++ Boolean value!"); 115 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, 116 Context.BoolTy, OpLoc)); 117} 118 119/// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 120Action::OwningExprResult 121Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 122 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc)); 123} 124 125/// ActOnCXXThrow - Parse throw expressions. 126Action::OwningExprResult 127Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) { 128 Expr *Ex = E.takeAs<Expr>(); 129 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex)) 130 return ExprError(); 131 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc)); 132} 133 134/// CheckCXXThrowOperand - Validate the operand of a throw. 135bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) { 136 // C++ [except.throw]p3: 137 // [...] adjusting the type from "array of T" or "function returning T" 138 // to "pointer to T" or "pointer to function returning T", [...] 139 DefaultFunctionArrayConversion(E); 140 141 // If the type of the exception would be an incomplete type or a pointer 142 // to an incomplete type other than (cv) void the program is ill-formed. 143 QualType Ty = E->getType(); 144 int isPointer = 0; 145 if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 146 Ty = Ptr->getPointeeType(); 147 isPointer = 1; 148 } 149 if (!isPointer || !Ty->isVoidType()) { 150 if (RequireCompleteType(ThrowLoc, Ty, 151 PDiag(isPointer ? diag::err_throw_incomplete_ptr 152 : diag::err_throw_incomplete) 153 << E->getSourceRange())) 154 return true; 155 } 156 157 // FIXME: Construct a temporary here. 158 return false; 159} 160 161Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { 162 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 163 /// is a non-lvalue expression whose value is the address of the object for 164 /// which the function is called. 165 166 if (!isa<FunctionDecl>(CurContext)) 167 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); 168 169 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) 170 if (MD->isInstance()) 171 return Owned(new (Context) CXXThisExpr(ThisLoc, 172 MD->getThisType(Context))); 173 174 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); 175} 176 177/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 178/// Can be interpreted either as function-style casting ("int(x)") 179/// or class type construction ("ClassType(x,y,z)") 180/// or creation of a value-initialized type ("int()"). 181Action::OwningExprResult 182Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep, 183 SourceLocation LParenLoc, 184 MultiExprArg exprs, 185 SourceLocation *CommaLocs, 186 SourceLocation RParenLoc) { 187 assert(TypeRep && "Missing type!"); 188 // FIXME: Preserve type source info. 189 QualType Ty = GetTypeFromParser(TypeRep); 190 unsigned NumExprs = exprs.size(); 191 Expr **Exprs = (Expr**)exprs.get(); 192 SourceLocation TyBeginLoc = TypeRange.getBegin(); 193 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); 194 195 if (Ty->isDependentType() || 196 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) { 197 exprs.release(); 198 199 return Owned(CXXUnresolvedConstructExpr::Create(Context, 200 TypeRange.getBegin(), Ty, 201 LParenLoc, 202 Exprs, NumExprs, 203 RParenLoc)); 204 } 205 206 if (Ty->isArrayType()) 207 return ExprError(Diag(TyBeginLoc, 208 diag::err_value_init_for_array_type) << FullRange); 209 if (!Ty->isVoidType() && 210 RequireCompleteType(TyBeginLoc, Ty, 211 PDiag(diag::err_invalid_incomplete_type_use) 212 << FullRange)) 213 return ExprError(); 214 215 if (RequireNonAbstractType(TyBeginLoc, Ty, 216 diag::err_allocation_of_abstract_type)) 217 return ExprError(); 218 219 220 // C++ [expr.type.conv]p1: 221 // If the expression list is a single expression, the type conversion 222 // expression is equivalent (in definedness, and if defined in meaning) to the 223 // corresponding cast expression. 224 // 225 if (NumExprs == 1) { 226 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 227 CXXMethodDecl *Method = 0; 228 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method, 229 /*FunctionalStyle=*/true)) 230 return ExprError(); 231 232 exprs.release(); 233 if (Method) { 234 OwningExprResult CastArg 235 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(), 236 Kind, Method, Owned(Exprs[0])); 237 if (CastArg.isInvalid()) 238 return ExprError(); 239 240 Exprs[0] = CastArg.takeAs<Expr>(); 241 } 242 243 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(), 244 Ty, TyBeginLoc, Kind, 245 Exprs[0], RParenLoc)); 246 } 247 248 if (const RecordType *RT = Ty->getAs<RecordType>()) { 249 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 250 251 if (NumExprs > 1 || !Record->hasTrivialConstructor() || 252 !Record->hasTrivialDestructor()) { 253 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 254 255 CXXConstructorDecl *Constructor 256 = PerformInitializationByConstructor(Ty, move(exprs), 257 TypeRange.getBegin(), 258 SourceRange(TypeRange.getBegin(), 259 RParenLoc), 260 DeclarationName(), 261 IK_Direct, 262 ConstructorArgs); 263 264 if (!Constructor) 265 return ExprError(); 266 267 OwningExprResult Result = 268 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc, 269 move_arg(ConstructorArgs), RParenLoc); 270 if (Result.isInvalid()) 271 return ExprError(); 272 273 return MaybeBindToTemporary(Result.takeAs<Expr>()); 274 } 275 276 // Fall through to value-initialize an object of class type that 277 // doesn't have a user-declared default constructor. 278 } 279 280 // C++ [expr.type.conv]p1: 281 // If the expression list specifies more than a single value, the type shall 282 // be a class with a suitably declared constructor. 283 // 284 if (NumExprs > 1) 285 return ExprError(Diag(CommaLocs[0], 286 diag::err_builtin_func_cast_more_than_one_arg) 287 << FullRange); 288 289 assert(NumExprs == 0 && "Expected 0 expressions"); 290 291 // C++ [expr.type.conv]p2: 292 // The expression T(), where T is a simple-type-specifier for a non-array 293 // complete object type or the (possibly cv-qualified) void type, creates an 294 // rvalue of the specified type, which is value-initialized. 295 // 296 exprs.release(); 297 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc)); 298} 299 300 301/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: 302/// @code new (memory) int[size][4] @endcode 303/// or 304/// @code ::new Foo(23, "hello") @endcode 305/// For the interpretation of this heap of arguments, consult the base version. 306Action::OwningExprResult 307Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 308 SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 309 SourceLocation PlacementRParen, bool ParenTypeId, 310 Declarator &D, SourceLocation ConstructorLParen, 311 MultiExprArg ConstructorArgs, 312 SourceLocation ConstructorRParen) { 313 Expr *ArraySize = 0; 314 unsigned Skip = 0; 315 // If the specified type is an array, unwrap it and save the expression. 316 if (D.getNumTypeObjects() > 0 && 317 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 318 DeclaratorChunk &Chunk = D.getTypeObject(0); 319 if (Chunk.Arr.hasStatic) 320 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 321 << D.getSourceRange()); 322 if (!Chunk.Arr.NumElts) 323 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 324 << D.getSourceRange()); 325 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 326 Skip = 1; 327 } 328 329 // Every dimension shall be of constant size. 330 if (D.getNumTypeObjects() > 0 && 331 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 332 for (unsigned I = 1, N = D.getNumTypeObjects(); I < N; ++I) { 333 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 334 break; 335 336 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 337 if (Expr *NumElts = (Expr *)Array.NumElts) { 338 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() && 339 !NumElts->isIntegerConstantExpr(Context)) { 340 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst) 341 << NumElts->getSourceRange(); 342 return ExprError(); 343 } 344 } 345 } 346 } 347 348 //FIXME: Store DeclaratorInfo in CXXNew expression. 349 DeclaratorInfo *DInfo = 0; 350 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip); 351 if (D.isInvalidType()) 352 return ExprError(); 353 354 return BuildCXXNew(StartLoc, UseGlobal, 355 PlacementLParen, 356 move(PlacementArgs), 357 PlacementRParen, 358 ParenTypeId, 359 AllocType, 360 D.getSourceRange().getBegin(), 361 D.getSourceRange(), 362 Owned(ArraySize), 363 ConstructorLParen, 364 move(ConstructorArgs), 365 ConstructorRParen); 366} 367 368Sema::OwningExprResult 369Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, 370 SourceLocation PlacementLParen, 371 MultiExprArg PlacementArgs, 372 SourceLocation PlacementRParen, 373 bool ParenTypeId, 374 QualType AllocType, 375 SourceLocation TypeLoc, 376 SourceRange TypeRange, 377 ExprArg ArraySizeE, 378 SourceLocation ConstructorLParen, 379 MultiExprArg ConstructorArgs, 380 SourceLocation ConstructorRParen) { 381 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange)) 382 return ExprError(); 383 384 QualType ResultType = Context.getPointerType(AllocType); 385 386 // That every array dimension except the first is constant was already 387 // checked by the type check above. 388 389 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral 390 // or enumeration type with a non-negative value." 391 Expr *ArraySize = (Expr *)ArraySizeE.get(); 392 if (ArraySize && !ArraySize->isTypeDependent()) { 393 QualType SizeType = ArraySize->getType(); 394 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType()) 395 return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 396 diag::err_array_size_not_integral) 397 << SizeType << ArraySize->getSourceRange()); 398 // Let's see if this is a constant < 0. If so, we reject it out of hand. 399 // We don't care about special rules, so we tell the machinery it's not 400 // evaluated - it gives us a result in more cases. 401 if (!ArraySize->isValueDependent()) { 402 llvm::APSInt Value; 403 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) { 404 if (Value < llvm::APSInt( 405 llvm::APInt::getNullValue(Value.getBitWidth()), 406 Value.isUnsigned())) 407 return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 408 diag::err_typecheck_negative_array_size) 409 << ArraySize->getSourceRange()); 410 } 411 } 412 413 ImpCastExprToType(ArraySize, Context.getSizeType()); 414 } 415 416 FunctionDecl *OperatorNew = 0; 417 FunctionDecl *OperatorDelete = 0; 418 Expr **PlaceArgs = (Expr**)PlacementArgs.get(); 419 unsigned NumPlaceArgs = PlacementArgs.size(); 420 if (!AllocType->isDependentType() && 421 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) && 422 FindAllocationFunctions(StartLoc, 423 SourceRange(PlacementLParen, PlacementRParen), 424 UseGlobal, AllocType, ArraySize, PlaceArgs, 425 NumPlaceArgs, OperatorNew, OperatorDelete)) 426 return ExprError(); 427 428 bool Init = ConstructorLParen.isValid(); 429 // --- Choosing a constructor --- 430 // C++ 5.3.4p15 431 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid) 432 // the object is not initialized. If the object, or any part of it, is 433 // const-qualified, it's an error. 434 // 2) If T is a POD and there's an empty initializer, the object is value- 435 // initialized. 436 // 3) If T is a POD and there's one initializer argument, the object is copy- 437 // constructed. 438 // 4) If T is a POD and there's more initializer arguments, it's an error. 439 // 5) If T is not a POD, the initializer arguments are used as constructor 440 // arguments. 441 // 442 // Or by the C++0x formulation: 443 // 1) If there's no initializer, the object is default-initialized according 444 // to C++0x rules. 445 // 2) Otherwise, the object is direct-initialized. 446 CXXConstructorDecl *Constructor = 0; 447 Expr **ConsArgs = (Expr**)ConstructorArgs.get(); 448 const RecordType *RT; 449 unsigned NumConsArgs = ConstructorArgs.size(); 450 if (AllocType->isDependentType()) { 451 // Skip all the checks. 452 } else if ((RT = AllocType->getAs<RecordType>()) && 453 !AllocType->isAggregateType()) { 454 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this); 455 456 Constructor = PerformInitializationByConstructor( 457 AllocType, move(ConstructorArgs), 458 TypeLoc, 459 SourceRange(TypeLoc, ConstructorRParen), 460 RT->getDecl()->getDeclName(), 461 NumConsArgs != 0 ? IK_Direct : IK_Default, 462 ConvertedConstructorArgs); 463 if (!Constructor) 464 return ExprError(); 465 466 // Take the converted constructor arguments and use them for the new 467 // expression. 468 NumConsArgs = ConvertedConstructorArgs.size(); 469 ConsArgs = (Expr **)ConvertedConstructorArgs.take(); 470 } else { 471 if (!Init) { 472 // FIXME: Check that no subpart is const. 473 if (AllocType.isConstQualified()) 474 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const) 475 << TypeRange); 476 } else if (NumConsArgs == 0) { 477 // Object is value-initialized. Do nothing. 478 } else if (NumConsArgs == 1) { 479 // Object is direct-initialized. 480 // FIXME: What DeclarationName do we pass in here? 481 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc, 482 DeclarationName() /*AllocType.getAsString()*/, 483 /*DirectInit=*/true)) 484 return ExprError(); 485 } else { 486 return ExprError(Diag(StartLoc, 487 diag::err_builtin_direct_init_more_than_one_arg) 488 << SourceRange(ConstructorLParen, ConstructorRParen)); 489 } 490 } 491 492 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) 493 494 PlacementArgs.release(); 495 ConstructorArgs.release(); 496 ArraySizeE.release(); 497 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs, 498 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init, 499 ConsArgs, NumConsArgs, OperatorDelete, ResultType, 500 StartLoc, Init ? ConstructorRParen : SourceLocation())); 501} 502 503/// CheckAllocatedType - Checks that a type is suitable as the allocated type 504/// in a new-expression. 505/// dimension off and stores the size expression in ArraySize. 506bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 507 SourceRange R) { 508 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 509 // abstract class type or array thereof. 510 if (AllocType->isFunctionType()) 511 return Diag(Loc, diag::err_bad_new_type) 512 << AllocType << 0 << R; 513 else if (AllocType->isReferenceType()) 514 return Diag(Loc, diag::err_bad_new_type) 515 << AllocType << 1 << R; 516 else if (!AllocType->isDependentType() && 517 RequireCompleteType(Loc, AllocType, 518 PDiag(diag::err_new_incomplete_type) 519 << R)) 520 return true; 521 else if (RequireNonAbstractType(Loc, AllocType, 522 diag::err_allocation_of_abstract_type)) 523 return true; 524 525 return false; 526} 527 528/// FindAllocationFunctions - Finds the overloads of operator new and delete 529/// that are appropriate for the allocation. 530bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 531 bool UseGlobal, QualType AllocType, 532 bool IsArray, Expr **PlaceArgs, 533 unsigned NumPlaceArgs, 534 FunctionDecl *&OperatorNew, 535 FunctionDecl *&OperatorDelete) { 536 // --- Choosing an allocation function --- 537 // C++ 5.3.4p8 - 14 & 18 538 // 1) If UseGlobal is true, only look in the global scope. Else, also look 539 // in the scope of the allocated class. 540 // 2) If an array size is given, look for operator new[], else look for 541 // operator new. 542 // 3) The first argument is always size_t. Append the arguments from the 543 // placement form. 544 // FIXME: Also find the appropriate delete operator. 545 546 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); 547 // We don't care about the actual value of this argument. 548 // FIXME: Should the Sema create the expression and embed it in the syntax 549 // tree? Or should the consumer just recalculate the value? 550 IntegerLiteral Size(llvm::APInt::getNullValue( 551 Context.Target.getPointerWidth(0)), 552 Context.getSizeType(), 553 SourceLocation()); 554 AllocArgs[0] = &Size; 555 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); 556 557 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 558 IsArray ? OO_Array_New : OO_New); 559 if (AllocType->isRecordType() && !UseGlobal) { 560 CXXRecordDecl *Record 561 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl()); 562 // FIXME: We fail to find inherited overloads. 563 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 564 AllocArgs.size(), Record, /*AllowMissing=*/true, 565 OperatorNew)) 566 return true; 567 } 568 if (!OperatorNew) { 569 // Didn't find a member overload. Look for a global one. 570 DeclareGlobalNewDelete(); 571 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 572 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 573 AllocArgs.size(), TUDecl, /*AllowMissing=*/false, 574 OperatorNew)) 575 return true; 576 } 577 578 // FindAllocationOverload can change the passed in arguments, so we need to 579 // copy them back. 580 if (NumPlaceArgs > 0) 581 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs); 582 583 return false; 584} 585 586/// FindAllocationOverload - Find an fitting overload for the allocation 587/// function in the specified scope. 588bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 589 DeclarationName Name, Expr** Args, 590 unsigned NumArgs, DeclContext *Ctx, 591 bool AllowMissing, FunctionDecl *&Operator) { 592 DeclContext::lookup_iterator Alloc, AllocEnd; 593 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name); 594 if (Alloc == AllocEnd) { 595 if (AllowMissing) 596 return false; 597 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 598 << Name << Range; 599 } 600 601 OverloadCandidateSet Candidates; 602 for (; Alloc != AllocEnd; ++Alloc) { 603 // Even member operator new/delete are implicitly treated as 604 // static, so don't use AddMemberCandidate. 605 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) 606 AddOverloadCandidate(Fn, Args, NumArgs, Candidates, 607 /*SuppressUserConversions=*/false); 608 } 609 610 // Do the resolution. 611 OverloadCandidateSet::iterator Best; 612 switch(BestViableFunction(Candidates, StartLoc, Best)) { 613 case OR_Success: { 614 // Got one! 615 FunctionDecl *FnDecl = Best->Function; 616 // The first argument is size_t, and the first parameter must be size_t, 617 // too. This is checked on declaration and can be assumed. (It can't be 618 // asserted on, though, since invalid decls are left in there.) 619 for (unsigned i = 1; i < NumArgs; ++i) { 620 // FIXME: Passing word to diagnostic. 621 if (PerformCopyInitialization(Args[i], 622 FnDecl->getParamDecl(i)->getType(), 623 "passing")) 624 return true; 625 } 626 Operator = FnDecl; 627 return false; 628 } 629 630 case OR_No_Viable_Function: 631 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 632 << Name << Range; 633 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false); 634 return true; 635 636 case OR_Ambiguous: 637 Diag(StartLoc, diag::err_ovl_ambiguous_call) 638 << Name << Range; 639 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true); 640 return true; 641 642 case OR_Deleted: 643 Diag(StartLoc, diag::err_ovl_deleted_call) 644 << Best->Function->isDeleted() 645 << Name << Range; 646 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true); 647 return true; 648 } 649 assert(false && "Unreachable, bad result from BestViableFunction"); 650 return true; 651} 652 653 654/// DeclareGlobalNewDelete - Declare the global forms of operator new and 655/// delete. These are: 656/// @code 657/// void* operator new(std::size_t) throw(std::bad_alloc); 658/// void* operator new[](std::size_t) throw(std::bad_alloc); 659/// void operator delete(void *) throw(); 660/// void operator delete[](void *) throw(); 661/// @endcode 662/// Note that the placement and nothrow forms of new are *not* implicitly 663/// declared. Their use requires including \<new\>. 664void Sema::DeclareGlobalNewDelete() { 665 if (GlobalNewDeleteDeclared) 666 return; 667 668 // C++ [basic.std.dynamic]p2: 669 // [...] The following allocation and deallocation functions (18.4) are 670 // implicitly declared in global scope in each translation unit of a 671 // program 672 // 673 // void* operator new(std::size_t) throw(std::bad_alloc); 674 // void* operator new[](std::size_t) throw(std::bad_alloc); 675 // void operator delete(void*) throw(); 676 // void operator delete[](void*) throw(); 677 // 678 // These implicit declarations introduce only the function names operator 679 // new, operator new[], operator delete, operator delete[]. 680 // 681 // Here, we need to refer to std::bad_alloc, so we will implicitly declare 682 // "std" or "bad_alloc" as necessary to form the exception specification. 683 // However, we do not make these implicit declarations visible to name 684 // lookup. 685 if (!StdNamespace) { 686 // The "std" namespace has not yet been defined, so build one implicitly. 687 StdNamespace = NamespaceDecl::Create(Context, 688 Context.getTranslationUnitDecl(), 689 SourceLocation(), 690 &PP.getIdentifierTable().get("std")); 691 StdNamespace->setImplicit(true); 692 } 693 694 if (!StdBadAlloc) { 695 // The "std::bad_alloc" class has not yet been declared, so build it 696 // implicitly. 697 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class, 698 StdNamespace, 699 SourceLocation(), 700 &PP.getIdentifierTable().get("bad_alloc"), 701 SourceLocation(), 0); 702 StdBadAlloc->setImplicit(true); 703 } 704 705 GlobalNewDeleteDeclared = true; 706 707 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 708 QualType SizeT = Context.getSizeType(); 709 710 DeclareGlobalAllocationFunction( 711 Context.DeclarationNames.getCXXOperatorName(OO_New), 712 VoidPtr, SizeT); 713 DeclareGlobalAllocationFunction( 714 Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 715 VoidPtr, SizeT); 716 DeclareGlobalAllocationFunction( 717 Context.DeclarationNames.getCXXOperatorName(OO_Delete), 718 Context.VoidTy, VoidPtr); 719 DeclareGlobalAllocationFunction( 720 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 721 Context.VoidTy, VoidPtr); 722} 723 724/// DeclareGlobalAllocationFunction - Declares a single implicit global 725/// allocation function if it doesn't already exist. 726void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 727 QualType Return, QualType Argument) { 728 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 729 730 // Check if this function is already declared. 731 { 732 DeclContext::lookup_iterator Alloc, AllocEnd; 733 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); 734 Alloc != AllocEnd; ++Alloc) { 735 // FIXME: Do we need to check for default arguments here? 736 FunctionDecl *Func = cast<FunctionDecl>(*Alloc); 737 if (Func->getNumParams() == 1 && 738 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument) 739 return; 740 } 741 } 742 743 QualType BadAllocType; 744 bool HasBadAllocExceptionSpec 745 = (Name.getCXXOverloadedOperator() == OO_New || 746 Name.getCXXOverloadedOperator() == OO_Array_New); 747 if (HasBadAllocExceptionSpec) { 748 assert(StdBadAlloc && "Must have std::bad_alloc declared"); 749 BadAllocType = Context.getTypeDeclType(StdBadAlloc); 750 } 751 752 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0, 753 true, false, 754 HasBadAllocExceptionSpec? 1 : 0, 755 &BadAllocType); 756 FunctionDecl *Alloc = 757 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, 758 FnType, /*DInfo=*/0, FunctionDecl::None, false, true); 759 Alloc->setImplicit(); 760 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 761 0, Argument, /*DInfo=*/0, 762 VarDecl::None, 0); 763 Alloc->setParams(Context, &Param, 1); 764 765 // FIXME: Also add this declaration to the IdentifierResolver, but 766 // make sure it is at the end of the chain to coincide with the 767 // global scope. 768 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc); 769} 770 771/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 772/// @code ::delete ptr; @endcode 773/// or 774/// @code delete [] ptr; @endcode 775Action::OwningExprResult 776Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 777 bool ArrayForm, ExprArg Operand) { 778 // C++ [expr.delete]p1: 779 // The operand shall have a pointer type, or a class type having a single 780 // conversion function to a pointer type. The result has type void. 781 // 782 // DR599 amends "pointer type" to "pointer to object type" in both cases. 783 784 FunctionDecl *OperatorDelete = 0; 785 786 Expr *Ex = (Expr *)Operand.get(); 787 if (!Ex->isTypeDependent()) { 788 QualType Type = Ex->getType(); 789 790 if (const RecordType *Record = Type->getAs<RecordType>()) { 791 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions; 792 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 793 OverloadedFunctionDecl *Conversions = 794 RD->getVisibleConversionFunctions(); 795 796 for (OverloadedFunctionDecl::function_iterator 797 Func = Conversions->function_begin(), 798 FuncEnd = Conversions->function_end(); 799 Func != FuncEnd; ++Func) { 800 // Skip over templated conversion functions; they aren't considered. 801 if (isa<FunctionTemplateDecl>(*Func)) 802 continue; 803 804 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 805 806 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 807 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 808 if (ConvPtrType->getPointeeType()->isObjectType()) 809 ObjectPtrConversions.push_back(Conv); 810 } 811 if (ObjectPtrConversions.size() == 1) { 812 // We have a single conversion to a pointer-to-object type. Perform 813 // that conversion. 814 Operand.release(); 815 if (!PerformImplicitConversion(Ex, 816 ObjectPtrConversions.front()->getConversionType(), 817 "converting")) { 818 Operand = Owned(Ex); 819 Type = Ex->getType(); 820 } 821 } 822 else if (ObjectPtrConversions.size() > 1) { 823 Diag(StartLoc, diag::err_ambiguous_delete_operand) 824 << Type << Ex->getSourceRange(); 825 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) { 826 CXXConversionDecl *Conv = ObjectPtrConversions[i]; 827 Diag(Conv->getLocation(), diag::err_ovl_candidate); 828 } 829 return ExprError(); 830 } 831 } 832 833 if (!Type->isPointerType()) 834 return ExprError(Diag(StartLoc, diag::err_delete_operand) 835 << Type << Ex->getSourceRange()); 836 837 QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); 838 if (Pointee->isFunctionType() || Pointee->isVoidType()) 839 return ExprError(Diag(StartLoc, diag::err_delete_operand) 840 << Type << Ex->getSourceRange()); 841 else if (!Pointee->isDependentType() && 842 RequireCompleteType(StartLoc, Pointee, 843 PDiag(diag::warn_delete_incomplete) 844 << Ex->getSourceRange())) 845 return ExprError(); 846 847 // FIXME: This should be shared with the code for finding the delete 848 // operator in ActOnCXXNew. 849 IntegerLiteral Size(llvm::APInt::getNullValue( 850 Context.Target.getPointerWidth(0)), 851 Context.getSizeType(), 852 SourceLocation()); 853 ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy), 854 CastExpr::CK_Unknown, &Size, false); 855 Expr *DeleteArg = &Cast; 856 857 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 858 ArrayForm ? OO_Array_Delete : OO_Delete); 859 860 if (Pointee->isRecordType() && !UseGlobal) { 861 CXXRecordDecl *Record 862 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl()); 863 // FIXME: We fail to find inherited overloads. 864 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, 865 &DeleteArg, 1, Record, /*AllowMissing=*/true, 866 OperatorDelete)) 867 return ExprError(); 868 if (!Record->hasTrivialDestructor()) 869 if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context)) 870 MarkDeclarationReferenced(StartLoc, 871 const_cast<CXXDestructorDecl*>(Dtor)); 872 } 873 874 if (!OperatorDelete) { 875 // Didn't find a member overload. Look for a global one. 876 DeclareGlobalNewDelete(); 877 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 878 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, 879 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false, 880 OperatorDelete)) 881 return ExprError(); 882 } 883 884 // FIXME: Check access and ambiguity of operator delete and destructor. 885 } 886 887 Operand.release(); 888 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 889 OperatorDelete, Ex, StartLoc)); 890} 891 892 893/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 894/// C++ if/switch/while/for statement. 895/// e.g: "if (int x = f()) {...}" 896Action::OwningExprResult 897Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc, 898 Declarator &D, 899 SourceLocation EqualLoc, 900 ExprArg AssignExprVal) { 901 assert(AssignExprVal.get() && "Null assignment expression"); 902 903 // C++ 6.4p2: 904 // The declarator shall not specify a function or an array. 905 // The type-specifier-seq shall not contain typedef and shall not declare a 906 // new class or enumeration. 907 908 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 909 "Parser allowed 'typedef' as storage class of condition decl."); 910 911 // FIXME: Store DeclaratorInfo in the expression. 912 DeclaratorInfo *DInfo = 0; 913 TagDecl *OwnedTag = 0; 914 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag); 915 916 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 917 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 918 // would be created and CXXConditionDeclExpr wants a VarDecl. 919 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type) 920 << SourceRange(StartLoc, EqualLoc)); 921 } else if (Ty->isArrayType()) { // ...or an array. 922 Diag(StartLoc, diag::err_invalid_use_of_array_type) 923 << SourceRange(StartLoc, EqualLoc); 924 } else if (OwnedTag && OwnedTag->isDefinition()) { 925 // The type-specifier-seq shall not declare a new class or enumeration. 926 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition); 927 } 928 929 DeclPtrTy Dcl = ActOnDeclarator(S, D); 930 if (!Dcl) 931 return ExprError(); 932 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false); 933 934 // Mark this variable as one that is declared within a conditional. 935 // We know that the decl had to be a VarDecl because that is the only type of 936 // decl that can be assigned and the grammar requires an '='. 937 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>()); 938 VD->setDeclaredInCondition(true); 939 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD)); 940} 941 942/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 943bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { 944 // C++ 6.4p4: 945 // The value of a condition that is an initialized declaration in a statement 946 // other than a switch statement is the value of the declared variable 947 // implicitly converted to type bool. If that conversion is ill-formed, the 948 // program is ill-formed. 949 // The value of a condition that is an expression is the value of the 950 // expression, implicitly converted to bool. 951 // 952 return PerformContextuallyConvertToBool(CondExpr); 953} 954 955/// Helper function to determine whether this is the (deprecated) C++ 956/// conversion from a string literal to a pointer to non-const char or 957/// non-const wchar_t (for narrow and wide string literals, 958/// respectively). 959bool 960Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 961 // Look inside the implicit cast, if it exists. 962 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 963 From = Cast->getSubExpr(); 964 965 // A string literal (2.13.4) that is not a wide string literal can 966 // be converted to an rvalue of type "pointer to char"; a wide 967 // string literal can be converted to an rvalue of type "pointer 968 // to wchar_t" (C++ 4.2p2). 969 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From)) 970 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 971 if (const BuiltinType *ToPointeeType 972 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 973 // This conversion is considered only when there is an 974 // explicit appropriate pointer target type (C++ 4.2p2). 975 if (!ToPtrType->getPointeeType().hasQualifiers() && 976 ((StrLit->isWide() && ToPointeeType->isWideCharType()) || 977 (!StrLit->isWide() && 978 (ToPointeeType->getKind() == BuiltinType::Char_U || 979 ToPointeeType->getKind() == BuiltinType::Char_S)))) 980 return true; 981 } 982 983 return false; 984} 985 986/// PerformImplicitConversion - Perform an implicit conversion of the 987/// expression From to the type ToType. Returns true if there was an 988/// error, false otherwise. The expression From is replaced with the 989/// converted expression. Flavor is the kind of conversion we're 990/// performing, used in the error message. If @p AllowExplicit, 991/// explicit user-defined conversions are permitted. @p Elidable should be true 992/// when called for copies which may be elided (C++ 12.8p15). C++0x overload 993/// resolution works differently in that case. 994bool 995Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 996 const char *Flavor, bool AllowExplicit, 997 bool Elidable) { 998 ImplicitConversionSequence ICS; 999 return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit, 1000 Elidable, ICS); 1001} 1002 1003bool 1004Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1005 const char *Flavor, bool AllowExplicit, 1006 bool Elidable, 1007 ImplicitConversionSequence& ICS) { 1008 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1009 if (Elidable && getLangOptions().CPlusPlus0x) { 1010 ICS = TryImplicitConversion(From, ToType, 1011 /*SuppressUserConversions=*/false, 1012 AllowExplicit, 1013 /*ForceRValue=*/true, 1014 /*InOverloadResolution=*/false); 1015 } 1016 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) { 1017 ICS = TryImplicitConversion(From, ToType, 1018 /*SuppressUserConversions=*/false, 1019 AllowExplicit, 1020 /*ForceRValue=*/false, 1021 /*InOverloadResolution=*/false); 1022 } 1023 return PerformImplicitConversion(From, ToType, ICS, Flavor); 1024} 1025 1026/// PerformImplicitConversion - Perform an implicit conversion of the 1027/// expression From to the type ToType using the pre-computed implicit 1028/// conversion sequence ICS. Returns true if there was an error, false 1029/// otherwise. The expression From is replaced with the converted 1030/// expression. Flavor is the kind of conversion we're performing, 1031/// used in the error message. 1032bool 1033Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1034 const ImplicitConversionSequence &ICS, 1035 const char* Flavor) { 1036 switch (ICS.ConversionKind) { 1037 case ImplicitConversionSequence::StandardConversion: 1038 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor)) 1039 return true; 1040 break; 1041 1042 case ImplicitConversionSequence::UserDefinedConversion: { 1043 1044 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 1045 CastExpr::CastKind CastKind = CastExpr::CK_Unknown; 1046 QualType BeforeToType; 1047 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 1048 CastKind = CastExpr::CK_UserDefinedConversion; 1049 1050 // If the user-defined conversion is specified by a conversion function, 1051 // the initial standard conversion sequence converts the source type to 1052 // the implicit object parameter of the conversion function. 1053 BeforeToType = Context.getTagDeclType(Conv->getParent()); 1054 } else if (const CXXConstructorDecl *Ctor = 1055 dyn_cast<CXXConstructorDecl>(FD)) { 1056 CastKind = CastExpr::CK_ConstructorConversion; 1057 1058 // If the user-defined conversion is specified by a constructor, the 1059 // initial standard conversion sequence converts the source type to the 1060 // type required by the argument of the constructor 1061 BeforeToType = Ctor->getParamDecl(0)->getType(); 1062 } 1063 else 1064 assert(0 && "Unknown conversion function kind!"); 1065 1066 if (PerformImplicitConversion(From, BeforeToType, 1067 ICS.UserDefined.Before, "converting")) 1068 return true; 1069 1070 OwningExprResult CastArg 1071 = BuildCXXCastArgument(From->getLocStart(), 1072 ToType.getNonReferenceType(), 1073 CastKind, cast<CXXMethodDecl>(FD), 1074 Owned(From)); 1075 1076 if (CastArg.isInvalid()) 1077 return true; 1078 1079 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(), 1080 CastKind, CastArg.takeAs<Expr>(), 1081 ToType->isLValueReferenceType()); 1082 return false; 1083 } 1084 1085 case ImplicitConversionSequence::EllipsisConversion: 1086 assert(false && "Cannot perform an ellipsis conversion"); 1087 return false; 1088 1089 case ImplicitConversionSequence::BadConversion: 1090 return true; 1091 } 1092 1093 // Everything went well. 1094 return false; 1095} 1096 1097/// PerformImplicitConversion - Perform an implicit conversion of the 1098/// expression From to the type ToType by following the standard 1099/// conversion sequence SCS. Returns true if there was an error, false 1100/// otherwise. The expression From is replaced with the converted 1101/// expression. Flavor is the context in which we're performing this 1102/// conversion, for use in error messages. 1103bool 1104Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1105 const StandardConversionSequence& SCS, 1106 const char *Flavor) { 1107 // Overall FIXME: we are recomputing too many types here and doing far too 1108 // much extra work. What this means is that we need to keep track of more 1109 // information that is computed when we try the implicit conversion initially, 1110 // so that we don't need to recompute anything here. 1111 QualType FromType = From->getType(); 1112 1113 if (SCS.CopyConstructor) { 1114 // FIXME: When can ToType be a reference type? 1115 assert(!ToType->isReferenceType()); 1116 if (SCS.Second == ICK_Derived_To_Base) 1117 ImpCastExprToType(From, ToType, CastExpr::CK_DerivedToBase, 1118 /*isLvalue=*/true); 1119 OwningExprResult FromResult = 1120 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 1121 ToType, SCS.CopyConstructor, 1122 MultiExprArg(*this, (void**)&From, 1)); 1123 1124 if (FromResult.isInvalid()) 1125 return true; 1126 1127 From = FromResult.takeAs<Expr>(); 1128 return false; 1129 } 1130 1131 // Perform the first implicit conversion. 1132 switch (SCS.First) { 1133 case ICK_Identity: 1134 case ICK_Lvalue_To_Rvalue: 1135 // Nothing to do. 1136 break; 1137 1138 case ICK_Array_To_Pointer: 1139 FromType = Context.getArrayDecayedType(FromType); 1140 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay); 1141 break; 1142 1143 case ICK_Function_To_Pointer: 1144 if (Context.getCanonicalType(FromType) == Context.OverloadTy) { 1145 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true); 1146 if (!Fn) 1147 return true; 1148 1149 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) 1150 return true; 1151 1152 FixOverloadedFunctionReference(From, Fn); 1153 FromType = From->getType(); 1154 } 1155 FromType = Context.getPointerType(FromType); 1156 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay); 1157 break; 1158 1159 default: 1160 assert(false && "Improper first standard conversion"); 1161 break; 1162 } 1163 1164 // Perform the second implicit conversion 1165 switch (SCS.Second) { 1166 case ICK_Identity: 1167 // Nothing to do. 1168 break; 1169 1170 case ICK_Integral_Promotion: 1171 case ICK_Floating_Promotion: 1172 case ICK_Complex_Promotion: 1173 case ICK_Integral_Conversion: 1174 case ICK_Floating_Conversion: 1175 case ICK_Complex_Conversion: 1176 case ICK_Floating_Integral: 1177 case ICK_Complex_Real: 1178 case ICK_Compatible_Conversion: 1179 // FIXME: Go deeper to get the unqualified type! 1180 FromType = ToType.getUnqualifiedType(); 1181 ImpCastExprToType(From, FromType); 1182 break; 1183 1184 case ICK_Pointer_Conversion: { 1185 if (SCS.IncompatibleObjC) { 1186 // Diagnose incompatible Objective-C conversions 1187 Diag(From->getSourceRange().getBegin(), 1188 diag::ext_typecheck_convert_incompatible_pointer) 1189 << From->getType() << ToType << Flavor 1190 << From->getSourceRange(); 1191 } 1192 1193 1194 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1195 if (CheckPointerConversion(From, ToType, Kind)) 1196 return true; 1197 ImpCastExprToType(From, ToType, Kind); 1198 break; 1199 } 1200 1201 case ICK_Pointer_Member: { 1202 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1203 if (CheckMemberPointerConversion(From, ToType, Kind)) 1204 return true; 1205 ImpCastExprToType(From, ToType, Kind); 1206 break; 1207 } 1208 case ICK_Boolean_Conversion: 1209 FromType = Context.BoolTy; 1210 ImpCastExprToType(From, FromType); 1211 break; 1212 1213 default: 1214 assert(false && "Improper second standard conversion"); 1215 break; 1216 } 1217 1218 switch (SCS.Third) { 1219 case ICK_Identity: 1220 // Nothing to do. 1221 break; 1222 1223 case ICK_Qualification: 1224 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue 1225 // references. 1226 ImpCastExprToType(From, ToType.getNonReferenceType(), 1227 CastExpr::CK_Unknown, 1228 ToType->isLValueReferenceType()); 1229 break; 1230 1231 default: 1232 assert(false && "Improper second standard conversion"); 1233 break; 1234 } 1235 1236 return false; 1237} 1238 1239Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 1240 SourceLocation KWLoc, 1241 SourceLocation LParen, 1242 TypeTy *Ty, 1243 SourceLocation RParen) { 1244 QualType T = GetTypeFromParser(Ty); 1245 1246 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 1247 // all traits except __is_class, __is_enum and __is_union require a the type 1248 // to be complete. 1249 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) { 1250 if (RequireCompleteType(KWLoc, T, 1251 diag::err_incomplete_type_used_in_type_trait_expr)) 1252 return ExprError(); 1253 } 1254 1255 // There is no point in eagerly computing the value. The traits are designed 1256 // to be used from type trait templates, so Ty will be a template parameter 1257 // 99% of the time. 1258 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T, 1259 RParen, Context.BoolTy)); 1260} 1261 1262QualType Sema::CheckPointerToMemberOperands( 1263 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) { 1264 const char *OpSpelling = isIndirect ? "->*" : ".*"; 1265 // C++ 5.5p2 1266 // The binary operator .* [p3: ->*] binds its second operand, which shall 1267 // be of type "pointer to member of T" (where T is a completely-defined 1268 // class type) [...] 1269 QualType RType = rex->getType(); 1270 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>(); 1271 if (!MemPtr) { 1272 Diag(Loc, diag::err_bad_memptr_rhs) 1273 << OpSpelling << RType << rex->getSourceRange(); 1274 return QualType(); 1275 } 1276 1277 QualType Class(MemPtr->getClass(), 0); 1278 1279 // C++ 5.5p2 1280 // [...] to its first operand, which shall be of class T or of a class of 1281 // which T is an unambiguous and accessible base class. [p3: a pointer to 1282 // such a class] 1283 QualType LType = lex->getType(); 1284 if (isIndirect) { 1285 if (const PointerType *Ptr = LType->getAs<PointerType>()) 1286 LType = Ptr->getPointeeType().getNonReferenceType(); 1287 else { 1288 Diag(Loc, diag::err_bad_memptr_lhs) 1289 << OpSpelling << 1 << LType << lex->getSourceRange(); 1290 return QualType(); 1291 } 1292 } 1293 1294 if (Context.getCanonicalType(Class).getUnqualifiedType() != 1295 Context.getCanonicalType(LType).getUnqualifiedType()) { 1296 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 1297 /*DetectVirtual=*/false); 1298 // FIXME: Would it be useful to print full ambiguity paths, or is that 1299 // overkill? 1300 if (!IsDerivedFrom(LType, Class, Paths) || 1301 Paths.isAmbiguous(Context.getCanonicalType(Class))) { 1302 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 1303 << (int)isIndirect << lex->getType() << lex->getSourceRange(); 1304 return QualType(); 1305 } 1306 } 1307 1308 // C++ 5.5p2 1309 // The result is an object or a function of the type specified by the 1310 // second operand. 1311 // The cv qualifiers are the union of those in the pointer and the left side, 1312 // in accordance with 5.5p5 and 5.2.5. 1313 // FIXME: This returns a dereferenced member function pointer as a normal 1314 // function type. However, the only operation valid on such functions is 1315 // calling them. There's also a GCC extension to get a function pointer to the 1316 // thing, which is another complication, because this type - unlike the type 1317 // that is the result of this expression - takes the class as the first 1318 // argument. 1319 // We probably need a "MemberFunctionClosureType" or something like that. 1320 QualType Result = MemPtr->getPointeeType(); 1321 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers()); 1322 return Result; 1323} 1324 1325/// \brief Get the target type of a standard or user-defined conversion. 1326static QualType TargetType(const ImplicitConversionSequence &ICS) { 1327 assert((ICS.ConversionKind == 1328 ImplicitConversionSequence::StandardConversion || 1329 ICS.ConversionKind == 1330 ImplicitConversionSequence::UserDefinedConversion) && 1331 "function only valid for standard or user-defined conversions"); 1332 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion) 1333 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr); 1334 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr); 1335} 1336 1337/// \brief Try to convert a type to another according to C++0x 5.16p3. 1338/// 1339/// This is part of the parameter validation for the ? operator. If either 1340/// value operand is a class type, the two operands are attempted to be 1341/// converted to each other. This function does the conversion in one direction. 1342/// It emits a diagnostic and returns true only if it finds an ambiguous 1343/// conversion. 1344static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 1345 SourceLocation QuestionLoc, 1346 ImplicitConversionSequence &ICS) { 1347 // C++0x 5.16p3 1348 // The process for determining whether an operand expression E1 of type T1 1349 // can be converted to match an operand expression E2 of type T2 is defined 1350 // as follows: 1351 // -- If E2 is an lvalue: 1352 if (To->isLvalue(Self.Context) == Expr::LV_Valid) { 1353 // E1 can be converted to match E2 if E1 can be implicitly converted to 1354 // type "lvalue reference to T2", subject to the constraint that in the 1355 // conversion the reference must bind directly to E1. 1356 if (!Self.CheckReferenceInit(From, 1357 Self.Context.getLValueReferenceType(To->getType()), 1358 To->getLocStart(), 1359 /*SuppressUserConversions=*/false, 1360 /*AllowExplicit=*/false, 1361 /*ForceRValue=*/false, 1362 &ICS)) 1363 { 1364 assert((ICS.ConversionKind == 1365 ImplicitConversionSequence::StandardConversion || 1366 ICS.ConversionKind == 1367 ImplicitConversionSequence::UserDefinedConversion) && 1368 "expected a definite conversion"); 1369 bool DirectBinding = 1370 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ? 1371 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding; 1372 if (DirectBinding) 1373 return false; 1374 } 1375 } 1376 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1377 // -- If E2 is an rvalue, or if the conversion above cannot be done: 1378 // -- if E1 and E2 have class type, and the underlying class types are 1379 // the same or one is a base class of the other: 1380 QualType FTy = From->getType(); 1381 QualType TTy = To->getType(); 1382 const RecordType *FRec = FTy->getAs<RecordType>(); 1383 const RecordType *TRec = TTy->getAs<RecordType>(); 1384 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy); 1385 if (FRec && TRec && (FRec == TRec || 1386 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { 1387 // E1 can be converted to match E2 if the class of T2 is the 1388 // same type as, or a base class of, the class of T1, and 1389 // [cv2 > cv1]. 1390 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) { 1391 // Could still fail if there's no copy constructor. 1392 // FIXME: Is this a hard error then, or just a conversion failure? The 1393 // standard doesn't say. 1394 ICS = Self.TryCopyInitialization(From, TTy, 1395 /*SuppressUserConversions=*/false, 1396 /*ForceRValue=*/false, 1397 /*InOverloadResolution=*/false); 1398 } 1399 } else { 1400 // -- Otherwise: E1 can be converted to match E2 if E1 can be 1401 // implicitly converted to the type that expression E2 would have 1402 // if E2 were converted to an rvalue. 1403 // First find the decayed type. 1404 if (TTy->isFunctionType()) 1405 TTy = Self.Context.getPointerType(TTy); 1406 else if (TTy->isArrayType()) 1407 TTy = Self.Context.getArrayDecayedType(TTy); 1408 1409 // Now try the implicit conversion. 1410 // FIXME: This doesn't detect ambiguities. 1411 ICS = Self.TryImplicitConversion(From, TTy, 1412 /*SuppressUserConversions=*/false, 1413 /*AllowExplicit=*/false, 1414 /*ForceRValue=*/false, 1415 /*InOverloadResolution=*/false); 1416 } 1417 return false; 1418} 1419 1420/// \brief Try to find a common type for two according to C++0x 5.16p5. 1421/// 1422/// This is part of the parameter validation for the ? operator. If either 1423/// value operand is a class type, overload resolution is used to find a 1424/// conversion to a common type. 1425static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS, 1426 SourceLocation Loc) { 1427 Expr *Args[2] = { LHS, RHS }; 1428 OverloadCandidateSet CandidateSet; 1429 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet); 1430 1431 OverloadCandidateSet::iterator Best; 1432 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) { 1433 case Sema::OR_Success: 1434 // We found a match. Perform the conversions on the arguments and move on. 1435 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0], 1436 Best->Conversions[0], "converting") || 1437 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1], 1438 Best->Conversions[1], "converting")) 1439 break; 1440 return false; 1441 1442 case Sema::OR_No_Viable_Function: 1443 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 1444 << LHS->getType() << RHS->getType() 1445 << LHS->getSourceRange() << RHS->getSourceRange(); 1446 return true; 1447 1448 case Sema::OR_Ambiguous: 1449 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl) 1450 << LHS->getType() << RHS->getType() 1451 << LHS->getSourceRange() << RHS->getSourceRange(); 1452 // FIXME: Print the possible common types by printing the return types of 1453 // the viable candidates. 1454 break; 1455 1456 case Sema::OR_Deleted: 1457 assert(false && "Conditional operator has only built-in overloads"); 1458 break; 1459 } 1460 return true; 1461} 1462 1463/// \brief Perform an "extended" implicit conversion as returned by 1464/// TryClassUnification. 1465/// 1466/// TryClassUnification generates ICSs that include reference bindings. 1467/// PerformImplicitConversion is not suitable for this; it chokes if the 1468/// second part of a standard conversion is ICK_DerivedToBase. This function 1469/// handles the reference binding specially. 1470static bool ConvertForConditional(Sema &Self, Expr *&E, 1471 const ImplicitConversionSequence &ICS) { 1472 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion && 1473 ICS.Standard.ReferenceBinding) { 1474 assert(ICS.Standard.DirectBinding && 1475 "TryClassUnification should never generate indirect ref bindings"); 1476 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of 1477 // redoing all the work. 1478 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType( 1479 TargetType(ICS)), 1480 /*FIXME:*/E->getLocStart(), 1481 /*SuppressUserConversions=*/false, 1482 /*AllowExplicit=*/false, 1483 /*ForceRValue=*/false); 1484 } 1485 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion && 1486 ICS.UserDefined.After.ReferenceBinding) { 1487 assert(ICS.UserDefined.After.DirectBinding && 1488 "TryClassUnification should never generate indirect ref bindings"); 1489 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType( 1490 TargetType(ICS)), 1491 /*FIXME:*/E->getLocStart(), 1492 /*SuppressUserConversions=*/false, 1493 /*AllowExplicit=*/false, 1494 /*ForceRValue=*/false); 1495 } 1496 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting")) 1497 return true; 1498 return false; 1499} 1500 1501/// \brief Check the operands of ?: under C++ semantics. 1502/// 1503/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 1504/// extension. In this case, LHS == Cond. (But they're not aliases.) 1505QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 1506 SourceLocation QuestionLoc) { 1507 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ 1508 // interface pointers. 1509 1510 // C++0x 5.16p1 1511 // The first expression is contextually converted to bool. 1512 if (!Cond->isTypeDependent()) { 1513 if (CheckCXXBooleanCondition(Cond)) 1514 return QualType(); 1515 } 1516 1517 // Either of the arguments dependent? 1518 if (LHS->isTypeDependent() || RHS->isTypeDependent()) 1519 return Context.DependentTy; 1520 1521 // C++0x 5.16p2 1522 // If either the second or the third operand has type (cv) void, ... 1523 QualType LTy = LHS->getType(); 1524 QualType RTy = RHS->getType(); 1525 bool LVoid = LTy->isVoidType(); 1526 bool RVoid = RTy->isVoidType(); 1527 if (LVoid || RVoid) { 1528 // ... then the [l2r] conversions are performed on the second and third 1529 // operands ... 1530 DefaultFunctionArrayConversion(LHS); 1531 DefaultFunctionArrayConversion(RHS); 1532 LTy = LHS->getType(); 1533 RTy = RHS->getType(); 1534 1535 // ... and one of the following shall hold: 1536 // -- The second or the third operand (but not both) is a throw- 1537 // expression; the result is of the type of the other and is an rvalue. 1538 bool LThrow = isa<CXXThrowExpr>(LHS); 1539 bool RThrow = isa<CXXThrowExpr>(RHS); 1540 if (LThrow && !RThrow) 1541 return RTy; 1542 if (RThrow && !LThrow) 1543 return LTy; 1544 1545 // -- Both the second and third operands have type void; the result is of 1546 // type void and is an rvalue. 1547 if (LVoid && RVoid) 1548 return Context.VoidTy; 1549 1550 // Neither holds, error. 1551 Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 1552 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 1553 << LHS->getSourceRange() << RHS->getSourceRange(); 1554 return QualType(); 1555 } 1556 1557 // Neither is void. 1558 1559 // C++0x 5.16p3 1560 // Otherwise, if the second and third operand have different types, and 1561 // either has (cv) class type, and attempt is made to convert each of those 1562 // operands to the other. 1563 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) && 1564 (LTy->isRecordType() || RTy->isRecordType())) { 1565 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; 1566 // These return true if a single direction is already ambiguous. 1567 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight)) 1568 return QualType(); 1569 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft)) 1570 return QualType(); 1571 1572 bool HaveL2R = ICSLeftToRight.ConversionKind != 1573 ImplicitConversionSequence::BadConversion; 1574 bool HaveR2L = ICSRightToLeft.ConversionKind != 1575 ImplicitConversionSequence::BadConversion; 1576 // If both can be converted, [...] the program is ill-formed. 1577 if (HaveL2R && HaveR2L) { 1578 Diag(QuestionLoc, diag::err_conditional_ambiguous) 1579 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange(); 1580 return QualType(); 1581 } 1582 1583 // If exactly one conversion is possible, that conversion is applied to 1584 // the chosen operand and the converted operands are used in place of the 1585 // original operands for the remainder of this section. 1586 if (HaveL2R) { 1587 if (ConvertForConditional(*this, LHS, ICSLeftToRight)) 1588 return QualType(); 1589 LTy = LHS->getType(); 1590 } else if (HaveR2L) { 1591 if (ConvertForConditional(*this, RHS, ICSRightToLeft)) 1592 return QualType(); 1593 RTy = RHS->getType(); 1594 } 1595 } 1596 1597 // C++0x 5.16p4 1598 // If the second and third operands are lvalues and have the same type, 1599 // the result is of that type [...] 1600 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy); 1601 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid && 1602 RHS->isLvalue(Context) == Expr::LV_Valid) 1603 return LTy; 1604 1605 // C++0x 5.16p5 1606 // Otherwise, the result is an rvalue. If the second and third operands 1607 // do not have the same type, and either has (cv) class type, ... 1608 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 1609 // ... overload resolution is used to determine the conversions (if any) 1610 // to be applied to the operands. If the overload resolution fails, the 1611 // program is ill-formed. 1612 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 1613 return QualType(); 1614 } 1615 1616 // C++0x 5.16p6 1617 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard 1618 // conversions are performed on the second and third operands. 1619 DefaultFunctionArrayConversion(LHS); 1620 DefaultFunctionArrayConversion(RHS); 1621 LTy = LHS->getType(); 1622 RTy = RHS->getType(); 1623 1624 // After those conversions, one of the following shall hold: 1625 // -- The second and third operands have the same type; the result 1626 // is of that type. 1627 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) 1628 return LTy; 1629 1630 // -- The second and third operands have arithmetic or enumeration type; 1631 // the usual arithmetic conversions are performed to bring them to a 1632 // common type, and the result is of that type. 1633 if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 1634 UsualArithmeticConversions(LHS, RHS); 1635 return LHS->getType(); 1636 } 1637 1638 // -- The second and third operands have pointer type, or one has pointer 1639 // type and the other is a null pointer constant; pointer conversions 1640 // and qualification conversions are performed to bring them to their 1641 // composite pointer type. The result is of the composite pointer type. 1642 QualType Composite = FindCompositePointerType(LHS, RHS); 1643 if (!Composite.isNull()) 1644 return Composite; 1645 1646 // Fourth bullet is same for pointers-to-member. However, the possible 1647 // conversions are far more limited: we have null-to-pointer, upcast of 1648 // containing class, and second-level cv-ness. 1649 // cv-ness is not a union, but must match one of the two operands. (Which, 1650 // frankly, is stupid.) 1651 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>(); 1652 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>(); 1653 if (LMemPtr && 1654 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 1655 ImpCastExprToType(RHS, LTy); 1656 return LTy; 1657 } 1658 if (RMemPtr && 1659 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 1660 ImpCastExprToType(LHS, RTy); 1661 return RTy; 1662 } 1663 if (LMemPtr && RMemPtr) { 1664 QualType LPointee = LMemPtr->getPointeeType(); 1665 QualType RPointee = RMemPtr->getPointeeType(); 1666 1667 QualifierCollector LPQuals, RPQuals; 1668 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee)); 1669 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee)); 1670 1671 // First, we check that the unqualified pointee type is the same. If it's 1672 // not, there's no conversion that will unify the two pointers. 1673 if (LPCan == RPCan) { 1674 1675 // Second, we take the greater of the two qualifications. If neither 1676 // is greater than the other, the conversion is not possible. 1677 1678 Qualifiers MergedQuals = LPQuals + RPQuals; 1679 1680 bool CompatibleQuals = true; 1681 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() && 1682 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers()) 1683 CompatibleQuals = false; 1684 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace()) 1685 // FIXME: 1686 // C99 6.5.15 as modified by TR 18037: 1687 // If the second and third operands are pointers into different 1688 // address spaces, the address spaces must overlap. 1689 CompatibleQuals = false; 1690 // FIXME: GC qualifiers? 1691 1692 if (CompatibleQuals) { 1693 // Third, we check if either of the container classes is derived from 1694 // the other. 1695 QualType LContainer(LMemPtr->getClass(), 0); 1696 QualType RContainer(RMemPtr->getClass(), 0); 1697 QualType MoreDerived; 1698 if (Context.getCanonicalType(LContainer) == 1699 Context.getCanonicalType(RContainer)) 1700 MoreDerived = LContainer; 1701 else if (IsDerivedFrom(LContainer, RContainer)) 1702 MoreDerived = LContainer; 1703 else if (IsDerivedFrom(RContainer, LContainer)) 1704 MoreDerived = RContainer; 1705 1706 if (!MoreDerived.isNull()) { 1707 // The type 'Q Pointee (MoreDerived::*)' is the common type. 1708 // We don't use ImpCastExprToType here because this could still fail 1709 // for ambiguous or inaccessible conversions. 1710 LPointee = Context.getQualifiedType(LPointee, MergedQuals); 1711 QualType Common 1712 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr()); 1713 if (PerformImplicitConversion(LHS, Common, "converting")) 1714 return QualType(); 1715 if (PerformImplicitConversion(RHS, Common, "converting")) 1716 return QualType(); 1717 return Common; 1718 } 1719 } 1720 } 1721 } 1722 1723 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 1724 << LHS->getType() << RHS->getType() 1725 << LHS->getSourceRange() << RHS->getSourceRange(); 1726 return QualType(); 1727} 1728 1729/// \brief Find a merged pointer type and convert the two expressions to it. 1730/// 1731/// This finds the composite pointer type (or member pointer type) for @p E1 1732/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this 1733/// type and returns it. 1734/// It does not emit diagnostics. 1735QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) { 1736 assert(getLangOptions().CPlusPlus && "This function assumes C++"); 1737 QualType T1 = E1->getType(), T2 = E2->getType(); 1738 1739 if (!T1->isPointerType() && !T1->isMemberPointerType() && 1740 !T2->isPointerType() && !T2->isMemberPointerType()) 1741 return QualType(); 1742 1743 // FIXME: Do we need to work on the canonical types? 1744 1745 // C++0x 5.9p2 1746 // Pointer conversions and qualification conversions are performed on 1747 // pointer operands to bring them to their composite pointer type. If 1748 // one operand is a null pointer constant, the composite pointer type is 1749 // the type of the other operand. 1750 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 1751 ImpCastExprToType(E1, T2); 1752 return T2; 1753 } 1754 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 1755 ImpCastExprToType(E2, T1); 1756 return T1; 1757 } 1758 1759 // Now both have to be pointers or member pointers. 1760 if (!T1->isPointerType() && !T1->isMemberPointerType() && 1761 !T2->isPointerType() && !T2->isMemberPointerType()) 1762 return QualType(); 1763 1764 // Otherwise, of one of the operands has type "pointer to cv1 void," then 1765 // the other has type "pointer to cv2 T" and the composite pointer type is 1766 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. 1767 // Otherwise, the composite pointer type is a pointer type similar to the 1768 // type of one of the operands, with a cv-qualification signature that is 1769 // the union of the cv-qualification signatures of the operand types. 1770 // In practice, the first part here is redundant; it's subsumed by the second. 1771 // What we do here is, we build the two possible composite types, and try the 1772 // conversions in both directions. If only one works, or if the two composite 1773 // types are the same, we have succeeded. 1774 // FIXME: extended qualifiers? 1775 llvm::SmallVector<unsigned, 4> QualifierUnion; 1776 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass; 1777 QualType Composite1 = T1, Composite2 = T2; 1778 do { 1779 const PointerType *Ptr1, *Ptr2; 1780 if ((Ptr1 = Composite1->getAs<PointerType>()) && 1781 (Ptr2 = Composite2->getAs<PointerType>())) { 1782 Composite1 = Ptr1->getPointeeType(); 1783 Composite2 = Ptr2->getPointeeType(); 1784 QualifierUnion.push_back( 1785 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 1786 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0)); 1787 continue; 1788 } 1789 1790 const MemberPointerType *MemPtr1, *MemPtr2; 1791 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 1792 (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 1793 Composite1 = MemPtr1->getPointeeType(); 1794 Composite2 = MemPtr2->getPointeeType(); 1795 QualifierUnion.push_back( 1796 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 1797 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), 1798 MemPtr2->getClass())); 1799 continue; 1800 } 1801 1802 // FIXME: block pointer types? 1803 1804 // Cannot unwrap any more types. 1805 break; 1806 } while (true); 1807 1808 // Rewrap the composites as pointers or member pointers with the union CVRs. 1809 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC 1810 = MemberOfClass.begin(); 1811 for (llvm::SmallVector<unsigned, 4>::iterator 1812 I = QualifierUnion.begin(), 1813 E = QualifierUnion.end(); 1814 I != E; (void)++I, ++MOC) { 1815 Qualifiers Quals = Qualifiers::fromCVRMask(*I); 1816 if (MOC->first && MOC->second) { 1817 // Rebuild member pointer type 1818 Composite1 = Context.getMemberPointerType( 1819 Context.getQualifiedType(Composite1, Quals), 1820 MOC->first); 1821 Composite2 = Context.getMemberPointerType( 1822 Context.getQualifiedType(Composite2, Quals), 1823 MOC->second); 1824 } else { 1825 // Rebuild pointer type 1826 Composite1 1827 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); 1828 Composite2 1829 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); 1830 } 1831 } 1832 1833 ImplicitConversionSequence E1ToC1 = 1834 TryImplicitConversion(E1, Composite1, 1835 /*SuppressUserConversions=*/false, 1836 /*AllowExplicit=*/false, 1837 /*ForceRValue=*/false, 1838 /*InOverloadResolution=*/false); 1839 ImplicitConversionSequence E2ToC1 = 1840 TryImplicitConversion(E2, Composite1, 1841 /*SuppressUserConversions=*/false, 1842 /*AllowExplicit=*/false, 1843 /*ForceRValue=*/false, 1844 /*InOverloadResolution=*/false); 1845 1846 ImplicitConversionSequence E1ToC2, E2ToC2; 1847 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion; 1848 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion; 1849 if (Context.getCanonicalType(Composite1) != 1850 Context.getCanonicalType(Composite2)) { 1851 E1ToC2 = TryImplicitConversion(E1, Composite2, 1852 /*SuppressUserConversions=*/false, 1853 /*AllowExplicit=*/false, 1854 /*ForceRValue=*/false, 1855 /*InOverloadResolution=*/false); 1856 E2ToC2 = TryImplicitConversion(E2, Composite2, 1857 /*SuppressUserConversions=*/false, 1858 /*AllowExplicit=*/false, 1859 /*ForceRValue=*/false, 1860 /*InOverloadResolution=*/false); 1861 } 1862 1863 bool ToC1Viable = E1ToC1.ConversionKind != 1864 ImplicitConversionSequence::BadConversion 1865 && E2ToC1.ConversionKind != 1866 ImplicitConversionSequence::BadConversion; 1867 bool ToC2Viable = E1ToC2.ConversionKind != 1868 ImplicitConversionSequence::BadConversion 1869 && E2ToC2.ConversionKind != 1870 ImplicitConversionSequence::BadConversion; 1871 if (ToC1Viable && !ToC2Viable) { 1872 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") && 1873 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting")) 1874 return Composite1; 1875 } 1876 if (ToC2Viable && !ToC1Viable) { 1877 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") && 1878 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting")) 1879 return Composite2; 1880 } 1881 return QualType(); 1882} 1883 1884Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) { 1885 if (!Context.getLangOptions().CPlusPlus) 1886 return Owned(E); 1887 1888 const RecordType *RT = E->getType()->getAs<RecordType>(); 1889 if (!RT) 1890 return Owned(E); 1891 1892 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1893 if (RD->hasTrivialDestructor()) 1894 return Owned(E); 1895 1896 if (CallExpr *CE = dyn_cast<CallExpr>(E)) { 1897 QualType Ty = CE->getCallee()->getType(); 1898 if (const PointerType *PT = Ty->getAs<PointerType>()) 1899 Ty = PT->getPointeeType(); 1900 1901 const FunctionType *FTy = Ty->getAs<FunctionType>(); 1902 if (FTy->getResultType()->isReferenceType()) 1903 return Owned(E); 1904 } 1905 CXXTemporary *Temp = CXXTemporary::Create(Context, 1906 RD->getDestructor(Context)); 1907 ExprTemporaries.push_back(Temp); 1908 if (CXXDestructorDecl *Destructor = 1909 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) 1910 MarkDeclarationReferenced(E->getExprLoc(), Destructor); 1911 // FIXME: Add the temporary to the temporaries vector. 1912 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E)); 1913} 1914 1915Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr, 1916 bool ShouldDestroyTemps) { 1917 assert(SubExpr && "sub expression can't be null!"); 1918 1919 if (ExprTemporaries.empty()) 1920 return SubExpr; 1921 1922 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr, 1923 &ExprTemporaries[0], 1924 ExprTemporaries.size(), 1925 ShouldDestroyTemps); 1926 ExprTemporaries.clear(); 1927 1928 return E; 1929} 1930 1931Sema::OwningExprResult 1932Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc, 1933 tok::TokenKind OpKind, TypeTy *&ObjectType) { 1934 // Since this might be a postfix expression, get rid of ParenListExprs. 1935 Base = MaybeConvertParenListExprToParenExpr(S, move(Base)); 1936 1937 Expr *BaseExpr = (Expr*)Base.get(); 1938 assert(BaseExpr && "no record expansion"); 1939 1940 QualType BaseType = BaseExpr->getType(); 1941 if (BaseType->isDependentType()) { 1942 // FIXME: member of the current instantiation 1943 ObjectType = BaseType.getAsOpaquePtr(); 1944 return move(Base); 1945 } 1946 1947 // C++ [over.match.oper]p8: 1948 // [...] When operator->returns, the operator-> is applied to the value 1949 // returned, with the original second operand. 1950 if (OpKind == tok::arrow) { 1951 while (BaseType->isRecordType()) { 1952 Base = BuildOverloadedArrowExpr(S, move(Base), BaseExpr->getExprLoc()); 1953 BaseExpr = (Expr*)Base.get(); 1954 if (BaseExpr == NULL) 1955 return ExprError(); 1956 BaseType = BaseExpr->getType(); 1957 } 1958 } 1959 1960 if (BaseType->isPointerType()) 1961 BaseType = BaseType->getPointeeType(); 1962 1963 // We could end up with various non-record types here, such as extended 1964 // vector types or Objective-C interfaces. Just return early and let 1965 // ActOnMemberReferenceExpr do the work. 1966 if (!BaseType->isRecordType()) { 1967 // C++ [basic.lookup.classref]p2: 1968 // [...] If the type of the object expression is of pointer to scalar 1969 // type, the unqualified-id is looked up in the context of the complete 1970 // postfix-expression. 1971 ObjectType = 0; 1972 return move(Base); 1973 } 1974 1975 // C++ [basic.lookup.classref]p2: 1976 // If the id-expression in a class member access (5.2.5) is an 1977 // unqualified-id, and the type of the object expres- sion is of a class 1978 // type C (or of pointer to a class type C), the unqualified-id is looked 1979 // up in the scope of class C. [...] 1980 ObjectType = BaseType.getAsOpaquePtr(); 1981 return move(Base); 1982} 1983 1984Sema::OwningExprResult 1985Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base, 1986 SourceLocation OpLoc, 1987 tok::TokenKind OpKind, 1988 SourceLocation ClassNameLoc, 1989 IdentifierInfo *ClassName, 1990 const CXXScopeSpec &SS, 1991 bool HasTrailingLParen) { 1992 if (SS.isInvalid()) 1993 return ExprError(); 1994 1995 QualType BaseType; 1996 if (isUnknownSpecialization(SS)) 1997 BaseType = Context.getTypenameType((NestedNameSpecifier *)SS.getScopeRep(), 1998 ClassName); 1999 else { 2000 TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, &SS); 2001 if (!BaseTy) { 2002 Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type) 2003 << ClassName; 2004 return ExprError(); 2005 } 2006 2007 BaseType = GetTypeFromParser(BaseTy); 2008 } 2009 2010 CanQualType CanBaseType = Context.getCanonicalType(BaseType); 2011 DeclarationName DtorName = 2012 Context.DeclarationNames.getCXXDestructorName(CanBaseType); 2013 2014 OwningExprResult Result 2015 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc, 2016 DtorName, DeclPtrTy(), &SS); 2017 if (Result.isInvalid() || HasTrailingLParen) 2018 return move(Result); 2019 2020 // The only way a reference to a destructor can be used is to 2021 // immediately call them. Since the next token is not a '(', produce a 2022 // diagnostic and build the call now. 2023 Expr *E = (Expr *)Result.get(); 2024 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(E->getLocEnd()); 2025 Diag(E->getLocStart(), diag::err_dtor_expr_without_call) 2026 << isa<CXXPseudoDestructorExpr>(E) 2027 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()"); 2028 2029 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc, 2030 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc); 2031} 2032 2033Sema::OwningExprResult 2034Sema::ActOnOverloadedOperatorReferenceExpr(Scope *S, ExprArg Base, 2035 SourceLocation OpLoc, 2036 tok::TokenKind OpKind, 2037 SourceLocation ClassNameLoc, 2038 OverloadedOperatorKind OverOpKind, 2039 const CXXScopeSpec *SS) { 2040 if (SS && SS->isInvalid()) 2041 return ExprError(); 2042 2043 DeclarationName Name = 2044 Context.DeclarationNames.getCXXOperatorName(OverOpKind); 2045 2046 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc, 2047 Name, DeclPtrTy(), SS); 2048} 2049 2050Sema::OwningExprResult 2051Sema::ActOnConversionOperatorReferenceExpr(Scope *S, ExprArg Base, 2052 SourceLocation OpLoc, 2053 tok::TokenKind OpKind, 2054 SourceLocation ClassNameLoc, 2055 TypeTy *Ty, 2056 const CXXScopeSpec *SS) { 2057 if (SS && SS->isInvalid()) 2058 return ExprError(); 2059 2060 //FIXME: Preserve type source info. 2061 QualType ConvType = GetTypeFromParser(Ty); 2062 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType); 2063 DeclarationName ConvName = 2064 Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon); 2065 2066 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc, 2067 ConvName, DeclPtrTy(), SS); 2068} 2069 2070Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc, 2071 QualType Ty, 2072 CastExpr::CastKind Kind, 2073 CXXMethodDecl *Method, 2074 ExprArg Arg) { 2075 Expr *From = Arg.takeAs<Expr>(); 2076 2077 switch (Kind) { 2078 default: assert(0 && "Unhandled cast kind!"); 2079 case CastExpr::CK_ConstructorConversion: { 2080 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 2081 2082 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method), 2083 MultiExprArg(*this, (void **)&From, 1), 2084 CastLoc, ConstructorArgs)) 2085 return ExprError(); 2086 2087 return BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), 2088 move_arg(ConstructorArgs)); 2089 } 2090 2091 case CastExpr::CK_UserDefinedConversion: { 2092 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 2093 2094 // Cast to base if needed. 2095 if (PerformObjectArgumentInitialization(From, Method)) 2096 return ExprError(); 2097 2098 // Create an implicit member expr to refer to the conversion operator. 2099 MemberExpr *ME = 2100 new (Context) MemberExpr(From, /*IsArrow=*/false, Method, 2101 SourceLocation(), Method->getType()); 2102 2103 2104 // And an implicit call expr that calls it. 2105 QualType ResultType = Method->getResultType().getNonReferenceType(); 2106 CXXMemberCallExpr *CE = 2107 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, 2108 ResultType, 2109 SourceLocation()); 2110 2111 return Owned(CE); 2112 } 2113 2114 } 2115} 2116 2117Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) { 2118 Expr *FullExpr = Arg.takeAs<Expr>(); 2119 if (FullExpr) 2120 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr, 2121 /*ShouldDestroyTemps=*/true); 2122 2123 2124 return Owned(FullExpr); 2125} 2126