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