clang API Documentation
00001 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements semantic analysis for Objective-C expressions. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Sema/SemaInternal.h" 00015 #include "clang/AST/ASTContext.h" 00016 #include "clang/AST/DeclObjC.h" 00017 #include "clang/AST/ExprObjC.h" 00018 #include "clang/AST/StmtVisitor.h" 00019 #include "clang/AST/TypeLoc.h" 00020 #include "clang/Analysis/DomainSpecific/CocoaConventions.h" 00021 #include "clang/Edit/Commit.h" 00022 #include "clang/Edit/Rewriters.h" 00023 #include "clang/Lex/Preprocessor.h" 00024 #include "clang/Sema/Initialization.h" 00025 #include "clang/Sema/Lookup.h" 00026 #include "clang/Sema/Scope.h" 00027 #include "clang/Sema/ScopeInfo.h" 00028 #include "llvm/ADT/SmallString.h" 00029 00030 using namespace clang; 00031 using namespace sema; 00032 using llvm::makeArrayRef; 00033 00034 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs, 00035 Expr **strings, 00036 unsigned NumStrings) { 00037 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings); 00038 00039 // Most ObjC strings are formed out of a single piece. However, we *can* 00040 // have strings formed out of multiple @ strings with multiple pptokens in 00041 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one 00042 // StringLiteral for ObjCStringLiteral to hold onto. 00043 StringLiteral *S = Strings[0]; 00044 00045 // If we have a multi-part string, merge it all together. 00046 if (NumStrings != 1) { 00047 // Concatenate objc strings. 00048 SmallString<128> StrBuf; 00049 SmallVector<SourceLocation, 8> StrLocs; 00050 00051 for (unsigned i = 0; i != NumStrings; ++i) { 00052 S = Strings[i]; 00053 00054 // ObjC strings can't be wide or UTF. 00055 if (!S->isAscii()) { 00056 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant) 00057 << S->getSourceRange(); 00058 return true; 00059 } 00060 00061 // Append the string. 00062 StrBuf += S->getString(); 00063 00064 // Get the locations of the string tokens. 00065 StrLocs.append(S->tokloc_begin(), S->tokloc_end()); 00066 } 00067 00068 // Create the aggregate string with the appropriate content and location 00069 // information. 00070 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType()); 00071 assert(CAT && "String literal not of constant array type!"); 00072 QualType StrTy = Context.getConstantArrayType( 00073 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1), 00074 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers()); 00075 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii, 00076 /*Pascal=*/false, StrTy, &StrLocs[0], 00077 StrLocs.size()); 00078 } 00079 00080 return BuildObjCStringLiteral(AtLocs[0], S); 00081 } 00082 00083 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){ 00084 // Verify that this composite string is acceptable for ObjC strings. 00085 if (CheckObjCString(S)) 00086 return true; 00087 00088 // Initialize the constant string interface lazily. This assumes 00089 // the NSString interface is seen in this translation unit. Note: We 00090 // don't use NSConstantString, since the runtime team considers this 00091 // interface private (even though it appears in the header files). 00092 QualType Ty = Context.getObjCConstantStringInterface(); 00093 if (!Ty.isNull()) { 00094 Ty = Context.getObjCObjectPointerType(Ty); 00095 } else if (getLangOpts().NoConstantCFStrings) { 00096 IdentifierInfo *NSIdent=nullptr; 00097 std::string StringClass(getLangOpts().ObjCConstantStringClass); 00098 00099 if (StringClass.empty()) 00100 NSIdent = &Context.Idents.get("NSConstantString"); 00101 else 00102 NSIdent = &Context.Idents.get(StringClass); 00103 00104 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc, 00105 LookupOrdinaryName); 00106 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { 00107 Context.setObjCConstantStringInterface(StrIF); 00108 Ty = Context.getObjCConstantStringInterface(); 00109 Ty = Context.getObjCObjectPointerType(Ty); 00110 } else { 00111 // If there is no NSConstantString interface defined then treat this 00112 // as error and recover from it. 00113 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent 00114 << S->getSourceRange(); 00115 Ty = Context.getObjCIdType(); 00116 } 00117 } else { 00118 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString); 00119 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc, 00120 LookupOrdinaryName); 00121 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { 00122 Context.setObjCConstantStringInterface(StrIF); 00123 Ty = Context.getObjCConstantStringInterface(); 00124 Ty = Context.getObjCObjectPointerType(Ty); 00125 } else { 00126 // If there is no NSString interface defined, implicitly declare 00127 // a @class NSString; and use that instead. This is to make sure 00128 // type of an NSString literal is represented correctly, instead of 00129 // being an 'id' type. 00130 Ty = Context.getObjCNSStringType(); 00131 if (Ty.isNull()) { 00132 ObjCInterfaceDecl *NSStringIDecl = 00133 ObjCInterfaceDecl::Create (Context, 00134 Context.getTranslationUnitDecl(), 00135 SourceLocation(), NSIdent, 00136 nullptr, SourceLocation()); 00137 Ty = Context.getObjCInterfaceType(NSStringIDecl); 00138 Context.setObjCNSStringType(Ty); 00139 } 00140 Ty = Context.getObjCObjectPointerType(Ty); 00141 } 00142 } 00143 00144 return new (Context) ObjCStringLiteral(S, Ty, AtLoc); 00145 } 00146 00147 /// \brief Emits an error if the given method does not exist, or if the return 00148 /// type is not an Objective-C object. 00149 static bool validateBoxingMethod(Sema &S, SourceLocation Loc, 00150 const ObjCInterfaceDecl *Class, 00151 Selector Sel, const ObjCMethodDecl *Method) { 00152 if (!Method) { 00153 // FIXME: Is there a better way to avoid quotes than using getName()? 00154 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName(); 00155 return false; 00156 } 00157 00158 // Make sure the return type is reasonable. 00159 QualType ReturnType = Method->getReturnType(); 00160 if (!ReturnType->isObjCObjectPointerType()) { 00161 S.Diag(Loc, diag::err_objc_literal_method_sig) 00162 << Sel; 00163 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return) 00164 << ReturnType; 00165 return false; 00166 } 00167 00168 return true; 00169 } 00170 00171 /// \brief Retrieve the NSNumber factory method that should be used to create 00172 /// an Objective-C literal for the given type. 00173 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc, 00174 QualType NumberType, 00175 bool isLiteral = false, 00176 SourceRange R = SourceRange()) { 00177 Optional<NSAPI::NSNumberLiteralMethodKind> Kind = 00178 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType); 00179 00180 if (!Kind) { 00181 if (isLiteral) { 00182 S.Diag(Loc, diag::err_invalid_nsnumber_type) 00183 << NumberType << R; 00184 } 00185 return nullptr; 00186 } 00187 00188 // If we already looked up this method, we're done. 00189 if (S.NSNumberLiteralMethods[*Kind]) 00190 return S.NSNumberLiteralMethods[*Kind]; 00191 00192 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind, 00193 /*Instance=*/false); 00194 00195 ASTContext &CX = S.Context; 00196 00197 // Look up the NSNumber class, if we haven't done so already. It's cached 00198 // in the Sema instance. 00199 if (!S.NSNumberDecl) { 00200 IdentifierInfo *NSNumberId = 00201 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber); 00202 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId, 00203 Loc, Sema::LookupOrdinaryName); 00204 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 00205 if (!S.NSNumberDecl) { 00206 if (S.getLangOpts().DebuggerObjCLiteral) { 00207 // Create a stub definition of NSNumber. 00208 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX, 00209 CX.getTranslationUnitDecl(), 00210 SourceLocation(), NSNumberId, 00211 nullptr, SourceLocation()); 00212 } else { 00213 // Otherwise, require a declaration of NSNumber. 00214 S.Diag(Loc, diag::err_undeclared_nsnumber); 00215 return nullptr; 00216 } 00217 } else if (!S.NSNumberDecl->hasDefinition()) { 00218 S.Diag(Loc, diag::err_undeclared_nsnumber); 00219 return nullptr; 00220 } 00221 00222 // generate the pointer to NSNumber type. 00223 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl); 00224 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject); 00225 } 00226 00227 // Look for the appropriate method within NSNumber. 00228 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel); 00229 if (!Method && S.getLangOpts().DebuggerObjCLiteral) { 00230 // create a stub definition this NSNumber factory method. 00231 TypeSourceInfo *ReturnTInfo = nullptr; 00232 Method = 00233 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel, 00234 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl, 00235 /*isInstance=*/false, /*isVariadic=*/false, 00236 /*isPropertyAccessor=*/false, 00237 /*isImplicitlyDeclared=*/true, 00238 /*isDefined=*/false, ObjCMethodDecl::Required, 00239 /*HasRelatedResultType=*/false); 00240 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method, 00241 SourceLocation(), SourceLocation(), 00242 &CX.Idents.get("value"), 00243 NumberType, /*TInfo=*/nullptr, 00244 SC_None, nullptr); 00245 Method->setMethodParams(S.Context, value, None); 00246 } 00247 00248 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method)) 00249 return nullptr; 00250 00251 // Note: if the parameter type is out-of-line, we'll catch it later in the 00252 // implicit conversion. 00253 00254 S.NSNumberLiteralMethods[*Kind] = Method; 00255 return Method; 00256 } 00257 00258 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the 00259 /// numeric literal expression. Type of the expression will be "NSNumber *". 00260 ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) { 00261 // Determine the type of the literal. 00262 QualType NumberType = Number->getType(); 00263 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) { 00264 // In C, character literals have type 'int'. That's not the type we want 00265 // to use to determine the Objective-c literal kind. 00266 switch (Char->getKind()) { 00267 case CharacterLiteral::Ascii: 00268 NumberType = Context.CharTy; 00269 break; 00270 00271 case CharacterLiteral::Wide: 00272 NumberType = Context.getWideCharType(); 00273 break; 00274 00275 case CharacterLiteral::UTF16: 00276 NumberType = Context.Char16Ty; 00277 break; 00278 00279 case CharacterLiteral::UTF32: 00280 NumberType = Context.Char32Ty; 00281 break; 00282 } 00283 } 00284 00285 // Look for the appropriate method within NSNumber. 00286 // Construct the literal. 00287 SourceRange NR(Number->getSourceRange()); 00288 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType, 00289 true, NR); 00290 if (!Method) 00291 return ExprError(); 00292 00293 // Convert the number to the type that the parameter expects. 00294 ParmVarDecl *ParamDecl = Method->parameters()[0]; 00295 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 00296 ParamDecl); 00297 ExprResult ConvertedNumber = PerformCopyInitialization(Entity, 00298 SourceLocation(), 00299 Number); 00300 if (ConvertedNumber.isInvalid()) 00301 return ExprError(); 00302 Number = ConvertedNumber.get(); 00303 00304 // Use the effective source range of the literal, including the leading '@'. 00305 return MaybeBindToTemporary( 00306 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method, 00307 SourceRange(AtLoc, NR.getEnd()))); 00308 } 00309 00310 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc, 00311 SourceLocation ValueLoc, 00312 bool Value) { 00313 ExprResult Inner; 00314 if (getLangOpts().CPlusPlus) { 00315 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false); 00316 } else { 00317 // C doesn't actually have a way to represent literal values of type 00318 // _Bool. So, we'll use 0/1 and implicit cast to _Bool. 00319 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0); 00320 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy, 00321 CK_IntegralToBoolean); 00322 } 00323 00324 return BuildObjCNumericLiteral(AtLoc, Inner.get()); 00325 } 00326 00327 /// \brief Check that the given expression is a valid element of an Objective-C 00328 /// collection literal. 00329 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, 00330 QualType T, 00331 bool ArrayLiteral = false) { 00332 // If the expression is type-dependent, there's nothing for us to do. 00333 if (Element->isTypeDependent()) 00334 return Element; 00335 00336 ExprResult Result = S.CheckPlaceholderExpr(Element); 00337 if (Result.isInvalid()) 00338 return ExprError(); 00339 Element = Result.get(); 00340 00341 // In C++, check for an implicit conversion to an Objective-C object pointer 00342 // type. 00343 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) { 00344 InitializedEntity Entity 00345 = InitializedEntity::InitializeParameter(S.Context, T, 00346 /*Consumed=*/false); 00347 InitializationKind Kind 00348 = InitializationKind::CreateCopy(Element->getLocStart(), 00349 SourceLocation()); 00350 InitializationSequence Seq(S, Entity, Kind, Element); 00351 if (!Seq.Failed()) 00352 return Seq.Perform(S, Entity, Kind, Element); 00353 } 00354 00355 Expr *OrigElement = Element; 00356 00357 // Perform lvalue-to-rvalue conversion. 00358 Result = S.DefaultLvalueConversion(Element); 00359 if (Result.isInvalid()) 00360 return ExprError(); 00361 Element = Result.get(); 00362 00363 // Make sure that we have an Objective-C pointer type or block. 00364 if (!Element->getType()->isObjCObjectPointerType() && 00365 !Element->getType()->isBlockPointerType()) { 00366 bool Recovered = false; 00367 00368 // If this is potentially an Objective-C numeric literal, add the '@'. 00369 if (isa<IntegerLiteral>(OrigElement) || 00370 isa<CharacterLiteral>(OrigElement) || 00371 isa<FloatingLiteral>(OrigElement) || 00372 isa<ObjCBoolLiteralExpr>(OrigElement) || 00373 isa<CXXBoolLiteralExpr>(OrigElement)) { 00374 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) { 00375 int Which = isa<CharacterLiteral>(OrigElement) ? 1 00376 : (isa<CXXBoolLiteralExpr>(OrigElement) || 00377 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2 00378 : 3; 00379 00380 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection) 00381 << Which << OrigElement->getSourceRange() 00382 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@"); 00383 00384 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(), 00385 OrigElement); 00386 if (Result.isInvalid()) 00387 return ExprError(); 00388 00389 Element = Result.get(); 00390 Recovered = true; 00391 } 00392 } 00393 // If this is potentially an Objective-C string literal, add the '@'. 00394 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) { 00395 if (String->isAscii()) { 00396 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection) 00397 << 0 << OrigElement->getSourceRange() 00398 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@"); 00399 00400 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String); 00401 if (Result.isInvalid()) 00402 return ExprError(); 00403 00404 Element = Result.get(); 00405 Recovered = true; 00406 } 00407 } 00408 00409 if (!Recovered) { 00410 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element) 00411 << Element->getType(); 00412 return ExprError(); 00413 } 00414 } 00415 if (ArrayLiteral) 00416 if (ObjCStringLiteral *getString = 00417 dyn_cast<ObjCStringLiteral>(OrigElement)) { 00418 if (StringLiteral *SL = getString->getString()) { 00419 unsigned numConcat = SL->getNumConcatenated(); 00420 if (numConcat > 1) { 00421 // Only warn if the concatenated string doesn't come from a macro. 00422 bool hasMacro = false; 00423 for (unsigned i = 0; i < numConcat ; ++i) 00424 if (SL->getStrTokenLoc(i).isMacroID()) { 00425 hasMacro = true; 00426 break; 00427 } 00428 if (!hasMacro) 00429 S.Diag(Element->getLocStart(), 00430 diag::warn_concatenated_nsarray_literal) 00431 << Element->getType(); 00432 } 00433 } 00434 } 00435 00436 // Make sure that the element has the type that the container factory 00437 // function expects. 00438 return S.PerformCopyInitialization( 00439 InitializedEntity::InitializeParameter(S.Context, T, 00440 /*Consumed=*/false), 00441 Element->getLocStart(), Element); 00442 } 00443 00444 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { 00445 if (ValueExpr->isTypeDependent()) { 00446 ObjCBoxedExpr *BoxedExpr = 00447 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR); 00448 return BoxedExpr; 00449 } 00450 ObjCMethodDecl *BoxingMethod = nullptr; 00451 QualType BoxedType; 00452 // Convert the expression to an RValue, so we can check for pointer types... 00453 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr); 00454 if (RValue.isInvalid()) { 00455 return ExprError(); 00456 } 00457 ValueExpr = RValue.get(); 00458 QualType ValueType(ValueExpr->getType()); 00459 if (const PointerType *PT = ValueType->getAs<PointerType>()) { 00460 QualType PointeeType = PT->getPointeeType(); 00461 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) { 00462 00463 if (!NSStringDecl) { 00464 IdentifierInfo *NSStringId = 00465 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString); 00466 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId, 00467 SR.getBegin(), LookupOrdinaryName); 00468 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl); 00469 if (!NSStringDecl) { 00470 if (getLangOpts().DebuggerObjCLiteral) { 00471 // Support boxed expressions in the debugger w/o NSString declaration. 00472 DeclContext *TU = Context.getTranslationUnitDecl(); 00473 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU, 00474 SourceLocation(), 00475 NSStringId, 00476 nullptr, SourceLocation()); 00477 } else { 00478 Diag(SR.getBegin(), diag::err_undeclared_nsstring); 00479 return ExprError(); 00480 } 00481 } else if (!NSStringDecl->hasDefinition()) { 00482 Diag(SR.getBegin(), diag::err_undeclared_nsstring); 00483 return ExprError(); 00484 } 00485 assert(NSStringDecl && "NSStringDecl should not be NULL"); 00486 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl); 00487 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject); 00488 } 00489 00490 if (!StringWithUTF8StringMethod) { 00491 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String"); 00492 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II); 00493 00494 // Look for the appropriate method within NSString. 00495 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String); 00496 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) { 00497 // Debugger needs to work even if NSString hasn't been defined. 00498 TypeSourceInfo *ReturnTInfo = nullptr; 00499 ObjCMethodDecl *M = ObjCMethodDecl::Create( 00500 Context, SourceLocation(), SourceLocation(), stringWithUTF8String, 00501 NSStringPointer, ReturnTInfo, NSStringDecl, 00502 /*isInstance=*/false, /*isVariadic=*/false, 00503 /*isPropertyAccessor=*/false, 00504 /*isImplicitlyDeclared=*/true, 00505 /*isDefined=*/false, ObjCMethodDecl::Required, 00506 /*HasRelatedResultType=*/false); 00507 QualType ConstCharType = Context.CharTy.withConst(); 00508 ParmVarDecl *value = 00509 ParmVarDecl::Create(Context, M, 00510 SourceLocation(), SourceLocation(), 00511 &Context.Idents.get("value"), 00512 Context.getPointerType(ConstCharType), 00513 /*TInfo=*/nullptr, 00514 SC_None, nullptr); 00515 M->setMethodParams(Context, value, None); 00516 BoxingMethod = M; 00517 } 00518 00519 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl, 00520 stringWithUTF8String, BoxingMethod)) 00521 return ExprError(); 00522 00523 StringWithUTF8StringMethod = BoxingMethod; 00524 } 00525 00526 BoxingMethod = StringWithUTF8StringMethod; 00527 BoxedType = NSStringPointer; 00528 } 00529 } else if (ValueType->isBuiltinType()) { 00530 // The other types we support are numeric, char and BOOL/bool. We could also 00531 // provide limited support for structure types, such as NSRange, NSRect, and 00532 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h> 00533 // for more details. 00534 00535 // Check for a top-level character literal. 00536 if (const CharacterLiteral *Char = 00537 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) { 00538 // In C, character literals have type 'int'. That's not the type we want 00539 // to use to determine the Objective-c literal kind. 00540 switch (Char->getKind()) { 00541 case CharacterLiteral::Ascii: 00542 ValueType = Context.CharTy; 00543 break; 00544 00545 case CharacterLiteral::Wide: 00546 ValueType = Context.getWideCharType(); 00547 break; 00548 00549 case CharacterLiteral::UTF16: 00550 ValueType = Context.Char16Ty; 00551 break; 00552 00553 case CharacterLiteral::UTF32: 00554 ValueType = Context.Char32Ty; 00555 break; 00556 } 00557 } 00558 CheckForIntOverflow(ValueExpr); 00559 // FIXME: Do I need to do anything special with BoolTy expressions? 00560 00561 // Look for the appropriate method within NSNumber. 00562 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType); 00563 BoxedType = NSNumberPointer; 00564 00565 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) { 00566 if (!ET->getDecl()->isComplete()) { 00567 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type) 00568 << ValueType << ValueExpr->getSourceRange(); 00569 return ExprError(); 00570 } 00571 00572 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), 00573 ET->getDecl()->getIntegerType()); 00574 BoxedType = NSNumberPointer; 00575 } 00576 00577 if (!BoxingMethod) { 00578 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type) 00579 << ValueType << ValueExpr->getSourceRange(); 00580 return ExprError(); 00581 } 00582 00583 // Convert the expression to the type that the parameter requires. 00584 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0]; 00585 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 00586 ParamDecl); 00587 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity, 00588 SourceLocation(), 00589 ValueExpr); 00590 if (ConvertedValueExpr.isInvalid()) 00591 return ExprError(); 00592 ValueExpr = ConvertedValueExpr.get(); 00593 00594 ObjCBoxedExpr *BoxedExpr = 00595 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType, 00596 BoxingMethod, SR); 00597 return MaybeBindToTemporary(BoxedExpr); 00598 } 00599 00600 /// Build an ObjC subscript pseudo-object expression, given that 00601 /// that's supported by the runtime. 00602 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 00603 Expr *IndexExpr, 00604 ObjCMethodDecl *getterMethod, 00605 ObjCMethodDecl *setterMethod) { 00606 assert(!LangOpts.isSubscriptPointerArithmetic()); 00607 00608 // We can't get dependent types here; our callers should have 00609 // filtered them out. 00610 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) && 00611 "base or index cannot have dependent type here"); 00612 00613 // Filter out placeholders in the index. In theory, overloads could 00614 // be preserved here, although that might not actually work correctly. 00615 ExprResult Result = CheckPlaceholderExpr(IndexExpr); 00616 if (Result.isInvalid()) 00617 return ExprError(); 00618 IndexExpr = Result.get(); 00619 00620 // Perform lvalue-to-rvalue conversion on the base. 00621 Result = DefaultLvalueConversion(BaseExpr); 00622 if (Result.isInvalid()) 00623 return ExprError(); 00624 BaseExpr = Result.get(); 00625 00626 // Build the pseudo-object expression. 00627 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr, 00628 Context.PseudoObjectTy, getterMethod, 00629 setterMethod, RB); 00630 } 00631 00632 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) { 00633 // Look up the NSArray class, if we haven't done so already. 00634 if (!NSArrayDecl) { 00635 NamedDecl *IF = LookupSingleName(TUScope, 00636 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray), 00637 SR.getBegin(), 00638 LookupOrdinaryName); 00639 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 00640 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral) 00641 NSArrayDecl = ObjCInterfaceDecl::Create (Context, 00642 Context.getTranslationUnitDecl(), 00643 SourceLocation(), 00644 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray), 00645 nullptr, SourceLocation()); 00646 00647 if (!NSArrayDecl) { 00648 Diag(SR.getBegin(), diag::err_undeclared_nsarray); 00649 return ExprError(); 00650 } 00651 } 00652 00653 // Find the arrayWithObjects:count: method, if we haven't done so already. 00654 QualType IdT = Context.getObjCIdType(); 00655 if (!ArrayWithObjectsMethod) { 00656 Selector 00657 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount); 00658 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel); 00659 if (!Method && getLangOpts().DebuggerObjCLiteral) { 00660 TypeSourceInfo *ReturnTInfo = nullptr; 00661 Method = ObjCMethodDecl::Create( 00662 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo, 00663 Context.getTranslationUnitDecl(), false /*Instance*/, 00664 false /*isVariadic*/, 00665 /*isPropertyAccessor=*/false, 00666 /*isImplicitlyDeclared=*/true, /*isDefined=*/false, 00667 ObjCMethodDecl::Required, false); 00668 SmallVector<ParmVarDecl *, 2> Params; 00669 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method, 00670 SourceLocation(), 00671 SourceLocation(), 00672 &Context.Idents.get("objects"), 00673 Context.getPointerType(IdT), 00674 /*TInfo=*/nullptr, 00675 SC_None, nullptr); 00676 Params.push_back(objects); 00677 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method, 00678 SourceLocation(), 00679 SourceLocation(), 00680 &Context.Idents.get("cnt"), 00681 Context.UnsignedLongTy, 00682 /*TInfo=*/nullptr, SC_None, 00683 nullptr); 00684 Params.push_back(cnt); 00685 Method->setMethodParams(Context, Params, None); 00686 } 00687 00688 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method)) 00689 return ExprError(); 00690 00691 // Dig out the type that all elements should be converted to. 00692 QualType T = Method->parameters()[0]->getType(); 00693 const PointerType *PtrT = T->getAs<PointerType>(); 00694 if (!PtrT || 00695 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) { 00696 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 00697 << Sel; 00698 Diag(Method->parameters()[0]->getLocation(), 00699 diag::note_objc_literal_method_param) 00700 << 0 << T 00701 << Context.getPointerType(IdT.withConst()); 00702 return ExprError(); 00703 } 00704 00705 // Check that the 'count' parameter is integral. 00706 if (!Method->parameters()[1]->getType()->isIntegerType()) { 00707 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 00708 << Sel; 00709 Diag(Method->parameters()[1]->getLocation(), 00710 diag::note_objc_literal_method_param) 00711 << 1 00712 << Method->parameters()[1]->getType() 00713 << "integral"; 00714 return ExprError(); 00715 } 00716 00717 // We've found a good +arrayWithObjects:count: method. Save it! 00718 ArrayWithObjectsMethod = Method; 00719 } 00720 00721 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType(); 00722 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType(); 00723 00724 // Check that each of the elements provided is valid in a collection literal, 00725 // performing conversions as necessary. 00726 Expr **ElementsBuffer = Elements.data(); 00727 for (unsigned I = 0, N = Elements.size(); I != N; ++I) { 00728 ExprResult Converted = CheckObjCCollectionLiteralElement(*this, 00729 ElementsBuffer[I], 00730 RequiredType, true); 00731 if (Converted.isInvalid()) 00732 return ExprError(); 00733 00734 ElementsBuffer[I] = Converted.get(); 00735 } 00736 00737 QualType Ty 00738 = Context.getObjCObjectPointerType( 00739 Context.getObjCInterfaceType(NSArrayDecl)); 00740 00741 return MaybeBindToTemporary( 00742 ObjCArrayLiteral::Create(Context, Elements, Ty, 00743 ArrayWithObjectsMethod, SR)); 00744 } 00745 00746 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, 00747 ObjCDictionaryElement *Elements, 00748 unsigned NumElements) { 00749 // Look up the NSDictionary class, if we haven't done so already. 00750 if (!NSDictionaryDecl) { 00751 NamedDecl *IF = LookupSingleName(TUScope, 00752 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary), 00753 SR.getBegin(), LookupOrdinaryName); 00754 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 00755 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral) 00756 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context, 00757 Context.getTranslationUnitDecl(), 00758 SourceLocation(), 00759 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary), 00760 nullptr, SourceLocation()); 00761 00762 if (!NSDictionaryDecl) { 00763 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary); 00764 return ExprError(); 00765 } 00766 } 00767 00768 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done 00769 // so already. 00770 QualType IdT = Context.getObjCIdType(); 00771 if (!DictionaryWithObjectsMethod) { 00772 Selector Sel = NSAPIObj->getNSDictionarySelector( 00773 NSAPI::NSDict_dictionaryWithObjectsForKeysCount); 00774 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel); 00775 if (!Method && getLangOpts().DebuggerObjCLiteral) { 00776 Method = ObjCMethodDecl::Create(Context, 00777 SourceLocation(), SourceLocation(), Sel, 00778 IdT, 00779 nullptr /*TypeSourceInfo */, 00780 Context.getTranslationUnitDecl(), 00781 false /*Instance*/, false/*isVariadic*/, 00782 /*isPropertyAccessor=*/false, 00783 /*isImplicitlyDeclared=*/true, /*isDefined=*/false, 00784 ObjCMethodDecl::Required, 00785 false); 00786 SmallVector<ParmVarDecl *, 3> Params; 00787 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method, 00788 SourceLocation(), 00789 SourceLocation(), 00790 &Context.Idents.get("objects"), 00791 Context.getPointerType(IdT), 00792 /*TInfo=*/nullptr, SC_None, 00793 nullptr); 00794 Params.push_back(objects); 00795 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method, 00796 SourceLocation(), 00797 SourceLocation(), 00798 &Context.Idents.get("keys"), 00799 Context.getPointerType(IdT), 00800 /*TInfo=*/nullptr, SC_None, 00801 nullptr); 00802 Params.push_back(keys); 00803 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method, 00804 SourceLocation(), 00805 SourceLocation(), 00806 &Context.Idents.get("cnt"), 00807 Context.UnsignedLongTy, 00808 /*TInfo=*/nullptr, SC_None, 00809 nullptr); 00810 Params.push_back(cnt); 00811 Method->setMethodParams(Context, Params, None); 00812 } 00813 00814 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel, 00815 Method)) 00816 return ExprError(); 00817 00818 // Dig out the type that all values should be converted to. 00819 QualType ValueT = Method->parameters()[0]->getType(); 00820 const PointerType *PtrValue = ValueT->getAs<PointerType>(); 00821 if (!PtrValue || 00822 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) { 00823 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 00824 << Sel; 00825 Diag(Method->parameters()[0]->getLocation(), 00826 diag::note_objc_literal_method_param) 00827 << 0 << ValueT 00828 << Context.getPointerType(IdT.withConst()); 00829 return ExprError(); 00830 } 00831 00832 // Dig out the type that all keys should be converted to. 00833 QualType KeyT = Method->parameters()[1]->getType(); 00834 const PointerType *PtrKey = KeyT->getAs<PointerType>(); 00835 if (!PtrKey || 00836 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), 00837 IdT)) { 00838 bool err = true; 00839 if (PtrKey) { 00840 if (QIDNSCopying.isNull()) { 00841 // key argument of selector is id<NSCopying>? 00842 if (ObjCProtocolDecl *NSCopyingPDecl = 00843 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) { 00844 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl}; 00845 QIDNSCopying = 00846 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 00847 (ObjCProtocolDecl**) PQ,1); 00848 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying); 00849 } 00850 } 00851 if (!QIDNSCopying.isNull()) 00852 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), 00853 QIDNSCopying); 00854 } 00855 00856 if (err) { 00857 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 00858 << Sel; 00859 Diag(Method->parameters()[1]->getLocation(), 00860 diag::note_objc_literal_method_param) 00861 << 1 << KeyT 00862 << Context.getPointerType(IdT.withConst()); 00863 return ExprError(); 00864 } 00865 } 00866 00867 // Check that the 'count' parameter is integral. 00868 QualType CountType = Method->parameters()[2]->getType(); 00869 if (!CountType->isIntegerType()) { 00870 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 00871 << Sel; 00872 Diag(Method->parameters()[2]->getLocation(), 00873 diag::note_objc_literal_method_param) 00874 << 2 << CountType 00875 << "integral"; 00876 return ExprError(); 00877 } 00878 00879 // We've found a good +dictionaryWithObjects:keys:count: method; save it! 00880 DictionaryWithObjectsMethod = Method; 00881 } 00882 00883 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType(); 00884 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType(); 00885 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType(); 00886 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType(); 00887 00888 // Check that each of the keys and values provided is valid in a collection 00889 // literal, performing conversions as necessary. 00890 bool HasPackExpansions = false; 00891 for (unsigned I = 0, N = NumElements; I != N; ++I) { 00892 // Check the key. 00893 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key, 00894 KeyT); 00895 if (Key.isInvalid()) 00896 return ExprError(); 00897 00898 // Check the value. 00899 ExprResult Value 00900 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT); 00901 if (Value.isInvalid()) 00902 return ExprError(); 00903 00904 Elements[I].Key = Key.get(); 00905 Elements[I].Value = Value.get(); 00906 00907 if (Elements[I].EllipsisLoc.isInvalid()) 00908 continue; 00909 00910 if (!Elements[I].Key->containsUnexpandedParameterPack() && 00911 !Elements[I].Value->containsUnexpandedParameterPack()) { 00912 Diag(Elements[I].EllipsisLoc, 00913 diag::err_pack_expansion_without_parameter_packs) 00914 << SourceRange(Elements[I].Key->getLocStart(), 00915 Elements[I].Value->getLocEnd()); 00916 return ExprError(); 00917 } 00918 00919 HasPackExpansions = true; 00920 } 00921 00922 00923 QualType Ty 00924 = Context.getObjCObjectPointerType( 00925 Context.getObjCInterfaceType(NSDictionaryDecl)); 00926 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create( 00927 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty, 00928 DictionaryWithObjectsMethod, SR)); 00929 } 00930 00931 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc, 00932 TypeSourceInfo *EncodedTypeInfo, 00933 SourceLocation RParenLoc) { 00934 QualType EncodedType = EncodedTypeInfo->getType(); 00935 QualType StrTy; 00936 if (EncodedType->isDependentType()) 00937 StrTy = Context.DependentTy; 00938 else { 00939 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled. 00940 !EncodedType->isVoidType()) // void is handled too. 00941 if (RequireCompleteType(AtLoc, EncodedType, 00942 diag::err_incomplete_type_objc_at_encode, 00943 EncodedTypeInfo->getTypeLoc())) 00944 return ExprError(); 00945 00946 std::string Str; 00947 QualType NotEncodedT; 00948 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT); 00949 if (!NotEncodedT.isNull()) 00950 Diag(AtLoc, diag::warn_incomplete_encoded_type) 00951 << EncodedType << NotEncodedT; 00952 00953 // The type of @encode is the same as the type of the corresponding string, 00954 // which is an array type. 00955 StrTy = Context.CharTy; 00956 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 00957 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 00958 StrTy.addConst(); 00959 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1), 00960 ArrayType::Normal, 0); 00961 } 00962 00963 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc); 00964 } 00965 00966 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc, 00967 SourceLocation EncodeLoc, 00968 SourceLocation LParenLoc, 00969 ParsedType ty, 00970 SourceLocation RParenLoc) { 00971 // FIXME: Preserve type source info ? 00972 TypeSourceInfo *TInfo; 00973 QualType EncodedType = GetTypeFromParser(ty, &TInfo); 00974 if (!TInfo) 00975 TInfo = Context.getTrivialTypeSourceInfo(EncodedType, 00976 PP.getLocForEndOfToken(LParenLoc)); 00977 00978 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc); 00979 } 00980 00981 static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S, 00982 SourceLocation AtLoc, 00983 SourceLocation LParenLoc, 00984 SourceLocation RParenLoc, 00985 ObjCMethodDecl *Method, 00986 ObjCMethodList &MethList) { 00987 ObjCMethodList *M = &MethList; 00988 bool Warned = false; 00989 for (M = M->getNext(); M; M=M->getNext()) { 00990 ObjCMethodDecl *MatchingMethodDecl = M->Method; 00991 if (MatchingMethodDecl == Method || 00992 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) || 00993 MatchingMethodDecl->getSelector() != Method->getSelector()) 00994 continue; 00995 if (!S.MatchTwoMethodDeclarations(Method, 00996 MatchingMethodDecl, Sema::MMS_loose)) { 00997 if (!Warned) { 00998 Warned = true; 00999 S.Diag(AtLoc, diag::warning_multiple_selectors) 01000 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(") 01001 << FixItHint::CreateInsertion(RParenLoc, ")"); 01002 S.Diag(Method->getLocation(), diag::note_method_declared_at) 01003 << Method->getDeclName(); 01004 } 01005 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at) 01006 << MatchingMethodDecl->getDeclName(); 01007 } 01008 } 01009 return Warned; 01010 } 01011 01012 static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc, 01013 ObjCMethodDecl *Method, 01014 SourceLocation LParenLoc, 01015 SourceLocation RParenLoc, 01016 bool WarnMultipleSelectors) { 01017 if (!WarnMultipleSelectors || 01018 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation())) 01019 return; 01020 bool Warned = false; 01021 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(), 01022 e = S.MethodPool.end(); b != e; b++) { 01023 // first, instance methods 01024 ObjCMethodList &InstMethList = b->second.first; 01025 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc, 01026 Method, InstMethList)) 01027 Warned = true; 01028 01029 // second, class methods 01030 ObjCMethodList &ClsMethList = b->second.second; 01031 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc, 01032 Method, ClsMethList) || Warned) 01033 return; 01034 } 01035 } 01036 01037 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, 01038 SourceLocation AtLoc, 01039 SourceLocation SelLoc, 01040 SourceLocation LParenLoc, 01041 SourceLocation RParenLoc, 01042 bool WarnMultipleSelectors) { 01043 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel, 01044 SourceRange(LParenLoc, RParenLoc), false, false); 01045 if (!Method) 01046 Method = LookupFactoryMethodInGlobalPool(Sel, 01047 SourceRange(LParenLoc, RParenLoc)); 01048 if (!Method) { 01049 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) { 01050 Selector MatchedSel = OM->getSelector(); 01051 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1), 01052 RParenLoc.getLocWithOffset(-1)); 01053 Diag(SelLoc, diag::warn_undeclared_selector_with_typo) 01054 << Sel << MatchedSel 01055 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString()); 01056 01057 } else 01058 Diag(SelLoc, diag::warn_undeclared_selector) << Sel; 01059 } else 01060 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc, 01061 WarnMultipleSelectors); 01062 01063 if (Method && 01064 Method->getImplementationControl() != ObjCMethodDecl::Optional && 01065 !getSourceManager().isInSystemHeader(Method->getLocation())) { 01066 llvm::DenseMap<Selector, SourceLocation>::iterator Pos 01067 = ReferencedSelectors.find(Sel); 01068 if (Pos == ReferencedSelectors.end()) 01069 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc)); 01070 } 01071 01072 // In ARC, forbid the user from using @selector for 01073 // retain/release/autorelease/dealloc/retainCount. 01074 if (getLangOpts().ObjCAutoRefCount) { 01075 switch (Sel.getMethodFamily()) { 01076 case OMF_retain: 01077 case OMF_release: 01078 case OMF_autorelease: 01079 case OMF_retainCount: 01080 case OMF_dealloc: 01081 Diag(AtLoc, diag::err_arc_illegal_selector) << 01082 Sel << SourceRange(LParenLoc, RParenLoc); 01083 break; 01084 01085 case OMF_None: 01086 case OMF_alloc: 01087 case OMF_copy: 01088 case OMF_finalize: 01089 case OMF_init: 01090 case OMF_mutableCopy: 01091 case OMF_new: 01092 case OMF_self: 01093 case OMF_initialize: 01094 case OMF_performSelector: 01095 break; 01096 } 01097 } 01098 QualType Ty = Context.getObjCSelType(); 01099 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc); 01100 } 01101 01102 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId, 01103 SourceLocation AtLoc, 01104 SourceLocation ProtoLoc, 01105 SourceLocation LParenLoc, 01106 SourceLocation ProtoIdLoc, 01107 SourceLocation RParenLoc) { 01108 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc); 01109 if (!PDecl) { 01110 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId; 01111 return true; 01112 } 01113 if (PDecl->hasDefinition()) 01114 PDecl = PDecl->getDefinition(); 01115 01116 QualType Ty = Context.getObjCProtoType(); 01117 if (Ty.isNull()) 01118 return true; 01119 Ty = Context.getObjCObjectPointerType(Ty); 01120 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc); 01121 } 01122 01123 /// Try to capture an implicit reference to 'self'. 01124 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) { 01125 DeclContext *DC = getFunctionLevelDeclContext(); 01126 01127 // If we're not in an ObjC method, error out. Note that, unlike the 01128 // C++ case, we don't require an instance method --- class methods 01129 // still have a 'self', and we really do still need to capture it! 01130 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC); 01131 if (!method) 01132 return nullptr; 01133 01134 tryCaptureVariable(method->getSelfDecl(), Loc); 01135 01136 return method; 01137 } 01138 01139 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) { 01140 if (T == Context.getObjCInstanceType()) 01141 return Context.getObjCIdType(); 01142 01143 return T; 01144 } 01145 01146 QualType Sema::getMessageSendResultType(QualType ReceiverType, 01147 ObjCMethodDecl *Method, 01148 bool isClassMessage, bool isSuperMessage) { 01149 assert(Method && "Must have a method"); 01150 if (!Method->hasRelatedResultType()) 01151 return Method->getSendResultType(); 01152 01153 // If a method has a related return type: 01154 // - if the method found is an instance method, but the message send 01155 // was a class message send, T is the declared return type of the method 01156 // found 01157 if (Method->isInstanceMethod() && isClassMessage) 01158 return stripObjCInstanceType(Context, Method->getSendResultType()); 01159 01160 // - if the receiver is super, T is a pointer to the class of the 01161 // enclosing method definition 01162 if (isSuperMessage) { 01163 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) 01164 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) 01165 return Context.getObjCObjectPointerType( 01166 Context.getObjCInterfaceType(Class)); 01167 } 01168 01169 // - if the receiver is the name of a class U, T is a pointer to U 01170 if (ReceiverType->getAs<ObjCInterfaceType>() || 01171 ReceiverType->isObjCQualifiedInterfaceType()) 01172 return Context.getObjCObjectPointerType(ReceiverType); 01173 // - if the receiver is of type Class or qualified Class type, 01174 // T is the declared return type of the method. 01175 if (ReceiverType->isObjCClassType() || 01176 ReceiverType->isObjCQualifiedClassType()) 01177 return stripObjCInstanceType(Context, Method->getSendResultType()); 01178 01179 // - if the receiver is id, qualified id, Class, or qualified Class, T 01180 // is the receiver type, otherwise 01181 // - T is the type of the receiver expression. 01182 return ReceiverType; 01183 } 01184 01185 /// Look for an ObjC method whose result type exactly matches the given type. 01186 static const ObjCMethodDecl * 01187 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD, 01188 QualType instancetype) { 01189 if (MD->getReturnType() == instancetype) 01190 return MD; 01191 01192 // For these purposes, a method in an @implementation overrides a 01193 // declaration in the @interface. 01194 if (const ObjCImplDecl *impl = 01195 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) { 01196 const ObjCContainerDecl *iface; 01197 if (const ObjCCategoryImplDecl *catImpl = 01198 dyn_cast<ObjCCategoryImplDecl>(impl)) { 01199 iface = catImpl->getCategoryDecl(); 01200 } else { 01201 iface = impl->getClassInterface(); 01202 } 01203 01204 const ObjCMethodDecl *ifaceMD = 01205 iface->getMethod(MD->getSelector(), MD->isInstanceMethod()); 01206 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype); 01207 } 01208 01209 SmallVector<const ObjCMethodDecl *, 4> overrides; 01210 MD->getOverriddenMethods(overrides); 01211 for (unsigned i = 0, e = overrides.size(); i != e; ++i) { 01212 if (const ObjCMethodDecl *result = 01213 findExplicitInstancetypeDeclarer(overrides[i], instancetype)) 01214 return result; 01215 } 01216 01217 return nullptr; 01218 } 01219 01220 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) { 01221 // Only complain if we're in an ObjC method and the required return 01222 // type doesn't match the method's declared return type. 01223 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext); 01224 if (!MD || !MD->hasRelatedResultType() || 01225 Context.hasSameUnqualifiedType(destType, MD->getReturnType())) 01226 return; 01227 01228 // Look for a method overridden by this method which explicitly uses 01229 // 'instancetype'. 01230 if (const ObjCMethodDecl *overridden = 01231 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) { 01232 SourceRange range = overridden->getReturnTypeSourceRange(); 01233 SourceLocation loc = range.getBegin(); 01234 if (loc.isInvalid()) 01235 loc = overridden->getLocation(); 01236 Diag(loc, diag::note_related_result_type_explicit) 01237 << /*current method*/ 1 << range; 01238 return; 01239 } 01240 01241 // Otherwise, if we have an interesting method family, note that. 01242 // This should always trigger if the above didn't. 01243 if (ObjCMethodFamily family = MD->getMethodFamily()) 01244 Diag(MD->getLocation(), diag::note_related_result_type_family) 01245 << /*current method*/ 1 01246 << family; 01247 } 01248 01249 void Sema::EmitRelatedResultTypeNote(const Expr *E) { 01250 E = E->IgnoreParenImpCasts(); 01251 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E); 01252 if (!MsgSend) 01253 return; 01254 01255 const ObjCMethodDecl *Method = MsgSend->getMethodDecl(); 01256 if (!Method) 01257 return; 01258 01259 if (!Method->hasRelatedResultType()) 01260 return; 01261 01262 if (Context.hasSameUnqualifiedType( 01263 Method->getReturnType().getNonReferenceType(), MsgSend->getType())) 01264 return; 01265 01266 if (!Context.hasSameUnqualifiedType(Method->getReturnType(), 01267 Context.getObjCInstanceType())) 01268 return; 01269 01270 Diag(Method->getLocation(), diag::note_related_result_type_inferred) 01271 << Method->isInstanceMethod() << Method->getSelector() 01272 << MsgSend->getType(); 01273 } 01274 01275 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType, 01276 MultiExprArg Args, 01277 Selector Sel, 01278 ArrayRef<SourceLocation> SelectorLocs, 01279 ObjCMethodDecl *Method, 01280 bool isClassMessage, bool isSuperMessage, 01281 SourceLocation lbrac, SourceLocation rbrac, 01282 SourceRange RecRange, 01283 QualType &ReturnType, ExprValueKind &VK) { 01284 SourceLocation SelLoc; 01285 if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) 01286 SelLoc = SelectorLocs.front(); 01287 else 01288 SelLoc = lbrac; 01289 01290 if (!Method) { 01291 // Apply default argument promotion as for (C99 6.5.2.2p6). 01292 for (unsigned i = 0, e = Args.size(); i != e; i++) { 01293 if (Args[i]->isTypeDependent()) 01294 continue; 01295 01296 ExprResult result; 01297 if (getLangOpts().DebuggerSupport) { 01298 QualType paramTy; // ignored 01299 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy); 01300 } else { 01301 result = DefaultArgumentPromotion(Args[i]); 01302 } 01303 if (result.isInvalid()) 01304 return true; 01305 Args[i] = result.get(); 01306 } 01307 01308 unsigned DiagID; 01309 if (getLangOpts().ObjCAutoRefCount) 01310 DiagID = diag::err_arc_method_not_found; 01311 else 01312 DiagID = isClassMessage ? diag::warn_class_method_not_found 01313 : diag::warn_inst_method_not_found; 01314 if (!getLangOpts().DebuggerSupport) { 01315 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType); 01316 if (OMD && !OMD->isInvalidDecl()) { 01317 if (getLangOpts().ObjCAutoRefCount) 01318 DiagID = diag::error_method_not_found_with_typo; 01319 else 01320 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo 01321 : diag::warn_instance_method_not_found_with_typo; 01322 Selector MatchedSel = OMD->getSelector(); 01323 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back()); 01324 if (MatchedSel.isUnarySelector()) 01325 Diag(SelLoc, DiagID) 01326 << Sel<< isClassMessage << MatchedSel 01327 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString()); 01328 else 01329 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel; 01330 } 01331 else 01332 Diag(SelLoc, DiagID) 01333 << Sel << isClassMessage << SourceRange(SelectorLocs.front(), 01334 SelectorLocs.back()); 01335 // Find the class to which we are sending this message. 01336 if (ReceiverType->isObjCObjectPointerType()) { 01337 if (ObjCInterfaceDecl *ThisClass = 01338 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) { 01339 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared); 01340 if (!RecRange.isInvalid()) 01341 if (ThisClass->lookupClassMethod(Sel)) 01342 Diag(RecRange.getBegin(),diag::note_receiver_expr_here) 01343 << FixItHint::CreateReplacement(RecRange, 01344 ThisClass->getNameAsString()); 01345 } 01346 } 01347 } 01348 01349 // In debuggers, we want to use __unknown_anytype for these 01350 // results so that clients can cast them. 01351 if (getLangOpts().DebuggerSupport) { 01352 ReturnType = Context.UnknownAnyTy; 01353 } else { 01354 ReturnType = Context.getObjCIdType(); 01355 } 01356 VK = VK_RValue; 01357 return false; 01358 } 01359 01360 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage, 01361 isSuperMessage); 01362 VK = Expr::getValueKindForType(Method->getReturnType()); 01363 01364 unsigned NumNamedArgs = Sel.getNumArgs(); 01365 // Method might have more arguments than selector indicates. This is due 01366 // to addition of c-style arguments in method. 01367 if (Method->param_size() > Sel.getNumArgs()) 01368 NumNamedArgs = Method->param_size(); 01369 // FIXME. This need be cleaned up. 01370 if (Args.size() < NumNamedArgs) { 01371 Diag(SelLoc, diag::err_typecheck_call_too_few_args) 01372 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size()); 01373 return false; 01374 } 01375 01376 bool IsError = false; 01377 for (unsigned i = 0; i < NumNamedArgs; i++) { 01378 // We can't do any type-checking on a type-dependent argument. 01379 if (Args[i]->isTypeDependent()) 01380 continue; 01381 01382 Expr *argExpr = Args[i]; 01383 01384 ParmVarDecl *param = Method->parameters()[i]; 01385 assert(argExpr && "CheckMessageArgumentTypes(): missing expression"); 01386 01387 // Strip the unbridged-cast placeholder expression off unless it's 01388 // a consumed argument. 01389 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 01390 !param->hasAttr<CFConsumedAttr>()) 01391 argExpr = stripARCUnbridgedCast(argExpr); 01392 01393 // If the parameter is __unknown_anytype, infer its type 01394 // from the argument. 01395 if (param->getType() == Context.UnknownAnyTy) { 01396 QualType paramType; 01397 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType); 01398 if (argE.isInvalid()) { 01399 IsError = true; 01400 } else { 01401 Args[i] = argE.get(); 01402 01403 // Update the parameter type in-place. 01404 param->setType(paramType); 01405 } 01406 continue; 01407 } 01408 01409 if (RequireCompleteType(argExpr->getSourceRange().getBegin(), 01410 param->getType(), 01411 diag::err_call_incomplete_argument, argExpr)) 01412 return true; 01413 01414 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 01415 param); 01416 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr); 01417 if (ArgE.isInvalid()) 01418 IsError = true; 01419 else 01420 Args[i] = ArgE.getAs<Expr>(); 01421 } 01422 01423 // Promote additional arguments to variadic methods. 01424 if (Method->isVariadic()) { 01425 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 01426 if (Args[i]->isTypeDependent()) 01427 continue; 01428 01429 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 01430 nullptr); 01431 IsError |= Arg.isInvalid(); 01432 Args[i] = Arg.get(); 01433 } 01434 } else { 01435 // Check for extra arguments to non-variadic methods. 01436 if (Args.size() != NumNamedArgs) { 01437 Diag(Args[NumNamedArgs]->getLocStart(), 01438 diag::err_typecheck_call_too_many_args) 01439 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size()) 01440 << Method->getSourceRange() 01441 << SourceRange(Args[NumNamedArgs]->getLocStart(), 01442 Args.back()->getLocEnd()); 01443 } 01444 } 01445 01446 DiagnoseSentinelCalls(Method, SelLoc, Args); 01447 01448 // Do additional checkings on method. 01449 IsError |= CheckObjCMethodCall( 01450 Method, SelLoc, makeArrayRef(Args.data(), Args.size())); 01451 01452 return IsError; 01453 } 01454 01455 bool Sema::isSelfExpr(Expr *RExpr) { 01456 // 'self' is objc 'self' in an objc method only. 01457 ObjCMethodDecl *Method = 01458 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor()); 01459 return isSelfExpr(RExpr, Method); 01460 } 01461 01462 bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) { 01463 if (!method) return false; 01464 01465 receiver = receiver->IgnoreParenLValueCasts(); 01466 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver)) 01467 if (DRE->getDecl() == method->getSelfDecl()) 01468 return true; 01469 return false; 01470 } 01471 01472 /// LookupMethodInType - Look up a method in an ObjCObjectType. 01473 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type, 01474 bool isInstance) { 01475 const ObjCObjectType *objType = type->castAs<ObjCObjectType>(); 01476 if (ObjCInterfaceDecl *iface = objType->getInterface()) { 01477 // Look it up in the main interface (and categories, etc.) 01478 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance)) 01479 return method; 01480 01481 // Okay, look for "private" methods declared in any 01482 // @implementations we've seen. 01483 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance)) 01484 return method; 01485 } 01486 01487 // Check qualifiers. 01488 for (const auto *I : objType->quals()) 01489 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance)) 01490 return method; 01491 01492 return nullptr; 01493 } 01494 01495 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier 01496 /// list of a qualified objective pointer type. 01497 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel, 01498 const ObjCObjectPointerType *OPT, 01499 bool Instance) 01500 { 01501 ObjCMethodDecl *MD = nullptr; 01502 for (const auto *PROTO : OPT->quals()) { 01503 if ((MD = PROTO->lookupMethod(Sel, Instance))) { 01504 return MD; 01505 } 01506 } 01507 return nullptr; 01508 } 01509 01510 static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) { 01511 if (!Receiver) 01512 return; 01513 01514 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver)) 01515 Receiver = OVE->getSourceExpr(); 01516 01517 Expr *RExpr = Receiver->IgnoreParenImpCasts(); 01518 SourceLocation Loc = RExpr->getLocStart(); 01519 QualType T = RExpr->getType(); 01520 const ObjCPropertyDecl *PDecl = nullptr; 01521 const ObjCMethodDecl *GDecl = nullptr; 01522 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) { 01523 RExpr = POE->getSyntacticForm(); 01524 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) { 01525 if (PRE->isImplicitProperty()) { 01526 GDecl = PRE->getImplicitPropertyGetter(); 01527 if (GDecl) { 01528 T = GDecl->getReturnType(); 01529 } 01530 } 01531 else { 01532 PDecl = PRE->getExplicitProperty(); 01533 if (PDecl) { 01534 T = PDecl->getType(); 01535 } 01536 } 01537 } 01538 } 01539 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) { 01540 // See if receiver is a method which envokes a synthesized getter 01541 // backing a 'weak' property. 01542 ObjCMethodDecl *Method = ME->getMethodDecl(); 01543 if (Method && Method->getSelector().getNumArgs() == 0) { 01544 PDecl = Method->findPropertyDecl(); 01545 if (PDecl) 01546 T = PDecl->getType(); 01547 } 01548 } 01549 01550 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) { 01551 if (!PDecl) 01552 return; 01553 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)) 01554 return; 01555 } 01556 01557 S.Diag(Loc, diag::warn_receiver_is_weak) 01558 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2)); 01559 01560 if (PDecl) 01561 S.Diag(PDecl->getLocation(), diag::note_property_declare); 01562 else if (GDecl) 01563 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl; 01564 01565 S.Diag(Loc, diag::note_arc_assign_to_strong); 01566 } 01567 01568 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an 01569 /// objective C interface. This is a property reference expression. 01570 ExprResult Sema:: 01571 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 01572 Expr *BaseExpr, SourceLocation OpLoc, 01573 DeclarationName MemberName, 01574 SourceLocation MemberLoc, 01575 SourceLocation SuperLoc, QualType SuperType, 01576 bool Super) { 01577 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType(); 01578 ObjCInterfaceDecl *IFace = IFaceT->getDecl(); 01579 01580 if (!MemberName.isIdentifier()) { 01581 Diag(MemberLoc, diag::err_invalid_property_name) 01582 << MemberName << QualType(OPT, 0); 01583 return ExprError(); 01584 } 01585 01586 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 01587 01588 SourceRange BaseRange = Super? SourceRange(SuperLoc) 01589 : BaseExpr->getSourceRange(); 01590 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(), 01591 diag::err_property_not_found_forward_class, 01592 MemberName, BaseRange)) 01593 return ExprError(); 01594 01595 // Search for a declared property first. 01596 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) { 01597 // Check whether we can reference this property. 01598 if (DiagnoseUseOfDecl(PD, MemberLoc)) 01599 return ExprError(); 01600 if (Super) 01601 return new (Context) 01602 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, 01603 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType); 01604 else 01605 return new (Context) 01606 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, 01607 OK_ObjCProperty, MemberLoc, BaseExpr); 01608 } 01609 // Check protocols on qualified interfaces. 01610 for (const auto *I : OPT->quals()) 01611 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) { 01612 // Check whether we can reference this property. 01613 if (DiagnoseUseOfDecl(PD, MemberLoc)) 01614 return ExprError(); 01615 01616 if (Super) 01617 return new (Context) ObjCPropertyRefExpr( 01618 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc, 01619 SuperLoc, SuperType); 01620 else 01621 return new (Context) 01622 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, 01623 OK_ObjCProperty, MemberLoc, BaseExpr); 01624 } 01625 // If that failed, look for an "implicit" property by seeing if the nullary 01626 // selector is implemented. 01627 01628 // FIXME: The logic for looking up nullary and unary selectors should be 01629 // shared with the code in ActOnInstanceMessage. 01630 01631 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 01632 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 01633 01634 // May be founf in property's qualified list. 01635 if (!Getter) 01636 Getter = LookupMethodInQualifiedType(Sel, OPT, true); 01637 01638 // If this reference is in an @implementation, check for 'private' methods. 01639 if (!Getter) 01640 Getter = IFace->lookupPrivateMethod(Sel); 01641 01642 if (Getter) { 01643 // Check if we can reference this property. 01644 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 01645 return ExprError(); 01646 } 01647 // If we found a getter then this may be a valid dot-reference, we 01648 // will look for the matching setter, in case it is needed. 01649 Selector SetterSel = 01650 SelectorTable::constructSetterSelector(PP.getIdentifierTable(), 01651 PP.getSelectorTable(), Member); 01652 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); 01653 01654 // May be founf in property's qualified list. 01655 if (!Setter) 01656 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true); 01657 01658 if (!Setter) { 01659 // If this reference is in an @implementation, also check for 'private' 01660 // methods. 01661 Setter = IFace->lookupPrivateMethod(SetterSel); 01662 } 01663 01664 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 01665 return ExprError(); 01666 01667 // Special warning if member name used in a property-dot for a setter accessor 01668 // does not use a property with same name; e.g. obj.X = ... for a property with 01669 // name 'x'. 01670 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() 01671 && !IFace->FindPropertyDeclaration(Member)) { 01672 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) { 01673 // Do not warn if user is using property-dot syntax to make call to 01674 // user named setter. 01675 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter)) 01676 Diag(MemberLoc, 01677 diag::warn_property_access_suggest) 01678 << MemberName << QualType(OPT, 0) << PDecl->getName() 01679 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName()); 01680 } 01681 } 01682 01683 if (Getter || Setter) { 01684 if (Super) 01685 return new (Context) 01686 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, 01687 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType); 01688 else 01689 return new (Context) 01690 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, 01691 OK_ObjCProperty, MemberLoc, BaseExpr); 01692 01693 } 01694 01695 // Attempt to correct for typos in property names. 01696 if (TypoCorrection Corrected = 01697 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc), 01698 LookupOrdinaryName, nullptr, nullptr, 01699 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(), 01700 CTK_ErrorRecovery, IFace, false, OPT)) { 01701 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest) 01702 << MemberName << QualType(OPT, 0)); 01703 DeclarationName TypoResult = Corrected.getCorrection(); 01704 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc, 01705 TypoResult, MemberLoc, 01706 SuperLoc, SuperType, Super); 01707 } 01708 ObjCInterfaceDecl *ClassDeclared; 01709 if (ObjCIvarDecl *Ivar = 01710 IFace->lookupInstanceVariable(Member, ClassDeclared)) { 01711 QualType T = Ivar->getType(); 01712 if (const ObjCObjectPointerType * OBJPT = 01713 T->getAsObjCInterfacePointerType()) { 01714 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(), 01715 diag::err_property_not_as_forward_class, 01716 MemberName, BaseExpr)) 01717 return ExprError(); 01718 } 01719 Diag(MemberLoc, 01720 diag::err_ivar_access_using_property_syntax_suggest) 01721 << MemberName << QualType(OPT, 0) << Ivar->getDeclName() 01722 << FixItHint::CreateReplacement(OpLoc, "->"); 01723 return ExprError(); 01724 } 01725 01726 Diag(MemberLoc, diag::err_property_not_found) 01727 << MemberName << QualType(OPT, 0); 01728 if (Setter) 01729 Diag(Setter->getLocation(), diag::note_getter_unavailable) 01730 << MemberName << BaseExpr->getSourceRange(); 01731 return ExprError(); 01732 } 01733 01734 01735 01736 ExprResult Sema:: 01737 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 01738 IdentifierInfo &propertyName, 01739 SourceLocation receiverNameLoc, 01740 SourceLocation propertyNameLoc) { 01741 01742 IdentifierInfo *receiverNamePtr = &receiverName; 01743 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr, 01744 receiverNameLoc); 01745 01746 bool IsSuper = false; 01747 if (!IFace) { 01748 // If the "receiver" is 'super' in a method, handle it as an expression-like 01749 // property reference. 01750 if (receiverNamePtr->isStr("super")) { 01751 IsSuper = true; 01752 01753 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) { 01754 if (CurMethod->isInstanceMethod()) { 01755 ObjCInterfaceDecl *Super = 01756 CurMethod->getClassInterface()->getSuperClass(); 01757 if (!Super) { 01758 // The current class does not have a superclass. 01759 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super) 01760 << CurMethod->getClassInterface()->getIdentifier(); 01761 return ExprError(); 01762 } 01763 QualType T = Context.getObjCInterfaceType(Super); 01764 T = Context.getObjCObjectPointerType(T); 01765 01766 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(), 01767 /*BaseExpr*/nullptr, 01768 SourceLocation()/*OpLoc*/, 01769 &propertyName, 01770 propertyNameLoc, 01771 receiverNameLoc, T, true); 01772 } 01773 01774 // Otherwise, if this is a class method, try dispatching to our 01775 // superclass. 01776 IFace = CurMethod->getClassInterface()->getSuperClass(); 01777 } 01778 } 01779 01780 if (!IFace) { 01781 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier 01782 << tok::l_paren; 01783 return ExprError(); 01784 } 01785 } 01786 01787 // Search for a declared property first. 01788 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName); 01789 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel); 01790 01791 // If this reference is in an @implementation, check for 'private' methods. 01792 if (!Getter) 01793 Getter = IFace->lookupPrivateClassMethod(Sel); 01794 01795 if (Getter) { 01796 // FIXME: refactor/share with ActOnMemberReference(). 01797 // Check if we can reference this property. 01798 if (DiagnoseUseOfDecl(Getter, propertyNameLoc)) 01799 return ExprError(); 01800 } 01801 01802 // Look for the matching setter, in case it is needed. 01803 Selector SetterSel = 01804 SelectorTable::constructSetterSelector(PP.getIdentifierTable(), 01805 PP.getSelectorTable(), 01806 &propertyName); 01807 01808 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 01809 if (!Setter) { 01810 // If this reference is in an @implementation, also check for 'private' 01811 // methods. 01812 Setter = IFace->lookupPrivateClassMethod(SetterSel); 01813 } 01814 // Look through local category implementations associated with the class. 01815 if (!Setter) 01816 Setter = IFace->getCategoryClassMethod(SetterSel); 01817 01818 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc)) 01819 return ExprError(); 01820 01821 if (Getter || Setter) { 01822 if (IsSuper) 01823 return new (Context) 01824 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, 01825 OK_ObjCProperty, propertyNameLoc, receiverNameLoc, 01826 Context.getObjCInterfaceType(IFace)); 01827 01828 return new (Context) ObjCPropertyRefExpr( 01829 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, 01830 propertyNameLoc, receiverNameLoc, IFace); 01831 } 01832 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found) 01833 << &propertyName << Context.getObjCInterfaceType(IFace)); 01834 } 01835 01836 namespace { 01837 01838 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback { 01839 public: 01840 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) { 01841 // Determine whether "super" is acceptable in the current context. 01842 if (Method && Method->getClassInterface()) 01843 WantObjCSuper = Method->getClassInterface()->getSuperClass(); 01844 } 01845 01846 bool ValidateCandidate(const TypoCorrection &candidate) override { 01847 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() || 01848 candidate.isKeyword("super"); 01849 } 01850 }; 01851 01852 } 01853 01854 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S, 01855 IdentifierInfo *Name, 01856 SourceLocation NameLoc, 01857 bool IsSuper, 01858 bool HasTrailingDot, 01859 ParsedType &ReceiverType) { 01860 ReceiverType = ParsedType(); 01861 01862 // If the identifier is "super" and there is no trailing dot, we're 01863 // messaging super. If the identifier is "super" and there is a 01864 // trailing dot, it's an instance message. 01865 if (IsSuper && S->isInObjcMethodScope()) 01866 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage; 01867 01868 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 01869 LookupName(Result, S); 01870 01871 switch (Result.getResultKind()) { 01872 case LookupResult::NotFound: 01873 // Normal name lookup didn't find anything. If we're in an 01874 // Objective-C method, look for ivars. If we find one, we're done! 01875 // FIXME: This is a hack. Ivar lookup should be part of normal 01876 // lookup. 01877 if (ObjCMethodDecl *Method = getCurMethodDecl()) { 01878 if (!Method->getClassInterface()) { 01879 // Fall back: let the parser try to parse it as an instance message. 01880 return ObjCInstanceMessage; 01881 } 01882 01883 ObjCInterfaceDecl *ClassDeclared; 01884 if (Method->getClassInterface()->lookupInstanceVariable(Name, 01885 ClassDeclared)) 01886 return ObjCInstanceMessage; 01887 } 01888 01889 // Break out; we'll perform typo correction below. 01890 break; 01891 01892 case LookupResult::NotFoundInCurrentInstantiation: 01893 case LookupResult::FoundOverloaded: 01894 case LookupResult::FoundUnresolvedValue: 01895 case LookupResult::Ambiguous: 01896 Result.suppressDiagnostics(); 01897 return ObjCInstanceMessage; 01898 01899 case LookupResult::Found: { 01900 // If the identifier is a class or not, and there is a trailing dot, 01901 // it's an instance message. 01902 if (HasTrailingDot) 01903 return ObjCInstanceMessage; 01904 // We found something. If it's a type, then we have a class 01905 // message. Otherwise, it's an instance message. 01906 NamedDecl *ND = Result.getFoundDecl(); 01907 QualType T; 01908 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) 01909 T = Context.getObjCInterfaceType(Class); 01910 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) { 01911 T = Context.getTypeDeclType(Type); 01912 DiagnoseUseOfDecl(Type, NameLoc); 01913 } 01914 else 01915 return ObjCInstanceMessage; 01916 01917 // We have a class message, and T is the type we're 01918 // messaging. Build source-location information for it. 01919 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc); 01920 ReceiverType = CreateParsedType(T, TSInfo); 01921 return ObjCClassMessage; 01922 } 01923 } 01924 01925 if (TypoCorrection Corrected = CorrectTypo( 01926 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr, 01927 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()), 01928 CTK_ErrorRecovery, nullptr, false, nullptr, false)) { 01929 if (Corrected.isKeyword()) { 01930 // If we've found the keyword "super" (the only keyword that would be 01931 // returned by CorrectTypo), this is a send to super. 01932 diagnoseTypo(Corrected, 01933 PDiag(diag::err_unknown_receiver_suggest) << Name); 01934 return ObjCSuperMessage; 01935 } else if (ObjCInterfaceDecl *Class = 01936 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { 01937 // If we found a declaration, correct when it refers to an Objective-C 01938 // class. 01939 diagnoseTypo(Corrected, 01940 PDiag(diag::err_unknown_receiver_suggest) << Name); 01941 QualType T = Context.getObjCInterfaceType(Class); 01942 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc); 01943 ReceiverType = CreateParsedType(T, TSInfo); 01944 return ObjCClassMessage; 01945 } 01946 } 01947 01948 // Fall back: let the parser try to parse it as an instance message. 01949 return ObjCInstanceMessage; 01950 } 01951 01952 ExprResult Sema::ActOnSuperMessage(Scope *S, 01953 SourceLocation SuperLoc, 01954 Selector Sel, 01955 SourceLocation LBracLoc, 01956 ArrayRef<SourceLocation> SelectorLocs, 01957 SourceLocation RBracLoc, 01958 MultiExprArg Args) { 01959 // Determine whether we are inside a method or not. 01960 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc); 01961 if (!Method) { 01962 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super); 01963 return ExprError(); 01964 } 01965 01966 ObjCInterfaceDecl *Class = Method->getClassInterface(); 01967 if (!Class) { 01968 Diag(SuperLoc, diag::error_no_super_class_message) 01969 << Method->getDeclName(); 01970 return ExprError(); 01971 } 01972 01973 ObjCInterfaceDecl *Super = Class->getSuperClass(); 01974 if (!Super) { 01975 // The current class does not have a superclass. 01976 Diag(SuperLoc, diag::error_root_class_cannot_use_super) 01977 << Class->getIdentifier(); 01978 return ExprError(); 01979 } 01980 01981 // We are in a method whose class has a superclass, so 'super' 01982 // is acting as a keyword. 01983 if (Method->getSelector() == Sel) 01984 getCurFunction()->ObjCShouldCallSuper = false; 01985 01986 if (Method->isInstanceMethod()) { 01987 // Since we are in an instance method, this is an instance 01988 // message to the superclass instance. 01989 QualType SuperTy = Context.getObjCInterfaceType(Super); 01990 SuperTy = Context.getObjCObjectPointerType(SuperTy); 01991 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc, 01992 Sel, /*Method=*/nullptr, 01993 LBracLoc, SelectorLocs, RBracLoc, Args); 01994 } 01995 01996 // Since we are in a class method, this is a class message to 01997 // the superclass. 01998 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr, 01999 Context.getObjCInterfaceType(Super), 02000 SuperLoc, Sel, /*Method=*/nullptr, 02001 LBracLoc, SelectorLocs, RBracLoc, Args); 02002 } 02003 02004 02005 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType, 02006 bool isSuperReceiver, 02007 SourceLocation Loc, 02008 Selector Sel, 02009 ObjCMethodDecl *Method, 02010 MultiExprArg Args) { 02011 TypeSourceInfo *receiverTypeInfo = nullptr; 02012 if (!ReceiverType.isNull()) 02013 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType); 02014 02015 return BuildClassMessage(receiverTypeInfo, ReceiverType, 02016 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(), 02017 Sel, Method, Loc, Loc, Loc, Args, 02018 /*isImplicit=*/true); 02019 02020 } 02021 02022 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg, 02023 unsigned DiagID, 02024 bool (*refactor)(const ObjCMessageExpr *, 02025 const NSAPI &, edit::Commit &)) { 02026 SourceLocation MsgLoc = Msg->getExprLoc(); 02027 if (S.Diags.isIgnored(DiagID, MsgLoc)) 02028 return; 02029 02030 SourceManager &SM = S.SourceMgr; 02031 edit::Commit ECommit(SM, S.LangOpts); 02032 if (refactor(Msg,*S.NSAPIObj, ECommit)) { 02033 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID) 02034 << Msg->getSelector() << Msg->getSourceRange(); 02035 // FIXME: Don't emit diagnostic at all if fixits are non-commitable. 02036 if (!ECommit.isCommitable()) 02037 return; 02038 for (edit::Commit::edit_iterator 02039 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) { 02040 const edit::Commit::Edit &Edit = *I; 02041 switch (Edit.Kind) { 02042 case edit::Commit::Act_Insert: 02043 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc, 02044 Edit.Text, 02045 Edit.BeforePrev)); 02046 break; 02047 case edit::Commit::Act_InsertFromRange: 02048 Builder.AddFixItHint( 02049 FixItHint::CreateInsertionFromRange(Edit.OrigLoc, 02050 Edit.getInsertFromRange(SM), 02051 Edit.BeforePrev)); 02052 break; 02053 case edit::Commit::Act_Remove: 02054 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM))); 02055 break; 02056 } 02057 } 02058 } 02059 } 02060 02061 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) { 02062 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use, 02063 edit::rewriteObjCRedundantCallWithLiteral); 02064 } 02065 02066 /// \brief Diagnose use of %s directive in an NSString which is being passed 02067 /// as formatting string to formatting method. 02068 static void 02069 DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S, 02070 ObjCMethodDecl *Method, 02071 Selector Sel, 02072 Expr **Args, unsigned NumArgs) { 02073 unsigned Idx = 0; 02074 bool Format = false; 02075 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily(); 02076 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) { 02077 Idx = 0; 02078 Format = true; 02079 } 02080 else if (Method) { 02081 for (const auto *I : Method->specific_attrs<FormatAttr>()) { 02082 if (S.GetFormatNSStringIdx(I, Idx)) { 02083 Format = true; 02084 break; 02085 } 02086 } 02087 } 02088 if (!Format || NumArgs <= Idx) 02089 return; 02090 02091 Expr *FormatExpr = Args[Idx]; 02092 if (ObjCStringLiteral *OSL = 02093 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) { 02094 StringLiteral *FormatString = OSL->getString(); 02095 if (S.FormatStringHasSArg(FormatString)) { 02096 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 02097 << "%s" << 0 << 0; 02098 if (Method) 02099 S.Diag(Method->getLocation(), diag::note_method_declared_at) 02100 << Method->getDeclName(); 02101 } 02102 } 02103 } 02104 02105 /// \brief Build an Objective-C class message expression. 02106 /// 02107 /// This routine takes care of both normal class messages and 02108 /// class messages to the superclass. 02109 /// 02110 /// \param ReceiverTypeInfo Type source information that describes the 02111 /// receiver of this message. This may be NULL, in which case we are 02112 /// sending to the superclass and \p SuperLoc must be a valid source 02113 /// location. 02114 02115 /// \param ReceiverType The type of the object receiving the 02116 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same 02117 /// type as that refers to. For a superclass send, this is the type of 02118 /// the superclass. 02119 /// 02120 /// \param SuperLoc The location of the "super" keyword in a 02121 /// superclass message. 02122 /// 02123 /// \param Sel The selector to which the message is being sent. 02124 /// 02125 /// \param Method The method that this class message is invoking, if 02126 /// already known. 02127 /// 02128 /// \param LBracLoc The location of the opening square bracket ']'. 02129 /// 02130 /// \param RBracLoc The location of the closing square bracket ']'. 02131 /// 02132 /// \param ArgsIn The message arguments. 02133 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 02134 QualType ReceiverType, 02135 SourceLocation SuperLoc, 02136 Selector Sel, 02137 ObjCMethodDecl *Method, 02138 SourceLocation LBracLoc, 02139 ArrayRef<SourceLocation> SelectorLocs, 02140 SourceLocation RBracLoc, 02141 MultiExprArg ArgsIn, 02142 bool isImplicit) { 02143 SourceLocation Loc = SuperLoc.isValid()? SuperLoc 02144 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin(); 02145 if (LBracLoc.isInvalid()) { 02146 Diag(Loc, diag::err_missing_open_square_message_send) 02147 << FixItHint::CreateInsertion(Loc, "["); 02148 LBracLoc = Loc; 02149 } 02150 SourceLocation SelLoc; 02151 if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) 02152 SelLoc = SelectorLocs.front(); 02153 else 02154 SelLoc = Loc; 02155 02156 if (ReceiverType->isDependentType()) { 02157 // If the receiver type is dependent, we can't type-check anything 02158 // at this point. Build a dependent expression. 02159 unsigned NumArgs = ArgsIn.size(); 02160 Expr **Args = ArgsIn.data(); 02161 assert(SuperLoc.isInvalid() && "Message to super with dependent type"); 02162 return ObjCMessageExpr::Create( 02163 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel, 02164 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc, 02165 isImplicit); 02166 } 02167 02168 // Find the class to which we are sending this message. 02169 ObjCInterfaceDecl *Class = nullptr; 02170 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>(); 02171 if (!ClassType || !(Class = ClassType->getInterface())) { 02172 Diag(Loc, diag::err_invalid_receiver_class_message) 02173 << ReceiverType; 02174 return ExprError(); 02175 } 02176 assert(Class && "We don't know which class we're messaging?"); 02177 // objc++ diagnoses during typename annotation. 02178 if (!getLangOpts().CPlusPlus) 02179 (void)DiagnoseUseOfDecl(Class, SelLoc); 02180 // Find the method we are messaging. 02181 if (!Method) { 02182 SourceRange TypeRange 02183 = SuperLoc.isValid()? SourceRange(SuperLoc) 02184 : ReceiverTypeInfo->getTypeLoc().getSourceRange(); 02185 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class), 02186 (getLangOpts().ObjCAutoRefCount 02187 ? diag::err_arc_receiver_forward_class 02188 : diag::warn_receiver_forward_class), 02189 TypeRange)) { 02190 // A forward class used in messaging is treated as a 'Class' 02191 Method = LookupFactoryMethodInGlobalPool(Sel, 02192 SourceRange(LBracLoc, RBracLoc)); 02193 if (Method && !getLangOpts().ObjCAutoRefCount) 02194 Diag(Method->getLocation(), diag::note_method_sent_forward_class) 02195 << Method->getDeclName(); 02196 } 02197 if (!Method) 02198 Method = Class->lookupClassMethod(Sel); 02199 02200 // If we have an implementation in scope, check "private" methods. 02201 if (!Method) 02202 Method = Class->lookupPrivateClassMethod(Sel); 02203 02204 if (Method && DiagnoseUseOfDecl(Method, SelLoc)) 02205 return ExprError(); 02206 } 02207 02208 // Check the argument types and determine the result type. 02209 QualType ReturnType; 02210 ExprValueKind VK = VK_RValue; 02211 02212 unsigned NumArgs = ArgsIn.size(); 02213 Expr **Args = ArgsIn.data(); 02214 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs), 02215 Sel, SelectorLocs, 02216 Method, true, 02217 SuperLoc.isValid(), LBracLoc, RBracLoc, 02218 SourceRange(), 02219 ReturnType, VK)) 02220 return ExprError(); 02221 02222 if (Method && !Method->getReturnType()->isVoidType() && 02223 RequireCompleteType(LBracLoc, Method->getReturnType(), 02224 diag::err_illegal_message_expr_incomplete_type)) 02225 return ExprError(); 02226 02227 // Warn about explicit call of +initialize on its own class. But not on 'super'. 02228 if (Method && Method->getMethodFamily() == OMF_initialize) { 02229 if (!SuperLoc.isValid()) { 02230 const ObjCInterfaceDecl *ID = 02231 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()); 02232 if (ID == Class) { 02233 Diag(Loc, diag::warn_direct_initialize_call); 02234 Diag(Method->getLocation(), diag::note_method_declared_at) 02235 << Method->getDeclName(); 02236 } 02237 } 02238 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { 02239 // [super initialize] is allowed only within an +initialize implementation 02240 if (CurMeth->getMethodFamily() != OMF_initialize) { 02241 Diag(Loc, diag::warn_direct_super_initialize_call); 02242 Diag(Method->getLocation(), diag::note_method_declared_at) 02243 << Method->getDeclName(); 02244 Diag(CurMeth->getLocation(), diag::note_method_declared_at) 02245 << CurMeth->getDeclName(); 02246 } 02247 } 02248 } 02249 02250 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs); 02251 02252 // Construct the appropriate ObjCMessageExpr. 02253 ObjCMessageExpr *Result; 02254 if (SuperLoc.isValid()) 02255 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 02256 SuperLoc, /*IsInstanceSuper=*/false, 02257 ReceiverType, Sel, SelectorLocs, 02258 Method, makeArrayRef(Args, NumArgs), 02259 RBracLoc, isImplicit); 02260 else { 02261 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 02262 ReceiverTypeInfo, Sel, SelectorLocs, 02263 Method, makeArrayRef(Args, NumArgs), 02264 RBracLoc, isImplicit); 02265 if (!isImplicit) 02266 checkCocoaAPI(*this, Result); 02267 } 02268 return MaybeBindToTemporary(Result); 02269 } 02270 02271 // ActOnClassMessage - used for both unary and keyword messages. 02272 // ArgExprs is optional - if it is present, the number of expressions 02273 // is obtained from Sel.getNumArgs(). 02274 ExprResult Sema::ActOnClassMessage(Scope *S, 02275 ParsedType Receiver, 02276 Selector Sel, 02277 SourceLocation LBracLoc, 02278 ArrayRef<SourceLocation> SelectorLocs, 02279 SourceLocation RBracLoc, 02280 MultiExprArg Args) { 02281 TypeSourceInfo *ReceiverTypeInfo; 02282 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo); 02283 if (ReceiverType.isNull()) 02284 return ExprError(); 02285 02286 02287 if (!ReceiverTypeInfo) 02288 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc); 02289 02290 return BuildClassMessage(ReceiverTypeInfo, ReceiverType, 02291 /*SuperLoc=*/SourceLocation(), Sel, 02292 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc, 02293 Args); 02294 } 02295 02296 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver, 02297 QualType ReceiverType, 02298 SourceLocation Loc, 02299 Selector Sel, 02300 ObjCMethodDecl *Method, 02301 MultiExprArg Args) { 02302 return BuildInstanceMessage(Receiver, ReceiverType, 02303 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(), 02304 Sel, Method, Loc, Loc, Loc, Args, 02305 /*isImplicit=*/true); 02306 } 02307 02308 /// \brief Build an Objective-C instance message expression. 02309 /// 02310 /// This routine takes care of both normal instance messages and 02311 /// instance messages to the superclass instance. 02312 /// 02313 /// \param Receiver The expression that computes the object that will 02314 /// receive this message. This may be empty, in which case we are 02315 /// sending to the superclass instance and \p SuperLoc must be a valid 02316 /// source location. 02317 /// 02318 /// \param ReceiverType The (static) type of the object receiving the 02319 /// message. When a \p Receiver expression is provided, this is the 02320 /// same type as that expression. For a superclass instance send, this 02321 /// is a pointer to the type of the superclass. 02322 /// 02323 /// \param SuperLoc The location of the "super" keyword in a 02324 /// superclass instance message. 02325 /// 02326 /// \param Sel The selector to which the message is being sent. 02327 /// 02328 /// \param Method The method that this instance message is invoking, if 02329 /// already known. 02330 /// 02331 /// \param LBracLoc The location of the opening square bracket ']'. 02332 /// 02333 /// \param RBracLoc The location of the closing square bracket ']'. 02334 /// 02335 /// \param ArgsIn The message arguments. 02336 ExprResult Sema::BuildInstanceMessage(Expr *Receiver, 02337 QualType ReceiverType, 02338 SourceLocation SuperLoc, 02339 Selector Sel, 02340 ObjCMethodDecl *Method, 02341 SourceLocation LBracLoc, 02342 ArrayRef<SourceLocation> SelectorLocs, 02343 SourceLocation RBracLoc, 02344 MultiExprArg ArgsIn, 02345 bool isImplicit) { 02346 // The location of the receiver. 02347 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart(); 02348 SourceRange RecRange = 02349 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange(); 02350 SourceLocation SelLoc; 02351 if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) 02352 SelLoc = SelectorLocs.front(); 02353 else 02354 SelLoc = Loc; 02355 02356 if (LBracLoc.isInvalid()) { 02357 Diag(Loc, diag::err_missing_open_square_message_send) 02358 << FixItHint::CreateInsertion(Loc, "["); 02359 LBracLoc = Loc; 02360 } 02361 02362 // If we have a receiver expression, perform appropriate promotions 02363 // and determine receiver type. 02364 if (Receiver) { 02365 if (Receiver->hasPlaceholderType()) { 02366 ExprResult Result; 02367 if (Receiver->getType() == Context.UnknownAnyTy) 02368 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType()); 02369 else 02370 Result = CheckPlaceholderExpr(Receiver); 02371 if (Result.isInvalid()) return ExprError(); 02372 Receiver = Result.get(); 02373 } 02374 02375 if (Receiver->isTypeDependent()) { 02376 // If the receiver is type-dependent, we can't type-check anything 02377 // at this point. Build a dependent expression. 02378 unsigned NumArgs = ArgsIn.size(); 02379 Expr **Args = ArgsIn.data(); 02380 assert(SuperLoc.isInvalid() && "Message to super with dependent type"); 02381 return ObjCMessageExpr::Create( 02382 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel, 02383 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), 02384 RBracLoc, isImplicit); 02385 } 02386 02387 // If necessary, apply function/array conversion to the receiver. 02388 // C99 6.7.5.3p[7,8]. 02389 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver); 02390 if (Result.isInvalid()) 02391 return ExprError(); 02392 Receiver = Result.get(); 02393 ReceiverType = Receiver->getType(); 02394 02395 // If the receiver is an ObjC pointer, a block pointer, or an 02396 // __attribute__((NSObject)) pointer, we don't need to do any 02397 // special conversion in order to look up a receiver. 02398 if (ReceiverType->isObjCRetainableType()) { 02399 // do nothing 02400 } else if (!getLangOpts().ObjCAutoRefCount && 02401 !Context.getObjCIdType().isNull() && 02402 (ReceiverType->isPointerType() || 02403 ReceiverType->isIntegerType())) { 02404 // Implicitly convert integers and pointers to 'id' but emit a warning. 02405 // But not in ARC. 02406 Diag(Loc, diag::warn_bad_receiver_type) 02407 << ReceiverType 02408 << Receiver->getSourceRange(); 02409 if (ReceiverType->isPointerType()) { 02410 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), 02411 CK_CPointerToObjCPointerCast).get(); 02412 } else { 02413 // TODO: specialized warning on null receivers? 02414 bool IsNull = Receiver->isNullPointerConstant(Context, 02415 Expr::NPC_ValueDependentIsNull); 02416 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer; 02417 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), 02418 Kind).get(); 02419 } 02420 ReceiverType = Receiver->getType(); 02421 } else if (getLangOpts().CPlusPlus) { 02422 // The receiver must be a complete type. 02423 if (RequireCompleteType(Loc, Receiver->getType(), 02424 diag::err_incomplete_receiver_type)) 02425 return ExprError(); 02426 02427 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver); 02428 if (result.isUsable()) { 02429 Receiver = result.get(); 02430 ReceiverType = Receiver->getType(); 02431 } 02432 } 02433 } 02434 02435 // There's a somewhat weird interaction here where we assume that we 02436 // won't actually have a method unless we also don't need to do some 02437 // of the more detailed type-checking on the receiver. 02438 02439 if (!Method) { 02440 // Handle messages to id. 02441 bool receiverIsId = ReceiverType->isObjCIdType(); 02442 if (receiverIsId || ReceiverType->isBlockPointerType() || 02443 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) { 02444 Method = LookupInstanceMethodInGlobalPool(Sel, 02445 SourceRange(LBracLoc, RBracLoc), 02446 receiverIsId); 02447 if (!Method) 02448 Method = LookupFactoryMethodInGlobalPool(Sel, 02449 SourceRange(LBracLoc,RBracLoc), 02450 receiverIsId); 02451 if (Method) { 02452 if (ObjCMethodDecl *BestMethod = 02453 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod())) 02454 Method = BestMethod; 02455 if (!AreMultipleMethodsInGlobalPool(Sel, Method->isInstanceMethod())) 02456 DiagnoseUseOfDecl(Method, SelLoc); 02457 } 02458 } else if (ReceiverType->isObjCClassType() || 02459 ReceiverType->isObjCQualifiedClassType()) { 02460 // Handle messages to Class. 02461 // We allow sending a message to a qualified Class ("Class<foo>"), which 02462 // is ok as long as one of the protocols implements the selector (if not, warn). 02463 if (const ObjCObjectPointerType *QClassTy 02464 = ReceiverType->getAsObjCQualifiedClassType()) { 02465 // Search protocols for class methods. 02466 Method = LookupMethodInQualifiedType(Sel, QClassTy, false); 02467 if (!Method) { 02468 Method = LookupMethodInQualifiedType(Sel, QClassTy, true); 02469 // warn if instance method found for a Class message. 02470 if (Method) { 02471 Diag(SelLoc, diag::warn_instance_method_on_class_found) 02472 << Method->getSelector() << Sel; 02473 Diag(Method->getLocation(), diag::note_method_declared_at) 02474 << Method->getDeclName(); 02475 } 02476 } 02477 } else { 02478 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { 02479 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) { 02480 // First check the public methods in the class interface. 02481 Method = ClassDecl->lookupClassMethod(Sel); 02482 02483 if (!Method) 02484 Method = ClassDecl->lookupPrivateClassMethod(Sel); 02485 } 02486 if (Method && DiagnoseUseOfDecl(Method, SelLoc)) 02487 return ExprError(); 02488 } 02489 if (!Method) { 02490 // If not messaging 'self', look for any factory method named 'Sel'. 02491 if (!Receiver || !isSelfExpr(Receiver)) { 02492 Method = LookupFactoryMethodInGlobalPool(Sel, 02493 SourceRange(LBracLoc, RBracLoc), 02494 true); 02495 if (!Method) { 02496 // If no class (factory) method was found, check if an _instance_ 02497 // method of the same name exists in the root class only. 02498 Method = LookupInstanceMethodInGlobalPool(Sel, 02499 SourceRange(LBracLoc, RBracLoc), 02500 true); 02501 if (Method) 02502 if (const ObjCInterfaceDecl *ID = 02503 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) { 02504 if (ID->getSuperClass()) 02505 Diag(SelLoc, diag::warn_root_inst_method_not_found) 02506 << Sel << SourceRange(LBracLoc, RBracLoc); 02507 } 02508 } 02509 if (Method) 02510 if (ObjCMethodDecl *BestMethod = 02511 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod())) 02512 Method = BestMethod; 02513 } 02514 } 02515 } 02516 } else { 02517 ObjCInterfaceDecl *ClassDecl = nullptr; 02518 02519 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as 02520 // long as one of the protocols implements the selector (if not, warn). 02521 // And as long as message is not deprecated/unavailable (warn if it is). 02522 if (const ObjCObjectPointerType *QIdTy 02523 = ReceiverType->getAsObjCQualifiedIdType()) { 02524 // Search protocols for instance methods. 02525 Method = LookupMethodInQualifiedType(Sel, QIdTy, true); 02526 if (!Method) 02527 Method = LookupMethodInQualifiedType(Sel, QIdTy, false); 02528 if (Method && DiagnoseUseOfDecl(Method, SelLoc)) 02529 return ExprError(); 02530 } else if (const ObjCObjectPointerType *OCIType 02531 = ReceiverType->getAsObjCInterfacePointerType()) { 02532 // We allow sending a message to a pointer to an interface (an object). 02533 ClassDecl = OCIType->getInterfaceDecl(); 02534 02535 // Try to complete the type. Under ARC, this is a hard error from which 02536 // we don't try to recover. 02537 const ObjCInterfaceDecl *forwardClass = nullptr; 02538 if (RequireCompleteType(Loc, OCIType->getPointeeType(), 02539 getLangOpts().ObjCAutoRefCount 02540 ? diag::err_arc_receiver_forward_instance 02541 : diag::warn_receiver_forward_instance, 02542 Receiver? Receiver->getSourceRange() 02543 : SourceRange(SuperLoc))) { 02544 if (getLangOpts().ObjCAutoRefCount) 02545 return ExprError(); 02546 02547 forwardClass = OCIType->getInterfaceDecl(); 02548 Diag(Receiver ? Receiver->getLocStart() 02549 : SuperLoc, diag::note_receiver_is_id); 02550 Method = nullptr; 02551 } else { 02552 Method = ClassDecl->lookupInstanceMethod(Sel); 02553 } 02554 02555 if (!Method) 02556 // Search protocol qualifiers. 02557 Method = LookupMethodInQualifiedType(Sel, OCIType, true); 02558 02559 if (!Method) { 02560 // If we have implementations in scope, check "private" methods. 02561 Method = ClassDecl->lookupPrivateMethod(Sel); 02562 02563 if (!Method && getLangOpts().ObjCAutoRefCount) { 02564 Diag(SelLoc, diag::err_arc_may_not_respond) 02565 << OCIType->getPointeeType() << Sel << RecRange 02566 << SourceRange(SelectorLocs.front(), SelectorLocs.back()); 02567 return ExprError(); 02568 } 02569 02570 if (!Method && (!Receiver || !isSelfExpr(Receiver))) { 02571 // If we still haven't found a method, look in the global pool. This 02572 // behavior isn't very desirable, however we need it for GCC 02573 // compatibility. FIXME: should we deviate?? 02574 if (OCIType->qual_empty()) { 02575 Method = LookupInstanceMethodInGlobalPool(Sel, 02576 SourceRange(LBracLoc, RBracLoc)); 02577 if (Method && !forwardClass) 02578 Diag(SelLoc, diag::warn_maynot_respond) 02579 << OCIType->getInterfaceDecl()->getIdentifier() 02580 << Sel << RecRange; 02581 } 02582 } 02583 } 02584 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass)) 02585 return ExprError(); 02586 } else { 02587 // Reject other random receiver types (e.g. structs). 02588 Diag(Loc, diag::err_bad_receiver_type) 02589 << ReceiverType << Receiver->getSourceRange(); 02590 return ExprError(); 02591 } 02592 } 02593 } 02594 02595 FunctionScopeInfo *DIFunctionScopeInfo = 02596 (Method && Method->getMethodFamily() == OMF_init) 02597 ? getEnclosingFunction() : nullptr; 02598 02599 if (DIFunctionScopeInfo && 02600 DIFunctionScopeInfo->ObjCIsDesignatedInit && 02601 (SuperLoc.isValid() || isSelfExpr(Receiver))) { 02602 bool isDesignatedInitChain = false; 02603 if (SuperLoc.isValid()) { 02604 if (const ObjCObjectPointerType * 02605 OCIType = ReceiverType->getAsObjCInterfacePointerType()) { 02606 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) { 02607 // Either we know this is a designated initializer or we 02608 // conservatively assume it because we don't know for sure. 02609 if (!ID->declaresOrInheritsDesignatedInitializers() || 02610 ID->isDesignatedInitializer(Sel)) { 02611 isDesignatedInitChain = true; 02612 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false; 02613 } 02614 } 02615 } 02616 } 02617 if (!isDesignatedInitChain) { 02618 const ObjCMethodDecl *InitMethod = nullptr; 02619 bool isDesignated = 02620 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod); 02621 assert(isDesignated && InitMethod); 02622 (void)isDesignated; 02623 Diag(SelLoc, SuperLoc.isValid() ? 02624 diag::warn_objc_designated_init_non_designated_init_call : 02625 diag::warn_objc_designated_init_non_super_designated_init_call); 02626 Diag(InitMethod->getLocation(), 02627 diag::note_objc_designated_init_marked_here); 02628 } 02629 } 02630 02631 if (DIFunctionScopeInfo && 02632 DIFunctionScopeInfo->ObjCIsSecondaryInit && 02633 (SuperLoc.isValid() || isSelfExpr(Receiver))) { 02634 if (SuperLoc.isValid()) { 02635 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call); 02636 } else { 02637 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false; 02638 } 02639 } 02640 02641 // Check the message arguments. 02642 unsigned NumArgs = ArgsIn.size(); 02643 Expr **Args = ArgsIn.data(); 02644 QualType ReturnType; 02645 ExprValueKind VK = VK_RValue; 02646 bool ClassMessage = (ReceiverType->isObjCClassType() || 02647 ReceiverType->isObjCQualifiedClassType()); 02648 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs), 02649 Sel, SelectorLocs, Method, 02650 ClassMessage, SuperLoc.isValid(), 02651 LBracLoc, RBracLoc, RecRange, ReturnType, VK)) 02652 return ExprError(); 02653 02654 if (Method && !Method->getReturnType()->isVoidType() && 02655 RequireCompleteType(LBracLoc, Method->getReturnType(), 02656 diag::err_illegal_message_expr_incomplete_type)) 02657 return ExprError(); 02658 02659 // In ARC, forbid the user from sending messages to 02660 // retain/release/autorelease/dealloc/retainCount explicitly. 02661 if (getLangOpts().ObjCAutoRefCount) { 02662 ObjCMethodFamily family = 02663 (Method ? Method->getMethodFamily() : Sel.getMethodFamily()); 02664 switch (family) { 02665 case OMF_init: 02666 if (Method) 02667 checkInitMethod(Method, ReceiverType); 02668 02669 case OMF_None: 02670 case OMF_alloc: 02671 case OMF_copy: 02672 case OMF_finalize: 02673 case OMF_mutableCopy: 02674 case OMF_new: 02675 case OMF_self: 02676 case OMF_initialize: 02677 break; 02678 02679 case OMF_dealloc: 02680 case OMF_retain: 02681 case OMF_release: 02682 case OMF_autorelease: 02683 case OMF_retainCount: 02684 Diag(SelLoc, diag::err_arc_illegal_explicit_message) 02685 << Sel << RecRange; 02686 break; 02687 02688 case OMF_performSelector: 02689 if (Method && NumArgs >= 1) { 02690 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) { 02691 Selector ArgSel = SelExp->getSelector(); 02692 ObjCMethodDecl *SelMethod = 02693 LookupInstanceMethodInGlobalPool(ArgSel, 02694 SelExp->getSourceRange()); 02695 if (!SelMethod) 02696 SelMethod = 02697 LookupFactoryMethodInGlobalPool(ArgSel, 02698 SelExp->getSourceRange()); 02699 if (SelMethod) { 02700 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily(); 02701 switch (SelFamily) { 02702 case OMF_alloc: 02703 case OMF_copy: 02704 case OMF_mutableCopy: 02705 case OMF_new: 02706 case OMF_self: 02707 case OMF_init: 02708 // Issue error, unless ns_returns_not_retained. 02709 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) { 02710 // selector names a +1 method 02711 Diag(SelLoc, 02712 diag::err_arc_perform_selector_retains); 02713 Diag(SelMethod->getLocation(), diag::note_method_declared_at) 02714 << SelMethod->getDeclName(); 02715 } 02716 break; 02717 default: 02718 // +0 call. OK. unless ns_returns_retained. 02719 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) { 02720 // selector names a +1 method 02721 Diag(SelLoc, 02722 diag::err_arc_perform_selector_retains); 02723 Diag(SelMethod->getLocation(), diag::note_method_declared_at) 02724 << SelMethod->getDeclName(); 02725 } 02726 break; 02727 } 02728 } 02729 } else { 02730 // error (may leak). 02731 Diag(SelLoc, diag::warn_arc_perform_selector_leaks); 02732 Diag(Args[0]->getExprLoc(), diag::note_used_here); 02733 } 02734 } 02735 break; 02736 } 02737 } 02738 02739 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs); 02740 02741 // Construct the appropriate ObjCMessageExpr instance. 02742 ObjCMessageExpr *Result; 02743 if (SuperLoc.isValid()) 02744 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 02745 SuperLoc, /*IsInstanceSuper=*/true, 02746 ReceiverType, Sel, SelectorLocs, Method, 02747 makeArrayRef(Args, NumArgs), RBracLoc, 02748 isImplicit); 02749 else { 02750 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 02751 Receiver, Sel, SelectorLocs, Method, 02752 makeArrayRef(Args, NumArgs), RBracLoc, 02753 isImplicit); 02754 if (!isImplicit) 02755 checkCocoaAPI(*this, Result); 02756 } 02757 02758 if (getLangOpts().ObjCAutoRefCount) { 02759 // Do not warn about IBOutlet weak property receivers being set to null 02760 // as this cannot asynchronously happen. 02761 bool WarnWeakReceiver = true; 02762 if (isImplicit && Method) 02763 if (const ObjCPropertyDecl *PropertyDecl = Method->findPropertyDecl()) 02764 WarnWeakReceiver = !PropertyDecl->hasAttr<IBOutletAttr>(); 02765 if (WarnWeakReceiver) 02766 DiagnoseARCUseOfWeakReceiver(*this, Receiver); 02767 02768 // In ARC, annotate delegate init calls. 02769 if (Result->getMethodFamily() == OMF_init && 02770 (SuperLoc.isValid() || isSelfExpr(Receiver))) { 02771 // Only consider init calls *directly* in init implementations, 02772 // not within blocks. 02773 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext); 02774 if (method && method->getMethodFamily() == OMF_init) { 02775 // The implicit assignment to self means we also don't want to 02776 // consume the result. 02777 Result->setDelegateInitCall(true); 02778 return Result; 02779 } 02780 } 02781 02782 // In ARC, check for message sends which are likely to introduce 02783 // retain cycles. 02784 checkRetainCycles(Result); 02785 02786 if (!isImplicit && Method) { 02787 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) { 02788 bool IsWeak = 02789 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak; 02790 if (!IsWeak && Sel.isUnarySelector()) 02791 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak; 02792 if (IsWeak && 02793 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc)) 02794 getCurFunction()->recordUseOfWeak(Result, Prop); 02795 } 02796 } 02797 } 02798 02799 return MaybeBindToTemporary(Result); 02800 } 02801 02802 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) { 02803 if (ObjCSelectorExpr *OSE = 02804 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) { 02805 Selector Sel = OSE->getSelector(); 02806 SourceLocation Loc = OSE->getAtLoc(); 02807 llvm::DenseMap<Selector, SourceLocation>::iterator Pos 02808 = S.ReferencedSelectors.find(Sel); 02809 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc) 02810 S.ReferencedSelectors.erase(Pos); 02811 } 02812 } 02813 02814 // ActOnInstanceMessage - used for both unary and keyword messages. 02815 // ArgExprs is optional - if it is present, the number of expressions 02816 // is obtained from Sel.getNumArgs(). 02817 ExprResult Sema::ActOnInstanceMessage(Scope *S, 02818 Expr *Receiver, 02819 Selector Sel, 02820 SourceLocation LBracLoc, 02821 ArrayRef<SourceLocation> SelectorLocs, 02822 SourceLocation RBracLoc, 02823 MultiExprArg Args) { 02824 if (!Receiver) 02825 return ExprError(); 02826 02827 // A ParenListExpr can show up while doing error recovery with invalid code. 02828 if (isa<ParenListExpr>(Receiver)) { 02829 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver); 02830 if (Result.isInvalid()) return ExprError(); 02831 Receiver = Result.get(); 02832 } 02833 02834 if (RespondsToSelectorSel.isNull()) { 02835 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector"); 02836 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId); 02837 } 02838 if (Sel == RespondsToSelectorSel) 02839 RemoveSelectorFromWarningCache(*this, Args[0]); 02840 02841 return BuildInstanceMessage(Receiver, Receiver->getType(), 02842 /*SuperLoc=*/SourceLocation(), Sel, 02843 /*Method=*/nullptr, LBracLoc, SelectorLocs, 02844 RBracLoc, Args); 02845 } 02846 02847 enum ARCConversionTypeClass { 02848 /// int, void, struct A 02849 ACTC_none, 02850 02851 /// id, void (^)() 02852 ACTC_retainable, 02853 02854 /// id*, id***, void (^*)(), 02855 ACTC_indirectRetainable, 02856 02857 /// void* might be a normal C type, or it might a CF type. 02858 ACTC_voidPtr, 02859 02860 /// struct A* 02861 ACTC_coreFoundation 02862 }; 02863 static bool isAnyRetainable(ARCConversionTypeClass ACTC) { 02864 return (ACTC == ACTC_retainable || 02865 ACTC == ACTC_coreFoundation || 02866 ACTC == ACTC_voidPtr); 02867 } 02868 static bool isAnyCLike(ARCConversionTypeClass ACTC) { 02869 return ACTC == ACTC_none || 02870 ACTC == ACTC_voidPtr || 02871 ACTC == ACTC_coreFoundation; 02872 } 02873 02874 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) { 02875 bool isIndirect = false; 02876 02877 // Ignore an outermost reference type. 02878 if (const ReferenceType *ref = type->getAs<ReferenceType>()) { 02879 type = ref->getPointeeType(); 02880 isIndirect = true; 02881 } 02882 02883 // Drill through pointers and arrays recursively. 02884 while (true) { 02885 if (const PointerType *ptr = type->getAs<PointerType>()) { 02886 type = ptr->getPointeeType(); 02887 02888 // The first level of pointer may be the innermost pointer on a CF type. 02889 if (!isIndirect) { 02890 if (type->isVoidType()) return ACTC_voidPtr; 02891 if (type->isRecordType()) return ACTC_coreFoundation; 02892 } 02893 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) { 02894 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0); 02895 } else { 02896 break; 02897 } 02898 isIndirect = true; 02899 } 02900 02901 if (isIndirect) { 02902 if (type->isObjCARCBridgableType()) 02903 return ACTC_indirectRetainable; 02904 return ACTC_none; 02905 } 02906 02907 if (type->isObjCARCBridgableType()) 02908 return ACTC_retainable; 02909 02910 return ACTC_none; 02911 } 02912 02913 namespace { 02914 /// A result from the cast checker. 02915 enum ACCResult { 02916 /// Cannot be casted. 02917 ACC_invalid, 02918 02919 /// Can be safely retained or not retained. 02920 ACC_bottom, 02921 02922 /// Can be casted at +0. 02923 ACC_plusZero, 02924 02925 /// Can be casted at +1. 02926 ACC_plusOne 02927 }; 02928 ACCResult merge(ACCResult left, ACCResult right) { 02929 if (left == right) return left; 02930 if (left == ACC_bottom) return right; 02931 if (right == ACC_bottom) return left; 02932 return ACC_invalid; 02933 } 02934 02935 /// A checker which white-lists certain expressions whose conversion 02936 /// to or from retainable type would otherwise be forbidden in ARC. 02937 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> { 02938 typedef StmtVisitor<ARCCastChecker, ACCResult> super; 02939 02940 ASTContext &Context; 02941 ARCConversionTypeClass SourceClass; 02942 ARCConversionTypeClass TargetClass; 02943 bool Diagnose; 02944 02945 static bool isCFType(QualType type) { 02946 // Someday this can use ns_bridged. For now, it has to do this. 02947 return type->isCARCBridgableType(); 02948 } 02949 02950 public: 02951 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source, 02952 ARCConversionTypeClass target, bool diagnose) 02953 : Context(Context), SourceClass(source), TargetClass(target), 02954 Diagnose(diagnose) {} 02955 02956 using super::Visit; 02957 ACCResult Visit(Expr *e) { 02958 return super::Visit(e->IgnoreParens()); 02959 } 02960 02961 ACCResult VisitStmt(Stmt *s) { 02962 return ACC_invalid; 02963 } 02964 02965 /// Null pointer constants can be casted however you please. 02966 ACCResult VisitExpr(Expr *e) { 02967 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 02968 return ACC_bottom; 02969 return ACC_invalid; 02970 } 02971 02972 /// Objective-C string literals can be safely casted. 02973 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) { 02974 // If we're casting to any retainable type, go ahead. Global 02975 // strings are immune to retains, so this is bottom. 02976 if (isAnyRetainable(TargetClass)) return ACC_bottom; 02977 02978 return ACC_invalid; 02979 } 02980 02981 /// Look through certain implicit and explicit casts. 02982 ACCResult VisitCastExpr(CastExpr *e) { 02983 switch (e->getCastKind()) { 02984 case CK_NullToPointer: 02985 return ACC_bottom; 02986 02987 case CK_NoOp: 02988 case CK_LValueToRValue: 02989 case CK_BitCast: 02990 case CK_CPointerToObjCPointerCast: 02991 case CK_BlockPointerToObjCPointerCast: 02992 case CK_AnyPointerToBlockPointerCast: 02993 return Visit(e->getSubExpr()); 02994 02995 default: 02996 return ACC_invalid; 02997 } 02998 } 02999 03000 /// Look through unary extension. 03001 ACCResult VisitUnaryExtension(UnaryOperator *e) { 03002 return Visit(e->getSubExpr()); 03003 } 03004 03005 /// Ignore the LHS of a comma operator. 03006 ACCResult VisitBinComma(BinaryOperator *e) { 03007 return Visit(e->getRHS()); 03008 } 03009 03010 /// Conditional operators are okay if both sides are okay. 03011 ACCResult VisitConditionalOperator(ConditionalOperator *e) { 03012 ACCResult left = Visit(e->getTrueExpr()); 03013 if (left == ACC_invalid) return ACC_invalid; 03014 return merge(left, Visit(e->getFalseExpr())); 03015 } 03016 03017 /// Look through pseudo-objects. 03018 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) { 03019 // If we're getting here, we should always have a result. 03020 return Visit(e->getResultExpr()); 03021 } 03022 03023 /// Statement expressions are okay if their result expression is okay. 03024 ACCResult VisitStmtExpr(StmtExpr *e) { 03025 return Visit(e->getSubStmt()->body_back()); 03026 } 03027 03028 /// Some declaration references are okay. 03029 ACCResult VisitDeclRefExpr(DeclRefExpr *e) { 03030 // References to global constants from system headers are okay. 03031 // These are things like 'kCFStringTransformToLatin'. They are 03032 // can also be assumed to be immune to retains. 03033 VarDecl *var = dyn_cast<VarDecl>(e->getDecl()); 03034 if (isAnyRetainable(TargetClass) && 03035 isAnyRetainable(SourceClass) && 03036 var && 03037 var->getStorageClass() == SC_Extern && 03038 var->getType().isConstQualified() && 03039 Context.getSourceManager().isInSystemHeader(var->getLocation())) { 03040 return ACC_bottom; 03041 } 03042 03043 // Nothing else. 03044 return ACC_invalid; 03045 } 03046 03047 /// Some calls are okay. 03048 ACCResult VisitCallExpr(CallExpr *e) { 03049 if (FunctionDecl *fn = e->getDirectCallee()) 03050 if (ACCResult result = checkCallToFunction(fn)) 03051 return result; 03052 03053 return super::VisitCallExpr(e); 03054 } 03055 03056 ACCResult checkCallToFunction(FunctionDecl *fn) { 03057 // Require a CF*Ref return type. 03058 if (!isCFType(fn->getReturnType())) 03059 return ACC_invalid; 03060 03061 if (!isAnyRetainable(TargetClass)) 03062 return ACC_invalid; 03063 03064 // Honor an explicit 'not retained' attribute. 03065 if (fn->hasAttr<CFReturnsNotRetainedAttr>()) 03066 return ACC_plusZero; 03067 03068 // Honor an explicit 'retained' attribute, except that for 03069 // now we're not going to permit implicit handling of +1 results, 03070 // because it's a bit frightening. 03071 if (fn->hasAttr<CFReturnsRetainedAttr>()) 03072 return Diagnose ? ACC_plusOne 03073 : ACC_invalid; // ACC_plusOne if we start accepting this 03074 03075 // Recognize this specific builtin function, which is used by CFSTR. 03076 unsigned builtinID = fn->getBuiltinID(); 03077 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString) 03078 return ACC_bottom; 03079 03080 // Otherwise, don't do anything implicit with an unaudited function. 03081 if (!fn->hasAttr<CFAuditedTransferAttr>()) 03082 return ACC_invalid; 03083 03084 // Otherwise, it's +0 unless it follows the create convention. 03085 if (ento::coreFoundation::followsCreateRule(fn)) 03086 return Diagnose ? ACC_plusOne 03087 : ACC_invalid; // ACC_plusOne if we start accepting this 03088 03089 return ACC_plusZero; 03090 } 03091 03092 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) { 03093 return checkCallToMethod(e->getMethodDecl()); 03094 } 03095 03096 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) { 03097 ObjCMethodDecl *method; 03098 if (e->isExplicitProperty()) 03099 method = e->getExplicitProperty()->getGetterMethodDecl(); 03100 else 03101 method = e->getImplicitPropertyGetter(); 03102 return checkCallToMethod(method); 03103 } 03104 03105 ACCResult checkCallToMethod(ObjCMethodDecl *method) { 03106 if (!method) return ACC_invalid; 03107 03108 // Check for message sends to functions returning CF types. We 03109 // just obey the Cocoa conventions with these, even though the 03110 // return type is CF. 03111 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType())) 03112 return ACC_invalid; 03113 03114 // If the method is explicitly marked not-retained, it's +0. 03115 if (method->hasAttr<CFReturnsNotRetainedAttr>()) 03116 return ACC_plusZero; 03117 03118 // If the method is explicitly marked as returning retained, or its 03119 // selector follows a +1 Cocoa convention, treat it as +1. 03120 if (method->hasAttr<CFReturnsRetainedAttr>()) 03121 return ACC_plusOne; 03122 03123 switch (method->getSelector().getMethodFamily()) { 03124 case OMF_alloc: 03125 case OMF_copy: 03126 case OMF_mutableCopy: 03127 case OMF_new: 03128 return ACC_plusOne; 03129 03130 default: 03131 // Otherwise, treat it as +0. 03132 return ACC_plusZero; 03133 } 03134 } 03135 }; 03136 } 03137 03138 bool Sema::isKnownName(StringRef name) { 03139 if (name.empty()) 03140 return false; 03141 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(), 03142 Sema::LookupOrdinaryName); 03143 return LookupName(R, TUScope, false); 03144 } 03145 03146 static void addFixitForObjCARCConversion(Sema &S, 03147 DiagnosticBuilder &DiagB, 03148 Sema::CheckedConversionKind CCK, 03149 SourceLocation afterLParen, 03150 QualType castType, 03151 Expr *castExpr, 03152 Expr *realCast, 03153 const char *bridgeKeyword, 03154 const char *CFBridgeName) { 03155 // We handle C-style and implicit casts here. 03156 switch (CCK) { 03157 case Sema::CCK_ImplicitConversion: 03158 case Sema::CCK_CStyleCast: 03159 case Sema::CCK_OtherCast: 03160 break; 03161 case Sema::CCK_FunctionalCast: 03162 return; 03163 } 03164 03165 if (CFBridgeName) { 03166 if (CCK == Sema::CCK_OtherCast) { 03167 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) { 03168 SourceRange range(NCE->getOperatorLoc(), 03169 NCE->getAngleBrackets().getEnd()); 03170 SmallString<32> BridgeCall; 03171 03172 SourceManager &SM = S.getSourceManager(); 03173 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1)); 03174 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) 03175 BridgeCall += ' '; 03176 03177 BridgeCall += CFBridgeName; 03178 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall)); 03179 } 03180 return; 03181 } 03182 Expr *castedE = castExpr; 03183 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE)) 03184 castedE = CCE->getSubExpr(); 03185 castedE = castedE->IgnoreImpCasts(); 03186 SourceRange range = castedE->getSourceRange(); 03187 03188 SmallString<32> BridgeCall; 03189 03190 SourceManager &SM = S.getSourceManager(); 03191 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1)); 03192 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) 03193 BridgeCall += ' '; 03194 03195 BridgeCall += CFBridgeName; 03196 03197 if (isa<ParenExpr>(castedE)) { 03198 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 03199 BridgeCall)); 03200 } else { 03201 BridgeCall += '('; 03202 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 03203 BridgeCall)); 03204 DiagB.AddFixItHint(FixItHint::CreateInsertion( 03205 S.PP.getLocForEndOfToken(range.getEnd()), 03206 ")")); 03207 } 03208 return; 03209 } 03210 03211 if (CCK == Sema::CCK_CStyleCast) { 03212 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword)); 03213 } else if (CCK == Sema::CCK_OtherCast) { 03214 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) { 03215 std::string castCode = "("; 03216 castCode += bridgeKeyword; 03217 castCode += castType.getAsString(); 03218 castCode += ")"; 03219 SourceRange Range(NCE->getOperatorLoc(), 03220 NCE->getAngleBrackets().getEnd()); 03221 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode)); 03222 } 03223 } else { 03224 std::string castCode = "("; 03225 castCode += bridgeKeyword; 03226 castCode += castType.getAsString(); 03227 castCode += ")"; 03228 Expr *castedE = castExpr->IgnoreImpCasts(); 03229 SourceRange range = castedE->getSourceRange(); 03230 if (isa<ParenExpr>(castedE)) { 03231 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 03232 castCode)); 03233 } else { 03234 castCode += "("; 03235 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 03236 castCode)); 03237 DiagB.AddFixItHint(FixItHint::CreateInsertion( 03238 S.PP.getLocForEndOfToken(range.getEnd()), 03239 ")")); 03240 } 03241 } 03242 } 03243 03244 template <typename T> 03245 static inline T *getObjCBridgeAttr(const TypedefType *TD) { 03246 TypedefNameDecl *TDNDecl = TD->getDecl(); 03247 QualType QT = TDNDecl->getUnderlyingType(); 03248 if (QT->isPointerType()) { 03249 QT = QT->getPointeeType(); 03250 if (const RecordType *RT = QT->getAs<RecordType>()) 03251 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl()) 03252 return RD->getAttr<T>(); 03253 } 03254 return nullptr; 03255 } 03256 03257 static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T, 03258 TypedefNameDecl *&TDNDecl) { 03259 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) { 03260 TDNDecl = TD->getDecl(); 03261 if (ObjCBridgeRelatedAttr *ObjCBAttr = 03262 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD)) 03263 return ObjCBAttr; 03264 T = TDNDecl->getUnderlyingType(); 03265 } 03266 return nullptr; 03267 } 03268 03269 static void 03270 diagnoseObjCARCConversion(Sema &S, SourceRange castRange, 03271 QualType castType, ARCConversionTypeClass castACTC, 03272 Expr *castExpr, Expr *realCast, 03273 ARCConversionTypeClass exprACTC, 03274 Sema::CheckedConversionKind CCK) { 03275 SourceLocation loc = 03276 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc()); 03277 03278 if (S.makeUnavailableInSystemHeader(loc, 03279 "converts between Objective-C and C pointers in -fobjc-arc")) 03280 return; 03281 03282 QualType castExprType = castExpr->getType(); 03283 TypedefNameDecl *TDNDecl = nullptr; 03284 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable && 03285 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) || 03286 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable && 03287 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl))) 03288 return; 03289 03290 unsigned srcKind = 0; 03291 switch (exprACTC) { 03292 case ACTC_none: 03293 case ACTC_coreFoundation: 03294 case ACTC_voidPtr: 03295 srcKind = (castExprType->isPointerType() ? 1 : 0); 03296 break; 03297 case ACTC_retainable: 03298 srcKind = (castExprType->isBlockPointerType() ? 2 : 3); 03299 break; 03300 case ACTC_indirectRetainable: 03301 srcKind = 4; 03302 break; 03303 } 03304 03305 // Check whether this could be fixed with a bridge cast. 03306 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin()); 03307 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc; 03308 03309 // Bridge from an ARC type to a CF type. 03310 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) { 03311 03312 S.Diag(loc, diag::err_arc_cast_requires_bridge) 03313 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit 03314 << 2 // of C pointer type 03315 << castExprType 03316 << unsigned(castType->isBlockPointerType()) // to ObjC|block type 03317 << castType 03318 << castRange 03319 << castExpr->getSourceRange(); 03320 bool br = S.isKnownName("CFBridgingRelease"); 03321 ACCResult CreateRule = 03322 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); 03323 assert(CreateRule != ACC_bottom && "This cast should already be accepted."); 03324 if (CreateRule != ACC_plusOne) 03325 { 03326 DiagnosticBuilder DiagB = 03327 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge) 03328 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge); 03329 03330 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 03331 castType, castExpr, realCast, "__bridge ", 03332 nullptr); 03333 } 03334 if (CreateRule != ACC_plusZero) 03335 { 03336 DiagnosticBuilder DiagB = 03337 (CCK == Sema::CCK_OtherCast && !br) ? 03338 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType : 03339 S.Diag(br ? castExpr->getExprLoc() : noteLoc, 03340 diag::note_arc_bridge_transfer) 03341 << castExprType << br; 03342 03343 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 03344 castType, castExpr, realCast, "__bridge_transfer ", 03345 br ? "CFBridgingRelease" : nullptr); 03346 } 03347 03348 return; 03349 } 03350 03351 // Bridge from a CF type to an ARC type. 03352 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) { 03353 bool br = S.isKnownName("CFBridgingRetain"); 03354 S.Diag(loc, diag::err_arc_cast_requires_bridge) 03355 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit 03356 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type 03357 << castExprType 03358 << 2 // to C pointer type 03359 << castType 03360 << castRange 03361 << castExpr->getSourceRange(); 03362 ACCResult CreateRule = 03363 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); 03364 assert(CreateRule != ACC_bottom && "This cast should already be accepted."); 03365 if (CreateRule != ACC_plusOne) 03366 { 03367 DiagnosticBuilder DiagB = 03368 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge) 03369 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge); 03370 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 03371 castType, castExpr, realCast, "__bridge ", 03372 nullptr); 03373 } 03374 if (CreateRule != ACC_plusZero) 03375 { 03376 DiagnosticBuilder DiagB = 03377 (CCK == Sema::CCK_OtherCast && !br) ? 03378 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType : 03379 S.Diag(br ? castExpr->getExprLoc() : noteLoc, 03380 diag::note_arc_bridge_retained) 03381 << castType << br; 03382 03383 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 03384 castType, castExpr, realCast, "__bridge_retained ", 03385 br ? "CFBridgingRetain" : nullptr); 03386 } 03387 03388 return; 03389 } 03390 03391 S.Diag(loc, diag::err_arc_mismatched_cast) 03392 << (CCK != Sema::CCK_ImplicitConversion) 03393 << srcKind << castExprType << castType 03394 << castRange << castExpr->getSourceRange(); 03395 } 03396 03397 template <typename TB> 03398 static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr, 03399 bool &HadTheAttribute, bool warn) { 03400 QualType T = castExpr->getType(); 03401 HadTheAttribute = false; 03402 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) { 03403 TypedefNameDecl *TDNDecl = TD->getDecl(); 03404 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) { 03405 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) { 03406 HadTheAttribute = true; 03407 NamedDecl *Target = nullptr; 03408 // Check for an existing type with this name. 03409 LookupResult R(S, DeclarationName(Parm), SourceLocation(), 03410 Sema::LookupOrdinaryName); 03411 if (S.LookupName(R, S.TUScope)) { 03412 Target = R.getFoundDecl(); 03413 if (Target && isa<ObjCInterfaceDecl>(Target)) { 03414 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target); 03415 if (const ObjCObjectPointerType *InterfacePointerType = 03416 castType->getAsObjCInterfacePointerType()) { 03417 ObjCInterfaceDecl *CastClass 03418 = InterfacePointerType->getObjectType()->getInterface(); 03419 if ((CastClass == ExprClass) || 03420 (CastClass && ExprClass->isSuperClassOf(CastClass))) 03421 return true; 03422 if (warn) 03423 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge) 03424 << T << Target->getName() << castType->getPointeeType(); 03425 return false; 03426 } else if (castType->isObjCIdType() || 03427 (S.Context.ObjCObjectAdoptsQTypeProtocols( 03428 castType, ExprClass))) 03429 // ok to cast to 'id'. 03430 // casting to id<p-list> is ok if bridge type adopts all of 03431 // p-list protocols. 03432 return true; 03433 else { 03434 if (warn) { 03435 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge) 03436 << T << Target->getName() << castType; 03437 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); 03438 S.Diag(Target->getLocStart(), diag::note_declared_at); 03439 } 03440 return false; 03441 } 03442 } 03443 } 03444 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface) 03445 << castExpr->getType() << Parm; 03446 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); 03447 if (Target) 03448 S.Diag(Target->getLocStart(), diag::note_declared_at); 03449 return true; 03450 } 03451 return false; 03452 } 03453 T = TDNDecl->getUnderlyingType(); 03454 } 03455 return true; 03456 } 03457 03458 template <typename TB> 03459 static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr, 03460 bool &HadTheAttribute, bool warn) { 03461 QualType T = castType; 03462 HadTheAttribute = false; 03463 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) { 03464 TypedefNameDecl *TDNDecl = TD->getDecl(); 03465 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) { 03466 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) { 03467 HadTheAttribute = true; 03468 NamedDecl *Target = nullptr; 03469 // Check for an existing type with this name. 03470 LookupResult R(S, DeclarationName(Parm), SourceLocation(), 03471 Sema::LookupOrdinaryName); 03472 if (S.LookupName(R, S.TUScope)) { 03473 Target = R.getFoundDecl(); 03474 if (Target && isa<ObjCInterfaceDecl>(Target)) { 03475 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target); 03476 if (const ObjCObjectPointerType *InterfacePointerType = 03477 castExpr->getType()->getAsObjCInterfacePointerType()) { 03478 ObjCInterfaceDecl *ExprClass 03479 = InterfacePointerType->getObjectType()->getInterface(); 03480 if ((CastClass == ExprClass) || 03481 (ExprClass && CastClass->isSuperClassOf(ExprClass))) 03482 return true; 03483 if (warn) { 03484 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf) 03485 << castExpr->getType()->getPointeeType() << T; 03486 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); 03487 } 03488 return false; 03489 } else if (castExpr->getType()->isObjCIdType() || 03490 (S.Context.QIdProtocolsAdoptObjCObjectProtocols( 03491 castExpr->getType(), CastClass))) 03492 // ok to cast an 'id' expression to a CFtype. 03493 // ok to cast an 'id<plist>' expression to CFtype provided plist 03494 // adopts all of CFtype's ObjetiveC's class plist. 03495 return true; 03496 else { 03497 if (warn) { 03498 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf) 03499 << castExpr->getType() << castType; 03500 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); 03501 S.Diag(Target->getLocStart(), diag::note_declared_at); 03502 } 03503 return false; 03504 } 03505 } 03506 } 03507 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject) 03508 << castExpr->getType() << castType; 03509 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); 03510 if (Target) 03511 S.Diag(Target->getLocStart(), diag::note_declared_at); 03512 return true; 03513 } 03514 return false; 03515 } 03516 T = TDNDecl->getUnderlyingType(); 03517 } 03518 return true; 03519 } 03520 03521 void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) { 03522 if (!getLangOpts().ObjC1) 03523 return; 03524 // warn in presence of __bridge casting to or from a toll free bridge cast. 03525 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType()); 03526 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType); 03527 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) { 03528 bool HasObjCBridgeAttr; 03529 bool ObjCBridgeAttrWillNotWarn = 03530 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, 03531 false); 03532 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr) 03533 return; 03534 bool HasObjCBridgeMutableAttr; 03535 bool ObjCBridgeMutableAttrWillNotWarn = 03536 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, 03537 HasObjCBridgeMutableAttr, false); 03538 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr) 03539 return; 03540 03541 if (HasObjCBridgeAttr) 03542 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, 03543 true); 03544 else if (HasObjCBridgeMutableAttr) 03545 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, 03546 HasObjCBridgeMutableAttr, true); 03547 } 03548 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) { 03549 bool HasObjCBridgeAttr; 03550 bool ObjCBridgeAttrWillNotWarn = 03551 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, 03552 false); 03553 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr) 03554 return; 03555 bool HasObjCBridgeMutableAttr; 03556 bool ObjCBridgeMutableAttrWillNotWarn = 03557 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, 03558 HasObjCBridgeMutableAttr, false); 03559 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr) 03560 return; 03561 03562 if (HasObjCBridgeAttr) 03563 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, 03564 true); 03565 else if (HasObjCBridgeMutableAttr) 03566 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, 03567 HasObjCBridgeMutableAttr, true); 03568 } 03569 } 03570 03571 void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) { 03572 QualType SrcType = castExpr->getType(); 03573 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) { 03574 if (PRE->isExplicitProperty()) { 03575 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty()) 03576 SrcType = PDecl->getType(); 03577 } 03578 else if (PRE->isImplicitProperty()) { 03579 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter()) 03580 SrcType = Getter->getReturnType(); 03581 03582 } 03583 } 03584 03585 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType); 03586 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType); 03587 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation) 03588 return; 03589 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(), 03590 castType, SrcType, castExpr); 03591 return; 03592 } 03593 03594 bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, 03595 CastKind &Kind) { 03596 if (!getLangOpts().ObjC1) 03597 return false; 03598 ARCConversionTypeClass exprACTC = 03599 classifyTypeForARCConversion(castExpr->getType()); 03600 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType); 03601 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) || 03602 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) { 03603 CheckTollFreeBridgeCast(castType, castExpr); 03604 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast 03605 : CK_CPointerToObjCPointerCast; 03606 return true; 03607 } 03608 return false; 03609 } 03610 03611 bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc, 03612 QualType DestType, QualType SrcType, 03613 ObjCInterfaceDecl *&RelatedClass, 03614 ObjCMethodDecl *&ClassMethod, 03615 ObjCMethodDecl *&InstanceMethod, 03616 TypedefNameDecl *&TDNDecl, 03617 bool CfToNs) { 03618 QualType T = CfToNs ? SrcType : DestType; 03619 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl); 03620 if (!ObjCBAttr) 03621 return false; 03622 03623 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass(); 03624 IdentifierInfo *CMId = ObjCBAttr->getClassMethod(); 03625 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod(); 03626 if (!RCId) 03627 return false; 03628 NamedDecl *Target = nullptr; 03629 // Check for an existing type with this name. 03630 LookupResult R(*this, DeclarationName(RCId), SourceLocation(), 03631 Sema::LookupOrdinaryName); 03632 if (!LookupName(R, TUScope)) { 03633 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId 03634 << SrcType << DestType; 03635 Diag(TDNDecl->getLocStart(), diag::note_declared_at); 03636 return false; 03637 } 03638 Target = R.getFoundDecl(); 03639 if (Target && isa<ObjCInterfaceDecl>(Target)) 03640 RelatedClass = cast<ObjCInterfaceDecl>(Target); 03641 else { 03642 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId 03643 << SrcType << DestType; 03644 Diag(TDNDecl->getLocStart(), diag::note_declared_at); 03645 if (Target) 03646 Diag(Target->getLocStart(), diag::note_declared_at); 03647 return false; 03648 } 03649 03650 // Check for an existing class method with the given selector name. 03651 if (CfToNs && CMId) { 03652 Selector Sel = Context.Selectors.getUnarySelector(CMId); 03653 ClassMethod = RelatedClass->lookupMethod(Sel, false); 03654 if (!ClassMethod) { 03655 Diag(Loc, diag::err_objc_bridged_related_known_method) 03656 << SrcType << DestType << Sel << false; 03657 Diag(TDNDecl->getLocStart(), diag::note_declared_at); 03658 return false; 03659 } 03660 } 03661 03662 // Check for an existing instance method with the given selector name. 03663 if (!CfToNs && IMId) { 03664 Selector Sel = Context.Selectors.getNullarySelector(IMId); 03665 InstanceMethod = RelatedClass->lookupMethod(Sel, true); 03666 if (!InstanceMethod) { 03667 Diag(Loc, diag::err_objc_bridged_related_known_method) 03668 << SrcType << DestType << Sel << true; 03669 Diag(TDNDecl->getLocStart(), diag::note_declared_at); 03670 return false; 03671 } 03672 } 03673 return true; 03674 } 03675 03676 bool 03677 Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc, 03678 QualType DestType, QualType SrcType, 03679 Expr *&SrcExpr) { 03680 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType); 03681 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType); 03682 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable); 03683 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation); 03684 if (!CfToNs && !NsToCf) 03685 return false; 03686 03687 ObjCInterfaceDecl *RelatedClass; 03688 ObjCMethodDecl *ClassMethod = nullptr; 03689 ObjCMethodDecl *InstanceMethod = nullptr; 03690 TypedefNameDecl *TDNDecl = nullptr; 03691 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass, 03692 ClassMethod, InstanceMethod, TDNDecl, CfToNs)) 03693 return false; 03694 03695 if (CfToNs) { 03696 // Implicit conversion from CF to ObjC object is needed. 03697 if (ClassMethod) { 03698 std::string ExpressionString = "["; 03699 ExpressionString += RelatedClass->getNameAsString(); 03700 ExpressionString += " "; 03701 ExpressionString += ClassMethod->getSelector().getAsString(); 03702 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd()); 03703 // Provide a fixit: [RelatedClass ClassMethod SrcExpr] 03704 Diag(Loc, diag::err_objc_bridged_related_known_method) 03705 << SrcType << DestType << ClassMethod->getSelector() << false 03706 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString) 03707 << FixItHint::CreateInsertion(SrcExprEndLoc, "]"); 03708 Diag(RelatedClass->getLocStart(), diag::note_declared_at); 03709 Diag(TDNDecl->getLocStart(), diag::note_declared_at); 03710 03711 QualType receiverType = 03712 Context.getObjCInterfaceType(RelatedClass); 03713 // Argument. 03714 Expr *args[] = { SrcExpr }; 03715 ExprResult msg = BuildClassMessageImplicit(receiverType, false, 03716 ClassMethod->getLocation(), 03717 ClassMethod->getSelector(), ClassMethod, 03718 MultiExprArg(args, 1)); 03719 SrcExpr = msg.get(); 03720 return true; 03721 } 03722 } 03723 else { 03724 // Implicit conversion from ObjC type to CF object is needed. 03725 if (InstanceMethod) { 03726 std::string ExpressionString; 03727 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd()); 03728 if (InstanceMethod->isPropertyAccessor()) 03729 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) { 03730 // fixit: ObjectExpr.propertyname when it is aproperty accessor. 03731 ExpressionString = "."; 03732 ExpressionString += PDecl->getNameAsString(); 03733 Diag(Loc, diag::err_objc_bridged_related_known_method) 03734 << SrcType << DestType << InstanceMethod->getSelector() << true 03735 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString); 03736 } 03737 if (ExpressionString.empty()) { 03738 // Provide a fixit: [ObjectExpr InstanceMethod] 03739 ExpressionString = " "; 03740 ExpressionString += InstanceMethod->getSelector().getAsString(); 03741 ExpressionString += "]"; 03742 03743 Diag(Loc, diag::err_objc_bridged_related_known_method) 03744 << SrcType << DestType << InstanceMethod->getSelector() << true 03745 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[") 03746 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString); 03747 } 03748 Diag(RelatedClass->getLocStart(), diag::note_declared_at); 03749 Diag(TDNDecl->getLocStart(), diag::note_declared_at); 03750 03751 ExprResult msg = 03752 BuildInstanceMessageImplicit(SrcExpr, SrcType, 03753 InstanceMethod->getLocation(), 03754 InstanceMethod->getSelector(), 03755 InstanceMethod, None); 03756 SrcExpr = msg.get(); 03757 return true; 03758 } 03759 } 03760 return false; 03761 } 03762 03763 Sema::ARCConversionResult 03764 Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType, 03765 Expr *&castExpr, CheckedConversionKind CCK, 03766 bool DiagnoseCFAudited, 03767 BinaryOperatorKind Opc) { 03768 QualType castExprType = castExpr->getType(); 03769 03770 // For the purposes of the classification, we assume reference types 03771 // will bind to temporaries. 03772 QualType effCastType = castType; 03773 if (const ReferenceType *ref = castType->getAs<ReferenceType>()) 03774 effCastType = ref->getPointeeType(); 03775 03776 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType); 03777 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType); 03778 if (exprACTC == castACTC) { 03779 // check for viablity and report error if casting an rvalue to a 03780 // life-time qualifier. 03781 if ((castACTC == ACTC_retainable) && 03782 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) && 03783 (castType != castExprType)) { 03784 const Type *DT = castType.getTypePtr(); 03785 QualType QDT = castType; 03786 // We desugar some types but not others. We ignore those 03787 // that cannot happen in a cast; i.e. auto, and those which 03788 // should not be de-sugared; i.e typedef. 03789 if (const ParenType *PT = dyn_cast<ParenType>(DT)) 03790 QDT = PT->desugar(); 03791 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT)) 03792 QDT = TP->desugar(); 03793 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT)) 03794 QDT = AT->desugar(); 03795 if (QDT != castType && 03796 QDT.getObjCLifetime() != Qualifiers::OCL_None) { 03797 SourceLocation loc = 03798 (castRange.isValid() ? castRange.getBegin() 03799 : castExpr->getExprLoc()); 03800 Diag(loc, diag::err_arc_nolifetime_behavior); 03801 } 03802 } 03803 return ACR_okay; 03804 } 03805 03806 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay; 03807 03808 // Allow all of these types to be cast to integer types (but not 03809 // vice-versa). 03810 if (castACTC == ACTC_none && castType->isIntegralType(Context)) 03811 return ACR_okay; 03812 03813 // Allow casts between pointers to lifetime types (e.g., __strong id*) 03814 // and pointers to void (e.g., cv void *). Casting from void* to lifetime* 03815 // must be explicit. 03816 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr) 03817 return ACR_okay; 03818 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr && 03819 CCK != CCK_ImplicitConversion) 03820 return ACR_okay; 03821 03822 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) { 03823 // For invalid casts, fall through. 03824 case ACC_invalid: 03825 break; 03826 03827 // Do nothing for both bottom and +0. 03828 case ACC_bottom: 03829 case ACC_plusZero: 03830 return ACR_okay; 03831 03832 // If the result is +1, consume it here. 03833 case ACC_plusOne: 03834 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(), 03835 CK_ARCConsumeObject, castExpr, 03836 nullptr, VK_RValue); 03837 ExprNeedsCleanups = true; 03838 return ACR_okay; 03839 } 03840 03841 // If this is a non-implicit cast from id or block type to a 03842 // CoreFoundation type, delay complaining in case the cast is used 03843 // in an acceptable context. 03844 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && 03845 CCK != CCK_ImplicitConversion) 03846 return ACR_unbridged; 03847 03848 // Do not issue bridge cast" diagnostic when implicit casting a cstring 03849 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with 03850 // suitable fix-it. 03851 if (castACTC == ACTC_retainable && exprACTC == ACTC_none && 03852 ConversionToObjCStringLiteralCheck(castType, castExpr)) 03853 return ACR_okay; 03854 03855 // Do not issue "bridge cast" diagnostic when implicit casting 03856 // a retainable object to a CF type parameter belonging to an audited 03857 // CF API function. Let caller issue a normal type mismatched diagnostic 03858 // instead. 03859 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable || 03860 castACTC != ACTC_coreFoundation) 03861 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable && 03862 (Opc == BO_NE || Opc == BO_EQ))) 03863 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, 03864 castExpr, castExpr, exprACTC, CCK); 03865 return ACR_okay; 03866 } 03867 03868 /// Given that we saw an expression with the ARCUnbridgedCastTy 03869 /// placeholder type, complain bitterly. 03870 void Sema::diagnoseARCUnbridgedCast(Expr *e) { 03871 // We expect the spurious ImplicitCastExpr to already have been stripped. 03872 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 03873 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens()); 03874 03875 SourceRange castRange; 03876 QualType castType; 03877 CheckedConversionKind CCK; 03878 03879 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) { 03880 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc()); 03881 castType = cast->getTypeAsWritten(); 03882 CCK = CCK_CStyleCast; 03883 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) { 03884 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange(); 03885 castType = cast->getTypeAsWritten(); 03886 CCK = CCK_OtherCast; 03887 } else { 03888 castType = cast->getType(); 03889 CCK = CCK_ImplicitConversion; 03890 } 03891 03892 ARCConversionTypeClass castACTC = 03893 classifyTypeForARCConversion(castType.getNonReferenceType()); 03894 03895 Expr *castExpr = realCast->getSubExpr(); 03896 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable); 03897 03898 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, 03899 castExpr, realCast, ACTC_retainable, CCK); 03900 } 03901 03902 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast 03903 /// type, remove the placeholder cast. 03904 Expr *Sema::stripARCUnbridgedCast(Expr *e) { 03905 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 03906 03907 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) { 03908 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr()); 03909 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub); 03910 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) { 03911 assert(uo->getOpcode() == UO_Extension); 03912 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr()); 03913 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(), 03914 sub->getValueKind(), sub->getObjectKind(), 03915 uo->getOperatorLoc()); 03916 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) { 03917 assert(!gse->isResultDependent()); 03918 03919 unsigned n = gse->getNumAssocs(); 03920 SmallVector<Expr*, 4> subExprs(n); 03921 SmallVector<TypeSourceInfo*, 4> subTypes(n); 03922 for (unsigned i = 0; i != n; ++i) { 03923 subTypes[i] = gse->getAssocTypeSourceInfo(i); 03924 Expr *sub = gse->getAssocExpr(i); 03925 if (i == gse->getResultIndex()) 03926 sub = stripARCUnbridgedCast(sub); 03927 subExprs[i] = sub; 03928 } 03929 03930 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(), 03931 gse->getControllingExpr(), 03932 subTypes, subExprs, 03933 gse->getDefaultLoc(), 03934 gse->getRParenLoc(), 03935 gse->containsUnexpandedParameterPack(), 03936 gse->getResultIndex()); 03937 } else { 03938 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!"); 03939 return cast<ImplicitCastExpr>(e)->getSubExpr(); 03940 } 03941 } 03942 03943 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType, 03944 QualType exprType) { 03945 QualType canCastType = 03946 Context.getCanonicalType(castType).getUnqualifiedType(); 03947 QualType canExprType = 03948 Context.getCanonicalType(exprType).getUnqualifiedType(); 03949 if (isa<ObjCObjectPointerType>(canCastType) && 03950 castType.getObjCLifetime() == Qualifiers::OCL_Weak && 03951 canExprType->isObjCObjectPointerType()) { 03952 if (const ObjCObjectPointerType *ObjT = 03953 canExprType->getAs<ObjCObjectPointerType>()) 03954 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl()) 03955 return !ObjI->isArcWeakrefUnavailable(); 03956 } 03957 return true; 03958 } 03959 03960 /// Look for an ObjCReclaimReturnedObject cast and destroy it. 03961 static Expr *maybeUndoReclaimObject(Expr *e) { 03962 // For now, we just undo operands that are *immediately* reclaim 03963 // expressions, which prevents the vast majority of potential 03964 // problems here. To catch them all, we'd need to rebuild arbitrary 03965 // value-propagating subexpressions --- we can't reliably rebuild 03966 // in-place because of expression sharing. 03967 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e)) 03968 if (ice->getCastKind() == CK_ARCReclaimReturnedObject) 03969 return ice->getSubExpr(); 03970 03971 return e; 03972 } 03973 03974 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, 03975 ObjCBridgeCastKind Kind, 03976 SourceLocation BridgeKeywordLoc, 03977 TypeSourceInfo *TSInfo, 03978 Expr *SubExpr) { 03979 ExprResult SubResult = UsualUnaryConversions(SubExpr); 03980 if (SubResult.isInvalid()) return ExprError(); 03981 SubExpr = SubResult.get(); 03982 03983 QualType T = TSInfo->getType(); 03984 QualType FromType = SubExpr->getType(); 03985 03986 CastKind CK; 03987 03988 bool MustConsume = false; 03989 if (T->isDependentType() || SubExpr->isTypeDependent()) { 03990 // Okay: we'll build a dependent expression type. 03991 CK = CK_Dependent; 03992 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) { 03993 // Casting CF -> id 03994 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast 03995 : CK_CPointerToObjCPointerCast); 03996 switch (Kind) { 03997 case OBC_Bridge: 03998 break; 03999 04000 case OBC_BridgeRetained: { 04001 bool br = isKnownName("CFBridgingRelease"); 04002 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) 04003 << 2 04004 << FromType 04005 << (T->isBlockPointerType()? 1 : 0) 04006 << T 04007 << SubExpr->getSourceRange() 04008 << Kind; 04009 Diag(BridgeKeywordLoc, diag::note_arc_bridge) 04010 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge"); 04011 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer) 04012 << FromType << br 04013 << FixItHint::CreateReplacement(BridgeKeywordLoc, 04014 br ? "CFBridgingRelease " 04015 : "__bridge_transfer "); 04016 04017 Kind = OBC_Bridge; 04018 break; 04019 } 04020 04021 case OBC_BridgeTransfer: 04022 // We must consume the Objective-C object produced by the cast. 04023 MustConsume = true; 04024 break; 04025 } 04026 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) { 04027 // Okay: id -> CF 04028 CK = CK_BitCast; 04029 switch (Kind) { 04030 case OBC_Bridge: 04031 // Reclaiming a value that's going to be __bridge-casted to CF 04032 // is very dangerous, so we don't do it. 04033 SubExpr = maybeUndoReclaimObject(SubExpr); 04034 break; 04035 04036 case OBC_BridgeRetained: 04037 // Produce the object before casting it. 04038 SubExpr = ImplicitCastExpr::Create(Context, FromType, 04039 CK_ARCProduceObject, 04040 SubExpr, nullptr, VK_RValue); 04041 break; 04042 04043 case OBC_BridgeTransfer: { 04044 bool br = isKnownName("CFBridgingRetain"); 04045 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) 04046 << (FromType->isBlockPointerType()? 1 : 0) 04047 << FromType 04048 << 2 04049 << T 04050 << SubExpr->getSourceRange() 04051 << Kind; 04052 04053 Diag(BridgeKeywordLoc, diag::note_arc_bridge) 04054 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge "); 04055 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained) 04056 << T << br 04057 << FixItHint::CreateReplacement(BridgeKeywordLoc, 04058 br ? "CFBridgingRetain " : "__bridge_retained"); 04059 04060 Kind = OBC_Bridge; 04061 break; 04062 } 04063 } 04064 } else { 04065 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible) 04066 << FromType << T << Kind 04067 << SubExpr->getSourceRange() 04068 << TSInfo->getTypeLoc().getSourceRange(); 04069 return ExprError(); 04070 } 04071 04072 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK, 04073 BridgeKeywordLoc, 04074 TSInfo, SubExpr); 04075 04076 if (MustConsume) { 04077 ExprNeedsCleanups = true; 04078 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result, 04079 nullptr, VK_RValue); 04080 } 04081 04082 return Result; 04083 } 04084 04085 ExprResult Sema::ActOnObjCBridgedCast(Scope *S, 04086 SourceLocation LParenLoc, 04087 ObjCBridgeCastKind Kind, 04088 SourceLocation BridgeKeywordLoc, 04089 ParsedType Type, 04090 SourceLocation RParenLoc, 04091 Expr *SubExpr) { 04092 TypeSourceInfo *TSInfo = nullptr; 04093 QualType T = GetTypeFromParser(Type, &TSInfo); 04094 if (Kind == OBC_Bridge) 04095 CheckTollFreeBridgeCast(T, SubExpr); 04096 if (!TSInfo) 04097 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc); 04098 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo, 04099 SubExpr); 04100 }