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