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