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