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