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