1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC 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 Objective-C expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/DeclObjC.h" 17 #include "clang/AST/ExprObjC.h" 18 #include "clang/AST/StmtVisitor.h" 19 #include "clang/AST/TypeLoc.h" 20 #include "clang/Analysis/DomainSpecific/CocoaConventions.h" 21 #include "clang/Edit/Commit.h" 22 #include "clang/Edit/Rewriters.h" 23 #include "clang/Lex/Preprocessor.h" 24 #include "clang/Sema/Initialization.h" 25 #include "clang/Sema/Lookup.h" 26 #include "clang/Sema/Scope.h" 27 #include "clang/Sema/ScopeInfo.h" 28 #include "llvm/ADT/SmallString.h" 29 30 using namespace clang; 31 using namespace sema; 32 using llvm::makeArrayRef; 33 34 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs, 35 Expr **strings, 36 unsigned NumStrings) { 37 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings); 38 39 // Most ObjC strings are formed out of a single piece. However, we *can* 40 // have strings formed out of multiple @ strings with multiple pptokens in 41 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one 42 // StringLiteral for ObjCStringLiteral to hold onto. 43 StringLiteral *S = Strings[0]; 44 45 // If we have a multi-part string, merge it all together. 46 if (NumStrings != 1) { 47 // Concatenate objc strings. 48 SmallString<128> StrBuf; 49 SmallVector<SourceLocation, 8> StrLocs; 50 51 for (unsigned i = 0; i != NumStrings; ++i) { 52 S = Strings[i]; 53 54 // ObjC strings can't be wide or UTF. 55 if (!S->isAscii()) { 56 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant) 57 << S->getSourceRange(); 58 return true; 59 } 60 61 // Append the string. 62 StrBuf += S->getString(); 63 64 // Get the locations of the string tokens. 65 StrLocs.append(S->tokloc_begin(), S->tokloc_end()); 66 } 67 68 // Create the aggregate string with the appropriate content and location 69 // information. 70 S = StringLiteral::Create(Context, StrBuf, 71 StringLiteral::Ascii, /*Pascal=*/false, 72 Context.getPointerType(Context.CharTy), 73 &StrLocs[0], StrLocs.size()); 74 } 75 76 return BuildObjCStringLiteral(AtLocs[0], S); 77 } 78 79 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){ 80 // Verify that this composite string is acceptable for ObjC strings. 81 if (CheckObjCString(S)) 82 return true; 83 84 // Initialize the constant string interface lazily. This assumes 85 // the NSString interface is seen in this translation unit. Note: We 86 // don't use NSConstantString, since the runtime team considers this 87 // interface private (even though it appears in the header files). 88 QualType Ty = Context.getObjCConstantStringInterface(); 89 if (!Ty.isNull()) { 90 Ty = Context.getObjCObjectPointerType(Ty); 91 } else if (getLangOpts().NoConstantCFStrings) { 92 IdentifierInfo *NSIdent=0; 93 std::string StringClass(getLangOpts().ObjCConstantStringClass); 94 95 if (StringClass.empty()) 96 NSIdent = &Context.Idents.get("NSConstantString"); 97 else 98 NSIdent = &Context.Idents.get(StringClass); 99 100 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc, 101 LookupOrdinaryName); 102 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { 103 Context.setObjCConstantStringInterface(StrIF); 104 Ty = Context.getObjCConstantStringInterface(); 105 Ty = Context.getObjCObjectPointerType(Ty); 106 } else { 107 // If there is no NSConstantString interface defined then treat this 108 // as error and recover from it. 109 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent 110 << S->getSourceRange(); 111 Ty = Context.getObjCIdType(); 112 } 113 } else { 114 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString); 115 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc, 116 LookupOrdinaryName); 117 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { 118 Context.setObjCConstantStringInterface(StrIF); 119 Ty = Context.getObjCConstantStringInterface(); 120 Ty = Context.getObjCObjectPointerType(Ty); 121 } else { 122 // If there is no NSString interface defined, implicitly declare 123 // a @class NSString; and use that instead. This is to make sure 124 // type of an NSString literal is represented correctly, instead of 125 // being an 'id' type. 126 Ty = Context.getObjCNSStringType(); 127 if (Ty.isNull()) { 128 ObjCInterfaceDecl *NSStringIDecl = 129 ObjCInterfaceDecl::Create (Context, 130 Context.getTranslationUnitDecl(), 131 SourceLocation(), NSIdent, 132 0, SourceLocation()); 133 Ty = Context.getObjCInterfaceType(NSStringIDecl); 134 Context.setObjCNSStringType(Ty); 135 } 136 Ty = Context.getObjCObjectPointerType(Ty); 137 } 138 } 139 140 return new (Context) ObjCStringLiteral(S, Ty, AtLoc); 141 } 142 143 /// \brief Emits an error if the given method does not exist, or if the return 144 /// type is not an Objective-C object. 145 static bool validateBoxingMethod(Sema &S, SourceLocation Loc, 146 const ObjCInterfaceDecl *Class, 147 Selector Sel, const ObjCMethodDecl *Method) { 148 if (!Method) { 149 // FIXME: Is there a better way to avoid quotes than using getName()? 150 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName(); 151 return false; 152 } 153 154 // Make sure the return type is reasonable. 155 QualType ReturnType = Method->getResultType(); 156 if (!ReturnType->isObjCObjectPointerType()) { 157 S.Diag(Loc, diag::err_objc_literal_method_sig) 158 << Sel; 159 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return) 160 << ReturnType; 161 return false; 162 } 163 164 return true; 165 } 166 167 /// \brief Retrieve the NSNumber factory method that should be used to create 168 /// an Objective-C literal for the given type. 169 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc, 170 QualType NumberType, 171 bool isLiteral = false, 172 SourceRange R = SourceRange()) { 173 Optional<NSAPI::NSNumberLiteralMethodKind> Kind = 174 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType); 175 176 if (!Kind) { 177 if (isLiteral) { 178 S.Diag(Loc, diag::err_invalid_nsnumber_type) 179 << NumberType << R; 180 } 181 return 0; 182 } 183 184 // If we already looked up this method, we're done. 185 if (S.NSNumberLiteralMethods[*Kind]) 186 return S.NSNumberLiteralMethods[*Kind]; 187 188 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind, 189 /*Instance=*/false); 190 191 ASTContext &CX = S.Context; 192 193 // Look up the NSNumber class, if we haven't done so already. It's cached 194 // in the Sema instance. 195 if (!S.NSNumberDecl) { 196 IdentifierInfo *NSNumberId = 197 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber); 198 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId, 199 Loc, Sema::LookupOrdinaryName); 200 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 201 if (!S.NSNumberDecl) { 202 if (S.getLangOpts().DebuggerObjCLiteral) { 203 // Create a stub definition of NSNumber. 204 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX, 205 CX.getTranslationUnitDecl(), 206 SourceLocation(), NSNumberId, 207 0, SourceLocation()); 208 } else { 209 // Otherwise, require a declaration of NSNumber. 210 S.Diag(Loc, diag::err_undeclared_nsnumber); 211 return 0; 212 } 213 } else if (!S.NSNumberDecl->hasDefinition()) { 214 S.Diag(Loc, diag::err_undeclared_nsnumber); 215 return 0; 216 } 217 218 // generate the pointer to NSNumber type. 219 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl); 220 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject); 221 } 222 223 // Look for the appropriate method within NSNumber. 224 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel); 225 if (!Method && S.getLangOpts().DebuggerObjCLiteral) { 226 // create a stub definition this NSNumber factory method. 227 TypeSourceInfo *ResultTInfo = 0; 228 Method = ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel, 229 S.NSNumberPointer, ResultTInfo, 230 S.NSNumberDecl, 231 /*isInstance=*/false, /*isVariadic=*/false, 232 /*isPropertyAccessor=*/false, 233 /*isImplicitlyDeclared=*/true, 234 /*isDefined=*/false, 235 ObjCMethodDecl::Required, 236 /*HasRelatedResultType=*/false); 237 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method, 238 SourceLocation(), SourceLocation(), 239 &CX.Idents.get("value"), 240 NumberType, /*TInfo=*/0, SC_None, 241 0); 242 Method->setMethodParams(S.Context, value, None); 243 } 244 245 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method)) 246 return 0; 247 248 // Note: if the parameter type is out-of-line, we'll catch it later in the 249 // implicit conversion. 250 251 S.NSNumberLiteralMethods[*Kind] = Method; 252 return Method; 253 } 254 255 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the 256 /// numeric literal expression. Type of the expression will be "NSNumber *". 257 ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) { 258 // Determine the type of the literal. 259 QualType NumberType = Number->getType(); 260 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) { 261 // In C, character literals have type 'int'. That's not the type we want 262 // to use to determine the Objective-c literal kind. 263 switch (Char->getKind()) { 264 case CharacterLiteral::Ascii: 265 NumberType = Context.CharTy; 266 break; 267 268 case CharacterLiteral::Wide: 269 NumberType = Context.getWideCharType(); 270 break; 271 272 case CharacterLiteral::UTF16: 273 NumberType = Context.Char16Ty; 274 break; 275 276 case CharacterLiteral::UTF32: 277 NumberType = Context.Char32Ty; 278 break; 279 } 280 } 281 282 // Look for the appropriate method within NSNumber. 283 // Construct the literal. 284 SourceRange NR(Number->getSourceRange()); 285 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType, 286 true, NR); 287 if (!Method) 288 return ExprError(); 289 290 // Convert the number to the type that the parameter expects. 291 ParmVarDecl *ParamDecl = Method->param_begin()[0]; 292 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 293 ParamDecl); 294 ExprResult ConvertedNumber = PerformCopyInitialization(Entity, 295 SourceLocation(), 296 Owned(Number)); 297 if (ConvertedNumber.isInvalid()) 298 return ExprError(); 299 Number = ConvertedNumber.get(); 300 301 // Use the effective source range of the literal, including the leading '@'. 302 return MaybeBindToTemporary( 303 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method, 304 SourceRange(AtLoc, NR.getEnd()))); 305 } 306 307 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc, 308 SourceLocation ValueLoc, 309 bool Value) { 310 ExprResult Inner; 311 if (getLangOpts().CPlusPlus) { 312 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false); 313 } else { 314 // C doesn't actually have a way to represent literal values of type 315 // _Bool. So, we'll use 0/1 and implicit cast to _Bool. 316 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0); 317 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy, 318 CK_IntegralToBoolean); 319 } 320 321 return BuildObjCNumericLiteral(AtLoc, Inner.get()); 322 } 323 324 /// \brief Check that the given expression is a valid element of an Objective-C 325 /// collection literal. 326 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, 327 QualType T, 328 bool ArrayLiteral = false) { 329 // If the expression is type-dependent, there's nothing for us to do. 330 if (Element->isTypeDependent()) 331 return Element; 332 333 ExprResult Result = S.CheckPlaceholderExpr(Element); 334 if (Result.isInvalid()) 335 return ExprError(); 336 Element = Result.get(); 337 338 // In C++, check for an implicit conversion to an Objective-C object pointer 339 // type. 340 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) { 341 InitializedEntity Entity 342 = InitializedEntity::InitializeParameter(S.Context, T, 343 /*Consumed=*/false); 344 InitializationKind Kind 345 = InitializationKind::CreateCopy(Element->getLocStart(), 346 SourceLocation()); 347 InitializationSequence Seq(S, Entity, Kind, Element); 348 if (!Seq.Failed()) 349 return Seq.Perform(S, Entity, Kind, Element); 350 } 351 352 Expr *OrigElement = Element; 353 354 // Perform lvalue-to-rvalue conversion. 355 Result = S.DefaultLvalueConversion(Element); 356 if (Result.isInvalid()) 357 return ExprError(); 358 Element = Result.get(); 359 360 // Make sure that we have an Objective-C pointer type or block. 361 if (!Element->getType()->isObjCObjectPointerType() && 362 !Element->getType()->isBlockPointerType()) { 363 bool Recovered = false; 364 365 // If this is potentially an Objective-C numeric literal, add the '@'. 366 if (isa<IntegerLiteral>(OrigElement) || 367 isa<CharacterLiteral>(OrigElement) || 368 isa<FloatingLiteral>(OrigElement) || 369 isa<ObjCBoolLiteralExpr>(OrigElement) || 370 isa<CXXBoolLiteralExpr>(OrigElement)) { 371 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) { 372 int Which = isa<CharacterLiteral>(OrigElement) ? 1 373 : (isa<CXXBoolLiteralExpr>(OrigElement) || 374 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2 375 : 3; 376 377 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection) 378 << Which << OrigElement->getSourceRange() 379 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@"); 380 381 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(), 382 OrigElement); 383 if (Result.isInvalid()) 384 return ExprError(); 385 386 Element = Result.get(); 387 Recovered = true; 388 } 389 } 390 // If this is potentially an Objective-C string literal, add the '@'. 391 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) { 392 if (String->isAscii()) { 393 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection) 394 << 0 << OrigElement->getSourceRange() 395 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@"); 396 397 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String); 398 if (Result.isInvalid()) 399 return ExprError(); 400 401 Element = Result.get(); 402 Recovered = true; 403 } 404 } 405 406 if (!Recovered) { 407 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element) 408 << Element->getType(); 409 return ExprError(); 410 } 411 } 412 if (ArrayLiteral) 413 if (ObjCStringLiteral *getString = dyn_cast<ObjCStringLiteral>(OrigElement)) { 414 if (getString->getString() && getString->getString()->getNumConcatenated() > 1) 415 S.Diag(Element->getLocStart(), diag::warn_concatenated_nsarray_literal) 416 << Element->getType(); 417 } 418 419 // Make sure that the element has the type that the container factory 420 // function expects. 421 return S.PerformCopyInitialization( 422 InitializedEntity::InitializeParameter(S.Context, T, 423 /*Consumed=*/false), 424 Element->getLocStart(), Element); 425 } 426 427 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { 428 if (ValueExpr->isTypeDependent()) { 429 ObjCBoxedExpr *BoxedExpr = 430 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, NULL, SR); 431 return Owned(BoxedExpr); 432 } 433 ObjCMethodDecl *BoxingMethod = NULL; 434 QualType BoxedType; 435 // Convert the expression to an RValue, so we can check for pointer types... 436 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr); 437 if (RValue.isInvalid()) { 438 return ExprError(); 439 } 440 ValueExpr = RValue.get(); 441 QualType ValueType(ValueExpr->getType()); 442 if (const PointerType *PT = ValueType->getAs<PointerType>()) { 443 QualType PointeeType = PT->getPointeeType(); 444 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) { 445 446 if (!NSStringDecl) { 447 IdentifierInfo *NSStringId = 448 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString); 449 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId, 450 SR.getBegin(), LookupOrdinaryName); 451 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl); 452 if (!NSStringDecl) { 453 if (getLangOpts().DebuggerObjCLiteral) { 454 // Support boxed expressions in the debugger w/o NSString declaration. 455 DeclContext *TU = Context.getTranslationUnitDecl(); 456 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU, 457 SourceLocation(), 458 NSStringId, 459 0, SourceLocation()); 460 } else { 461 Diag(SR.getBegin(), diag::err_undeclared_nsstring); 462 return ExprError(); 463 } 464 } else if (!NSStringDecl->hasDefinition()) { 465 Diag(SR.getBegin(), diag::err_undeclared_nsstring); 466 return ExprError(); 467 } 468 assert(NSStringDecl && "NSStringDecl should not be NULL"); 469 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl); 470 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject); 471 } 472 473 if (!StringWithUTF8StringMethod) { 474 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String"); 475 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II); 476 477 // Look for the appropriate method within NSString. 478 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String); 479 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) { 480 // Debugger needs to work even if NSString hasn't been defined. 481 TypeSourceInfo *ResultTInfo = 0; 482 ObjCMethodDecl *M = 483 ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(), 484 stringWithUTF8String, NSStringPointer, 485 ResultTInfo, NSStringDecl, 486 /*isInstance=*/false, /*isVariadic=*/false, 487 /*isPropertyAccessor=*/false, 488 /*isImplicitlyDeclared=*/true, 489 /*isDefined=*/false, 490 ObjCMethodDecl::Required, 491 /*HasRelatedResultType=*/false); 492 QualType ConstCharType = Context.CharTy.withConst(); 493 ParmVarDecl *value = 494 ParmVarDecl::Create(Context, M, 495 SourceLocation(), SourceLocation(), 496 &Context.Idents.get("value"), 497 Context.getPointerType(ConstCharType), 498 /*TInfo=*/0, 499 SC_None, 0); 500 M->setMethodParams(Context, value, None); 501 BoxingMethod = M; 502 } 503 504 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl, 505 stringWithUTF8String, BoxingMethod)) 506 return ExprError(); 507 508 StringWithUTF8StringMethod = BoxingMethod; 509 } 510 511 BoxingMethod = StringWithUTF8StringMethod; 512 BoxedType = NSStringPointer; 513 } 514 } else if (ValueType->isBuiltinType()) { 515 // The other types we support are numeric, char and BOOL/bool. We could also 516 // provide limited support for structure types, such as NSRange, NSRect, and 517 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h> 518 // for more details. 519 520 // Check for a top-level character literal. 521 if (const CharacterLiteral *Char = 522 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) { 523 // In C, character literals have type 'int'. That's not the type we want 524 // to use to determine the Objective-c literal kind. 525 switch (Char->getKind()) { 526 case CharacterLiteral::Ascii: 527 ValueType = Context.CharTy; 528 break; 529 530 case CharacterLiteral::Wide: 531 ValueType = Context.getWideCharType(); 532 break; 533 534 case CharacterLiteral::UTF16: 535 ValueType = Context.Char16Ty; 536 break; 537 538 case CharacterLiteral::UTF32: 539 ValueType = Context.Char32Ty; 540 break; 541 } 542 } 543 544 // FIXME: Do I need to do anything special with BoolTy expressions? 545 546 // Look for the appropriate method within NSNumber. 547 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType); 548 BoxedType = NSNumberPointer; 549 550 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) { 551 if (!ET->getDecl()->isComplete()) { 552 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type) 553 << ValueType << ValueExpr->getSourceRange(); 554 return ExprError(); 555 } 556 557 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), 558 ET->getDecl()->getIntegerType()); 559 BoxedType = NSNumberPointer; 560 } 561 562 if (!BoxingMethod) { 563 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type) 564 << ValueType << ValueExpr->getSourceRange(); 565 return ExprError(); 566 } 567 568 // Convert the expression to the type that the parameter requires. 569 ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0]; 570 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 571 ParamDecl); 572 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity, 573 SourceLocation(), 574 Owned(ValueExpr)); 575 if (ConvertedValueExpr.isInvalid()) 576 return ExprError(); 577 ValueExpr = ConvertedValueExpr.get(); 578 579 ObjCBoxedExpr *BoxedExpr = 580 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType, 581 BoxingMethod, SR); 582 return MaybeBindToTemporary(BoxedExpr); 583 } 584 585 /// Build an ObjC subscript pseudo-object expression, given that 586 /// that's supported by the runtime. 587 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 588 Expr *IndexExpr, 589 ObjCMethodDecl *getterMethod, 590 ObjCMethodDecl *setterMethod) { 591 assert(!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic()); 592 593 // We can't get dependent types here; our callers should have 594 // filtered them out. 595 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) && 596 "base or index cannot have dependent type here"); 597 598 // Filter out placeholders in the index. In theory, overloads could 599 // be preserved here, although that might not actually work correctly. 600 ExprResult Result = CheckPlaceholderExpr(IndexExpr); 601 if (Result.isInvalid()) 602 return ExprError(); 603 IndexExpr = Result.get(); 604 605 // Perform lvalue-to-rvalue conversion on the base. 606 Result = DefaultLvalueConversion(BaseExpr); 607 if (Result.isInvalid()) 608 return ExprError(); 609 BaseExpr = Result.get(); 610 611 // Build the pseudo-object expression. 612 return Owned(ObjCSubscriptRefExpr::Create(Context, 613 BaseExpr, 614 IndexExpr, 615 Context.PseudoObjectTy, 616 getterMethod, 617 setterMethod, RB)); 618 619 } 620 621 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) { 622 // Look up the NSArray class, if we haven't done so already. 623 if (!NSArrayDecl) { 624 NamedDecl *IF = LookupSingleName(TUScope, 625 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray), 626 SR.getBegin(), 627 LookupOrdinaryName); 628 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 629 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral) 630 NSArrayDecl = ObjCInterfaceDecl::Create (Context, 631 Context.getTranslationUnitDecl(), 632 SourceLocation(), 633 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray), 634 0, SourceLocation()); 635 636 if (!NSArrayDecl) { 637 Diag(SR.getBegin(), diag::err_undeclared_nsarray); 638 return ExprError(); 639 } 640 } 641 642 // Find the arrayWithObjects:count: method, if we haven't done so already. 643 QualType IdT = Context.getObjCIdType(); 644 if (!ArrayWithObjectsMethod) { 645 Selector 646 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount); 647 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel); 648 if (!Method && getLangOpts().DebuggerObjCLiteral) { 649 TypeSourceInfo *ResultTInfo = 0; 650 Method = ObjCMethodDecl::Create(Context, 651 SourceLocation(), SourceLocation(), Sel, 652 IdT, 653 ResultTInfo, 654 Context.getTranslationUnitDecl(), 655 false /*Instance*/, false/*isVariadic*/, 656 /*isPropertyAccessor=*/false, 657 /*isImplicitlyDeclared=*/true, /*isDefined=*/false, 658 ObjCMethodDecl::Required, 659 false); 660 SmallVector<ParmVarDecl *, 2> Params; 661 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method, 662 SourceLocation(), 663 SourceLocation(), 664 &Context.Idents.get("objects"), 665 Context.getPointerType(IdT), 666 /*TInfo=*/0, SC_None, 0); 667 Params.push_back(objects); 668 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method, 669 SourceLocation(), 670 SourceLocation(), 671 &Context.Idents.get("cnt"), 672 Context.UnsignedLongTy, 673 /*TInfo=*/0, SC_None, 0); 674 Params.push_back(cnt); 675 Method->setMethodParams(Context, Params, None); 676 } 677 678 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method)) 679 return ExprError(); 680 681 // Dig out the type that all elements should be converted to. 682 QualType T = Method->param_begin()[0]->getType(); 683 const PointerType *PtrT = T->getAs<PointerType>(); 684 if (!PtrT || 685 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) { 686 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 687 << Sel; 688 Diag(Method->param_begin()[0]->getLocation(), 689 diag::note_objc_literal_method_param) 690 << 0 << T 691 << Context.getPointerType(IdT.withConst()); 692 return ExprError(); 693 } 694 695 // Check that the 'count' parameter is integral. 696 if (!Method->param_begin()[1]->getType()->isIntegerType()) { 697 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 698 << Sel; 699 Diag(Method->param_begin()[1]->getLocation(), 700 diag::note_objc_literal_method_param) 701 << 1 702 << Method->param_begin()[1]->getType() 703 << "integral"; 704 return ExprError(); 705 } 706 707 // We've found a good +arrayWithObjects:count: method. Save it! 708 ArrayWithObjectsMethod = Method; 709 } 710 711 QualType ObjectsType = ArrayWithObjectsMethod->param_begin()[0]->getType(); 712 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType(); 713 714 // Check that each of the elements provided is valid in a collection literal, 715 // performing conversions as necessary. 716 Expr **ElementsBuffer = Elements.data(); 717 for (unsigned I = 0, N = Elements.size(); I != N; ++I) { 718 ExprResult Converted = CheckObjCCollectionLiteralElement(*this, 719 ElementsBuffer[I], 720 RequiredType, true); 721 if (Converted.isInvalid()) 722 return ExprError(); 723 724 ElementsBuffer[I] = Converted.get(); 725 } 726 727 QualType Ty 728 = Context.getObjCObjectPointerType( 729 Context.getObjCInterfaceType(NSArrayDecl)); 730 731 return MaybeBindToTemporary( 732 ObjCArrayLiteral::Create(Context, Elements, Ty, 733 ArrayWithObjectsMethod, SR)); 734 } 735 736 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, 737 ObjCDictionaryElement *Elements, 738 unsigned NumElements) { 739 // Look up the NSDictionary class, if we haven't done so already. 740 if (!NSDictionaryDecl) { 741 NamedDecl *IF = LookupSingleName(TUScope, 742 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary), 743 SR.getBegin(), LookupOrdinaryName); 744 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 745 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral) 746 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context, 747 Context.getTranslationUnitDecl(), 748 SourceLocation(), 749 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary), 750 0, SourceLocation()); 751 752 if (!NSDictionaryDecl) { 753 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary); 754 return ExprError(); 755 } 756 } 757 758 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done 759 // so already. 760 QualType IdT = Context.getObjCIdType(); 761 if (!DictionaryWithObjectsMethod) { 762 Selector Sel = NSAPIObj->getNSDictionarySelector( 763 NSAPI::NSDict_dictionaryWithObjectsForKeysCount); 764 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel); 765 if (!Method && getLangOpts().DebuggerObjCLiteral) { 766 Method = ObjCMethodDecl::Create(Context, 767 SourceLocation(), SourceLocation(), Sel, 768 IdT, 769 0 /*TypeSourceInfo */, 770 Context.getTranslationUnitDecl(), 771 false /*Instance*/, false/*isVariadic*/, 772 /*isPropertyAccessor=*/false, 773 /*isImplicitlyDeclared=*/true, /*isDefined=*/false, 774 ObjCMethodDecl::Required, 775 false); 776 SmallVector<ParmVarDecl *, 3> Params; 777 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method, 778 SourceLocation(), 779 SourceLocation(), 780 &Context.Idents.get("objects"), 781 Context.getPointerType(IdT), 782 /*TInfo=*/0, SC_None, 0); 783 Params.push_back(objects); 784 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method, 785 SourceLocation(), 786 SourceLocation(), 787 &Context.Idents.get("keys"), 788 Context.getPointerType(IdT), 789 /*TInfo=*/0, SC_None, 0); 790 Params.push_back(keys); 791 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method, 792 SourceLocation(), 793 SourceLocation(), 794 &Context.Idents.get("cnt"), 795 Context.UnsignedLongTy, 796 /*TInfo=*/0, SC_None, 0); 797 Params.push_back(cnt); 798 Method->setMethodParams(Context, Params, None); 799 } 800 801 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel, 802 Method)) 803 return ExprError(); 804 805 // Dig out the type that all values should be converted to. 806 QualType ValueT = Method->param_begin()[0]->getType(); 807 const PointerType *PtrValue = ValueT->getAs<PointerType>(); 808 if (!PtrValue || 809 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) { 810 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 811 << Sel; 812 Diag(Method->param_begin()[0]->getLocation(), 813 diag::note_objc_literal_method_param) 814 << 0 << ValueT 815 << Context.getPointerType(IdT.withConst()); 816 return ExprError(); 817 } 818 819 // Dig out the type that all keys should be converted to. 820 QualType KeyT = Method->param_begin()[1]->getType(); 821 const PointerType *PtrKey = KeyT->getAs<PointerType>(); 822 if (!PtrKey || 823 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), 824 IdT)) { 825 bool err = true; 826 if (PtrKey) { 827 if (QIDNSCopying.isNull()) { 828 // key argument of selector is id<NSCopying>? 829 if (ObjCProtocolDecl *NSCopyingPDecl = 830 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) { 831 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl}; 832 QIDNSCopying = 833 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 834 (ObjCProtocolDecl**) PQ,1); 835 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying); 836 } 837 } 838 if (!QIDNSCopying.isNull()) 839 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), 840 QIDNSCopying); 841 } 842 843 if (err) { 844 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 845 << Sel; 846 Diag(Method->param_begin()[1]->getLocation(), 847 diag::note_objc_literal_method_param) 848 << 1 << KeyT 849 << Context.getPointerType(IdT.withConst()); 850 return ExprError(); 851 } 852 } 853 854 // Check that the 'count' parameter is integral. 855 QualType CountType = Method->param_begin()[2]->getType(); 856 if (!CountType->isIntegerType()) { 857 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 858 << Sel; 859 Diag(Method->param_begin()[2]->getLocation(), 860 diag::note_objc_literal_method_param) 861 << 2 << CountType 862 << "integral"; 863 return ExprError(); 864 } 865 866 // We've found a good +dictionaryWithObjects:keys:count: method; save it! 867 DictionaryWithObjectsMethod = Method; 868 } 869 870 QualType ValuesT = DictionaryWithObjectsMethod->param_begin()[0]->getType(); 871 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType(); 872 QualType KeysT = DictionaryWithObjectsMethod->param_begin()[1]->getType(); 873 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType(); 874 875 // Check that each of the keys and values provided is valid in a collection 876 // literal, performing conversions as necessary. 877 bool HasPackExpansions = false; 878 for (unsigned I = 0, N = NumElements; I != N; ++I) { 879 // Check the key. 880 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key, 881 KeyT); 882 if (Key.isInvalid()) 883 return ExprError(); 884 885 // Check the value. 886 ExprResult Value 887 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT); 888 if (Value.isInvalid()) 889 return ExprError(); 890 891 Elements[I].Key = Key.get(); 892 Elements[I].Value = Value.get(); 893 894 if (Elements[I].EllipsisLoc.isInvalid()) 895 continue; 896 897 if (!Elements[I].Key->containsUnexpandedParameterPack() && 898 !Elements[I].Value->containsUnexpandedParameterPack()) { 899 Diag(Elements[I].EllipsisLoc, 900 diag::err_pack_expansion_without_parameter_packs) 901 << SourceRange(Elements[I].Key->getLocStart(), 902 Elements[I].Value->getLocEnd()); 903 return ExprError(); 904 } 905 906 HasPackExpansions = true; 907 } 908 909 910 QualType Ty 911 = Context.getObjCObjectPointerType( 912 Context.getObjCInterfaceType(NSDictionaryDecl)); 913 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create( 914 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty, 915 DictionaryWithObjectsMethod, SR)); 916 } 917 918 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc, 919 TypeSourceInfo *EncodedTypeInfo, 920 SourceLocation RParenLoc) { 921 QualType EncodedType = EncodedTypeInfo->getType(); 922 QualType StrTy; 923 if (EncodedType->isDependentType()) 924 StrTy = Context.DependentTy; 925 else { 926 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled. 927 !EncodedType->isVoidType()) // void is handled too. 928 if (RequireCompleteType(AtLoc, EncodedType, 929 diag::err_incomplete_type_objc_at_encode, 930 EncodedTypeInfo->getTypeLoc())) 931 return ExprError(); 932 933 std::string Str; 934 Context.getObjCEncodingForType(EncodedType, Str); 935 936 // The type of @encode is the same as the type of the corresponding string, 937 // which is an array type. 938 StrTy = Context.CharTy; 939 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 940 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 941 StrTy.addConst(); 942 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1), 943 ArrayType::Normal, 0); 944 } 945 946 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc); 947 } 948 949 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc, 950 SourceLocation EncodeLoc, 951 SourceLocation LParenLoc, 952 ParsedType ty, 953 SourceLocation RParenLoc) { 954 // FIXME: Preserve type source info ? 955 TypeSourceInfo *TInfo; 956 QualType EncodedType = GetTypeFromParser(ty, &TInfo); 957 if (!TInfo) 958 TInfo = Context.getTrivialTypeSourceInfo(EncodedType, 959 PP.getLocForEndOfToken(LParenLoc)); 960 961 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc); 962 } 963 964 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, 965 SourceLocation AtLoc, 966 SourceLocation SelLoc, 967 SourceLocation LParenLoc, 968 SourceLocation RParenLoc) { 969 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel, 970 SourceRange(LParenLoc, RParenLoc), false, false); 971 if (!Method) 972 Method = LookupFactoryMethodInGlobalPool(Sel, 973 SourceRange(LParenLoc, RParenLoc)); 974 if (!Method) { 975 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) { 976 Selector MatchedSel = OM->getSelector(); 977 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1), 978 RParenLoc.getLocWithOffset(-1)); 979 Diag(SelLoc, diag::warn_undeclared_selector_with_typo) 980 << Sel << MatchedSel 981 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString()); 982 983 } else 984 Diag(SelLoc, diag::warn_undeclared_selector) << Sel; 985 } 986 987 if (!Method || 988 Method->getImplementationControl() != ObjCMethodDecl::Optional) { 989 llvm::DenseMap<Selector, SourceLocation>::iterator Pos 990 = ReferencedSelectors.find(Sel); 991 if (Pos == ReferencedSelectors.end()) 992 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc)); 993 } 994 995 // In ARC, forbid the user from using @selector for 996 // retain/release/autorelease/dealloc/retainCount. 997 if (getLangOpts().ObjCAutoRefCount) { 998 switch (Sel.getMethodFamily()) { 999 case OMF_retain: 1000 case OMF_release: 1001 case OMF_autorelease: 1002 case OMF_retainCount: 1003 case OMF_dealloc: 1004 Diag(AtLoc, diag::err_arc_illegal_selector) << 1005 Sel << SourceRange(LParenLoc, RParenLoc); 1006 break; 1007 1008 case OMF_None: 1009 case OMF_alloc: 1010 case OMF_copy: 1011 case OMF_finalize: 1012 case OMF_init: 1013 case OMF_mutableCopy: 1014 case OMF_new: 1015 case OMF_self: 1016 case OMF_performSelector: 1017 break; 1018 } 1019 } 1020 QualType Ty = Context.getObjCSelType(); 1021 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc); 1022 } 1023 1024 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId, 1025 SourceLocation AtLoc, 1026 SourceLocation ProtoLoc, 1027 SourceLocation LParenLoc, 1028 SourceLocation ProtoIdLoc, 1029 SourceLocation RParenLoc) { 1030 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc); 1031 if (!PDecl) { 1032 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId; 1033 return true; 1034 } 1035 1036 QualType Ty = Context.getObjCProtoType(); 1037 if (Ty.isNull()) 1038 return true; 1039 Ty = Context.getObjCObjectPointerType(Ty); 1040 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc); 1041 } 1042 1043 /// Try to capture an implicit reference to 'self'. 1044 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) { 1045 DeclContext *DC = getFunctionLevelDeclContext(); 1046 1047 // If we're not in an ObjC method, error out. Note that, unlike the 1048 // C++ case, we don't require an instance method --- class methods 1049 // still have a 'self', and we really do still need to capture it! 1050 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC); 1051 if (!method) 1052 return 0; 1053 1054 tryCaptureVariable(method->getSelfDecl(), Loc); 1055 1056 return method; 1057 } 1058 1059 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) { 1060 if (T == Context.getObjCInstanceType()) 1061 return Context.getObjCIdType(); 1062 1063 return T; 1064 } 1065 1066 QualType Sema::getMessageSendResultType(QualType ReceiverType, 1067 ObjCMethodDecl *Method, 1068 bool isClassMessage, bool isSuperMessage) { 1069 assert(Method && "Must have a method"); 1070 if (!Method->hasRelatedResultType()) 1071 return Method->getSendResultType(); 1072 1073 // If a method has a related return type: 1074 // - if the method found is an instance method, but the message send 1075 // was a class message send, T is the declared return type of the method 1076 // found 1077 if (Method->isInstanceMethod() && isClassMessage) 1078 return stripObjCInstanceType(Context, Method->getSendResultType()); 1079 1080 // - if the receiver is super, T is a pointer to the class of the 1081 // enclosing method definition 1082 if (isSuperMessage) { 1083 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) 1084 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) 1085 return Context.getObjCObjectPointerType( 1086 Context.getObjCInterfaceType(Class)); 1087 } 1088 1089 // - if the receiver is the name of a class U, T is a pointer to U 1090 if (ReceiverType->getAs<ObjCInterfaceType>() || 1091 ReceiverType->isObjCQualifiedInterfaceType()) 1092 return Context.getObjCObjectPointerType(ReceiverType); 1093 // - if the receiver is of type Class or qualified Class type, 1094 // T is the declared return type of the method. 1095 if (ReceiverType->isObjCClassType() || 1096 ReceiverType->isObjCQualifiedClassType()) 1097 return stripObjCInstanceType(Context, Method->getSendResultType()); 1098 1099 // - if the receiver is id, qualified id, Class, or qualified Class, T 1100 // is the receiver type, otherwise 1101 // - T is the type of the receiver expression. 1102 return ReceiverType; 1103 } 1104 1105 /// Look for an ObjC method whose result type exactly matches the given type. 1106 static const ObjCMethodDecl * 1107 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD, 1108 QualType instancetype) { 1109 if (MD->getResultType() == instancetype) return MD; 1110 1111 // For these purposes, a method in an @implementation overrides a 1112 // declaration in the @interface. 1113 if (const ObjCImplDecl *impl = 1114 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) { 1115 const ObjCContainerDecl *iface; 1116 if (const ObjCCategoryImplDecl *catImpl = 1117 dyn_cast<ObjCCategoryImplDecl>(impl)) { 1118 iface = catImpl->getCategoryDecl(); 1119 } else { 1120 iface = impl->getClassInterface(); 1121 } 1122 1123 const ObjCMethodDecl *ifaceMD = 1124 iface->getMethod(MD->getSelector(), MD->isInstanceMethod()); 1125 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype); 1126 } 1127 1128 SmallVector<const ObjCMethodDecl *, 4> overrides; 1129 MD->getOverriddenMethods(overrides); 1130 for (unsigned i = 0, e = overrides.size(); i != e; ++i) { 1131 if (const ObjCMethodDecl *result = 1132 findExplicitInstancetypeDeclarer(overrides[i], instancetype)) 1133 return result; 1134 } 1135 1136 return 0; 1137 } 1138 1139 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) { 1140 // Only complain if we're in an ObjC method and the required return 1141 // type doesn't match the method's declared return type. 1142 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext); 1143 if (!MD || !MD->hasRelatedResultType() || 1144 Context.hasSameUnqualifiedType(destType, MD->getResultType())) 1145 return; 1146 1147 // Look for a method overridden by this method which explicitly uses 1148 // 'instancetype'. 1149 if (const ObjCMethodDecl *overridden = 1150 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) { 1151 SourceLocation loc; 1152 SourceRange range; 1153 if (TypeSourceInfo *TSI = overridden->getResultTypeSourceInfo()) { 1154 range = TSI->getTypeLoc().getSourceRange(); 1155 loc = range.getBegin(); 1156 } 1157 if (loc.isInvalid()) 1158 loc = overridden->getLocation(); 1159 Diag(loc, diag::note_related_result_type_explicit) 1160 << /*current method*/ 1 << range; 1161 return; 1162 } 1163 1164 // Otherwise, if we have an interesting method family, note that. 1165 // This should always trigger if the above didn't. 1166 if (ObjCMethodFamily family = MD->getMethodFamily()) 1167 Diag(MD->getLocation(), diag::note_related_result_type_family) 1168 << /*current method*/ 1 1169 << family; 1170 } 1171 1172 void Sema::EmitRelatedResultTypeNote(const Expr *E) { 1173 E = E->IgnoreParenImpCasts(); 1174 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E); 1175 if (!MsgSend) 1176 return; 1177 1178 const ObjCMethodDecl *Method = MsgSend->getMethodDecl(); 1179 if (!Method) 1180 return; 1181 1182 if (!Method->hasRelatedResultType()) 1183 return; 1184 1185 if (Context.hasSameUnqualifiedType(Method->getResultType() 1186 .getNonReferenceType(), 1187 MsgSend->getType())) 1188 return; 1189 1190 if (!Context.hasSameUnqualifiedType(Method->getResultType(), 1191 Context.getObjCInstanceType())) 1192 return; 1193 1194 Diag(Method->getLocation(), diag::note_related_result_type_inferred) 1195 << Method->isInstanceMethod() << Method->getSelector() 1196 << MsgSend->getType(); 1197 } 1198 1199 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType, 1200 MultiExprArg Args, 1201 Selector Sel, 1202 ArrayRef<SourceLocation> SelectorLocs, 1203 ObjCMethodDecl *Method, 1204 bool isClassMessage, bool isSuperMessage, 1205 SourceLocation lbrac, SourceLocation rbrac, 1206 QualType &ReturnType, ExprValueKind &VK) { 1207 SourceLocation SelLoc; 1208 if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) 1209 SelLoc = SelectorLocs.front(); 1210 else 1211 SelLoc = lbrac; 1212 1213 if (!Method) { 1214 // Apply default argument promotion as for (C99 6.5.2.2p6). 1215 for (unsigned i = 0, e = Args.size(); i != e; i++) { 1216 if (Args[i]->isTypeDependent()) 1217 continue; 1218 1219 ExprResult result; 1220 if (getLangOpts().DebuggerSupport) { 1221 QualType paramTy; // ignored 1222 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy); 1223 } else { 1224 result = DefaultArgumentPromotion(Args[i]); 1225 } 1226 if (result.isInvalid()) 1227 return true; 1228 Args[i] = result.take(); 1229 } 1230 1231 unsigned DiagID; 1232 if (getLangOpts().ObjCAutoRefCount) 1233 DiagID = diag::err_arc_method_not_found; 1234 else 1235 DiagID = isClassMessage ? diag::warn_class_method_not_found 1236 : diag::warn_inst_method_not_found; 1237 if (!getLangOpts().DebuggerSupport) { 1238 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType); 1239 if (OMD && !OMD->isInvalidDecl()) { 1240 if (getLangOpts().ObjCAutoRefCount) 1241 DiagID = diag::error_method_not_found_with_typo; 1242 else 1243 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo 1244 : diag::warn_instance_method_not_found_with_typo; 1245 Selector MatchedSel = OMD->getSelector(); 1246 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back()); 1247 Diag(SelLoc, DiagID) 1248 << Sel<< isClassMessage << MatchedSel 1249 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString()); 1250 } 1251 else 1252 Diag(SelLoc, DiagID) 1253 << Sel << isClassMessage << SourceRange(SelectorLocs.front(), 1254 SelectorLocs.back()); 1255 // Find the class to which we are sending this message. 1256 if (ReceiverType->isObjCObjectPointerType()) { 1257 if (ObjCInterfaceDecl *Class = 1258 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) 1259 Diag(Class->getLocation(), diag::note_receiver_class_declared); 1260 } 1261 } 1262 1263 // In debuggers, we want to use __unknown_anytype for these 1264 // results so that clients can cast them. 1265 if (getLangOpts().DebuggerSupport) { 1266 ReturnType = Context.UnknownAnyTy; 1267 } else { 1268 ReturnType = Context.getObjCIdType(); 1269 } 1270 VK = VK_RValue; 1271 return false; 1272 } 1273 1274 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage, 1275 isSuperMessage); 1276 VK = Expr::getValueKindForType(Method->getResultType()); 1277 1278 unsigned NumNamedArgs = Sel.getNumArgs(); 1279 // Method might have more arguments than selector indicates. This is due 1280 // to addition of c-style arguments in method. 1281 if (Method->param_size() > Sel.getNumArgs()) 1282 NumNamedArgs = Method->param_size(); 1283 // FIXME. This need be cleaned up. 1284 if (Args.size() < NumNamedArgs) { 1285 Diag(SelLoc, diag::err_typecheck_call_too_few_args) 1286 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size()); 1287 return false; 1288 } 1289 1290 bool IsError = false; 1291 for (unsigned i = 0; i < NumNamedArgs; i++) { 1292 // We can't do any type-checking on a type-dependent argument. 1293 if (Args[i]->isTypeDependent()) 1294 continue; 1295 1296 Expr *argExpr = Args[i]; 1297 1298 ParmVarDecl *param = Method->param_begin()[i]; 1299 assert(argExpr && "CheckMessageArgumentTypes(): missing expression"); 1300 1301 // Strip the unbridged-cast placeholder expression off unless it's 1302 // a consumed argument. 1303 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 1304 !param->hasAttr<CFConsumedAttr>()) 1305 argExpr = stripARCUnbridgedCast(argExpr); 1306 1307 // If the parameter is __unknown_anytype, infer its type 1308 // from the argument. 1309 if (param->getType() == Context.UnknownAnyTy) { 1310 QualType paramType; 1311 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType); 1312 if (argE.isInvalid()) { 1313 IsError = true; 1314 } else { 1315 Args[i] = argE.take(); 1316 1317 // Update the parameter type in-place. 1318 param->setType(paramType); 1319 } 1320 continue; 1321 } 1322 1323 if (RequireCompleteType(argExpr->getSourceRange().getBegin(), 1324 param->getType(), 1325 diag::err_call_incomplete_argument, argExpr)) 1326 return true; 1327 1328 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 1329 param); 1330 ExprResult ArgE = PerformCopyInitialization(Entity, SelLoc, Owned(argExpr)); 1331 if (ArgE.isInvalid()) 1332 IsError = true; 1333 else 1334 Args[i] = ArgE.takeAs<Expr>(); 1335 } 1336 1337 // Promote additional arguments to variadic methods. 1338 if (Method->isVariadic()) { 1339 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 1340 if (Args[i]->isTypeDependent()) 1341 continue; 1342 1343 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 1344 0); 1345 IsError |= Arg.isInvalid(); 1346 Args[i] = Arg.take(); 1347 } 1348 } else { 1349 // Check for extra arguments to non-variadic methods. 1350 if (Args.size() != NumNamedArgs) { 1351 Diag(Args[NumNamedArgs]->getLocStart(), 1352 diag::err_typecheck_call_too_many_args) 1353 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size()) 1354 << Method->getSourceRange() 1355 << SourceRange(Args[NumNamedArgs]->getLocStart(), 1356 Args.back()->getLocEnd()); 1357 } 1358 } 1359 1360 DiagnoseSentinelCalls(Method, SelLoc, Args); 1361 1362 // Do additional checkings on method. 1363 IsError |= CheckObjCMethodCall( 1364 Method, SelLoc, makeArrayRef<const Expr *>(Args.data(), Args.size())); 1365 1366 return IsError; 1367 } 1368 1369 bool Sema::isSelfExpr(Expr *receiver) { 1370 // 'self' is objc 'self' in an objc method only. 1371 ObjCMethodDecl *method = 1372 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor()); 1373 if (!method) return false; 1374 1375 receiver = receiver->IgnoreParenLValueCasts(); 1376 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver)) 1377 if (DRE->getDecl() == method->getSelfDecl()) 1378 return true; 1379 return false; 1380 } 1381 1382 /// LookupMethodInType - Look up a method in an ObjCObjectType. 1383 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type, 1384 bool isInstance) { 1385 const ObjCObjectType *objType = type->castAs<ObjCObjectType>(); 1386 if (ObjCInterfaceDecl *iface = objType->getInterface()) { 1387 // Look it up in the main interface (and categories, etc.) 1388 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance)) 1389 return method; 1390 1391 // Okay, look for "private" methods declared in any 1392 // @implementations we've seen. 1393 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance)) 1394 return method; 1395 } 1396 1397 // Check qualifiers. 1398 for (ObjCObjectType::qual_iterator 1399 i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i) 1400 if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance)) 1401 return method; 1402 1403 return 0; 1404 } 1405 1406 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier 1407 /// list of a qualified objective pointer type. 1408 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel, 1409 const ObjCObjectPointerType *OPT, 1410 bool Instance) 1411 { 1412 ObjCMethodDecl *MD = 0; 1413 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 1414 E = OPT->qual_end(); I != E; ++I) { 1415 ObjCProtocolDecl *PROTO = (*I); 1416 if ((MD = PROTO->lookupMethod(Sel, Instance))) { 1417 return MD; 1418 } 1419 } 1420 return 0; 1421 } 1422 1423 static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) { 1424 if (!Receiver) 1425 return; 1426 1427 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver)) 1428 Receiver = OVE->getSourceExpr(); 1429 1430 Expr *RExpr = Receiver->IgnoreParenImpCasts(); 1431 SourceLocation Loc = RExpr->getLocStart(); 1432 QualType T = RExpr->getType(); 1433 const ObjCPropertyDecl *PDecl = 0; 1434 const ObjCMethodDecl *GDecl = 0; 1435 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) { 1436 RExpr = POE->getSyntacticForm(); 1437 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) { 1438 if (PRE->isImplicitProperty()) { 1439 GDecl = PRE->getImplicitPropertyGetter(); 1440 if (GDecl) { 1441 T = GDecl->getResultType(); 1442 } 1443 } 1444 else { 1445 PDecl = PRE->getExplicitProperty(); 1446 if (PDecl) { 1447 T = PDecl->getType(); 1448 } 1449 } 1450 } 1451 } 1452 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) { 1453 // See if receiver is a method which envokes a synthesized getter 1454 // backing a 'weak' property. 1455 ObjCMethodDecl *Method = ME->getMethodDecl(); 1456 if (Method && Method->getSelector().getNumArgs() == 0) { 1457 PDecl = Method->findPropertyDecl(); 1458 if (PDecl) 1459 T = PDecl->getType(); 1460 } 1461 } 1462 1463 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) { 1464 if (!PDecl) 1465 return; 1466 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)) 1467 return; 1468 } 1469 1470 S.Diag(Loc, diag::warn_receiver_is_weak) 1471 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2)); 1472 1473 if (PDecl) 1474 S.Diag(PDecl->getLocation(), diag::note_property_declare); 1475 else if (GDecl) 1476 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl; 1477 1478 S.Diag(Loc, diag::note_arc_assign_to_strong); 1479 } 1480 1481 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an 1482 /// objective C interface. This is a property reference expression. 1483 ExprResult Sema:: 1484 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 1485 Expr *BaseExpr, SourceLocation OpLoc, 1486 DeclarationName MemberName, 1487 SourceLocation MemberLoc, 1488 SourceLocation SuperLoc, QualType SuperType, 1489 bool Super) { 1490 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType(); 1491 ObjCInterfaceDecl *IFace = IFaceT->getDecl(); 1492 1493 if (!MemberName.isIdentifier()) { 1494 Diag(MemberLoc, diag::err_invalid_property_name) 1495 << MemberName << QualType(OPT, 0); 1496 return ExprError(); 1497 } 1498 1499 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 1500 1501 SourceRange BaseRange = Super? SourceRange(SuperLoc) 1502 : BaseExpr->getSourceRange(); 1503 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(), 1504 diag::err_property_not_found_forward_class, 1505 MemberName, BaseRange)) 1506 return ExprError(); 1507 1508 // Search for a declared property first. 1509 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) { 1510 // Check whether we can reference this property. 1511 if (DiagnoseUseOfDecl(PD, MemberLoc)) 1512 return ExprError(); 1513 if (Super) 1514 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, 1515 VK_LValue, OK_ObjCProperty, 1516 MemberLoc, 1517 SuperLoc, SuperType)); 1518 else 1519 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, 1520 VK_LValue, OK_ObjCProperty, 1521 MemberLoc, BaseExpr)); 1522 } 1523 // Check protocols on qualified interfaces. 1524 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 1525 E = OPT->qual_end(); I != E; ++I) 1526 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) { 1527 // Check whether we can reference this property. 1528 if (DiagnoseUseOfDecl(PD, MemberLoc)) 1529 return ExprError(); 1530 1531 if (Super) 1532 return Owned(new (Context) ObjCPropertyRefExpr(PD, 1533 Context.PseudoObjectTy, 1534 VK_LValue, 1535 OK_ObjCProperty, 1536 MemberLoc, 1537 SuperLoc, SuperType)); 1538 else 1539 return Owned(new (Context) ObjCPropertyRefExpr(PD, 1540 Context.PseudoObjectTy, 1541 VK_LValue, 1542 OK_ObjCProperty, 1543 MemberLoc, 1544 BaseExpr)); 1545 } 1546 // If that failed, look for an "implicit" property by seeing if the nullary 1547 // selector is implemented. 1548 1549 // FIXME: The logic for looking up nullary and unary selectors should be 1550 // shared with the code in ActOnInstanceMessage. 1551 1552 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 1553 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 1554 1555 // May be founf in property's qualified list. 1556 if (!Getter) 1557 Getter = LookupMethodInQualifiedType(Sel, OPT, true); 1558 1559 // If this reference is in an @implementation, check for 'private' methods. 1560 if (!Getter) 1561 Getter = IFace->lookupPrivateMethod(Sel); 1562 1563 if (Getter) { 1564 // Check if we can reference this property. 1565 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 1566 return ExprError(); 1567 } 1568 // If we found a getter then this may be a valid dot-reference, we 1569 // will look for the matching setter, in case it is needed. 1570 Selector SetterSel = 1571 SelectorTable::constructSetterSelector(PP.getIdentifierTable(), 1572 PP.getSelectorTable(), Member); 1573 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); 1574 1575 // May be founf in property's qualified list. 1576 if (!Setter) 1577 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true); 1578 1579 if (!Setter) { 1580 // If this reference is in an @implementation, also check for 'private' 1581 // methods. 1582 Setter = IFace->lookupPrivateMethod(SetterSel); 1583 } 1584 1585 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 1586 return ExprError(); 1587 1588 if (Getter || Setter) { 1589 if (Super) 1590 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter, 1591 Context.PseudoObjectTy, 1592 VK_LValue, OK_ObjCProperty, 1593 MemberLoc, 1594 SuperLoc, SuperType)); 1595 else 1596 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter, 1597 Context.PseudoObjectTy, 1598 VK_LValue, OK_ObjCProperty, 1599 MemberLoc, BaseExpr)); 1600 1601 } 1602 1603 // Attempt to correct for typos in property names. 1604 DeclFilterCCC<ObjCPropertyDecl> Validator; 1605 if (TypoCorrection Corrected = CorrectTypo( 1606 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL, 1607 NULL, Validator, IFace, false, OPT)) { 1608 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest) 1609 << MemberName << QualType(OPT, 0)); 1610 DeclarationName TypoResult = Corrected.getCorrection(); 1611 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc, 1612 TypoResult, MemberLoc, 1613 SuperLoc, SuperType, Super); 1614 } 1615 ObjCInterfaceDecl *ClassDeclared; 1616 if (ObjCIvarDecl *Ivar = 1617 IFace->lookupInstanceVariable(Member, ClassDeclared)) { 1618 QualType T = Ivar->getType(); 1619 if (const ObjCObjectPointerType * OBJPT = 1620 T->getAsObjCInterfacePointerType()) { 1621 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(), 1622 diag::err_property_not_as_forward_class, 1623 MemberName, BaseExpr)) 1624 return ExprError(); 1625 } 1626 Diag(MemberLoc, 1627 diag::err_ivar_access_using_property_syntax_suggest) 1628 << MemberName << QualType(OPT, 0) << Ivar->getDeclName() 1629 << FixItHint::CreateReplacement(OpLoc, "->"); 1630 return ExprError(); 1631 } 1632 1633 Diag(MemberLoc, diag::err_property_not_found) 1634 << MemberName << QualType(OPT, 0); 1635 if (Setter) 1636 Diag(Setter->getLocation(), diag::note_getter_unavailable) 1637 << MemberName << BaseExpr->getSourceRange(); 1638 return ExprError(); 1639 } 1640 1641 1642 1643 ExprResult Sema:: 1644 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 1645 IdentifierInfo &propertyName, 1646 SourceLocation receiverNameLoc, 1647 SourceLocation propertyNameLoc) { 1648 1649 IdentifierInfo *receiverNamePtr = &receiverName; 1650 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr, 1651 receiverNameLoc); 1652 1653 bool IsSuper = false; 1654 if (IFace == 0) { 1655 // If the "receiver" is 'super' in a method, handle it as an expression-like 1656 // property reference. 1657 if (receiverNamePtr->isStr("super")) { 1658 IsSuper = true; 1659 1660 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) { 1661 if (CurMethod->isInstanceMethod()) { 1662 ObjCInterfaceDecl *Super = 1663 CurMethod->getClassInterface()->getSuperClass(); 1664 if (!Super) { 1665 // The current class does not have a superclass. 1666 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super) 1667 << CurMethod->getClassInterface()->getIdentifier(); 1668 return ExprError(); 1669 } 1670 QualType T = Context.getObjCInterfaceType(Super); 1671 T = Context.getObjCObjectPointerType(T); 1672 1673 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(), 1674 /*BaseExpr*/0, 1675 SourceLocation()/*OpLoc*/, 1676 &propertyName, 1677 propertyNameLoc, 1678 receiverNameLoc, T, true); 1679 } 1680 1681 // Otherwise, if this is a class method, try dispatching to our 1682 // superclass. 1683 IFace = CurMethod->getClassInterface()->getSuperClass(); 1684 } 1685 } 1686 1687 if (IFace == 0) { 1688 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen); 1689 return ExprError(); 1690 } 1691 } 1692 1693 // Search for a declared property first. 1694 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName); 1695 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel); 1696 1697 // If this reference is in an @implementation, check for 'private' methods. 1698 if (!Getter) 1699 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) 1700 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 1701 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation()) 1702 Getter = ImpDecl->getClassMethod(Sel); 1703 1704 if (Getter) { 1705 // FIXME: refactor/share with ActOnMemberReference(). 1706 // Check if we can reference this property. 1707 if (DiagnoseUseOfDecl(Getter, propertyNameLoc)) 1708 return ExprError(); 1709 } 1710 1711 // Look for the matching setter, in case it is needed. 1712 Selector SetterSel = 1713 SelectorTable::constructSetterSelector(PP.getIdentifierTable(), 1714 PP.getSelectorTable(), 1715 &propertyName); 1716 1717 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 1718 if (!Setter) { 1719 // If this reference is in an @implementation, also check for 'private' 1720 // methods. 1721 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) 1722 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 1723 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation()) 1724 Setter = ImpDecl->getClassMethod(SetterSel); 1725 } 1726 // Look through local category implementations associated with the class. 1727 if (!Setter) 1728 Setter = IFace->getCategoryClassMethod(SetterSel); 1729 1730 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc)) 1731 return ExprError(); 1732 1733 if (Getter || Setter) { 1734 if (IsSuper) 1735 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter, 1736 Context.PseudoObjectTy, 1737 VK_LValue, OK_ObjCProperty, 1738 propertyNameLoc, 1739 receiverNameLoc, 1740 Context.getObjCInterfaceType(IFace))); 1741 1742 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter, 1743 Context.PseudoObjectTy, 1744 VK_LValue, OK_ObjCProperty, 1745 propertyNameLoc, 1746 receiverNameLoc, IFace)); 1747 } 1748 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found) 1749 << &propertyName << Context.getObjCInterfaceType(IFace)); 1750 } 1751 1752 namespace { 1753 1754 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback { 1755 public: 1756 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) { 1757 // Determine whether "super" is acceptable in the current context. 1758 if (Method && Method->getClassInterface()) 1759 WantObjCSuper = Method->getClassInterface()->getSuperClass(); 1760 } 1761 1762 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 1763 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() || 1764 candidate.isKeyword("super"); 1765 } 1766 }; 1767 1768 } 1769 1770 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S, 1771 IdentifierInfo *Name, 1772 SourceLocation NameLoc, 1773 bool IsSuper, 1774 bool HasTrailingDot, 1775 ParsedType &ReceiverType) { 1776 ReceiverType = ParsedType(); 1777 1778 // If the identifier is "super" and there is no trailing dot, we're 1779 // messaging super. If the identifier is "super" and there is a 1780 // trailing dot, it's an instance message. 1781 if (IsSuper && S->isInObjcMethodScope()) 1782 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage; 1783 1784 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1785 LookupName(Result, S); 1786 1787 switch (Result.getResultKind()) { 1788 case LookupResult::NotFound: 1789 // Normal name lookup didn't find anything. If we're in an 1790 // Objective-C method, look for ivars. If we find one, we're done! 1791 // FIXME: This is a hack. Ivar lookup should be part of normal 1792 // lookup. 1793 if (ObjCMethodDecl *Method = getCurMethodDecl()) { 1794 if (!Method->getClassInterface()) { 1795 // Fall back: let the parser try to parse it as an instance message. 1796 return ObjCInstanceMessage; 1797 } 1798 1799 ObjCInterfaceDecl *ClassDeclared; 1800 if (Method->getClassInterface()->lookupInstanceVariable(Name, 1801 ClassDeclared)) 1802 return ObjCInstanceMessage; 1803 } 1804 1805 // Break out; we'll perform typo correction below. 1806 break; 1807 1808 case LookupResult::NotFoundInCurrentInstantiation: 1809 case LookupResult::FoundOverloaded: 1810 case LookupResult::FoundUnresolvedValue: 1811 case LookupResult::Ambiguous: 1812 Result.suppressDiagnostics(); 1813 return ObjCInstanceMessage; 1814 1815 case LookupResult::Found: { 1816 // If the identifier is a class or not, and there is a trailing dot, 1817 // it's an instance message. 1818 if (HasTrailingDot) 1819 return ObjCInstanceMessage; 1820 // We found something. If it's a type, then we have a class 1821 // message. Otherwise, it's an instance message. 1822 NamedDecl *ND = Result.getFoundDecl(); 1823 QualType T; 1824 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) 1825 T = Context.getObjCInterfaceType(Class); 1826 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) { 1827 T = Context.getTypeDeclType(Type); 1828 DiagnoseUseOfDecl(Type, NameLoc); 1829 } 1830 else 1831 return ObjCInstanceMessage; 1832 1833 // We have a class message, and T is the type we're 1834 // messaging. Build source-location information for it. 1835 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc); 1836 ReceiverType = CreateParsedType(T, TSInfo); 1837 return ObjCClassMessage; 1838 } 1839 } 1840 1841 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl()); 1842 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 1843 Result.getLookupKind(), S, NULL, 1844 Validator)) { 1845 if (Corrected.isKeyword()) { 1846 // If we've found the keyword "super" (the only keyword that would be 1847 // returned by CorrectTypo), this is a send to super. 1848 diagnoseTypo(Corrected, 1849 PDiag(diag::err_unknown_receiver_suggest) << Name); 1850 return ObjCSuperMessage; 1851 } else if (ObjCInterfaceDecl *Class = 1852 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { 1853 // If we found a declaration, correct when it refers to an Objective-C 1854 // class. 1855 diagnoseTypo(Corrected, 1856 PDiag(diag::err_unknown_receiver_suggest) << Name); 1857 QualType T = Context.getObjCInterfaceType(Class); 1858 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc); 1859 ReceiverType = CreateParsedType(T, TSInfo); 1860 return ObjCClassMessage; 1861 } 1862 } 1863 1864 // Fall back: let the parser try to parse it as an instance message. 1865 return ObjCInstanceMessage; 1866 } 1867 1868 ExprResult Sema::ActOnSuperMessage(Scope *S, 1869 SourceLocation SuperLoc, 1870 Selector Sel, 1871 SourceLocation LBracLoc, 1872 ArrayRef<SourceLocation> SelectorLocs, 1873 SourceLocation RBracLoc, 1874 MultiExprArg Args) { 1875 // Determine whether we are inside a method or not. 1876 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc); 1877 if (!Method) { 1878 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super); 1879 return ExprError(); 1880 } 1881 1882 ObjCInterfaceDecl *Class = Method->getClassInterface(); 1883 if (!Class) { 1884 Diag(SuperLoc, diag::error_no_super_class_message) 1885 << Method->getDeclName(); 1886 return ExprError(); 1887 } 1888 1889 ObjCInterfaceDecl *Super = Class->getSuperClass(); 1890 if (!Super) { 1891 // The current class does not have a superclass. 1892 Diag(SuperLoc, diag::error_root_class_cannot_use_super) 1893 << Class->getIdentifier(); 1894 return ExprError(); 1895 } 1896 1897 // We are in a method whose class has a superclass, so 'super' 1898 // is acting as a keyword. 1899 if (Method->getSelector() == Sel) 1900 getCurFunction()->ObjCShouldCallSuper = false; 1901 1902 if (Method->isInstanceMethod()) { 1903 // Since we are in an instance method, this is an instance 1904 // message to the superclass instance. 1905 QualType SuperTy = Context.getObjCInterfaceType(Super); 1906 SuperTy = Context.getObjCObjectPointerType(SuperTy); 1907 return BuildInstanceMessage(0, SuperTy, SuperLoc, 1908 Sel, /*Method=*/0, 1909 LBracLoc, SelectorLocs, RBracLoc, Args); 1910 } 1911 1912 // Since we are in a class method, this is a class message to 1913 // the superclass. 1914 return BuildClassMessage(/*ReceiverTypeInfo=*/0, 1915 Context.getObjCInterfaceType(Super), 1916 SuperLoc, Sel, /*Method=*/0, 1917 LBracLoc, SelectorLocs, RBracLoc, Args); 1918 } 1919 1920 1921 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType, 1922 bool isSuperReceiver, 1923 SourceLocation Loc, 1924 Selector Sel, 1925 ObjCMethodDecl *Method, 1926 MultiExprArg Args) { 1927 TypeSourceInfo *receiverTypeInfo = 0; 1928 if (!ReceiverType.isNull()) 1929 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType); 1930 1931 return BuildClassMessage(receiverTypeInfo, ReceiverType, 1932 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(), 1933 Sel, Method, Loc, Loc, Loc, Args, 1934 /*isImplicit=*/true); 1935 1936 } 1937 1938 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg, 1939 unsigned DiagID, 1940 bool (*refactor)(const ObjCMessageExpr *, 1941 const NSAPI &, edit::Commit &)) { 1942 SourceLocation MsgLoc = Msg->getExprLoc(); 1943 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored) 1944 return; 1945 1946 SourceManager &SM = S.SourceMgr; 1947 edit::Commit ECommit(SM, S.LangOpts); 1948 if (refactor(Msg,*S.NSAPIObj, ECommit)) { 1949 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID) 1950 << Msg->getSelector() << Msg->getSourceRange(); 1951 // FIXME: Don't emit diagnostic at all if fixits are non-commitable. 1952 if (!ECommit.isCommitable()) 1953 return; 1954 for (edit::Commit::edit_iterator 1955 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) { 1956 const edit::Commit::Edit &Edit = *I; 1957 switch (Edit.Kind) { 1958 case edit::Commit::Act_Insert: 1959 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc, 1960 Edit.Text, 1961 Edit.BeforePrev)); 1962 break; 1963 case edit::Commit::Act_InsertFromRange: 1964 Builder.AddFixItHint( 1965 FixItHint::CreateInsertionFromRange(Edit.OrigLoc, 1966 Edit.getInsertFromRange(SM), 1967 Edit.BeforePrev)); 1968 break; 1969 case edit::Commit::Act_Remove: 1970 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM))); 1971 break; 1972 } 1973 } 1974 } 1975 } 1976 1977 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) { 1978 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use, 1979 edit::rewriteObjCRedundantCallWithLiteral); 1980 } 1981 1982 /// \brief Build an Objective-C class message expression. 1983 /// 1984 /// This routine takes care of both normal class messages and 1985 /// class messages to the superclass. 1986 /// 1987 /// \param ReceiverTypeInfo Type source information that describes the 1988 /// receiver of this message. This may be NULL, in which case we are 1989 /// sending to the superclass and \p SuperLoc must be a valid source 1990 /// location. 1991 1992 /// \param ReceiverType The type of the object receiving the 1993 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same 1994 /// type as that refers to. For a superclass send, this is the type of 1995 /// the superclass. 1996 /// 1997 /// \param SuperLoc The location of the "super" keyword in a 1998 /// superclass message. 1999 /// 2000 /// \param Sel The selector to which the message is being sent. 2001 /// 2002 /// \param Method The method that this class message is invoking, if 2003 /// already known. 2004 /// 2005 /// \param LBracLoc The location of the opening square bracket ']'. 2006 /// 2007 /// \param RBracLoc The location of the closing square bracket ']'. 2008 /// 2009 /// \param ArgsIn The message arguments. 2010 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 2011 QualType ReceiverType, 2012 SourceLocation SuperLoc, 2013 Selector Sel, 2014 ObjCMethodDecl *Method, 2015 SourceLocation LBracLoc, 2016 ArrayRef<SourceLocation> SelectorLocs, 2017 SourceLocation RBracLoc, 2018 MultiExprArg ArgsIn, 2019 bool isImplicit) { 2020 SourceLocation Loc = SuperLoc.isValid()? SuperLoc 2021 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin(); 2022 if (LBracLoc.isInvalid()) { 2023 Diag(Loc, diag::err_missing_open_square_message_send) 2024 << FixItHint::CreateInsertion(Loc, "["); 2025 LBracLoc = Loc; 2026 } 2027 SourceLocation SelLoc; 2028 if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) 2029 SelLoc = SelectorLocs.front(); 2030 else 2031 SelLoc = Loc; 2032 2033 if (ReceiverType->isDependentType()) { 2034 // If the receiver type is dependent, we can't type-check anything 2035 // at this point. Build a dependent expression. 2036 unsigned NumArgs = ArgsIn.size(); 2037 Expr **Args = ArgsIn.data(); 2038 assert(SuperLoc.isInvalid() && "Message to super with dependent type"); 2039 return Owned(ObjCMessageExpr::Create(Context, ReceiverType, 2040 VK_RValue, LBracLoc, ReceiverTypeInfo, 2041 Sel, SelectorLocs, /*Method=*/0, 2042 makeArrayRef(Args, NumArgs),RBracLoc, 2043 isImplicit)); 2044 } 2045 2046 // Find the class to which we are sending this message. 2047 ObjCInterfaceDecl *Class = 0; 2048 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>(); 2049 if (!ClassType || !(Class = ClassType->getInterface())) { 2050 Diag(Loc, diag::err_invalid_receiver_class_message) 2051 << ReceiverType; 2052 return ExprError(); 2053 } 2054 assert(Class && "We don't know which class we're messaging?"); 2055 // objc++ diagnoses during typename annotation. 2056 if (!getLangOpts().CPlusPlus) 2057 (void)DiagnoseUseOfDecl(Class, SelLoc); 2058 // Find the method we are messaging. 2059 if (!Method) { 2060 SourceRange TypeRange 2061 = SuperLoc.isValid()? SourceRange(SuperLoc) 2062 : ReceiverTypeInfo->getTypeLoc().getSourceRange(); 2063 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class), 2064 (getLangOpts().ObjCAutoRefCount 2065 ? diag::err_arc_receiver_forward_class 2066 : diag::warn_receiver_forward_class), 2067 TypeRange)) { 2068 // A forward class used in messaging is treated as a 'Class' 2069 Method = LookupFactoryMethodInGlobalPool(Sel, 2070 SourceRange(LBracLoc, RBracLoc)); 2071 if (Method && !getLangOpts().ObjCAutoRefCount) 2072 Diag(Method->getLocation(), diag::note_method_sent_forward_class) 2073 << Method->getDeclName(); 2074 } 2075 if (!Method) 2076 Method = Class->lookupClassMethod(Sel); 2077 2078 // If we have an implementation in scope, check "private" methods. 2079 if (!Method) 2080 Method = Class->lookupPrivateClassMethod(Sel); 2081 2082 if (Method && DiagnoseUseOfDecl(Method, SelLoc)) 2083 return ExprError(); 2084 } 2085 2086 // Check the argument types and determine the result type. 2087 QualType ReturnType; 2088 ExprValueKind VK = VK_RValue; 2089 2090 unsigned NumArgs = ArgsIn.size(); 2091 Expr **Args = ArgsIn.data(); 2092 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs), 2093 Sel, SelectorLocs, 2094 Method, true, 2095 SuperLoc.isValid(), LBracLoc, RBracLoc, 2096 ReturnType, VK)) 2097 return ExprError(); 2098 2099 if (Method && !Method->getResultType()->isVoidType() && 2100 RequireCompleteType(LBracLoc, Method->getResultType(), 2101 diag::err_illegal_message_expr_incomplete_type)) 2102 return ExprError(); 2103 2104 // Construct the appropriate ObjCMessageExpr. 2105 ObjCMessageExpr *Result; 2106 if (SuperLoc.isValid()) 2107 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 2108 SuperLoc, /*IsInstanceSuper=*/false, 2109 ReceiverType, Sel, SelectorLocs, 2110 Method, makeArrayRef(Args, NumArgs), 2111 RBracLoc, isImplicit); 2112 else { 2113 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 2114 ReceiverTypeInfo, Sel, SelectorLocs, 2115 Method, makeArrayRef(Args, NumArgs), 2116 RBracLoc, isImplicit); 2117 if (!isImplicit) 2118 checkCocoaAPI(*this, Result); 2119 } 2120 return MaybeBindToTemporary(Result); 2121 } 2122 2123 // ActOnClassMessage - used for both unary and keyword messages. 2124 // ArgExprs is optional - if it is present, the number of expressions 2125 // is obtained from Sel.getNumArgs(). 2126 ExprResult Sema::ActOnClassMessage(Scope *S, 2127 ParsedType Receiver, 2128 Selector Sel, 2129 SourceLocation LBracLoc, 2130 ArrayRef<SourceLocation> SelectorLocs, 2131 SourceLocation RBracLoc, 2132 MultiExprArg Args) { 2133 TypeSourceInfo *ReceiverTypeInfo; 2134 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo); 2135 if (ReceiverType.isNull()) 2136 return ExprError(); 2137 2138 2139 if (!ReceiverTypeInfo) 2140 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc); 2141 2142 return BuildClassMessage(ReceiverTypeInfo, ReceiverType, 2143 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0, 2144 LBracLoc, SelectorLocs, RBracLoc, Args); 2145 } 2146 2147 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver, 2148 QualType ReceiverType, 2149 SourceLocation Loc, 2150 Selector Sel, 2151 ObjCMethodDecl *Method, 2152 MultiExprArg Args) { 2153 return BuildInstanceMessage(Receiver, ReceiverType, 2154 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(), 2155 Sel, Method, Loc, Loc, Loc, Args, 2156 /*isImplicit=*/true); 2157 } 2158 2159 /// \brief Build an Objective-C instance message expression. 2160 /// 2161 /// This routine takes care of both normal instance messages and 2162 /// instance messages to the superclass instance. 2163 /// 2164 /// \param Receiver The expression that computes the object that will 2165 /// receive this message. This may be empty, in which case we are 2166 /// sending to the superclass instance and \p SuperLoc must be a valid 2167 /// source location. 2168 /// 2169 /// \param ReceiverType The (static) type of the object receiving the 2170 /// message. When a \p Receiver expression is provided, this is the 2171 /// same type as that expression. For a superclass instance send, this 2172 /// is a pointer to the type of the superclass. 2173 /// 2174 /// \param SuperLoc The location of the "super" keyword in a 2175 /// superclass instance message. 2176 /// 2177 /// \param Sel The selector to which the message is being sent. 2178 /// 2179 /// \param Method The method that this instance message is invoking, if 2180 /// already known. 2181 /// 2182 /// \param LBracLoc The location of the opening square bracket ']'. 2183 /// 2184 /// \param RBracLoc The location of the closing square bracket ']'. 2185 /// 2186 /// \param ArgsIn The message arguments. 2187 ExprResult Sema::BuildInstanceMessage(Expr *Receiver, 2188 QualType ReceiverType, 2189 SourceLocation SuperLoc, 2190 Selector Sel, 2191 ObjCMethodDecl *Method, 2192 SourceLocation LBracLoc, 2193 ArrayRef<SourceLocation> SelectorLocs, 2194 SourceLocation RBracLoc, 2195 MultiExprArg ArgsIn, 2196 bool isImplicit) { 2197 // The location of the receiver. 2198 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart(); 2199 SourceRange RecRange = 2200 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange(); 2201 SourceLocation SelLoc; 2202 if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) 2203 SelLoc = SelectorLocs.front(); 2204 else 2205 SelLoc = Loc; 2206 2207 if (LBracLoc.isInvalid()) { 2208 Diag(Loc, diag::err_missing_open_square_message_send) 2209 << FixItHint::CreateInsertion(Loc, "["); 2210 LBracLoc = Loc; 2211 } 2212 2213 // If we have a receiver expression, perform appropriate promotions 2214 // and determine receiver type. 2215 if (Receiver) { 2216 if (Receiver->hasPlaceholderType()) { 2217 ExprResult Result; 2218 if (Receiver->getType() == Context.UnknownAnyTy) 2219 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType()); 2220 else 2221 Result = CheckPlaceholderExpr(Receiver); 2222 if (Result.isInvalid()) return ExprError(); 2223 Receiver = Result.take(); 2224 } 2225 2226 if (Receiver->isTypeDependent()) { 2227 // If the receiver is type-dependent, we can't type-check anything 2228 // at this point. Build a dependent expression. 2229 unsigned NumArgs = ArgsIn.size(); 2230 Expr **Args = ArgsIn.data(); 2231 assert(SuperLoc.isInvalid() && "Message to super with dependent type"); 2232 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy, 2233 VK_RValue, LBracLoc, Receiver, Sel, 2234 SelectorLocs, /*Method=*/0, 2235 makeArrayRef(Args, NumArgs), 2236 RBracLoc, isImplicit)); 2237 } 2238 2239 // If necessary, apply function/array conversion to the receiver. 2240 // C99 6.7.5.3p[7,8]. 2241 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver); 2242 if (Result.isInvalid()) 2243 return ExprError(); 2244 Receiver = Result.take(); 2245 ReceiverType = Receiver->getType(); 2246 2247 // If the receiver is an ObjC pointer, a block pointer, or an 2248 // __attribute__((NSObject)) pointer, we don't need to do any 2249 // special conversion in order to look up a receiver. 2250 if (ReceiverType->isObjCRetainableType()) { 2251 // do nothing 2252 } else if (!getLangOpts().ObjCAutoRefCount && 2253 !Context.getObjCIdType().isNull() && 2254 (ReceiverType->isPointerType() || 2255 ReceiverType->isIntegerType())) { 2256 // Implicitly convert integers and pointers to 'id' but emit a warning. 2257 // But not in ARC. 2258 Diag(Loc, diag::warn_bad_receiver_type) 2259 << ReceiverType 2260 << Receiver->getSourceRange(); 2261 if (ReceiverType->isPointerType()) { 2262 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), 2263 CK_CPointerToObjCPointerCast).take(); 2264 } else { 2265 // TODO: specialized warning on null receivers? 2266 bool IsNull = Receiver->isNullPointerConstant(Context, 2267 Expr::NPC_ValueDependentIsNull); 2268 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer; 2269 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), 2270 Kind).take(); 2271 } 2272 ReceiverType = Receiver->getType(); 2273 } else if (getLangOpts().CPlusPlus) { 2274 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver); 2275 if (result.isUsable()) { 2276 Receiver = result.take(); 2277 ReceiverType = Receiver->getType(); 2278 } 2279 } 2280 } 2281 2282 // There's a somewhat weird interaction here where we assume that we 2283 // won't actually have a method unless we also don't need to do some 2284 // of the more detailed type-checking on the receiver. 2285 2286 if (!Method) { 2287 // Handle messages to id. 2288 bool receiverIsId = ReceiverType->isObjCIdType(); 2289 if (receiverIsId || ReceiverType->isBlockPointerType() || 2290 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) { 2291 Method = LookupInstanceMethodInGlobalPool(Sel, 2292 SourceRange(LBracLoc, RBracLoc), 2293 receiverIsId); 2294 if (!Method) 2295 Method = LookupFactoryMethodInGlobalPool(Sel, 2296 SourceRange(LBracLoc,RBracLoc), 2297 receiverIsId); 2298 } else if (ReceiverType->isObjCClassType() || 2299 ReceiverType->isObjCQualifiedClassType()) { 2300 // Handle messages to Class. 2301 // We allow sending a message to a qualified Class ("Class<foo>"), which 2302 // is ok as long as one of the protocols implements the selector (if not, warn). 2303 if (const ObjCObjectPointerType *QClassTy 2304 = ReceiverType->getAsObjCQualifiedClassType()) { 2305 // Search protocols for class methods. 2306 Method = LookupMethodInQualifiedType(Sel, QClassTy, false); 2307 if (!Method) { 2308 Method = LookupMethodInQualifiedType(Sel, QClassTy, true); 2309 // warn if instance method found for a Class message. 2310 if (Method) { 2311 Diag(SelLoc, diag::warn_instance_method_on_class_found) 2312 << Method->getSelector() << Sel; 2313 Diag(Method->getLocation(), diag::note_method_declared_at) 2314 << Method->getDeclName(); 2315 } 2316 } 2317 } else { 2318 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { 2319 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) { 2320 // First check the public methods in the class interface. 2321 Method = ClassDecl->lookupClassMethod(Sel); 2322 2323 if (!Method) 2324 Method = ClassDecl->lookupPrivateClassMethod(Sel); 2325 } 2326 if (Method && DiagnoseUseOfDecl(Method, SelLoc)) 2327 return ExprError(); 2328 } 2329 if (!Method) { 2330 // If not messaging 'self', look for any factory method named 'Sel'. 2331 if (!Receiver || !isSelfExpr(Receiver)) { 2332 Method = LookupFactoryMethodInGlobalPool(Sel, 2333 SourceRange(LBracLoc, RBracLoc), 2334 true); 2335 if (!Method) { 2336 // If no class (factory) method was found, check if an _instance_ 2337 // method of the same name exists in the root class only. 2338 Method = LookupInstanceMethodInGlobalPool(Sel, 2339 SourceRange(LBracLoc, RBracLoc), 2340 true); 2341 if (Method) 2342 if (const ObjCInterfaceDecl *ID = 2343 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) { 2344 if (ID->getSuperClass()) 2345 Diag(SelLoc, diag::warn_root_inst_method_not_found) 2346 << Sel << SourceRange(LBracLoc, RBracLoc); 2347 } 2348 } 2349 } 2350 } 2351 } 2352 } else { 2353 ObjCInterfaceDecl* ClassDecl = 0; 2354 2355 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as 2356 // long as one of the protocols implements the selector (if not, warn). 2357 // And as long as message is not deprecated/unavailable (warn if it is). 2358 if (const ObjCObjectPointerType *QIdTy 2359 = ReceiverType->getAsObjCQualifiedIdType()) { 2360 // Search protocols for instance methods. 2361 Method = LookupMethodInQualifiedType(Sel, QIdTy, true); 2362 if (!Method) 2363 Method = LookupMethodInQualifiedType(Sel, QIdTy, false); 2364 if (Method && DiagnoseUseOfDecl(Method, SelLoc)) 2365 return ExprError(); 2366 } else if (const ObjCObjectPointerType *OCIType 2367 = ReceiverType->getAsObjCInterfacePointerType()) { 2368 // We allow sending a message to a pointer to an interface (an object). 2369 ClassDecl = OCIType->getInterfaceDecl(); 2370 2371 // Try to complete the type. Under ARC, this is a hard error from which 2372 // we don't try to recover. 2373 const ObjCInterfaceDecl *forwardClass = 0; 2374 if (RequireCompleteType(Loc, OCIType->getPointeeType(), 2375 getLangOpts().ObjCAutoRefCount 2376 ? diag::err_arc_receiver_forward_instance 2377 : diag::warn_receiver_forward_instance, 2378 Receiver? Receiver->getSourceRange() 2379 : SourceRange(SuperLoc))) { 2380 if (getLangOpts().ObjCAutoRefCount) 2381 return ExprError(); 2382 2383 forwardClass = OCIType->getInterfaceDecl(); 2384 Diag(Receiver ? Receiver->getLocStart() 2385 : SuperLoc, diag::note_receiver_is_id); 2386 Method = 0; 2387 } else { 2388 Method = ClassDecl->lookupInstanceMethod(Sel); 2389 } 2390 2391 if (!Method) 2392 // Search protocol qualifiers. 2393 Method = LookupMethodInQualifiedType(Sel, OCIType, true); 2394 2395 if (!Method) { 2396 // If we have implementations in scope, check "private" methods. 2397 Method = ClassDecl->lookupPrivateMethod(Sel); 2398 2399 if (!Method && getLangOpts().ObjCAutoRefCount) { 2400 Diag(SelLoc, diag::err_arc_may_not_respond) 2401 << OCIType->getPointeeType() << Sel << RecRange 2402 << SourceRange(SelectorLocs.front(), SelectorLocs.back()); 2403 return ExprError(); 2404 } 2405 2406 if (!Method && (!Receiver || !isSelfExpr(Receiver))) { 2407 // If we still haven't found a method, look in the global pool. This 2408 // behavior isn't very desirable, however we need it for GCC 2409 // compatibility. FIXME: should we deviate?? 2410 if (OCIType->qual_empty()) { 2411 Method = LookupInstanceMethodInGlobalPool(Sel, 2412 SourceRange(LBracLoc, RBracLoc)); 2413 if (Method && !forwardClass) 2414 Diag(SelLoc, diag::warn_maynot_respond) 2415 << OCIType->getInterfaceDecl()->getIdentifier() 2416 << Sel << RecRange; 2417 } 2418 } 2419 } 2420 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass)) 2421 return ExprError(); 2422 } else { 2423 // Reject other random receiver types (e.g. structs). 2424 Diag(Loc, diag::err_bad_receiver_type) 2425 << ReceiverType << Receiver->getSourceRange(); 2426 return ExprError(); 2427 } 2428 } 2429 } 2430 2431 // Check the message arguments. 2432 unsigned NumArgs = ArgsIn.size(); 2433 Expr **Args = ArgsIn.data(); 2434 QualType ReturnType; 2435 ExprValueKind VK = VK_RValue; 2436 bool ClassMessage = (ReceiverType->isObjCClassType() || 2437 ReceiverType->isObjCQualifiedClassType()); 2438 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs), 2439 Sel, SelectorLocs, Method, 2440 ClassMessage, SuperLoc.isValid(), 2441 LBracLoc, RBracLoc, ReturnType, VK)) 2442 return ExprError(); 2443 2444 if (Method && !Method->getResultType()->isVoidType() && 2445 RequireCompleteType(LBracLoc, Method->getResultType(), 2446 diag::err_illegal_message_expr_incomplete_type)) 2447 return ExprError(); 2448 2449 // In ARC, forbid the user from sending messages to 2450 // retain/release/autorelease/dealloc/retainCount explicitly. 2451 if (getLangOpts().ObjCAutoRefCount) { 2452 ObjCMethodFamily family = 2453 (Method ? Method->getMethodFamily() : Sel.getMethodFamily()); 2454 switch (family) { 2455 case OMF_init: 2456 if (Method) 2457 checkInitMethod(Method, ReceiverType); 2458 2459 case OMF_None: 2460 case OMF_alloc: 2461 case OMF_copy: 2462 case OMF_finalize: 2463 case OMF_mutableCopy: 2464 case OMF_new: 2465 case OMF_self: 2466 break; 2467 2468 case OMF_dealloc: 2469 case OMF_retain: 2470 case OMF_release: 2471 case OMF_autorelease: 2472 case OMF_retainCount: 2473 Diag(SelLoc, diag::err_arc_illegal_explicit_message) 2474 << Sel << RecRange; 2475 break; 2476 2477 case OMF_performSelector: 2478 if (Method && NumArgs >= 1) { 2479 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) { 2480 Selector ArgSel = SelExp->getSelector(); 2481 ObjCMethodDecl *SelMethod = 2482 LookupInstanceMethodInGlobalPool(ArgSel, 2483 SelExp->getSourceRange()); 2484 if (!SelMethod) 2485 SelMethod = 2486 LookupFactoryMethodInGlobalPool(ArgSel, 2487 SelExp->getSourceRange()); 2488 if (SelMethod) { 2489 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily(); 2490 switch (SelFamily) { 2491 case OMF_alloc: 2492 case OMF_copy: 2493 case OMF_mutableCopy: 2494 case OMF_new: 2495 case OMF_self: 2496 case OMF_init: 2497 // Issue error, unless ns_returns_not_retained. 2498 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) { 2499 // selector names a +1 method 2500 Diag(SelLoc, 2501 diag::err_arc_perform_selector_retains); 2502 Diag(SelMethod->getLocation(), diag::note_method_declared_at) 2503 << SelMethod->getDeclName(); 2504 } 2505 break; 2506 default: 2507 // +0 call. OK. unless ns_returns_retained. 2508 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) { 2509 // selector names a +1 method 2510 Diag(SelLoc, 2511 diag::err_arc_perform_selector_retains); 2512 Diag(SelMethod->getLocation(), diag::note_method_declared_at) 2513 << SelMethod->getDeclName(); 2514 } 2515 break; 2516 } 2517 } 2518 } else { 2519 // error (may leak). 2520 Diag(SelLoc, diag::warn_arc_perform_selector_leaks); 2521 Diag(Args[0]->getExprLoc(), diag::note_used_here); 2522 } 2523 } 2524 break; 2525 } 2526 } 2527 2528 // Construct the appropriate ObjCMessageExpr instance. 2529 ObjCMessageExpr *Result; 2530 if (SuperLoc.isValid()) 2531 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 2532 SuperLoc, /*IsInstanceSuper=*/true, 2533 ReceiverType, Sel, SelectorLocs, Method, 2534 makeArrayRef(Args, NumArgs), RBracLoc, 2535 isImplicit); 2536 else { 2537 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 2538 Receiver, Sel, SelectorLocs, Method, 2539 makeArrayRef(Args, NumArgs), RBracLoc, 2540 isImplicit); 2541 if (!isImplicit) 2542 checkCocoaAPI(*this, Result); 2543 } 2544 2545 if (getLangOpts().ObjCAutoRefCount) { 2546 DiagnoseARCUseOfWeakReceiver(*this, Receiver); 2547 2548 // In ARC, annotate delegate init calls. 2549 if (Result->getMethodFamily() == OMF_init && 2550 (SuperLoc.isValid() || isSelfExpr(Receiver))) { 2551 // Only consider init calls *directly* in init implementations, 2552 // not within blocks. 2553 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext); 2554 if (method && method->getMethodFamily() == OMF_init) { 2555 // The implicit assignment to self means we also don't want to 2556 // consume the result. 2557 Result->setDelegateInitCall(true); 2558 return Owned(Result); 2559 } 2560 } 2561 2562 // In ARC, check for message sends which are likely to introduce 2563 // retain cycles. 2564 checkRetainCycles(Result); 2565 2566 if (!isImplicit && Method) { 2567 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) { 2568 bool IsWeak = 2569 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak; 2570 if (!IsWeak && Sel.isUnarySelector()) 2571 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak; 2572 2573 if (IsWeak) { 2574 DiagnosticsEngine::Level Level = 2575 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 2576 LBracLoc); 2577 if (Level != DiagnosticsEngine::Ignored) 2578 getCurFunction()->recordUseOfWeak(Result, Prop); 2579 2580 } 2581 } 2582 } 2583 } 2584 2585 return MaybeBindToTemporary(Result); 2586 } 2587 2588 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) { 2589 if (ObjCSelectorExpr *OSE = 2590 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) { 2591 Selector Sel = OSE->getSelector(); 2592 SourceLocation Loc = OSE->getAtLoc(); 2593 llvm::DenseMap<Selector, SourceLocation>::iterator Pos 2594 = S.ReferencedSelectors.find(Sel); 2595 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc) 2596 S.ReferencedSelectors.erase(Pos); 2597 } 2598 } 2599 2600 // ActOnInstanceMessage - used for both unary and keyword messages. 2601 // ArgExprs is optional - if it is present, the number of expressions 2602 // is obtained from Sel.getNumArgs(). 2603 ExprResult Sema::ActOnInstanceMessage(Scope *S, 2604 Expr *Receiver, 2605 Selector Sel, 2606 SourceLocation LBracLoc, 2607 ArrayRef<SourceLocation> SelectorLocs, 2608 SourceLocation RBracLoc, 2609 MultiExprArg Args) { 2610 if (!Receiver) 2611 return ExprError(); 2612 2613 // A ParenListExpr can show up while doing error recovery with invalid code. 2614 if (isa<ParenListExpr>(Receiver)) { 2615 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver); 2616 if (Result.isInvalid()) return ExprError(); 2617 Receiver = Result.take(); 2618 } 2619 2620 if (RespondsToSelectorSel.isNull()) { 2621 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector"); 2622 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId); 2623 } 2624 if (Sel == RespondsToSelectorSel) 2625 RemoveSelectorFromWarningCache(*this, Args[0]); 2626 2627 return BuildInstanceMessage(Receiver, Receiver->getType(), 2628 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0, 2629 LBracLoc, SelectorLocs, RBracLoc, Args); 2630 } 2631 2632 enum ARCConversionTypeClass { 2633 /// int, void, struct A 2634 ACTC_none, 2635 2636 /// id, void (^)() 2637 ACTC_retainable, 2638 2639 /// id*, id***, void (^*)(), 2640 ACTC_indirectRetainable, 2641 2642 /// void* might be a normal C type, or it might a CF type. 2643 ACTC_voidPtr, 2644 2645 /// struct A* 2646 ACTC_coreFoundation 2647 }; 2648 static bool isAnyRetainable(ARCConversionTypeClass ACTC) { 2649 return (ACTC == ACTC_retainable || 2650 ACTC == ACTC_coreFoundation || 2651 ACTC == ACTC_voidPtr); 2652 } 2653 static bool isAnyCLike(ARCConversionTypeClass ACTC) { 2654 return ACTC == ACTC_none || 2655 ACTC == ACTC_voidPtr || 2656 ACTC == ACTC_coreFoundation; 2657 } 2658 2659 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) { 2660 bool isIndirect = false; 2661 2662 // Ignore an outermost reference type. 2663 if (const ReferenceType *ref = type->getAs<ReferenceType>()) { 2664 type = ref->getPointeeType(); 2665 isIndirect = true; 2666 } 2667 2668 // Drill through pointers and arrays recursively. 2669 while (true) { 2670 if (const PointerType *ptr = type->getAs<PointerType>()) { 2671 type = ptr->getPointeeType(); 2672 2673 // The first level of pointer may be the innermost pointer on a CF type. 2674 if (!isIndirect) { 2675 if (type->isVoidType()) return ACTC_voidPtr; 2676 if (type->isRecordType()) return ACTC_coreFoundation; 2677 } 2678 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) { 2679 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0); 2680 } else { 2681 break; 2682 } 2683 isIndirect = true; 2684 } 2685 2686 if (isIndirect) { 2687 if (type->isObjCARCBridgableType()) 2688 return ACTC_indirectRetainable; 2689 return ACTC_none; 2690 } 2691 2692 if (type->isObjCARCBridgableType()) 2693 return ACTC_retainable; 2694 2695 return ACTC_none; 2696 } 2697 2698 namespace { 2699 /// A result from the cast checker. 2700 enum ACCResult { 2701 /// Cannot be casted. 2702 ACC_invalid, 2703 2704 /// Can be safely retained or not retained. 2705 ACC_bottom, 2706 2707 /// Can be casted at +0. 2708 ACC_plusZero, 2709 2710 /// Can be casted at +1. 2711 ACC_plusOne 2712 }; 2713 ACCResult merge(ACCResult left, ACCResult right) { 2714 if (left == right) return left; 2715 if (left == ACC_bottom) return right; 2716 if (right == ACC_bottom) return left; 2717 return ACC_invalid; 2718 } 2719 2720 /// A checker which white-lists certain expressions whose conversion 2721 /// to or from retainable type would otherwise be forbidden in ARC. 2722 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> { 2723 typedef StmtVisitor<ARCCastChecker, ACCResult> super; 2724 2725 ASTContext &Context; 2726 ARCConversionTypeClass SourceClass; 2727 ARCConversionTypeClass TargetClass; 2728 bool Diagnose; 2729 2730 static bool isCFType(QualType type) { 2731 // Someday this can use ns_bridged. For now, it has to do this. 2732 return type->isCARCBridgableType(); 2733 } 2734 2735 public: 2736 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source, 2737 ARCConversionTypeClass target, bool diagnose) 2738 : Context(Context), SourceClass(source), TargetClass(target), 2739 Diagnose(diagnose) {} 2740 2741 using super::Visit; 2742 ACCResult Visit(Expr *e) { 2743 return super::Visit(e->IgnoreParens()); 2744 } 2745 2746 ACCResult VisitStmt(Stmt *s) { 2747 return ACC_invalid; 2748 } 2749 2750 /// Null pointer constants can be casted however you please. 2751 ACCResult VisitExpr(Expr *e) { 2752 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 2753 return ACC_bottom; 2754 return ACC_invalid; 2755 } 2756 2757 /// Objective-C string literals can be safely casted. 2758 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) { 2759 // If we're casting to any retainable type, go ahead. Global 2760 // strings are immune to retains, so this is bottom. 2761 if (isAnyRetainable(TargetClass)) return ACC_bottom; 2762 2763 return ACC_invalid; 2764 } 2765 2766 /// Look through certain implicit and explicit casts. 2767 ACCResult VisitCastExpr(CastExpr *e) { 2768 switch (e->getCastKind()) { 2769 case CK_NullToPointer: 2770 return ACC_bottom; 2771 2772 case CK_NoOp: 2773 case CK_LValueToRValue: 2774 case CK_BitCast: 2775 case CK_CPointerToObjCPointerCast: 2776 case CK_BlockPointerToObjCPointerCast: 2777 case CK_AnyPointerToBlockPointerCast: 2778 return Visit(e->getSubExpr()); 2779 2780 default: 2781 return ACC_invalid; 2782 } 2783 } 2784 2785 /// Look through unary extension. 2786 ACCResult VisitUnaryExtension(UnaryOperator *e) { 2787 return Visit(e->getSubExpr()); 2788 } 2789 2790 /// Ignore the LHS of a comma operator. 2791 ACCResult VisitBinComma(BinaryOperator *e) { 2792 return Visit(e->getRHS()); 2793 } 2794 2795 /// Conditional operators are okay if both sides are okay. 2796 ACCResult VisitConditionalOperator(ConditionalOperator *e) { 2797 ACCResult left = Visit(e->getTrueExpr()); 2798 if (left == ACC_invalid) return ACC_invalid; 2799 return merge(left, Visit(e->getFalseExpr())); 2800 } 2801 2802 /// Look through pseudo-objects. 2803 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) { 2804 // If we're getting here, we should always have a result. 2805 return Visit(e->getResultExpr()); 2806 } 2807 2808 /// Statement expressions are okay if their result expression is okay. 2809 ACCResult VisitStmtExpr(StmtExpr *e) { 2810 return Visit(e->getSubStmt()->body_back()); 2811 } 2812 2813 /// Some declaration references are okay. 2814 ACCResult VisitDeclRefExpr(DeclRefExpr *e) { 2815 // References to global constants from system headers are okay. 2816 // These are things like 'kCFStringTransformToLatin'. They are 2817 // can also be assumed to be immune to retains. 2818 VarDecl *var = dyn_cast<VarDecl>(e->getDecl()); 2819 if (isAnyRetainable(TargetClass) && 2820 isAnyRetainable(SourceClass) && 2821 var && 2822 var->getStorageClass() == SC_Extern && 2823 var->getType().isConstQualified() && 2824 Context.getSourceManager().isInSystemHeader(var->getLocation())) { 2825 return ACC_bottom; 2826 } 2827 2828 // Nothing else. 2829 return ACC_invalid; 2830 } 2831 2832 /// Some calls are okay. 2833 ACCResult VisitCallExpr(CallExpr *e) { 2834 if (FunctionDecl *fn = e->getDirectCallee()) 2835 if (ACCResult result = checkCallToFunction(fn)) 2836 return result; 2837 2838 return super::VisitCallExpr(e); 2839 } 2840 2841 ACCResult checkCallToFunction(FunctionDecl *fn) { 2842 // Require a CF*Ref return type. 2843 if (!isCFType(fn->getResultType())) 2844 return ACC_invalid; 2845 2846 if (!isAnyRetainable(TargetClass)) 2847 return ACC_invalid; 2848 2849 // Honor an explicit 'not retained' attribute. 2850 if (fn->hasAttr<CFReturnsNotRetainedAttr>()) 2851 return ACC_plusZero; 2852 2853 // Honor an explicit 'retained' attribute, except that for 2854 // now we're not going to permit implicit handling of +1 results, 2855 // because it's a bit frightening. 2856 if (fn->hasAttr<CFReturnsRetainedAttr>()) 2857 return Diagnose ? ACC_plusOne 2858 : ACC_invalid; // ACC_plusOne if we start accepting this 2859 2860 // Recognize this specific builtin function, which is used by CFSTR. 2861 unsigned builtinID = fn->getBuiltinID(); 2862 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString) 2863 return ACC_bottom; 2864 2865 // Otherwise, don't do anything implicit with an unaudited function. 2866 if (!fn->hasAttr<CFAuditedTransferAttr>()) 2867 return ACC_invalid; 2868 2869 // Otherwise, it's +0 unless it follows the create convention. 2870 if (ento::coreFoundation::followsCreateRule(fn)) 2871 return Diagnose ? ACC_plusOne 2872 : ACC_invalid; // ACC_plusOne if we start accepting this 2873 2874 return ACC_plusZero; 2875 } 2876 2877 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) { 2878 return checkCallToMethod(e->getMethodDecl()); 2879 } 2880 2881 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) { 2882 ObjCMethodDecl *method; 2883 if (e->isExplicitProperty()) 2884 method = e->getExplicitProperty()->getGetterMethodDecl(); 2885 else 2886 method = e->getImplicitPropertyGetter(); 2887 return checkCallToMethod(method); 2888 } 2889 2890 ACCResult checkCallToMethod(ObjCMethodDecl *method) { 2891 if (!method) return ACC_invalid; 2892 2893 // Check for message sends to functions returning CF types. We 2894 // just obey the Cocoa conventions with these, even though the 2895 // return type is CF. 2896 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType())) 2897 return ACC_invalid; 2898 2899 // If the method is explicitly marked not-retained, it's +0. 2900 if (method->hasAttr<CFReturnsNotRetainedAttr>()) 2901 return ACC_plusZero; 2902 2903 // If the method is explicitly marked as returning retained, or its 2904 // selector follows a +1 Cocoa convention, treat it as +1. 2905 if (method->hasAttr<CFReturnsRetainedAttr>()) 2906 return ACC_plusOne; 2907 2908 switch (method->getSelector().getMethodFamily()) { 2909 case OMF_alloc: 2910 case OMF_copy: 2911 case OMF_mutableCopy: 2912 case OMF_new: 2913 return ACC_plusOne; 2914 2915 default: 2916 // Otherwise, treat it as +0. 2917 return ACC_plusZero; 2918 } 2919 } 2920 }; 2921 } 2922 2923 bool Sema::isKnownName(StringRef name) { 2924 if (name.empty()) 2925 return false; 2926 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(), 2927 Sema::LookupOrdinaryName); 2928 return LookupName(R, TUScope, false); 2929 } 2930 2931 static void addFixitForObjCARCConversion(Sema &S, 2932 DiagnosticBuilder &DiagB, 2933 Sema::CheckedConversionKind CCK, 2934 SourceLocation afterLParen, 2935 QualType castType, 2936 Expr *castExpr, 2937 Expr *realCast, 2938 const char *bridgeKeyword, 2939 const char *CFBridgeName) { 2940 // We handle C-style and implicit casts here. 2941 switch (CCK) { 2942 case Sema::CCK_ImplicitConversion: 2943 case Sema::CCK_CStyleCast: 2944 case Sema::CCK_OtherCast: 2945 break; 2946 case Sema::CCK_FunctionalCast: 2947 return; 2948 } 2949 2950 if (CFBridgeName) { 2951 if (CCK == Sema::CCK_OtherCast) { 2952 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) { 2953 SourceRange range(NCE->getOperatorLoc(), 2954 NCE->getAngleBrackets().getEnd()); 2955 SmallString<32> BridgeCall; 2956 2957 SourceManager &SM = S.getSourceManager(); 2958 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1)); 2959 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) 2960 BridgeCall += ' '; 2961 2962 BridgeCall += CFBridgeName; 2963 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall)); 2964 } 2965 return; 2966 } 2967 Expr *castedE = castExpr; 2968 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE)) 2969 castedE = CCE->getSubExpr(); 2970 castedE = castedE->IgnoreImpCasts(); 2971 SourceRange range = castedE->getSourceRange(); 2972 2973 SmallString<32> BridgeCall; 2974 2975 SourceManager &SM = S.getSourceManager(); 2976 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1)); 2977 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) 2978 BridgeCall += ' '; 2979 2980 BridgeCall += CFBridgeName; 2981 2982 if (isa<ParenExpr>(castedE)) { 2983 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 2984 BridgeCall)); 2985 } else { 2986 BridgeCall += '('; 2987 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 2988 BridgeCall)); 2989 DiagB.AddFixItHint(FixItHint::CreateInsertion( 2990 S.PP.getLocForEndOfToken(range.getEnd()), 2991 ")")); 2992 } 2993 return; 2994 } 2995 2996 if (CCK == Sema::CCK_CStyleCast) { 2997 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword)); 2998 } else if (CCK == Sema::CCK_OtherCast) { 2999 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) { 3000 std::string castCode = "("; 3001 castCode += bridgeKeyword; 3002 castCode += castType.getAsString(); 3003 castCode += ")"; 3004 SourceRange Range(NCE->getOperatorLoc(), 3005 NCE->getAngleBrackets().getEnd()); 3006 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode)); 3007 } 3008 } else { 3009 std::string castCode = "("; 3010 castCode += bridgeKeyword; 3011 castCode += castType.getAsString(); 3012 castCode += ")"; 3013 Expr *castedE = castExpr->IgnoreImpCasts(); 3014 SourceRange range = castedE->getSourceRange(); 3015 if (isa<ParenExpr>(castedE)) { 3016 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 3017 castCode)); 3018 } else { 3019 castCode += "("; 3020 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 3021 castCode)); 3022 DiagB.AddFixItHint(FixItHint::CreateInsertion( 3023 S.PP.getLocForEndOfToken(range.getEnd()), 3024 ")")); 3025 } 3026 } 3027 } 3028 3029 static void 3030 diagnoseObjCARCConversion(Sema &S, SourceRange castRange, 3031 QualType castType, ARCConversionTypeClass castACTC, 3032 Expr *castExpr, Expr *realCast, 3033 ARCConversionTypeClass exprACTC, 3034 Sema::CheckedConversionKind CCK) { 3035 SourceLocation loc = 3036 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc()); 3037 3038 if (S.makeUnavailableInSystemHeader(loc, 3039 "converts between Objective-C and C pointers in -fobjc-arc")) 3040 return; 3041 3042 QualType castExprType = castExpr->getType(); 3043 3044 unsigned srcKind = 0; 3045 switch (exprACTC) { 3046 case ACTC_none: 3047 case ACTC_coreFoundation: 3048 case ACTC_voidPtr: 3049 srcKind = (castExprType->isPointerType() ? 1 : 0); 3050 break; 3051 case ACTC_retainable: 3052 srcKind = (castExprType->isBlockPointerType() ? 2 : 3); 3053 break; 3054 case ACTC_indirectRetainable: 3055 srcKind = 4; 3056 break; 3057 } 3058 3059 // Check whether this could be fixed with a bridge cast. 3060 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin()); 3061 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc; 3062 3063 // Bridge from an ARC type to a CF type. 3064 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) { 3065 3066 S.Diag(loc, diag::err_arc_cast_requires_bridge) 3067 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit 3068 << 2 // of C pointer type 3069 << castExprType 3070 << unsigned(castType->isBlockPointerType()) // to ObjC|block type 3071 << castType 3072 << castRange 3073 << castExpr->getSourceRange(); 3074 bool br = S.isKnownName("CFBridgingRelease"); 3075 ACCResult CreateRule = 3076 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); 3077 assert(CreateRule != ACC_bottom && "This cast should already be accepted."); 3078 if (CreateRule != ACC_plusOne) 3079 { 3080 DiagnosticBuilder DiagB = 3081 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge) 3082 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge); 3083 3084 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 3085 castType, castExpr, realCast, "__bridge ", 0); 3086 } 3087 if (CreateRule != ACC_plusZero) 3088 { 3089 DiagnosticBuilder DiagB = 3090 (CCK == Sema::CCK_OtherCast && !br) ? 3091 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType : 3092 S.Diag(br ? castExpr->getExprLoc() : noteLoc, 3093 diag::note_arc_bridge_transfer) 3094 << castExprType << br; 3095 3096 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 3097 castType, castExpr, realCast, "__bridge_transfer ", 3098 br ? "CFBridgingRelease" : 0); 3099 } 3100 3101 return; 3102 } 3103 3104 // Bridge from a CF type to an ARC type. 3105 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) { 3106 bool br = S.isKnownName("CFBridgingRetain"); 3107 S.Diag(loc, diag::err_arc_cast_requires_bridge) 3108 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit 3109 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type 3110 << castExprType 3111 << 2 // to C pointer type 3112 << castType 3113 << castRange 3114 << castExpr->getSourceRange(); 3115 ACCResult CreateRule = 3116 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); 3117 assert(CreateRule != ACC_bottom && "This cast should already be accepted."); 3118 if (CreateRule != ACC_plusOne) 3119 { 3120 DiagnosticBuilder DiagB = 3121 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge) 3122 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge); 3123 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 3124 castType, castExpr, realCast, "__bridge ", 0); 3125 } 3126 if (CreateRule != ACC_plusZero) 3127 { 3128 DiagnosticBuilder DiagB = 3129 (CCK == Sema::CCK_OtherCast && !br) ? 3130 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType : 3131 S.Diag(br ? castExpr->getExprLoc() : noteLoc, 3132 diag::note_arc_bridge_retained) 3133 << castType << br; 3134 3135 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 3136 castType, castExpr, realCast, "__bridge_retained ", 3137 br ? "CFBridgingRetain" : 0); 3138 } 3139 3140 return; 3141 } 3142 3143 S.Diag(loc, diag::err_arc_mismatched_cast) 3144 << (CCK != Sema::CCK_ImplicitConversion) 3145 << srcKind << castExprType << castType 3146 << castRange << castExpr->getSourceRange(); 3147 } 3148 3149 Sema::ARCConversionResult 3150 Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType, 3151 Expr *&castExpr, CheckedConversionKind CCK, 3152 bool DiagnoseCFAudited) { 3153 QualType castExprType = castExpr->getType(); 3154 3155 // For the purposes of the classification, we assume reference types 3156 // will bind to temporaries. 3157 QualType effCastType = castType; 3158 if (const ReferenceType *ref = castType->getAs<ReferenceType>()) 3159 effCastType = ref->getPointeeType(); 3160 3161 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType); 3162 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType); 3163 if (exprACTC == castACTC) { 3164 // check for viablity and report error if casting an rvalue to a 3165 // life-time qualifier. 3166 if ((castACTC == ACTC_retainable) && 3167 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) && 3168 (castType != castExprType)) { 3169 const Type *DT = castType.getTypePtr(); 3170 QualType QDT = castType; 3171 // We desugar some types but not others. We ignore those 3172 // that cannot happen in a cast; i.e. auto, and those which 3173 // should not be de-sugared; i.e typedef. 3174 if (const ParenType *PT = dyn_cast<ParenType>(DT)) 3175 QDT = PT->desugar(); 3176 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT)) 3177 QDT = TP->desugar(); 3178 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT)) 3179 QDT = AT->desugar(); 3180 if (QDT != castType && 3181 QDT.getObjCLifetime() != Qualifiers::OCL_None) { 3182 SourceLocation loc = 3183 (castRange.isValid() ? castRange.getBegin() 3184 : castExpr->getExprLoc()); 3185 Diag(loc, diag::err_arc_nolifetime_behavior); 3186 } 3187 } 3188 return ACR_okay; 3189 } 3190 3191 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay; 3192 3193 // Allow all of these types to be cast to integer types (but not 3194 // vice-versa). 3195 if (castACTC == ACTC_none && castType->isIntegralType(Context)) 3196 return ACR_okay; 3197 3198 // Allow casts between pointers to lifetime types (e.g., __strong id*) 3199 // and pointers to void (e.g., cv void *). Casting from void* to lifetime* 3200 // must be explicit. 3201 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr) 3202 return ACR_okay; 3203 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr && 3204 CCK != CCK_ImplicitConversion) 3205 return ACR_okay; 3206 3207 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) { 3208 // For invalid casts, fall through. 3209 case ACC_invalid: 3210 break; 3211 3212 // Do nothing for both bottom and +0. 3213 case ACC_bottom: 3214 case ACC_plusZero: 3215 return ACR_okay; 3216 3217 // If the result is +1, consume it here. 3218 case ACC_plusOne: 3219 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(), 3220 CK_ARCConsumeObject, castExpr, 3221 0, VK_RValue); 3222 ExprNeedsCleanups = true; 3223 return ACR_okay; 3224 } 3225 3226 // If this is a non-implicit cast from id or block type to a 3227 // CoreFoundation type, delay complaining in case the cast is used 3228 // in an acceptable context. 3229 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && 3230 CCK != CCK_ImplicitConversion) 3231 return ACR_unbridged; 3232 3233 // Do not issue "bridge cast" diagnostic when implicit casting 3234 // a retainable object to a CF type parameter belonging to an audited 3235 // CF API function. Let caller issue a normal type mismatched diagnostic 3236 // instead. 3237 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable || 3238 castACTC != ACTC_coreFoundation) 3239 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, 3240 castExpr, castExpr, exprACTC, CCK); 3241 return ACR_okay; 3242 } 3243 3244 /// Given that we saw an expression with the ARCUnbridgedCastTy 3245 /// placeholder type, complain bitterly. 3246 void Sema::diagnoseARCUnbridgedCast(Expr *e) { 3247 // We expect the spurious ImplicitCastExpr to already have been stripped. 3248 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 3249 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens()); 3250 3251 SourceRange castRange; 3252 QualType castType; 3253 CheckedConversionKind CCK; 3254 3255 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) { 3256 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc()); 3257 castType = cast->getTypeAsWritten(); 3258 CCK = CCK_CStyleCast; 3259 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) { 3260 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange(); 3261 castType = cast->getTypeAsWritten(); 3262 CCK = CCK_OtherCast; 3263 } else { 3264 castType = cast->getType(); 3265 CCK = CCK_ImplicitConversion; 3266 } 3267 3268 ARCConversionTypeClass castACTC = 3269 classifyTypeForARCConversion(castType.getNonReferenceType()); 3270 3271 Expr *castExpr = realCast->getSubExpr(); 3272 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable); 3273 3274 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, 3275 castExpr, realCast, ACTC_retainable, CCK); 3276 } 3277 3278 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast 3279 /// type, remove the placeholder cast. 3280 Expr *Sema::stripARCUnbridgedCast(Expr *e) { 3281 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 3282 3283 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) { 3284 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr()); 3285 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub); 3286 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) { 3287 assert(uo->getOpcode() == UO_Extension); 3288 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr()); 3289 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(), 3290 sub->getValueKind(), sub->getObjectKind(), 3291 uo->getOperatorLoc()); 3292 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) { 3293 assert(!gse->isResultDependent()); 3294 3295 unsigned n = gse->getNumAssocs(); 3296 SmallVector<Expr*, 4> subExprs(n); 3297 SmallVector<TypeSourceInfo*, 4> subTypes(n); 3298 for (unsigned i = 0; i != n; ++i) { 3299 subTypes[i] = gse->getAssocTypeSourceInfo(i); 3300 Expr *sub = gse->getAssocExpr(i); 3301 if (i == gse->getResultIndex()) 3302 sub = stripARCUnbridgedCast(sub); 3303 subExprs[i] = sub; 3304 } 3305 3306 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(), 3307 gse->getControllingExpr(), 3308 subTypes, subExprs, 3309 gse->getDefaultLoc(), 3310 gse->getRParenLoc(), 3311 gse->containsUnexpandedParameterPack(), 3312 gse->getResultIndex()); 3313 } else { 3314 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!"); 3315 return cast<ImplicitCastExpr>(e)->getSubExpr(); 3316 } 3317 } 3318 3319 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType, 3320 QualType exprType) { 3321 QualType canCastType = 3322 Context.getCanonicalType(castType).getUnqualifiedType(); 3323 QualType canExprType = 3324 Context.getCanonicalType(exprType).getUnqualifiedType(); 3325 if (isa<ObjCObjectPointerType>(canCastType) && 3326 castType.getObjCLifetime() == Qualifiers::OCL_Weak && 3327 canExprType->isObjCObjectPointerType()) { 3328 if (const ObjCObjectPointerType *ObjT = 3329 canExprType->getAs<ObjCObjectPointerType>()) 3330 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl()) 3331 return !ObjI->isArcWeakrefUnavailable(); 3332 } 3333 return true; 3334 } 3335 3336 /// Look for an ObjCReclaimReturnedObject cast and destroy it. 3337 static Expr *maybeUndoReclaimObject(Expr *e) { 3338 // For now, we just undo operands that are *immediately* reclaim 3339 // expressions, which prevents the vast majority of potential 3340 // problems here. To catch them all, we'd need to rebuild arbitrary 3341 // value-propagating subexpressions --- we can't reliably rebuild 3342 // in-place because of expression sharing. 3343 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e)) 3344 if (ice->getCastKind() == CK_ARCReclaimReturnedObject) 3345 return ice->getSubExpr(); 3346 3347 return e; 3348 } 3349 3350 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, 3351 ObjCBridgeCastKind Kind, 3352 SourceLocation BridgeKeywordLoc, 3353 TypeSourceInfo *TSInfo, 3354 Expr *SubExpr) { 3355 ExprResult SubResult = UsualUnaryConversions(SubExpr); 3356 if (SubResult.isInvalid()) return ExprError(); 3357 SubExpr = SubResult.take(); 3358 3359 QualType T = TSInfo->getType(); 3360 QualType FromType = SubExpr->getType(); 3361 3362 CastKind CK; 3363 3364 bool MustConsume = false; 3365 if (T->isDependentType() || SubExpr->isTypeDependent()) { 3366 // Okay: we'll build a dependent expression type. 3367 CK = CK_Dependent; 3368 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) { 3369 // Casting CF -> id 3370 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast 3371 : CK_CPointerToObjCPointerCast); 3372 switch (Kind) { 3373 case OBC_Bridge: 3374 break; 3375 3376 case OBC_BridgeRetained: { 3377 bool br = isKnownName("CFBridgingRelease"); 3378 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) 3379 << 2 3380 << FromType 3381 << (T->isBlockPointerType()? 1 : 0) 3382 << T 3383 << SubExpr->getSourceRange() 3384 << Kind; 3385 Diag(BridgeKeywordLoc, diag::note_arc_bridge) 3386 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge"); 3387 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer) 3388 << FromType << br 3389 << FixItHint::CreateReplacement(BridgeKeywordLoc, 3390 br ? "CFBridgingRelease " 3391 : "__bridge_transfer "); 3392 3393 Kind = OBC_Bridge; 3394 break; 3395 } 3396 3397 case OBC_BridgeTransfer: 3398 // We must consume the Objective-C object produced by the cast. 3399 MustConsume = true; 3400 break; 3401 } 3402 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) { 3403 // Okay: id -> CF 3404 CK = CK_BitCast; 3405 switch (Kind) { 3406 case OBC_Bridge: 3407 // Reclaiming a value that's going to be __bridge-casted to CF 3408 // is very dangerous, so we don't do it. 3409 SubExpr = maybeUndoReclaimObject(SubExpr); 3410 break; 3411 3412 case OBC_BridgeRetained: 3413 // Produce the object before casting it. 3414 SubExpr = ImplicitCastExpr::Create(Context, FromType, 3415 CK_ARCProduceObject, 3416 SubExpr, 0, VK_RValue); 3417 break; 3418 3419 case OBC_BridgeTransfer: { 3420 bool br = isKnownName("CFBridgingRetain"); 3421 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) 3422 << (FromType->isBlockPointerType()? 1 : 0) 3423 << FromType 3424 << 2 3425 << T 3426 << SubExpr->getSourceRange() 3427 << Kind; 3428 3429 Diag(BridgeKeywordLoc, diag::note_arc_bridge) 3430 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge "); 3431 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained) 3432 << T << br 3433 << FixItHint::CreateReplacement(BridgeKeywordLoc, 3434 br ? "CFBridgingRetain " : "__bridge_retained"); 3435 3436 Kind = OBC_Bridge; 3437 break; 3438 } 3439 } 3440 } else { 3441 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible) 3442 << FromType << T << Kind 3443 << SubExpr->getSourceRange() 3444 << TSInfo->getTypeLoc().getSourceRange(); 3445 return ExprError(); 3446 } 3447 3448 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK, 3449 BridgeKeywordLoc, 3450 TSInfo, SubExpr); 3451 3452 if (MustConsume) { 3453 ExprNeedsCleanups = true; 3454 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result, 3455 0, VK_RValue); 3456 } 3457 3458 return Result; 3459 } 3460 3461 ExprResult Sema::ActOnObjCBridgedCast(Scope *S, 3462 SourceLocation LParenLoc, 3463 ObjCBridgeCastKind Kind, 3464 SourceLocation BridgeKeywordLoc, 3465 ParsedType Type, 3466 SourceLocation RParenLoc, 3467 Expr *SubExpr) { 3468 TypeSourceInfo *TSInfo = 0; 3469 QualType T = GetTypeFromParser(Type, &TSInfo); 3470 if (!TSInfo) 3471 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc); 3472 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo, 3473 SubExpr); 3474 } 3475