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