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