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