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