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