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