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