1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for Objective-C expressions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21 #include "clang/Edit/Commit.h"
22 #include "clang/Edit/Rewriters.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Sema/Initialization.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "llvm/ADT/SmallString.h"
30 using namespace clang;
32 using llvm::makeArrayRef;
34 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
36 unsigned NumStrings) {
37 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
39 // Most ObjC strings are formed out of a single piece. However, we *can*
40 // have strings formed out of multiple @ strings with multiple pptokens in
41 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
42 // StringLiteral for ObjCStringLiteral to hold onto.
43 StringLiteral *S = Strings[0];
45 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
47 // Concatenate objc strings.
48 SmallString<128> StrBuf;
49 SmallVector<SourceLocation, 8> StrLocs;
51 for (unsigned i = 0; i != NumStrings; ++i) {
54 // ObjC strings can't be wide or UTF.
56 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
62 StrBuf += S->getString();
64 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
68 // Create the aggregate string with the appropriate content and location
70 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
71 assert(CAT && "String literal not of constant array type!");
72 QualType StrTy = Context.getConstantArrayType(
73 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
74 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
75 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
76 /*Pascal=*/false, StrTy, &StrLocs[0],
80 return BuildObjCStringLiteral(AtLocs[0], S);
83 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
84 // Verify that this composite string is acceptable for ObjC strings.
85 if (CheckObjCString(S))
88 // Initialize the constant string interface lazily. This assumes
89 // the NSString interface is seen in this translation unit. Note: We
90 // don't use NSConstantString, since the runtime team considers this
91 // interface private (even though it appears in the header files).
92 QualType Ty = Context.getObjCConstantStringInterface();
94 Ty = Context.getObjCObjectPointerType(Ty);
95 } else if (getLangOpts().NoConstantCFStrings) {
96 IdentifierInfo *NSIdent=nullptr;
97 std::string StringClass(getLangOpts().ObjCConstantStringClass);
99 if (StringClass.empty())
100 NSIdent = &Context.Idents.get("NSConstantString");
102 NSIdent = &Context.Idents.get(StringClass);
104 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
106 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
107 Context.setObjCConstantStringInterface(StrIF);
108 Ty = Context.getObjCConstantStringInterface();
109 Ty = Context.getObjCObjectPointerType(Ty);
111 // If there is no NSConstantString interface defined then treat this
112 // as error and recover from it.
113 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
114 << S->getSourceRange();
115 Ty = Context.getObjCIdType();
118 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
119 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
121 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
122 Context.setObjCConstantStringInterface(StrIF);
123 Ty = Context.getObjCConstantStringInterface();
124 Ty = Context.getObjCObjectPointerType(Ty);
126 // If there is no NSString interface defined, implicitly declare
127 // a @class NSString; and use that instead. This is to make sure
128 // type of an NSString literal is represented correctly, instead of
129 // being an 'id' type.
130 Ty = Context.getObjCNSStringType();
132 ObjCInterfaceDecl *NSStringIDecl =
133 ObjCInterfaceDecl::Create (Context,
134 Context.getTranslationUnitDecl(),
135 SourceLocation(), NSIdent,
136 nullptr, nullptr, SourceLocation());
137 Ty = Context.getObjCInterfaceType(NSStringIDecl);
138 Context.setObjCNSStringType(Ty);
140 Ty = Context.getObjCObjectPointerType(Ty);
144 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
147 /// \brief Emits an error if the given method does not exist, or if the return
148 /// type is not an Objective-C object.
149 static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
150 const ObjCInterfaceDecl *Class,
151 Selector Sel, const ObjCMethodDecl *Method) {
153 // FIXME: Is there a better way to avoid quotes than using getName()?
154 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
158 // Make sure the return type is reasonable.
159 QualType ReturnType = Method->getReturnType();
160 if (!ReturnType->isObjCObjectPointerType()) {
161 S.Diag(Loc, diag::err_objc_literal_method_sig)
163 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
171 /// \brief Retrieve the NSNumber factory method that should be used to create
172 /// an Objective-C literal for the given type.
173 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
175 bool isLiteral = false,
176 SourceRange R = SourceRange()) {
177 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
178 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
182 S.Diag(Loc, diag::err_invalid_nsnumber_type)
188 // If we already looked up this method, we're done.
189 if (S.NSNumberLiteralMethods[*Kind])
190 return S.NSNumberLiteralMethods[*Kind];
192 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
195 ASTContext &CX = S.Context;
197 // Look up the NSNumber class, if we haven't done so already. It's cached
198 // in the Sema instance.
199 if (!S.NSNumberDecl) {
200 IdentifierInfo *NSNumberId =
201 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
202 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
203 Loc, Sema::LookupOrdinaryName);
204 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
205 if (!S.NSNumberDecl) {
206 if (S.getLangOpts().DebuggerObjCLiteral) {
207 // Create a stub definition of NSNumber.
208 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
209 CX.getTranslationUnitDecl(),
210 SourceLocation(), NSNumberId,
214 // Otherwise, require a declaration of NSNumber.
215 S.Diag(Loc, diag::err_undeclared_nsnumber);
218 } else if (!S.NSNumberDecl->hasDefinition()) {
219 S.Diag(Loc, diag::err_undeclared_nsnumber);
224 if (S.NSNumberPointer.isNull()) {
225 // generate the pointer to NSNumber type.
226 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
227 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
230 // Look for the appropriate method within NSNumber.
231 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
232 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
233 // create a stub definition this NSNumber factory method.
234 TypeSourceInfo *ReturnTInfo = nullptr;
236 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
237 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
238 /*isInstance=*/false, /*isVariadic=*/false,
239 /*isPropertyAccessor=*/false,
240 /*isImplicitlyDeclared=*/true,
241 /*isDefined=*/false, ObjCMethodDecl::Required,
242 /*HasRelatedResultType=*/false);
243 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
244 SourceLocation(), SourceLocation(),
245 &CX.Idents.get("value"),
246 NumberType, /*TInfo=*/nullptr,
248 Method->setMethodParams(S.Context, value, None);
251 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
254 // Note: if the parameter type is out-of-line, we'll catch it later in the
255 // implicit conversion.
257 S.NSNumberLiteralMethods[*Kind] = Method;
261 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
262 /// numeric literal expression. Type of the expression will be "NSNumber *".
263 ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
264 // Determine the type of the literal.
265 QualType NumberType = Number->getType();
266 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
267 // In C, character literals have type 'int'. That's not the type we want
268 // to use to determine the Objective-c literal kind.
269 switch (Char->getKind()) {
270 case CharacterLiteral::Ascii:
271 NumberType = Context.CharTy;
274 case CharacterLiteral::Wide:
275 NumberType = Context.getWideCharType();
278 case CharacterLiteral::UTF16:
279 NumberType = Context.Char16Ty;
282 case CharacterLiteral::UTF32:
283 NumberType = Context.Char32Ty;
288 // Look for the appropriate method within NSNumber.
289 // Construct the literal.
290 SourceRange NR(Number->getSourceRange());
291 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
296 // Convert the number to the type that the parameter expects.
297 ParmVarDecl *ParamDecl = Method->parameters()[0];
298 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
300 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
303 if (ConvertedNumber.isInvalid())
305 Number = ConvertedNumber.get();
307 // Use the effective source range of the literal, including the leading '@'.
308 return MaybeBindToTemporary(
309 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
310 SourceRange(AtLoc, NR.getEnd())));
313 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
314 SourceLocation ValueLoc,
317 if (getLangOpts().CPlusPlus) {
318 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
320 // C doesn't actually have a way to represent literal values of type
321 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
322 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
323 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
324 CK_IntegralToBoolean);
327 return BuildObjCNumericLiteral(AtLoc, Inner.get());
330 /// \brief Check that the given expression is a valid element of an Objective-C
331 /// collection literal.
332 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
334 bool ArrayLiteral = false) {
335 // If the expression is type-dependent, there's nothing for us to do.
336 if (Element->isTypeDependent())
339 ExprResult Result = S.CheckPlaceholderExpr(Element);
340 if (Result.isInvalid())
342 Element = Result.get();
344 // In C++, check for an implicit conversion to an Objective-C object pointer
346 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
347 InitializedEntity Entity
348 = InitializedEntity::InitializeParameter(S.Context, T,
350 InitializationKind Kind
351 = InitializationKind::CreateCopy(Element->getLocStart(),
353 InitializationSequence Seq(S, Entity, Kind, Element);
355 return Seq.Perform(S, Entity, Kind, Element);
358 Expr *OrigElement = Element;
360 // Perform lvalue-to-rvalue conversion.
361 Result = S.DefaultLvalueConversion(Element);
362 if (Result.isInvalid())
364 Element = Result.get();
366 // Make sure that we have an Objective-C pointer type or block.
367 if (!Element->getType()->isObjCObjectPointerType() &&
368 !Element->getType()->isBlockPointerType()) {
369 bool Recovered = false;
371 // If this is potentially an Objective-C numeric literal, add the '@'.
372 if (isa<IntegerLiteral>(OrigElement) ||
373 isa<CharacterLiteral>(OrigElement) ||
374 isa<FloatingLiteral>(OrigElement) ||
375 isa<ObjCBoolLiteralExpr>(OrigElement) ||
376 isa<CXXBoolLiteralExpr>(OrigElement)) {
377 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
378 int Which = isa<CharacterLiteral>(OrigElement) ? 1
379 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
380 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
383 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
384 << Which << OrigElement->getSourceRange()
385 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
387 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
389 if (Result.isInvalid())
392 Element = Result.get();
396 // If this is potentially an Objective-C string literal, add the '@'.
397 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
398 if (String->isAscii()) {
399 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
400 << 0 << OrigElement->getSourceRange()
401 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
403 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
404 if (Result.isInvalid())
407 Element = Result.get();
413 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
414 << Element->getType();
419 if (ObjCStringLiteral *getString =
420 dyn_cast<ObjCStringLiteral>(OrigElement)) {
421 if (StringLiteral *SL = getString->getString()) {
422 unsigned numConcat = SL->getNumConcatenated();
424 // Only warn if the concatenated string doesn't come from a macro.
425 bool hasMacro = false;
426 for (unsigned i = 0; i < numConcat ; ++i)
427 if (SL->getStrTokenLoc(i).isMacroID()) {
432 S.Diag(Element->getLocStart(),
433 diag::warn_concatenated_nsarray_literal)
434 << Element->getType();
439 // Make sure that the element has the type that the container factory
441 return S.PerformCopyInitialization(
442 InitializedEntity::InitializeParameter(S.Context, T,
444 Element->getLocStart(), Element);
447 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
448 if (ValueExpr->isTypeDependent()) {
449 ObjCBoxedExpr *BoxedExpr =
450 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
453 ObjCMethodDecl *BoxingMethod = nullptr;
455 // Convert the expression to an RValue, so we can check for pointer types...
456 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
457 if (RValue.isInvalid()) {
460 ValueExpr = RValue.get();
461 QualType ValueType(ValueExpr->getType());
462 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
463 QualType PointeeType = PT->getPointeeType();
464 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
467 IdentifierInfo *NSStringId =
468 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
469 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
470 SR.getBegin(), LookupOrdinaryName);
471 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
473 if (getLangOpts().DebuggerObjCLiteral) {
474 // Support boxed expressions in the debugger w/o NSString declaration.
475 DeclContext *TU = Context.getTranslationUnitDecl();
476 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
482 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
485 } else if (!NSStringDecl->hasDefinition()) {
486 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
489 assert(NSStringDecl && "NSStringDecl should not be NULL");
490 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
491 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
494 if (!StringWithUTF8StringMethod) {
495 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
496 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
498 // Look for the appropriate method within NSString.
499 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
500 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
501 // Debugger needs to work even if NSString hasn't been defined.
502 TypeSourceInfo *ReturnTInfo = nullptr;
503 ObjCMethodDecl *M = ObjCMethodDecl::Create(
504 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
505 NSStringPointer, ReturnTInfo, NSStringDecl,
506 /*isInstance=*/false, /*isVariadic=*/false,
507 /*isPropertyAccessor=*/false,
508 /*isImplicitlyDeclared=*/true,
509 /*isDefined=*/false, ObjCMethodDecl::Required,
510 /*HasRelatedResultType=*/false);
511 QualType ConstCharType = Context.CharTy.withConst();
513 ParmVarDecl::Create(Context, M,
514 SourceLocation(), SourceLocation(),
515 &Context.Idents.get("value"),
516 Context.getPointerType(ConstCharType),
519 M->setMethodParams(Context, value, None);
523 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
524 stringWithUTF8String, BoxingMethod))
527 StringWithUTF8StringMethod = BoxingMethod;
530 BoxingMethod = StringWithUTF8StringMethod;
531 BoxedType = NSStringPointer;
533 } else if (ValueType->isBuiltinType()) {
534 // The other types we support are numeric, char and BOOL/bool. We could also
535 // provide limited support for structure types, such as NSRange, NSRect, and
536 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
539 // Check for a top-level character literal.
540 if (const CharacterLiteral *Char =
541 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
542 // In C, character literals have type 'int'. That's not the type we want
543 // to use to determine the Objective-c literal kind.
544 switch (Char->getKind()) {
545 case CharacterLiteral::Ascii:
546 ValueType = Context.CharTy;
549 case CharacterLiteral::Wide:
550 ValueType = Context.getWideCharType();
553 case CharacterLiteral::UTF16:
554 ValueType = Context.Char16Ty;
557 case CharacterLiteral::UTF32:
558 ValueType = Context.Char32Ty;
562 CheckForIntOverflow(ValueExpr);
563 // FIXME: Do I need to do anything special with BoolTy expressions?
565 // Look for the appropriate method within NSNumber.
566 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
567 BoxedType = NSNumberPointer;
568 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
569 if (!ET->getDecl()->isComplete()) {
570 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
571 << ValueType << ValueExpr->getSourceRange();
575 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
576 ET->getDecl()->getIntegerType());
577 BoxedType = NSNumberPointer;
578 } else if (ValueType->isObjCBoxableRecordType()) {
579 // Support for structure types, that marked as objc_boxable
580 // struct __attribute__((objc_boxable)) s { ... };
582 // Look up the NSValue class, if we haven't done so already. It's cached
583 // in the Sema instance.
585 IdentifierInfo *NSValueId =
586 NSAPIObj->getNSClassId(NSAPI::ClassId_NSValue);
587 NamedDecl *IF = LookupSingleName(TUScope, NSValueId,
588 SR.getBegin(), Sema::LookupOrdinaryName);
589 NSValueDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
591 if (getLangOpts().DebuggerObjCLiteral) {
592 // Create a stub definition of NSValue.
593 DeclContext *TU = Context.getTranslationUnitDecl();
594 NSValueDecl = ObjCInterfaceDecl::Create(Context, TU,
595 SourceLocation(), NSValueId,
599 // Otherwise, require a declaration of NSValue.
600 Diag(SR.getBegin(), diag::err_undeclared_nsvalue);
603 } else if (!NSValueDecl->hasDefinition()) {
604 Diag(SR.getBegin(), diag::err_undeclared_nsvalue);
608 // generate the pointer to NSValue type.
609 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
610 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
613 if (!ValueWithBytesObjCTypeMethod) {
614 IdentifierInfo *II[] = {
615 &Context.Idents.get("valueWithBytes"),
616 &Context.Idents.get("objCType")
618 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
620 // Look for the appropriate method within NSValue.
621 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
622 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
623 // Debugger needs to work even if NSValue hasn't been defined.
624 TypeSourceInfo *ReturnTInfo = nullptr;
625 ObjCMethodDecl *M = ObjCMethodDecl::Create(
629 ValueWithBytesObjCType,
633 /*isInstance=*/false,
634 /*isVariadic=*/false,
635 /*isPropertyAccessor=*/false,
636 /*isImplicitlyDeclared=*/true,
638 ObjCMethodDecl::Required,
639 /*HasRelatedResultType=*/false);
641 SmallVector<ParmVarDecl *, 2> Params;
644 ParmVarDecl::Create(Context, M,
645 SourceLocation(), SourceLocation(),
646 &Context.Idents.get("bytes"),
647 Context.VoidPtrTy.withConst(),
650 Params.push_back(bytes);
652 QualType ConstCharType = Context.CharTy.withConst();
654 ParmVarDecl::Create(Context, M,
655 SourceLocation(), SourceLocation(),
656 &Context.Idents.get("type"),
657 Context.getPointerType(ConstCharType),
660 Params.push_back(type);
662 M->setMethodParams(Context, Params, None);
666 if (!validateBoxingMethod(*this, SR.getBegin(), NSValueDecl,
667 ValueWithBytesObjCType, BoxingMethod))
670 ValueWithBytesObjCTypeMethod = BoxingMethod;
673 if (!ValueType.isTriviallyCopyableType(Context)) {
675 diag::err_objc_non_trivially_copyable_boxed_expression_type)
676 << ValueType << ValueExpr->getSourceRange();
680 BoxingMethod = ValueWithBytesObjCTypeMethod;
681 BoxedType = NSValuePointer;
685 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
686 << ValueType << ValueExpr->getSourceRange();
690 DiagnoseUseOfDecl(BoxingMethod, SR.getBegin());
692 ExprResult ConvertedValueExpr;
693 if (ValueType->isObjCBoxableRecordType()) {
694 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
695 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
698 // Convert the expression to the type that the parameter requires.
699 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
700 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
702 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
706 if (ConvertedValueExpr.isInvalid())
708 ValueExpr = ConvertedValueExpr.get();
710 ObjCBoxedExpr *BoxedExpr =
711 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
713 return MaybeBindToTemporary(BoxedExpr);
716 /// Build an ObjC subscript pseudo-object expression, given that
717 /// that's supported by the runtime.
718 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
720 ObjCMethodDecl *getterMethod,
721 ObjCMethodDecl *setterMethod) {
722 assert(!LangOpts.isSubscriptPointerArithmetic());
724 // We can't get dependent types here; our callers should have
725 // filtered them out.
726 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
727 "base or index cannot have dependent type here");
729 // Filter out placeholders in the index. In theory, overloads could
730 // be preserved here, although that might not actually work correctly.
731 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
732 if (Result.isInvalid())
734 IndexExpr = Result.get();
736 // Perform lvalue-to-rvalue conversion on the base.
737 Result = DefaultLvalueConversion(BaseExpr);
738 if (Result.isInvalid())
740 BaseExpr = Result.get();
742 // Build the pseudo-object expression.
743 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
744 Context.PseudoObjectTy, getterMethod,
748 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
749 // Look up the NSArray class, if we haven't done so already.
751 NamedDecl *IF = LookupSingleName(TUScope,
752 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
755 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
756 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
757 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
758 Context.getTranslationUnitDecl(),
760 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
761 nullptr, nullptr, SourceLocation());
764 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
769 // Find the arrayWithObjects:count: method, if we haven't done so already.
770 QualType IdT = Context.getObjCIdType();
771 if (!ArrayWithObjectsMethod) {
773 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
774 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
775 if (!Method && getLangOpts().DebuggerObjCLiteral) {
776 TypeSourceInfo *ReturnTInfo = nullptr;
777 Method = ObjCMethodDecl::Create(
778 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
779 Context.getTranslationUnitDecl(), false /*Instance*/,
780 false /*isVariadic*/,
781 /*isPropertyAccessor=*/false,
782 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
783 ObjCMethodDecl::Required, false);
784 SmallVector<ParmVarDecl *, 2> Params;
785 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
788 &Context.Idents.get("objects"),
789 Context.getPointerType(IdT),
792 Params.push_back(objects);
793 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
796 &Context.Idents.get("cnt"),
797 Context.UnsignedLongTy,
798 /*TInfo=*/nullptr, SC_None,
800 Params.push_back(cnt);
801 Method->setMethodParams(Context, Params, None);
804 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
807 // Dig out the type that all elements should be converted to.
808 QualType T = Method->parameters()[0]->getType();
809 const PointerType *PtrT = T->getAs<PointerType>();
811 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
812 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
814 Diag(Method->parameters()[0]->getLocation(),
815 diag::note_objc_literal_method_param)
817 << Context.getPointerType(IdT.withConst());
821 // Check that the 'count' parameter is integral.
822 if (!Method->parameters()[1]->getType()->isIntegerType()) {
823 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
825 Diag(Method->parameters()[1]->getLocation(),
826 diag::note_objc_literal_method_param)
828 << Method->parameters()[1]->getType()
833 // We've found a good +arrayWithObjects:count: method. Save it!
834 ArrayWithObjectsMethod = Method;
837 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
838 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
840 // Check that each of the elements provided is valid in a collection literal,
841 // performing conversions as necessary.
842 Expr **ElementsBuffer = Elements.data();
843 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
844 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
847 if (Converted.isInvalid())
850 ElementsBuffer[I] = Converted.get();
854 = Context.getObjCObjectPointerType(
855 Context.getObjCInterfaceType(NSArrayDecl));
857 return MaybeBindToTemporary(
858 ObjCArrayLiteral::Create(Context, Elements, Ty,
859 ArrayWithObjectsMethod, SR));
862 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
863 ObjCDictionaryElement *Elements,
864 unsigned NumElements) {
865 // Look up the NSDictionary class, if we haven't done so already.
866 if (!NSDictionaryDecl) {
867 NamedDecl *IF = LookupSingleName(TUScope,
868 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
869 SR.getBegin(), LookupOrdinaryName);
870 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
871 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
872 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
873 Context.getTranslationUnitDecl(),
875 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
876 nullptr, nullptr, SourceLocation());
878 if (!NSDictionaryDecl) {
879 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
884 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
886 QualType IdT = Context.getObjCIdType();
887 if (!DictionaryWithObjectsMethod) {
888 Selector Sel = NSAPIObj->getNSDictionarySelector(
889 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
890 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
891 if (!Method && getLangOpts().DebuggerObjCLiteral) {
892 Method = ObjCMethodDecl::Create(Context,
893 SourceLocation(), SourceLocation(), Sel,
895 nullptr /*TypeSourceInfo */,
896 Context.getTranslationUnitDecl(),
897 false /*Instance*/, false/*isVariadic*/,
898 /*isPropertyAccessor=*/false,
899 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
900 ObjCMethodDecl::Required,
902 SmallVector<ParmVarDecl *, 3> Params;
903 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
906 &Context.Idents.get("objects"),
907 Context.getPointerType(IdT),
908 /*TInfo=*/nullptr, SC_None,
910 Params.push_back(objects);
911 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
914 &Context.Idents.get("keys"),
915 Context.getPointerType(IdT),
916 /*TInfo=*/nullptr, SC_None,
918 Params.push_back(keys);
919 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
922 &Context.Idents.get("cnt"),
923 Context.UnsignedLongTy,
924 /*TInfo=*/nullptr, SC_None,
926 Params.push_back(cnt);
927 Method->setMethodParams(Context, Params, None);
930 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
934 // Dig out the type that all values should be converted to.
935 QualType ValueT = Method->parameters()[0]->getType();
936 const PointerType *PtrValue = ValueT->getAs<PointerType>();
938 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
939 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
941 Diag(Method->parameters()[0]->getLocation(),
942 diag::note_objc_literal_method_param)
944 << Context.getPointerType(IdT.withConst());
948 // Dig out the type that all keys should be converted to.
949 QualType KeyT = Method->parameters()[1]->getType();
950 const PointerType *PtrKey = KeyT->getAs<PointerType>();
952 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
956 if (QIDNSCopying.isNull()) {
957 // key argument of selector is id<NSCopying>?
958 if (ObjCProtocolDecl *NSCopyingPDecl =
959 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
960 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
962 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
964 (ObjCProtocolDecl**) PQ,
967 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
970 if (!QIDNSCopying.isNull())
971 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
976 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
978 Diag(Method->parameters()[1]->getLocation(),
979 diag::note_objc_literal_method_param)
981 << Context.getPointerType(IdT.withConst());
986 // Check that the 'count' parameter is integral.
987 QualType CountType = Method->parameters()[2]->getType();
988 if (!CountType->isIntegerType()) {
989 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
991 Diag(Method->parameters()[2]->getLocation(),
992 diag::note_objc_literal_method_param)
998 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
999 DictionaryWithObjectsMethod = Method;
1002 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
1003 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
1004 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
1005 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1007 // Check that each of the keys and values provided is valid in a collection
1008 // literal, performing conversions as necessary.
1009 bool HasPackExpansions = false;
1010 for (unsigned I = 0, N = NumElements; I != N; ++I) {
1012 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
1014 if (Key.isInvalid())
1019 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
1020 if (Value.isInvalid())
1023 Elements[I].Key = Key.get();
1024 Elements[I].Value = Value.get();
1026 if (Elements[I].EllipsisLoc.isInvalid())
1029 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
1030 !Elements[I].Value->containsUnexpandedParameterPack()) {
1031 Diag(Elements[I].EllipsisLoc,
1032 diag::err_pack_expansion_without_parameter_packs)
1033 << SourceRange(Elements[I].Key->getLocStart(),
1034 Elements[I].Value->getLocEnd());
1038 HasPackExpansions = true;
1043 = Context.getObjCObjectPointerType(
1044 Context.getObjCInterfaceType(NSDictionaryDecl));
1045 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
1046 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
1047 DictionaryWithObjectsMethod, SR));
1050 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
1051 TypeSourceInfo *EncodedTypeInfo,
1052 SourceLocation RParenLoc) {
1053 QualType EncodedType = EncodedTypeInfo->getType();
1055 if (EncodedType->isDependentType())
1056 StrTy = Context.DependentTy;
1058 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1059 !EncodedType->isVoidType()) // void is handled too.
1060 if (RequireCompleteType(AtLoc, EncodedType,
1061 diag::err_incomplete_type_objc_at_encode,
1062 EncodedTypeInfo->getTypeLoc()))
1066 QualType NotEncodedT;
1067 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1068 if (!NotEncodedT.isNull())
1069 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1070 << EncodedType << NotEncodedT;
1072 // The type of @encode is the same as the type of the corresponding string,
1073 // which is an array type.
1074 StrTy = Context.CharTy;
1075 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1076 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1078 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
1079 ArrayType::Normal, 0);
1082 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
1085 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1086 SourceLocation EncodeLoc,
1087 SourceLocation LParenLoc,
1089 SourceLocation RParenLoc) {
1090 // FIXME: Preserve type source info ?
1091 TypeSourceInfo *TInfo;
1092 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1094 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1095 PP.getLocForEndOfToken(LParenLoc));
1097 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
1100 static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1101 SourceLocation AtLoc,
1102 SourceLocation LParenLoc,
1103 SourceLocation RParenLoc,
1104 ObjCMethodDecl *Method,
1105 ObjCMethodList &MethList) {
1106 ObjCMethodList *M = &MethList;
1107 bool Warned = false;
1108 for (M = M->getNext(); M; M=M->getNext()) {
1109 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
1110 if (MatchingMethodDecl == Method ||
1111 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1112 MatchingMethodDecl->getSelector() != Method->getSelector())
1114 if (!S.MatchTwoMethodDeclarations(Method,
1115 MatchingMethodDecl, Sema::MMS_loose)) {
1118 S.Diag(AtLoc, diag::warning_multiple_selectors)
1119 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1120 << FixItHint::CreateInsertion(RParenLoc, ")");
1121 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1122 << Method->getDeclName();
1124 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1125 << MatchingMethodDecl->getDeclName();
1131 static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1132 ObjCMethodDecl *Method,
1133 SourceLocation LParenLoc,
1134 SourceLocation RParenLoc,
1135 bool WarnMultipleSelectors) {
1136 if (!WarnMultipleSelectors ||
1137 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
1139 bool Warned = false;
1140 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1141 e = S.MethodPool.end(); b != e; b++) {
1142 // first, instance methods
1143 ObjCMethodList &InstMethList = b->second.first;
1144 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1145 Method, InstMethList))
1148 // second, class methods
1149 ObjCMethodList &ClsMethList = b->second.second;
1150 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1151 Method, ClsMethList) || Warned)
1156 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1157 SourceLocation AtLoc,
1158 SourceLocation SelLoc,
1159 SourceLocation LParenLoc,
1160 SourceLocation RParenLoc,
1161 bool WarnMultipleSelectors) {
1162 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1163 SourceRange(LParenLoc, RParenLoc));
1165 Method = LookupFactoryMethodInGlobalPool(Sel,
1166 SourceRange(LParenLoc, RParenLoc));
1168 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1169 Selector MatchedSel = OM->getSelector();
1170 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1171 RParenLoc.getLocWithOffset(-1));
1172 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1173 << Sel << MatchedSel
1174 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1177 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
1179 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1180 WarnMultipleSelectors);
1183 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1184 !getSourceManager().isInSystemHeader(Method->getLocation()))
1185 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
1187 // In ARC, forbid the user from using @selector for
1188 // retain/release/autorelease/dealloc/retainCount.
1189 if (getLangOpts().ObjCAutoRefCount) {
1190 switch (Sel.getMethodFamily()) {
1193 case OMF_autorelease:
1194 case OMF_retainCount:
1196 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1197 Sel << SourceRange(LParenLoc, RParenLoc);
1205 case OMF_mutableCopy:
1208 case OMF_initialize:
1209 case OMF_performSelector:
1213 QualType Ty = Context.getObjCSelType();
1214 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1217 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1218 SourceLocation AtLoc,
1219 SourceLocation ProtoLoc,
1220 SourceLocation LParenLoc,
1221 SourceLocation ProtoIdLoc,
1222 SourceLocation RParenLoc) {
1223 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
1225 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
1228 if (PDecl->hasDefinition())
1229 PDecl = PDecl->getDefinition();
1231 QualType Ty = Context.getObjCProtoType();
1234 Ty = Context.getObjCObjectPointerType(Ty);
1235 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1238 /// Try to capture an implicit reference to 'self'.
1239 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1240 DeclContext *DC = getFunctionLevelDeclContext();
1242 // If we're not in an ObjC method, error out. Note that, unlike the
1243 // C++ case, we don't require an instance method --- class methods
1244 // still have a 'self', and we really do still need to capture it!
1245 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1249 tryCaptureVariable(method->getSelfDecl(), Loc);
1254 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1255 QualType origType = T;
1256 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1257 if (T == Context.getObjCInstanceType()) {
1258 return Context.getAttributedType(
1259 AttributedType::getNullabilityAttrKind(*nullability),
1260 Context.getObjCIdType(),
1261 Context.getObjCIdType());
1267 if (T == Context.getObjCInstanceType())
1268 return Context.getObjCIdType();
1273 /// Determine the result type of a message send based on the receiver type,
1274 /// method, and the kind of message send.
1276 /// This is the "base" result type, which will still need to be adjusted
1277 /// to account for nullability.
1278 static QualType getBaseMessageSendResultType(Sema &S,
1279 QualType ReceiverType,
1280 ObjCMethodDecl *Method,
1281 bool isClassMessage,
1282 bool isSuperMessage) {
1283 assert(Method && "Must have a method");
1284 if (!Method->hasRelatedResultType())
1285 return Method->getSendResultType(ReceiverType);
1287 ASTContext &Context = S.Context;
1289 // Local function that transfers the nullability of the method's
1290 // result type to the returned result.
1291 auto transferNullability = [&](QualType type) -> QualType {
1292 // If the method's result type has nullability, extract it.
1293 if (auto nullability = Method->getSendResultType(ReceiverType)
1294 ->getNullability(Context)){
1295 // Strip off any outer nullability sugar from the provided type.
1296 (void)AttributedType::stripOuterNullability(type);
1298 // Form a new attributed type using the method result type's nullability.
1299 return Context.getAttributedType(
1300 AttributedType::getNullabilityAttrKind(*nullability),
1308 // If a method has a related return type:
1309 // - if the method found is an instance method, but the message send
1310 // was a class message send, T is the declared return type of the method
1312 if (Method->isInstanceMethod() && isClassMessage)
1313 return stripObjCInstanceType(Context,
1314 Method->getSendResultType(ReceiverType));
1316 // - if the receiver is super, T is a pointer to the class of the
1317 // enclosing method definition
1318 if (isSuperMessage) {
1319 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1320 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1321 return transferNullability(
1322 Context.getObjCObjectPointerType(
1323 Context.getObjCInterfaceType(Class)));
1327 // - if the receiver is the name of a class U, T is a pointer to U
1328 if (ReceiverType->getAsObjCInterfaceType())
1329 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1330 // - if the receiver is of type Class or qualified Class type,
1331 // T is the declared return type of the method.
1332 if (ReceiverType->isObjCClassType() ||
1333 ReceiverType->isObjCQualifiedClassType())
1334 return stripObjCInstanceType(Context,
1335 Method->getSendResultType(ReceiverType));
1337 // - if the receiver is id, qualified id, Class, or qualified Class, T
1338 // is the receiver type, otherwise
1339 // - T is the type of the receiver expression.
1340 return transferNullability(ReceiverType);
1343 QualType Sema::getMessageSendResultType(QualType ReceiverType,
1344 ObjCMethodDecl *Method,
1345 bool isClassMessage,
1346 bool isSuperMessage) {
1347 // Produce the result type.
1348 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1353 // If this is a class message, ignore the nullability of the receiver.
1357 // Map the nullability of the result into a table index.
1358 unsigned receiverNullabilityIdx = 0;
1359 if (auto nullability = ReceiverType->getNullability(Context))
1360 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1362 unsigned resultNullabilityIdx = 0;
1363 if (auto nullability = resultType->getNullability(Context))
1364 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1366 // The table of nullability mappings, indexed by the receiver's nullability
1367 // and then the result type's nullability.
1368 static const uint8_t None = 0;
1369 static const uint8_t NonNull = 1;
1370 static const uint8_t Nullable = 2;
1371 static const uint8_t Unspecified = 3;
1372 static const uint8_t nullabilityMap[4][4] = {
1373 // None NonNull Nullable Unspecified
1374 /* None */ { None, None, Nullable, None },
1375 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1376 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1377 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1380 unsigned newResultNullabilityIdx
1381 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1382 if (newResultNullabilityIdx == resultNullabilityIdx)
1385 // Strip off the existing nullability. This removes as little type sugar as
1388 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1389 resultType = attributed->getModifiedType();
1391 resultType = resultType.getDesugaredType(Context);
1393 } while (resultType->getNullability(Context));
1395 // Add nullability back if needed.
1396 if (newResultNullabilityIdx > 0) {
1398 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1399 return Context.getAttributedType(
1400 AttributedType::getNullabilityAttrKind(newNullability),
1401 resultType, resultType);
1407 /// Look for an ObjC method whose result type exactly matches the given type.
1408 static const ObjCMethodDecl *
1409 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1410 QualType instancetype) {
1411 if (MD->getReturnType() == instancetype)
1414 // For these purposes, a method in an @implementation overrides a
1415 // declaration in the @interface.
1416 if (const ObjCImplDecl *impl =
1417 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1418 const ObjCContainerDecl *iface;
1419 if (const ObjCCategoryImplDecl *catImpl =
1420 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1421 iface = catImpl->getCategoryDecl();
1423 iface = impl->getClassInterface();
1426 const ObjCMethodDecl *ifaceMD =
1427 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1428 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1431 SmallVector<const ObjCMethodDecl *, 4> overrides;
1432 MD->getOverriddenMethods(overrides);
1433 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1434 if (const ObjCMethodDecl *result =
1435 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1442 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1443 // Only complain if we're in an ObjC method and the required return
1444 // type doesn't match the method's declared return type.
1445 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1446 if (!MD || !MD->hasRelatedResultType() ||
1447 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
1450 // Look for a method overridden by this method which explicitly uses
1452 if (const ObjCMethodDecl *overridden =
1453 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1454 SourceRange range = overridden->getReturnTypeSourceRange();
1455 SourceLocation loc = range.getBegin();
1456 if (loc.isInvalid())
1457 loc = overridden->getLocation();
1458 Diag(loc, diag::note_related_result_type_explicit)
1459 << /*current method*/ 1 << range;
1463 // Otherwise, if we have an interesting method family, note that.
1464 // This should always trigger if the above didn't.
1465 if (ObjCMethodFamily family = MD->getMethodFamily())
1466 Diag(MD->getLocation(), diag::note_related_result_type_family)
1467 << /*current method*/ 1
1471 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1472 E = E->IgnoreParenImpCasts();
1473 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1477 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1481 if (!Method->hasRelatedResultType())
1484 if (Context.hasSameUnqualifiedType(
1485 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
1488 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
1489 Context.getObjCInstanceType()))
1492 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1493 << Method->isInstanceMethod() << Method->getSelector()
1494 << MsgSend->getType();
1497 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
1500 ArrayRef<SourceLocation> SelectorLocs,
1501 ObjCMethodDecl *Method,
1502 bool isClassMessage, bool isSuperMessage,
1503 SourceLocation lbrac, SourceLocation rbrac,
1504 SourceRange RecRange,
1505 QualType &ReturnType, ExprValueKind &VK) {
1506 SourceLocation SelLoc;
1507 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1508 SelLoc = SelectorLocs.front();
1513 // Apply default argument promotion as for (C99 6.5.2.2p6).
1514 for (unsigned i = 0, e = Args.size(); i != e; i++) {
1515 if (Args[i]->isTypeDependent())
1519 if (getLangOpts().DebuggerSupport) {
1520 QualType paramTy; // ignored
1521 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
1523 result = DefaultArgumentPromotion(Args[i]);
1525 if (result.isInvalid())
1527 Args[i] = result.get();
1531 if (getLangOpts().ObjCAutoRefCount)
1532 DiagID = diag::err_arc_method_not_found;
1534 DiagID = isClassMessage ? diag::warn_class_method_not_found
1535 : diag::warn_inst_method_not_found;
1536 if (!getLangOpts().DebuggerSupport) {
1537 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
1538 if (OMD && !OMD->isInvalidDecl()) {
1539 if (getLangOpts().ObjCAutoRefCount)
1540 DiagID = diag::error_method_not_found_with_typo;
1542 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1543 : diag::warn_instance_method_not_found_with_typo;
1544 Selector MatchedSel = OMD->getSelector();
1545 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
1546 if (MatchedSel.isUnarySelector())
1547 Diag(SelLoc, DiagID)
1548 << Sel<< isClassMessage << MatchedSel
1549 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1551 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
1554 Diag(SelLoc, DiagID)
1555 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
1556 SelectorLocs.back());
1557 // Find the class to which we are sending this message.
1558 if (ReceiverType->isObjCObjectPointerType()) {
1559 if (ObjCInterfaceDecl *ThisClass =
1560 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1561 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1562 if (!RecRange.isInvalid())
1563 if (ThisClass->lookupClassMethod(Sel))
1564 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1565 << FixItHint::CreateReplacement(RecRange,
1566 ThisClass->getNameAsString());
1571 // In debuggers, we want to use __unknown_anytype for these
1572 // results so that clients can cast them.
1573 if (getLangOpts().DebuggerSupport) {
1574 ReturnType = Context.UnknownAnyTy;
1576 ReturnType = Context.getObjCIdType();
1582 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1584 VK = Expr::getValueKindForType(Method->getReturnType());
1586 unsigned NumNamedArgs = Sel.getNumArgs();
1587 // Method might have more arguments than selector indicates. This is due
1588 // to addition of c-style arguments in method.
1589 if (Method->param_size() > Sel.getNumArgs())
1590 NumNamedArgs = Method->param_size();
1591 // FIXME. This need be cleaned up.
1592 if (Args.size() < NumNamedArgs) {
1593 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
1594 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
1598 // Compute the set of type arguments to be substituted into each parameter
1600 Optional<ArrayRef<QualType>> typeArgs
1601 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
1602 bool IsError = false;
1603 for (unsigned i = 0; i < NumNamedArgs; i++) {
1604 // We can't do any type-checking on a type-dependent argument.
1605 if (Args[i]->isTypeDependent())
1608 Expr *argExpr = Args[i];
1610 ParmVarDecl *param = Method->parameters()[i];
1611 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1613 // Strip the unbridged-cast placeholder expression off unless it's
1614 // a consumed argument.
1615 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1616 !param->hasAttr<CFConsumedAttr>())
1617 argExpr = stripARCUnbridgedCast(argExpr);
1619 // If the parameter is __unknown_anytype, infer its type
1620 // from the argument.
1621 if (param->getType() == Context.UnknownAnyTy) {
1623 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
1624 if (argE.isInvalid()) {
1627 Args[i] = argE.get();
1629 // Update the parameter type in-place.
1630 param->setType(paramType);
1635 QualType origParamType = param->getType();
1636 QualType paramType = param->getType();
1638 paramType = paramType.substObjCTypeArgs(
1641 ObjCSubstitutionContext::Parameter);
1643 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1645 diag::err_call_incomplete_argument, argExpr))
1648 InitializedEntity Entity
1649 = InitializedEntity::InitializeParameter(Context, param, paramType);
1650 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
1651 if (ArgE.isInvalid())
1654 Args[i] = ArgE.getAs<Expr>();
1656 // If we are type-erasing a block to a block-compatible
1657 // Objective-C pointer type, we may need to extend the lifetime
1658 // of the block object.
1659 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
1660 origParamType->isBlockCompatibleObjCPointerType(Context)) {
1661 ExprResult arg = Args[i];
1662 maybeExtendBlockObject(arg);
1663 Args[i] = arg.get();
1668 // Promote additional arguments to variadic methods.
1669 if (Method->isVariadic()) {
1670 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
1671 if (Args[i]->isTypeDependent())
1674 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1676 IsError |= Arg.isInvalid();
1677 Args[i] = Arg.get();
1680 // Check for extra arguments to non-variadic methods.
1681 if (Args.size() != NumNamedArgs) {
1682 Diag(Args[NumNamedArgs]->getLocStart(),
1683 diag::err_typecheck_call_too_many_args)
1684 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1685 << Method->getSourceRange()
1686 << SourceRange(Args[NumNamedArgs]->getLocStart(),
1687 Args.back()->getLocEnd());
1691 DiagnoseSentinelCalls(Method, SelLoc, Args);
1693 // Do additional checkings on method.
1694 IsError |= CheckObjCMethodCall(
1695 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
1700 bool Sema::isSelfExpr(Expr *RExpr) {
1701 // 'self' is objc 'self' in an objc method only.
1702 ObjCMethodDecl *Method =
1703 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1704 return isSelfExpr(RExpr, Method);
1707 bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
1708 if (!method) return false;
1710 receiver = receiver->IgnoreParenLValueCasts();
1711 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1712 if (DRE->getDecl() == method->getSelfDecl())
1717 /// LookupMethodInType - Look up a method in an ObjCObjectType.
1718 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1720 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1721 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1722 // Look it up in the main interface (and categories, etc.)
1723 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1726 // Okay, look for "private" methods declared in any
1727 // @implementations we've seen.
1728 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1732 // Check qualifiers.
1733 for (const auto *I : objType->quals())
1734 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
1740 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1741 /// list of a qualified objective pointer type.
1742 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1743 const ObjCObjectPointerType *OPT,
1746 ObjCMethodDecl *MD = nullptr;
1747 for (const auto *PROTO : OPT->quals()) {
1748 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1755 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1756 /// objective C interface. This is a property reference expression.
1758 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1759 Expr *BaseExpr, SourceLocation OpLoc,
1760 DeclarationName MemberName,
1761 SourceLocation MemberLoc,
1762 SourceLocation SuperLoc, QualType SuperType,
1764 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1765 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1767 if (!MemberName.isIdentifier()) {
1768 Diag(MemberLoc, diag::err_invalid_property_name)
1769 << MemberName << QualType(OPT, 0);
1773 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1775 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1776 : BaseExpr->getSourceRange();
1777 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1778 diag::err_property_not_found_forward_class,
1779 MemberName, BaseRange))
1782 // Search for a declared property first.
1783 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1784 // Check whether we can reference this property.
1785 if (DiagnoseUseOfDecl(PD, MemberLoc))
1788 return new (Context)
1789 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1790 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1792 return new (Context)
1793 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1794 OK_ObjCProperty, MemberLoc, BaseExpr);
1796 // Check protocols on qualified interfaces.
1797 for (const auto *I : OPT->quals())
1798 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
1799 // Check whether we can reference this property.
1800 if (DiagnoseUseOfDecl(PD, MemberLoc))
1804 return new (Context) ObjCPropertyRefExpr(
1805 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1806 SuperLoc, SuperType);
1808 return new (Context)
1809 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1810 OK_ObjCProperty, MemberLoc, BaseExpr);
1812 // If that failed, look for an "implicit" property by seeing if the nullary
1813 // selector is implemented.
1815 // FIXME: The logic for looking up nullary and unary selectors should be
1816 // shared with the code in ActOnInstanceMessage.
1818 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1819 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1821 // May be founf in property's qualified list.
1823 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
1825 // If this reference is in an @implementation, check for 'private' methods.
1827 Getter = IFace->lookupPrivateMethod(Sel);
1830 // Check if we can reference this property.
1831 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1834 // If we found a getter then this may be a valid dot-reference, we
1835 // will look for the matching setter, in case it is needed.
1836 Selector SetterSel =
1837 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1838 PP.getSelectorTable(), Member);
1839 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1841 // May be founf in property's qualified list.
1843 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1846 // If this reference is in an @implementation, also check for 'private'
1848 Setter = IFace->lookupPrivateMethod(SetterSel);
1851 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1854 // Special warning if member name used in a property-dot for a setter accessor
1855 // does not use a property with same name; e.g. obj.X = ... for a property with
1857 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor()
1858 && !IFace->FindPropertyDeclaration(Member)) {
1859 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1860 // Do not warn if user is using property-dot syntax to make call to
1861 // user named setter.
1862 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
1864 diag::warn_property_access_suggest)
1865 << MemberName << QualType(OPT, 0) << PDecl->getName()
1866 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
1870 if (Getter || Setter) {
1872 return new (Context)
1873 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1874 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1876 return new (Context)
1877 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1878 OK_ObjCProperty, MemberLoc, BaseExpr);
1882 // Attempt to correct for typos in property names.
1883 if (TypoCorrection Corrected =
1884 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1885 LookupOrdinaryName, nullptr, nullptr,
1886 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1887 CTK_ErrorRecovery, IFace, false, OPT)) {
1888 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1889 << MemberName << QualType(OPT, 0));
1890 DeclarationName TypoResult = Corrected.getCorrection();
1891 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1892 TypoResult, MemberLoc,
1893 SuperLoc, SuperType, Super);
1895 ObjCInterfaceDecl *ClassDeclared;
1896 if (ObjCIvarDecl *Ivar =
1897 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1898 QualType T = Ivar->getType();
1899 if (const ObjCObjectPointerType * OBJPT =
1900 T->getAsObjCInterfacePointerType()) {
1901 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1902 diag::err_property_not_as_forward_class,
1903 MemberName, BaseExpr))
1907 diag::err_ivar_access_using_property_syntax_suggest)
1908 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1909 << FixItHint::CreateReplacement(OpLoc, "->");
1913 Diag(MemberLoc, diag::err_property_not_found)
1914 << MemberName << QualType(OPT, 0);
1916 Diag(Setter->getLocation(), diag::note_getter_unavailable)
1917 << MemberName << BaseExpr->getSourceRange();
1924 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1925 IdentifierInfo &propertyName,
1926 SourceLocation receiverNameLoc,
1927 SourceLocation propertyNameLoc) {
1929 IdentifierInfo *receiverNamePtr = &receiverName;
1930 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1935 // If the "receiver" is 'super' in a method, handle it as an expression-like
1936 // property reference.
1937 if (receiverNamePtr->isStr("super")) {
1938 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
1939 if (auto classDecl = CurMethod->getClassInterface()) {
1940 SuperType = QualType(classDecl->getSuperClassType(), 0);
1941 if (CurMethod->isInstanceMethod()) {
1942 if (SuperType.isNull()) {
1943 // The current class does not have a superclass.
1944 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1945 << CurMethod->getClassInterface()->getIdentifier();
1948 QualType T = Context.getObjCObjectPointerType(SuperType);
1950 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
1951 /*BaseExpr*/nullptr,
1952 SourceLocation()/*OpLoc*/,
1955 receiverNameLoc, T, true);
1958 // Otherwise, if this is a class method, try dispatching to our
1960 IFace = CurMethod->getClassInterface()->getSuperClass();
1966 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1972 // Search for a declared property first.
1973 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
1974 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
1976 // If this reference is in an @implementation, check for 'private' methods.
1978 Getter = IFace->lookupPrivateClassMethod(Sel);
1981 // FIXME: refactor/share with ActOnMemberReference().
1982 // Check if we can reference this property.
1983 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1987 // Look for the matching setter, in case it is needed.
1988 Selector SetterSel =
1989 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1990 PP.getSelectorTable(),
1993 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1995 // If this reference is in an @implementation, also check for 'private'
1997 Setter = IFace->lookupPrivateClassMethod(SetterSel);
1999 // Look through local category implementations associated with the class.
2001 Setter = IFace->getCategoryClassMethod(SetterSel);
2003 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2006 if (Getter || Setter) {
2007 if (!SuperType.isNull())
2008 return new (Context)
2009 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2010 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
2013 return new (Context) ObjCPropertyRefExpr(
2014 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2015 propertyNameLoc, receiverNameLoc, IFace);
2017 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2018 << &propertyName << Context.getObjCInterfaceType(IFace));
2023 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
2025 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2026 // Determine whether "super" is acceptable in the current context.
2027 if (Method && Method->getClassInterface())
2028 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2031 bool ValidateCandidate(const TypoCorrection &candidate) override {
2032 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2033 candidate.isKeyword("super");
2039 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
2040 IdentifierInfo *Name,
2041 SourceLocation NameLoc,
2043 bool HasTrailingDot,
2044 ParsedType &ReceiverType) {
2045 ReceiverType = ParsedType();
2047 // If the identifier is "super" and there is no trailing dot, we're
2048 // messaging super. If the identifier is "super" and there is a
2049 // trailing dot, it's an instance message.
2050 if (IsSuper && S->isInObjcMethodScope())
2051 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
2053 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2054 LookupName(Result, S);
2056 switch (Result.getResultKind()) {
2057 case LookupResult::NotFound:
2058 // Normal name lookup didn't find anything. If we're in an
2059 // Objective-C method, look for ivars. If we find one, we're done!
2060 // FIXME: This is a hack. Ivar lookup should be part of normal
2062 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
2063 if (!Method->getClassInterface()) {
2064 // Fall back: let the parser try to parse it as an instance message.
2065 return ObjCInstanceMessage;
2068 ObjCInterfaceDecl *ClassDeclared;
2069 if (Method->getClassInterface()->lookupInstanceVariable(Name,
2071 return ObjCInstanceMessage;
2074 // Break out; we'll perform typo correction below.
2077 case LookupResult::NotFoundInCurrentInstantiation:
2078 case LookupResult::FoundOverloaded:
2079 case LookupResult::FoundUnresolvedValue:
2080 case LookupResult::Ambiguous:
2081 Result.suppressDiagnostics();
2082 return ObjCInstanceMessage;
2084 case LookupResult::Found: {
2085 // If the identifier is a class or not, and there is a trailing dot,
2086 // it's an instance message.
2088 return ObjCInstanceMessage;
2089 // We found something. If it's a type, then we have a class
2090 // message. Otherwise, it's an instance message.
2091 NamedDecl *ND = Result.getFoundDecl();
2093 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2094 T = Context.getObjCInterfaceType(Class);
2095 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
2096 T = Context.getTypeDeclType(Type);
2097 DiagnoseUseOfDecl(Type, NameLoc);
2100 return ObjCInstanceMessage;
2102 // We have a class message, and T is the type we're
2103 // messaging. Build source-location information for it.
2104 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2105 ReceiverType = CreateParsedType(T, TSInfo);
2106 return ObjCClassMessage;
2110 if (TypoCorrection Corrected = CorrectTypo(
2111 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
2112 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
2113 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
2114 if (Corrected.isKeyword()) {
2115 // If we've found the keyword "super" (the only keyword that would be
2116 // returned by CorrectTypo), this is a send to super.
2117 diagnoseTypo(Corrected,
2118 PDiag(diag::err_unknown_receiver_suggest) << Name);
2119 return ObjCSuperMessage;
2120 } else if (ObjCInterfaceDecl *Class =
2121 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2122 // If we found a declaration, correct when it refers to an Objective-C
2124 diagnoseTypo(Corrected,
2125 PDiag(diag::err_unknown_receiver_suggest) << Name);
2126 QualType T = Context.getObjCInterfaceType(Class);
2127 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2128 ReceiverType = CreateParsedType(T, TSInfo);
2129 return ObjCClassMessage;
2133 // Fall back: let the parser try to parse it as an instance message.
2134 return ObjCInstanceMessage;
2137 ExprResult Sema::ActOnSuperMessage(Scope *S,
2138 SourceLocation SuperLoc,
2140 SourceLocation LBracLoc,
2141 ArrayRef<SourceLocation> SelectorLocs,
2142 SourceLocation RBracLoc,
2143 MultiExprArg Args) {
2144 // Determine whether we are inside a method or not.
2145 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
2147 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2151 ObjCInterfaceDecl *Class = Method->getClassInterface();
2153 Diag(SuperLoc, diag::error_no_super_class_message)
2154 << Method->getDeclName();
2158 QualType SuperTy(Class->getSuperClassType(), 0);
2159 if (SuperTy.isNull()) {
2160 // The current class does not have a superclass.
2161 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
2162 << Class->getIdentifier();
2166 // We are in a method whose class has a superclass, so 'super'
2167 // is acting as a keyword.
2168 if (Method->getSelector() == Sel)
2169 getCurFunction()->ObjCShouldCallSuper = false;
2171 if (Method->isInstanceMethod()) {
2172 // Since we are in an instance method, this is an instance
2173 // message to the superclass instance.
2174 SuperTy = Context.getObjCObjectPointerType(SuperTy);
2175 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2176 Sel, /*Method=*/nullptr,
2177 LBracLoc, SelectorLocs, RBracLoc, Args);
2180 // Since we are in a class method, this is a class message to
2182 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
2184 SuperLoc, Sel, /*Method=*/nullptr,
2185 LBracLoc, SelectorLocs, RBracLoc, Args);
2189 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2190 bool isSuperReceiver,
2193 ObjCMethodDecl *Method,
2194 MultiExprArg Args) {
2195 TypeSourceInfo *receiverTypeInfo = nullptr;
2196 if (!ReceiverType.isNull())
2197 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2199 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2200 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2201 Sel, Method, Loc, Loc, Loc, Args,
2202 /*isImplicit=*/true);
2206 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2208 bool (*refactor)(const ObjCMessageExpr *,
2209 const NSAPI &, edit::Commit &)) {
2210 SourceLocation MsgLoc = Msg->getExprLoc();
2211 if (S.Diags.isIgnored(DiagID, MsgLoc))
2214 SourceManager &SM = S.SourceMgr;
2215 edit::Commit ECommit(SM, S.LangOpts);
2216 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2217 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2218 << Msg->getSelector() << Msg->getSourceRange();
2219 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2220 if (!ECommit.isCommitable())
2222 for (edit::Commit::edit_iterator
2223 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2224 const edit::Commit::Edit &Edit = *I;
2225 switch (Edit.Kind) {
2226 case edit::Commit::Act_Insert:
2227 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2231 case edit::Commit::Act_InsertFromRange:
2232 Builder.AddFixItHint(
2233 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2234 Edit.getInsertFromRange(SM),
2237 case edit::Commit::Act_Remove:
2238 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2245 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2246 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2247 edit::rewriteObjCRedundantCallWithLiteral);
2250 /// \brief Diagnose use of %s directive in an NSString which is being passed
2251 /// as formatting string to formatting method.
2253 DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2254 ObjCMethodDecl *Method,
2256 Expr **Args, unsigned NumArgs) {
2258 bool Format = false;
2259 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2260 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
2265 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2266 if (S.GetFormatNSStringIdx(I, Idx)) {
2272 if (!Format || NumArgs <= Idx)
2275 Expr *FormatExpr = Args[Idx];
2276 if (ObjCStringLiteral *OSL =
2277 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2278 StringLiteral *FormatString = OSL->getString();
2279 if (S.FormatStringHasSArg(FormatString)) {
2280 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2283 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2284 << Method->getDeclName();
2289 /// \brief Build an Objective-C class message expression.
2291 /// This routine takes care of both normal class messages and
2292 /// class messages to the superclass.
2294 /// \param ReceiverTypeInfo Type source information that describes the
2295 /// receiver of this message. This may be NULL, in which case we are
2296 /// sending to the superclass and \p SuperLoc must be a valid source
2299 /// \param ReceiverType The type of the object receiving the
2300 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2301 /// type as that refers to. For a superclass send, this is the type of
2304 /// \param SuperLoc The location of the "super" keyword in a
2305 /// superclass message.
2307 /// \param Sel The selector to which the message is being sent.
2309 /// \param Method The method that this class message is invoking, if
2312 /// \param LBracLoc The location of the opening square bracket ']'.
2314 /// \param RBracLoc The location of the closing square bracket ']'.
2316 /// \param ArgsIn The message arguments.
2317 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
2318 QualType ReceiverType,
2319 SourceLocation SuperLoc,
2321 ObjCMethodDecl *Method,
2322 SourceLocation LBracLoc,
2323 ArrayRef<SourceLocation> SelectorLocs,
2324 SourceLocation RBracLoc,
2325 MultiExprArg ArgsIn,
2327 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
2328 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
2329 if (LBracLoc.isInvalid()) {
2330 Diag(Loc, diag::err_missing_open_square_message_send)
2331 << FixItHint::CreateInsertion(Loc, "[");
2334 SourceLocation SelLoc;
2335 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2336 SelLoc = SelectorLocs.front();
2340 if (ReceiverType->isDependentType()) {
2341 // If the receiver type is dependent, we can't type-check anything
2342 // at this point. Build a dependent expression.
2343 unsigned NumArgs = ArgsIn.size();
2344 Expr **Args = ArgsIn.data();
2345 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2346 return ObjCMessageExpr::Create(
2347 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2348 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2352 // Find the class to which we are sending this message.
2353 ObjCInterfaceDecl *Class = nullptr;
2354 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2355 if (!ClassType || !(Class = ClassType->getInterface())) {
2356 Diag(Loc, diag::err_invalid_receiver_class_message)
2360 assert(Class && "We don't know which class we're messaging?");
2361 // objc++ diagnoses during typename annotation.
2362 if (!getLangOpts().CPlusPlus)
2363 (void)DiagnoseUseOfDecl(Class, SelLoc);
2364 // Find the method we are messaging.
2366 SourceRange TypeRange
2367 = SuperLoc.isValid()? SourceRange(SuperLoc)
2368 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
2369 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
2370 (getLangOpts().ObjCAutoRefCount
2371 ? diag::err_arc_receiver_forward_class
2372 : diag::warn_receiver_forward_class),
2374 // A forward class used in messaging is treated as a 'Class'
2375 Method = LookupFactoryMethodInGlobalPool(Sel,
2376 SourceRange(LBracLoc, RBracLoc));
2377 if (Method && !getLangOpts().ObjCAutoRefCount)
2378 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2379 << Method->getDeclName();
2382 Method = Class->lookupClassMethod(Sel);
2384 // If we have an implementation in scope, check "private" methods.
2386 Method = Class->lookupPrivateClassMethod(Sel);
2388 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2392 // Check the argument types and determine the result type.
2393 QualType ReturnType;
2394 ExprValueKind VK = VK_RValue;
2396 unsigned NumArgs = ArgsIn.size();
2397 Expr **Args = ArgsIn.data();
2398 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2401 SuperLoc.isValid(), LBracLoc, RBracLoc,
2406 if (Method && !Method->getReturnType()->isVoidType() &&
2407 RequireCompleteType(LBracLoc, Method->getReturnType(),
2408 diag::err_illegal_message_expr_incomplete_type))
2411 // Warn about explicit call of +initialize on its own class. But not on 'super'.
2412 if (Method && Method->getMethodFamily() == OMF_initialize) {
2413 if (!SuperLoc.isValid()) {
2414 const ObjCInterfaceDecl *ID =
2415 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2417 Diag(Loc, diag::warn_direct_initialize_call);
2418 Diag(Method->getLocation(), diag::note_method_declared_at)
2419 << Method->getDeclName();
2422 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2423 // [super initialize] is allowed only within an +initialize implementation
2424 if (CurMeth->getMethodFamily() != OMF_initialize) {
2425 Diag(Loc, diag::warn_direct_super_initialize_call);
2426 Diag(Method->getLocation(), diag::note_method_declared_at)
2427 << Method->getDeclName();
2428 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2429 << CurMeth->getDeclName();
2434 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2436 // Construct the appropriate ObjCMessageExpr.
2437 ObjCMessageExpr *Result;
2438 if (SuperLoc.isValid())
2439 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2440 SuperLoc, /*IsInstanceSuper=*/false,
2441 ReceiverType, Sel, SelectorLocs,
2442 Method, makeArrayRef(Args, NumArgs),
2443 RBracLoc, isImplicit);
2445 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2446 ReceiverTypeInfo, Sel, SelectorLocs,
2447 Method, makeArrayRef(Args, NumArgs),
2448 RBracLoc, isImplicit);
2450 checkCocoaAPI(*this, Result);
2452 return MaybeBindToTemporary(Result);
2455 // ActOnClassMessage - used for both unary and keyword messages.
2456 // ArgExprs is optional - if it is present, the number of expressions
2457 // is obtained from Sel.getNumArgs().
2458 ExprResult Sema::ActOnClassMessage(Scope *S,
2459 ParsedType Receiver,
2461 SourceLocation LBracLoc,
2462 ArrayRef<SourceLocation> SelectorLocs,
2463 SourceLocation RBracLoc,
2464 MultiExprArg Args) {
2465 TypeSourceInfo *ReceiverTypeInfo;
2466 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2467 if (ReceiverType.isNull())
2471 if (!ReceiverTypeInfo)
2472 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2474 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
2475 /*SuperLoc=*/SourceLocation(), Sel,
2476 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2480 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2481 QualType ReceiverType,
2484 ObjCMethodDecl *Method,
2485 MultiExprArg Args) {
2486 return BuildInstanceMessage(Receiver, ReceiverType,
2487 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2488 Sel, Method, Loc, Loc, Loc, Args,
2489 /*isImplicit=*/true);
2492 /// \brief Build an Objective-C instance message expression.
2494 /// This routine takes care of both normal instance messages and
2495 /// instance messages to the superclass instance.
2497 /// \param Receiver The expression that computes the object that will
2498 /// receive this message. This may be empty, in which case we are
2499 /// sending to the superclass instance and \p SuperLoc must be a valid
2500 /// source location.
2502 /// \param ReceiverType The (static) type of the object receiving the
2503 /// message. When a \p Receiver expression is provided, this is the
2504 /// same type as that expression. For a superclass instance send, this
2505 /// is a pointer to the type of the superclass.
2507 /// \param SuperLoc The location of the "super" keyword in a
2508 /// superclass instance message.
2510 /// \param Sel The selector to which the message is being sent.
2512 /// \param Method The method that this instance message is invoking, if
2515 /// \param LBracLoc The location of the opening square bracket ']'.
2517 /// \param RBracLoc The location of the closing square bracket ']'.
2519 /// \param ArgsIn The message arguments.
2520 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2521 QualType ReceiverType,
2522 SourceLocation SuperLoc,
2524 ObjCMethodDecl *Method,
2525 SourceLocation LBracLoc,
2526 ArrayRef<SourceLocation> SelectorLocs,
2527 SourceLocation RBracLoc,
2528 MultiExprArg ArgsIn,
2530 // The location of the receiver.
2531 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
2532 SourceRange RecRange =
2533 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2534 SourceLocation SelLoc;
2535 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2536 SelLoc = SelectorLocs.front();
2540 if (LBracLoc.isInvalid()) {
2541 Diag(Loc, diag::err_missing_open_square_message_send)
2542 << FixItHint::CreateInsertion(Loc, "[");
2546 // If we have a receiver expression, perform appropriate promotions
2547 // and determine receiver type.
2549 if (Receiver->hasPlaceholderType()) {
2551 if (Receiver->getType() == Context.UnknownAnyTy)
2552 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2554 Result = CheckPlaceholderExpr(Receiver);
2555 if (Result.isInvalid()) return ExprError();
2556 Receiver = Result.get();
2559 if (Receiver->isTypeDependent()) {
2560 // If the receiver is type-dependent, we can't type-check anything
2561 // at this point. Build a dependent expression.
2562 unsigned NumArgs = ArgsIn.size();
2563 Expr **Args = ArgsIn.data();
2564 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2565 return ObjCMessageExpr::Create(
2566 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2567 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2568 RBracLoc, isImplicit);
2571 // If necessary, apply function/array conversion to the receiver.
2572 // C99 6.7.5.3p[7,8].
2573 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2574 if (Result.isInvalid())
2576 Receiver = Result.get();
2577 ReceiverType = Receiver->getType();
2579 // If the receiver is an ObjC pointer, a block pointer, or an
2580 // __attribute__((NSObject)) pointer, we don't need to do any
2581 // special conversion in order to look up a receiver.
2582 if (ReceiverType->isObjCRetainableType()) {
2584 } else if (!getLangOpts().ObjCAutoRefCount &&
2585 !Context.getObjCIdType().isNull() &&
2586 (ReceiverType->isPointerType() ||
2587 ReceiverType->isIntegerType())) {
2588 // Implicitly convert integers and pointers to 'id' but emit a warning.
2590 Diag(Loc, diag::warn_bad_receiver_type)
2592 << Receiver->getSourceRange();
2593 if (ReceiverType->isPointerType()) {
2594 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2595 CK_CPointerToObjCPointerCast).get();
2597 // TODO: specialized warning on null receivers?
2598 bool IsNull = Receiver->isNullPointerConstant(Context,
2599 Expr::NPC_ValueDependentIsNull);
2600 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2601 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2604 ReceiverType = Receiver->getType();
2605 } else if (getLangOpts().CPlusPlus) {
2606 // The receiver must be a complete type.
2607 if (RequireCompleteType(Loc, Receiver->getType(),
2608 diag::err_incomplete_receiver_type))
2611 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2612 if (result.isUsable()) {
2613 Receiver = result.get();
2614 ReceiverType = Receiver->getType();
2619 // There's a somewhat weird interaction here where we assume that we
2620 // won't actually have a method unless we also don't need to do some
2621 // of the more detailed type-checking on the receiver.
2624 // Handle messages to id and __kindof types (where we use the
2625 // global method pool).
2626 // FIXME: The type bound is currently ignored by lookup in the
2628 const ObjCObjectType *typeBound = nullptr;
2629 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2631 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
2632 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2633 Method = LookupInstanceMethodInGlobalPool(Sel,
2634 SourceRange(LBracLoc, RBracLoc),
2637 Method = LookupFactoryMethodInGlobalPool(Sel,
2638 SourceRange(LBracLoc,RBracLoc),
2641 if (ObjCMethodDecl *BestMethod =
2642 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2643 Method = BestMethod;
2644 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2645 SourceRange(LBracLoc, RBracLoc),
2646 receiverIsIdLike)) {
2647 DiagnoseUseOfDecl(Method, SelLoc);
2650 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
2651 ReceiverType->isObjCQualifiedClassType()) {
2652 // Handle messages to Class.
2653 // We allow sending a message to a qualified Class ("Class<foo>"), which
2654 // is ok as long as one of the protocols implements the selector (if not,
2656 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2657 const ObjCObjectPointerType *QClassTy
2658 = ReceiverType->getAsObjCQualifiedClassType();
2659 // Search protocols for class methods.
2660 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2662 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2663 // warn if instance method found for a Class message.
2665 Diag(SelLoc, diag::warn_instance_method_on_class_found)
2666 << Method->getSelector() << Sel;
2667 Diag(Method->getLocation(), diag::note_method_declared_at)
2668 << Method->getDeclName();
2672 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2673 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2674 // First check the public methods in the class interface.
2675 Method = ClassDecl->lookupClassMethod(Sel);
2678 Method = ClassDecl->lookupPrivateClassMethod(Sel);
2680 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2684 // If not messaging 'self', look for any factory method named 'Sel'.
2685 if (!Receiver || !isSelfExpr(Receiver)) {
2686 Method = LookupFactoryMethodInGlobalPool(Sel,
2687 SourceRange(LBracLoc, RBracLoc));
2689 // If no class (factory) method was found, check if an _instance_
2690 // method of the same name exists in the root class only.
2691 Method = LookupInstanceMethodInGlobalPool(Sel,
2692 SourceRange(LBracLoc, RBracLoc));
2694 if (const ObjCInterfaceDecl *ID =
2695 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2696 if (ID->getSuperClass())
2697 Diag(SelLoc, diag::warn_root_inst_method_not_found)
2698 << Sel << SourceRange(LBracLoc, RBracLoc);
2702 if (ObjCMethodDecl *BestMethod =
2703 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2704 Method = BestMethod;
2709 ObjCInterfaceDecl *ClassDecl = nullptr;
2711 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2712 // long as one of the protocols implements the selector (if not, warn).
2713 // And as long as message is not deprecated/unavailable (warn if it is).
2714 if (const ObjCObjectPointerType *QIdTy
2715 = ReceiverType->getAsObjCQualifiedIdType()) {
2716 // Search protocols for instance methods.
2717 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2719 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2720 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2722 } else if (const ObjCObjectPointerType *OCIType
2723 = ReceiverType->getAsObjCInterfacePointerType()) {
2724 // We allow sending a message to a pointer to an interface (an object).
2725 ClassDecl = OCIType->getInterfaceDecl();
2727 // Try to complete the type. Under ARC, this is a hard error from which
2728 // we don't try to recover.
2729 const ObjCInterfaceDecl *forwardClass = nullptr;
2730 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
2731 getLangOpts().ObjCAutoRefCount
2732 ? diag::err_arc_receiver_forward_instance
2733 : diag::warn_receiver_forward_instance,
2734 Receiver? Receiver->getSourceRange()
2735 : SourceRange(SuperLoc))) {
2736 if (getLangOpts().ObjCAutoRefCount)
2739 forwardClass = OCIType->getInterfaceDecl();
2740 Diag(Receiver ? Receiver->getLocStart()
2741 : SuperLoc, diag::note_receiver_is_id);
2744 Method = ClassDecl->lookupInstanceMethod(Sel);
2748 // Search protocol qualifiers.
2749 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2752 // If we have implementations in scope, check "private" methods.
2753 Method = ClassDecl->lookupPrivateMethod(Sel);
2755 if (!Method && getLangOpts().ObjCAutoRefCount) {
2756 Diag(SelLoc, diag::err_arc_may_not_respond)
2757 << OCIType->getPointeeType() << Sel << RecRange
2758 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
2762 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2763 // If we still haven't found a method, look in the global pool. This
2764 // behavior isn't very desirable, however we need it for GCC
2765 // compatibility. FIXME: should we deviate??
2766 if (OCIType->qual_empty()) {
2767 Method = LookupInstanceMethodInGlobalPool(Sel,
2768 SourceRange(LBracLoc, RBracLoc));
2770 if (auto BestMethod =
2771 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2772 Method = BestMethod;
2773 AreMultipleMethodsInGlobalPool(Sel, Method,
2774 SourceRange(LBracLoc, RBracLoc),
2777 if (Method && !forwardClass)
2778 Diag(SelLoc, diag::warn_maynot_respond)
2779 << OCIType->getInterfaceDecl()->getIdentifier()
2784 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
2787 // Reject other random receiver types (e.g. structs).
2788 Diag(Loc, diag::err_bad_receiver_type)
2789 << ReceiverType << Receiver->getSourceRange();
2795 FunctionScopeInfo *DIFunctionScopeInfo =
2796 (Method && Method->getMethodFamily() == OMF_init)
2797 ? getEnclosingFunction() : nullptr;
2799 if (DIFunctionScopeInfo &&
2800 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
2801 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2802 bool isDesignatedInitChain = false;
2803 if (SuperLoc.isValid()) {
2804 if (const ObjCObjectPointerType *
2805 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2806 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
2807 // Either we know this is a designated initializer or we
2808 // conservatively assume it because we don't know for sure.
2809 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2810 ID->isDesignatedInitializer(Sel)) {
2811 isDesignatedInitChain = true;
2812 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
2817 if (!isDesignatedInitChain) {
2818 const ObjCMethodDecl *InitMethod = nullptr;
2820 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2821 assert(isDesignated && InitMethod);
2823 Diag(SelLoc, SuperLoc.isValid() ?
2824 diag::warn_objc_designated_init_non_designated_init_call :
2825 diag::warn_objc_designated_init_non_super_designated_init_call);
2826 Diag(InitMethod->getLocation(),
2827 diag::note_objc_designated_init_marked_here);
2831 if (DIFunctionScopeInfo &&
2832 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
2833 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2834 if (SuperLoc.isValid()) {
2835 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2837 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
2841 // Check the message arguments.
2842 unsigned NumArgs = ArgsIn.size();
2843 Expr **Args = ArgsIn.data();
2844 QualType ReturnType;
2845 ExprValueKind VK = VK_RValue;
2846 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2847 ReceiverType->isObjCQualifiedClassType());
2848 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2849 Sel, SelectorLocs, Method,
2850 ClassMessage, SuperLoc.isValid(),
2851 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
2854 if (Method && !Method->getReturnType()->isVoidType() &&
2855 RequireCompleteType(LBracLoc, Method->getReturnType(),
2856 diag::err_illegal_message_expr_incomplete_type))
2859 // In ARC, forbid the user from sending messages to
2860 // retain/release/autorelease/dealloc/retainCount explicitly.
2861 if (getLangOpts().ObjCAutoRefCount) {
2862 ObjCMethodFamily family =
2863 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2867 checkInitMethod(Method, ReceiverType);
2873 case OMF_mutableCopy:
2876 case OMF_initialize:
2882 case OMF_autorelease:
2883 case OMF_retainCount:
2884 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2888 case OMF_performSelector:
2889 if (Method && NumArgs >= 1) {
2890 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2891 Selector ArgSel = SelExp->getSelector();
2892 ObjCMethodDecl *SelMethod =
2893 LookupInstanceMethodInGlobalPool(ArgSel,
2894 SelExp->getSourceRange());
2897 LookupFactoryMethodInGlobalPool(ArgSel,
2898 SelExp->getSourceRange());
2900 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2901 switch (SelFamily) {
2904 case OMF_mutableCopy:
2908 // Issue error, unless ns_returns_not_retained.
2909 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2910 // selector names a +1 method
2912 diag::err_arc_perform_selector_retains);
2913 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2914 << SelMethod->getDeclName();
2918 // +0 call. OK. unless ns_returns_retained.
2919 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2920 // selector names a +1 method
2922 diag::err_arc_perform_selector_retains);
2923 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2924 << SelMethod->getDeclName();
2930 // error (may leak).
2931 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
2932 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2939 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2941 // Construct the appropriate ObjCMessageExpr instance.
2942 ObjCMessageExpr *Result;
2943 if (SuperLoc.isValid())
2944 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2945 SuperLoc, /*IsInstanceSuper=*/true,
2946 ReceiverType, Sel, SelectorLocs, Method,
2947 makeArrayRef(Args, NumArgs), RBracLoc,
2950 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2951 Receiver, Sel, SelectorLocs, Method,
2952 makeArrayRef(Args, NumArgs), RBracLoc,
2955 checkCocoaAPI(*this, Result);
2958 if (getLangOpts().ObjCAutoRefCount) {
2959 // In ARC, annotate delegate init calls.
2960 if (Result->getMethodFamily() == OMF_init &&
2961 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2962 // Only consider init calls *directly* in init implementations,
2963 // not within blocks.
2964 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2965 if (method && method->getMethodFamily() == OMF_init) {
2966 // The implicit assignment to self means we also don't want to
2967 // consume the result.
2968 Result->setDelegateInitCall(true);
2973 // In ARC, check for message sends which are likely to introduce
2975 checkRetainCycles(Result);
2977 if (!isImplicit && Method) {
2978 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2980 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2981 if (!IsWeak && Sel.isUnarySelector())
2982 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
2984 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
2985 getCurFunction()->recordUseOfWeak(Result, Prop);
2990 CheckObjCCircularContainer(Result);
2992 return MaybeBindToTemporary(Result);
2995 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2996 if (ObjCSelectorExpr *OSE =
2997 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2998 Selector Sel = OSE->getSelector();
2999 SourceLocation Loc = OSE->getAtLoc();
3000 auto Pos = S.ReferencedSelectors.find(Sel);
3001 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3002 S.ReferencedSelectors.erase(Pos);
3006 // ActOnInstanceMessage - used for both unary and keyword messages.
3007 // ArgExprs is optional - if it is present, the number of expressions
3008 // is obtained from Sel.getNumArgs().
3009 ExprResult Sema::ActOnInstanceMessage(Scope *S,
3012 SourceLocation LBracLoc,
3013 ArrayRef<SourceLocation> SelectorLocs,
3014 SourceLocation RBracLoc,
3015 MultiExprArg Args) {
3019 // A ParenListExpr can show up while doing error recovery with invalid code.
3020 if (isa<ParenListExpr>(Receiver)) {
3021 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3022 if (Result.isInvalid()) return ExprError();
3023 Receiver = Result.get();
3026 if (RespondsToSelectorSel.isNull()) {
3027 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3028 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3030 if (Sel == RespondsToSelectorSel)
3031 RemoveSelectorFromWarningCache(*this, Args[0]);
3033 return BuildInstanceMessage(Receiver, Receiver->getType(),
3034 /*SuperLoc=*/SourceLocation(), Sel,
3035 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3039 enum ARCConversionTypeClass {
3040 /// int, void, struct A
3046 /// id*, id***, void (^*)(),
3047 ACTC_indirectRetainable,
3049 /// void* might be a normal C type, or it might a CF type.
3055 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3056 return (ACTC == ACTC_retainable ||
3057 ACTC == ACTC_coreFoundation ||
3058 ACTC == ACTC_voidPtr);
3060 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3061 return ACTC == ACTC_none ||
3062 ACTC == ACTC_voidPtr ||
3063 ACTC == ACTC_coreFoundation;
3066 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
3067 bool isIndirect = false;
3069 // Ignore an outermost reference type.
3070 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
3071 type = ref->getPointeeType();
3075 // Drill through pointers and arrays recursively.
3077 if (const PointerType *ptr = type->getAs<PointerType>()) {
3078 type = ptr->getPointeeType();
3080 // The first level of pointer may be the innermost pointer on a CF type.
3082 if (type->isVoidType()) return ACTC_voidPtr;
3083 if (type->isRecordType()) return ACTC_coreFoundation;
3085 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3086 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3094 if (type->isObjCARCBridgableType())
3095 return ACTC_indirectRetainable;
3099 if (type->isObjCARCBridgableType())
3100 return ACTC_retainable;
3106 /// A result from the cast checker.
3108 /// Cannot be casted.
3111 /// Can be safely retained or not retained.
3114 /// Can be casted at +0.
3117 /// Can be casted at +1.
3120 ACCResult merge(ACCResult left, ACCResult right) {
3121 if (left == right) return left;
3122 if (left == ACC_bottom) return right;
3123 if (right == ACC_bottom) return left;
3127 /// A checker which white-lists certain expressions whose conversion
3128 /// to or from retainable type would otherwise be forbidden in ARC.
3129 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3130 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3132 ASTContext &Context;
3133 ARCConversionTypeClass SourceClass;
3134 ARCConversionTypeClass TargetClass;
3137 static bool isCFType(QualType type) {
3138 // Someday this can use ns_bridged. For now, it has to do this.
3139 return type->isCARCBridgableType();
3143 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
3144 ARCConversionTypeClass target, bool diagnose)
3145 : Context(Context), SourceClass(source), TargetClass(target),
3146 Diagnose(diagnose) {}
3149 ACCResult Visit(Expr *e) {
3150 return super::Visit(e->IgnoreParens());
3153 ACCResult VisitStmt(Stmt *s) {
3157 /// Null pointer constants can be casted however you please.
3158 ACCResult VisitExpr(Expr *e) {
3159 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3164 /// Objective-C string literals can be safely casted.
3165 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3166 // If we're casting to any retainable type, go ahead. Global
3167 // strings are immune to retains, so this is bottom.
3168 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3173 /// Look through certain implicit and explicit casts.
3174 ACCResult VisitCastExpr(CastExpr *e) {
3175 switch (e->getCastKind()) {
3176 case CK_NullToPointer:
3180 case CK_LValueToRValue:
3182 case CK_CPointerToObjCPointerCast:
3183 case CK_BlockPointerToObjCPointerCast:
3184 case CK_AnyPointerToBlockPointerCast:
3185 return Visit(e->getSubExpr());
3192 /// Look through unary extension.
3193 ACCResult VisitUnaryExtension(UnaryOperator *e) {
3194 return Visit(e->getSubExpr());
3197 /// Ignore the LHS of a comma operator.
3198 ACCResult VisitBinComma(BinaryOperator *e) {
3199 return Visit(e->getRHS());
3202 /// Conditional operators are okay if both sides are okay.
3203 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3204 ACCResult left = Visit(e->getTrueExpr());
3205 if (left == ACC_invalid) return ACC_invalid;
3206 return merge(left, Visit(e->getFalseExpr()));
3209 /// Look through pseudo-objects.
3210 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3211 // If we're getting here, we should always have a result.
3212 return Visit(e->getResultExpr());
3215 /// Statement expressions are okay if their result expression is okay.
3216 ACCResult VisitStmtExpr(StmtExpr *e) {
3217 return Visit(e->getSubStmt()->body_back());
3220 /// Some declaration references are okay.
3221 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
3222 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
3223 // References to global constants are okay.
3224 if (isAnyRetainable(TargetClass) &&
3225 isAnyRetainable(SourceClass) &&
3227 var->getStorageClass() == SC_Extern &&
3228 var->getType().isConstQualified()) {
3230 // In system headers, they can also be assumed to be immune to retains.
3231 // These are things like 'kCFStringTransformToLatin'.
3232 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3235 return ACC_plusZero;
3242 /// Some calls are okay.
3243 ACCResult VisitCallExpr(CallExpr *e) {
3244 if (FunctionDecl *fn = e->getDirectCallee())
3245 if (ACCResult result = checkCallToFunction(fn))
3248 return super::VisitCallExpr(e);
3251 ACCResult checkCallToFunction(FunctionDecl *fn) {
3252 // Require a CF*Ref return type.
3253 if (!isCFType(fn->getReturnType()))
3256 if (!isAnyRetainable(TargetClass))
3259 // Honor an explicit 'not retained' attribute.
3260 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3261 return ACC_plusZero;
3263 // Honor an explicit 'retained' attribute, except that for
3264 // now we're not going to permit implicit handling of +1 results,
3265 // because it's a bit frightening.
3266 if (fn->hasAttr<CFReturnsRetainedAttr>())
3267 return Diagnose ? ACC_plusOne
3268 : ACC_invalid; // ACC_plusOne if we start accepting this
3270 // Recognize this specific builtin function, which is used by CFSTR.
3271 unsigned builtinID = fn->getBuiltinID();
3272 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3275 // Otherwise, don't do anything implicit with an unaudited function.
3276 if (!fn->hasAttr<CFAuditedTransferAttr>())
3279 // Otherwise, it's +0 unless it follows the create convention.
3280 if (ento::coreFoundation::followsCreateRule(fn))
3281 return Diagnose ? ACC_plusOne
3282 : ACC_invalid; // ACC_plusOne if we start accepting this
3284 return ACC_plusZero;
3287 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3288 return checkCallToMethod(e->getMethodDecl());
3291 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3292 ObjCMethodDecl *method;
3293 if (e->isExplicitProperty())
3294 method = e->getExplicitProperty()->getGetterMethodDecl();
3296 method = e->getImplicitPropertyGetter();
3297 return checkCallToMethod(method);
3300 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3301 if (!method) return ACC_invalid;
3303 // Check for message sends to functions returning CF types. We
3304 // just obey the Cocoa conventions with these, even though the
3305 // return type is CF.
3306 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
3309 // If the method is explicitly marked not-retained, it's +0.
3310 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3311 return ACC_plusZero;
3313 // If the method is explicitly marked as returning retained, or its
3314 // selector follows a +1 Cocoa convention, treat it as +1.
3315 if (method->hasAttr<CFReturnsRetainedAttr>())
3318 switch (method->getSelector().getMethodFamily()) {
3321 case OMF_mutableCopy:
3326 // Otherwise, treat it as +0.
3327 return ACC_plusZero;
3333 bool Sema::isKnownName(StringRef name) {
3336 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
3337 Sema::LookupOrdinaryName);
3338 return LookupName(R, TUScope, false);
3341 static void addFixitForObjCARCConversion(Sema &S,
3342 DiagnosticBuilder &DiagB,
3343 Sema::CheckedConversionKind CCK,
3344 SourceLocation afterLParen,
3348 const char *bridgeKeyword,
3349 const char *CFBridgeName) {
3350 // We handle C-style and implicit casts here.
3352 case Sema::CCK_ImplicitConversion:
3353 case Sema::CCK_CStyleCast:
3354 case Sema::CCK_OtherCast:
3356 case Sema::CCK_FunctionalCast:
3361 if (CCK == Sema::CCK_OtherCast) {
3362 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3363 SourceRange range(NCE->getOperatorLoc(),
3364 NCE->getAngleBrackets().getEnd());
3365 SmallString<32> BridgeCall;
3367 SourceManager &SM = S.getSourceManager();
3368 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3369 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3372 BridgeCall += CFBridgeName;
3373 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3377 Expr *castedE = castExpr;
3378 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3379 castedE = CCE->getSubExpr();
3380 castedE = castedE->IgnoreImpCasts();
3381 SourceRange range = castedE->getSourceRange();
3383 SmallString<32> BridgeCall;
3385 SourceManager &SM = S.getSourceManager();
3386 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3387 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3390 BridgeCall += CFBridgeName;
3392 if (isa<ParenExpr>(castedE)) {
3393 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3397 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3399 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3400 S.PP.getLocForEndOfToken(range.getEnd()),
3406 if (CCK == Sema::CCK_CStyleCast) {
3407 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
3408 } else if (CCK == Sema::CCK_OtherCast) {
3409 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3410 std::string castCode = "(";
3411 castCode += bridgeKeyword;
3412 castCode += castType.getAsString();
3414 SourceRange Range(NCE->getOperatorLoc(),
3415 NCE->getAngleBrackets().getEnd());
3416 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3419 std::string castCode = "(";
3420 castCode += bridgeKeyword;
3421 castCode += castType.getAsString();
3423 Expr *castedE = castExpr->IgnoreImpCasts();
3424 SourceRange range = castedE->getSourceRange();
3425 if (isa<ParenExpr>(castedE)) {
3426 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3430 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3432 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3433 S.PP.getLocForEndOfToken(range.getEnd()),
3439 template <typename T>
3440 static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3441 TypedefNameDecl *TDNDecl = TD->getDecl();
3442 QualType QT = TDNDecl->getUnderlyingType();
3443 if (QT->isPointerType()) {
3444 QT = QT->getPointeeType();
3445 if (const RecordType *RT = QT->getAs<RecordType>())
3446 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
3447 return RD->getAttr<T>();
3452 static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3453 TypedefNameDecl *&TDNDecl) {
3454 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3455 TDNDecl = TD->getDecl();
3456 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3457 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3459 T = TDNDecl->getUnderlyingType();
3465 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3466 QualType castType, ARCConversionTypeClass castACTC,
3467 Expr *castExpr, Expr *realCast,
3468 ARCConversionTypeClass exprACTC,
3469 Sema::CheckedConversionKind CCK) {
3470 SourceLocation loc =
3471 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
3473 if (S.makeUnavailableInSystemHeader(loc,
3474 "converts between Objective-C and C pointers in -fobjc-arc"))
3477 QualType castExprType = castExpr->getType();
3478 TypedefNameDecl *TDNDecl = nullptr;
3479 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3480 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3481 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3482 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3485 unsigned srcKind = 0;
3488 case ACTC_coreFoundation:
3490 srcKind = (castExprType->isPointerType() ? 1 : 0);
3492 case ACTC_retainable:
3493 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3495 case ACTC_indirectRetainable:
3500 // Check whether this could be fixed with a bridge cast.
3501 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3502 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
3504 // Bridge from an ARC type to a CF type.
3505 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
3507 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3508 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3509 << 2 // of C pointer type
3511 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3514 << castExpr->getSourceRange();
3515 bool br = S.isKnownName("CFBridgingRelease");
3516 ACCResult CreateRule =
3517 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3518 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3519 if (CreateRule != ACC_plusOne)
3521 DiagnosticBuilder DiagB =
3522 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3523 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3525 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3526 castType, castExpr, realCast, "__bridge ",
3529 if (CreateRule != ACC_plusZero)
3531 DiagnosticBuilder DiagB =
3532 (CCK == Sema::CCK_OtherCast && !br) ?
3533 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3534 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3535 diag::note_arc_bridge_transfer)
3536 << castExprType << br;
3538 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3539 castType, castExpr, realCast, "__bridge_transfer ",
3540 br ? "CFBridgingRelease" : nullptr);
3546 // Bridge from a CF type to an ARC type.
3547 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
3548 bool br = S.isKnownName("CFBridgingRetain");
3549 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3550 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3551 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3553 << 2 // to C pointer type
3556 << castExpr->getSourceRange();
3557 ACCResult CreateRule =
3558 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3559 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3560 if (CreateRule != ACC_plusOne)
3562 DiagnosticBuilder DiagB =
3563 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3564 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3565 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3566 castType, castExpr, realCast, "__bridge ",
3569 if (CreateRule != ACC_plusZero)
3571 DiagnosticBuilder DiagB =
3572 (CCK == Sema::CCK_OtherCast && !br) ?
3573 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3574 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3575 diag::note_arc_bridge_retained)
3578 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3579 castType, castExpr, realCast, "__bridge_retained ",
3580 br ? "CFBridgingRetain" : nullptr);
3586 S.Diag(loc, diag::err_arc_mismatched_cast)
3587 << (CCK != Sema::CCK_ImplicitConversion)
3588 << srcKind << castExprType << castType
3589 << castRange << castExpr->getSourceRange();
3592 template <typename TB>
3593 static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3594 bool &HadTheAttribute, bool warn) {
3595 QualType T = castExpr->getType();
3596 HadTheAttribute = false;
3597 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3598 TypedefNameDecl *TDNDecl = TD->getDecl();
3599 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3600 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3601 HadTheAttribute = true;
3602 if (Parm->isStr("id"))
3605 NamedDecl *Target = nullptr;
3606 // Check for an existing type with this name.
3607 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3608 Sema::LookupOrdinaryName);
3609 if (S.LookupName(R, S.TUScope)) {
3610 Target = R.getFoundDecl();
3611 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3612 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3613 if (const ObjCObjectPointerType *InterfacePointerType =
3614 castType->getAsObjCInterfacePointerType()) {
3615 ObjCInterfaceDecl *CastClass
3616 = InterfacePointerType->getObjectType()->getInterface();
3617 if ((CastClass == ExprClass) ||
3618 (CastClass && CastClass->isSuperClassOf(ExprClass)))
3621 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3622 << T << Target->getName() << castType->getPointeeType();
3624 } else if (castType->isObjCIdType() ||
3625 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3626 castType, ExprClass)))
3627 // ok to cast to 'id'.
3628 // casting to id<p-list> is ok if bridge type adopts all of
3629 // p-list protocols.
3633 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3634 << T << Target->getName() << castType;
3635 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3636 S.Diag(Target->getLocStart(), diag::note_declared_at);
3641 } else if (!castType->isObjCIdType()) {
3642 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
3643 << castExpr->getType() << Parm;
3644 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3646 S.Diag(Target->getLocStart(), diag::note_declared_at);
3652 T = TDNDecl->getUnderlyingType();
3657 template <typename TB>
3658 static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3659 bool &HadTheAttribute, bool warn) {
3660 QualType T = castType;
3661 HadTheAttribute = false;
3662 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3663 TypedefNameDecl *TDNDecl = TD->getDecl();
3664 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3665 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3666 HadTheAttribute = true;
3667 if (Parm->isStr("id"))
3670 NamedDecl *Target = nullptr;
3671 // Check for an existing type with this name.
3672 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3673 Sema::LookupOrdinaryName);
3674 if (S.LookupName(R, S.TUScope)) {
3675 Target = R.getFoundDecl();
3676 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3677 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3678 if (const ObjCObjectPointerType *InterfacePointerType =
3679 castExpr->getType()->getAsObjCInterfacePointerType()) {
3680 ObjCInterfaceDecl *ExprClass
3681 = InterfacePointerType->getObjectType()->getInterface();
3682 if ((CastClass == ExprClass) ||
3683 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
3686 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3687 << castExpr->getType()->getPointeeType() << T;
3688 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3691 } else if (castExpr->getType()->isObjCIdType() ||
3692 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3693 castExpr->getType(), CastClass)))
3694 // ok to cast an 'id' expression to a CFtype.
3695 // ok to cast an 'id<plist>' expression to CFtype provided plist
3696 // adopts all of CFtype's ObjetiveC's class plist.
3700 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3701 << castExpr->getType() << castType;
3702 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3703 S.Diag(Target->getLocStart(), diag::note_declared_at);
3709 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3710 << castExpr->getType() << castType;
3711 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3713 S.Diag(Target->getLocStart(), diag::note_declared_at);
3718 T = TDNDecl->getUnderlyingType();
3723 void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
3724 if (!getLangOpts().ObjC1)
3726 // warn in presence of __bridge casting to or from a toll free bridge cast.
3727 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3728 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3729 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
3730 bool HasObjCBridgeAttr;
3731 bool ObjCBridgeAttrWillNotWarn =
3732 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3734 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3736 bool HasObjCBridgeMutableAttr;
3737 bool ObjCBridgeMutableAttrWillNotWarn =
3738 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3739 HasObjCBridgeMutableAttr, false);
3740 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3743 if (HasObjCBridgeAttr)
3744 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3746 else if (HasObjCBridgeMutableAttr)
3747 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3748 HasObjCBridgeMutableAttr, true);
3750 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
3751 bool HasObjCBridgeAttr;
3752 bool ObjCBridgeAttrWillNotWarn =
3753 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3755 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3757 bool HasObjCBridgeMutableAttr;
3758 bool ObjCBridgeMutableAttrWillNotWarn =
3759 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3760 HasObjCBridgeMutableAttr, false);
3761 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3764 if (HasObjCBridgeAttr)
3765 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3767 else if (HasObjCBridgeMutableAttr)
3768 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3769 HasObjCBridgeMutableAttr, true);
3773 void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3774 QualType SrcType = castExpr->getType();
3775 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3776 if (PRE->isExplicitProperty()) {
3777 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3778 SrcType = PDecl->getType();
3780 else if (PRE->isImplicitProperty()) {
3781 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3782 SrcType = Getter->getReturnType();
3787 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3788 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3789 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3791 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3792 castType, SrcType, castExpr);
3796 bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3798 if (!getLangOpts().ObjC1)
3800 ARCConversionTypeClass exprACTC =
3801 classifyTypeForARCConversion(castExpr->getType());
3802 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3803 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3804 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3805 CheckTollFreeBridgeCast(castType, castExpr);
3806 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3807 : CK_CPointerToObjCPointerCast;
3813 bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3814 QualType DestType, QualType SrcType,
3815 ObjCInterfaceDecl *&RelatedClass,
3816 ObjCMethodDecl *&ClassMethod,
3817 ObjCMethodDecl *&InstanceMethod,
3818 TypedefNameDecl *&TDNDecl,
3820 QualType T = CfToNs ? SrcType : DestType;
3821 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3825 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3826 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3827 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3830 NamedDecl *Target = nullptr;
3831 // Check for an existing type with this name.
3832 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3833 Sema::LookupOrdinaryName);
3834 if (!LookupName(R, TUScope)) {
3835 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
3836 << SrcType << DestType;
3837 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3840 Target = R.getFoundDecl();
3841 if (Target && isa<ObjCInterfaceDecl>(Target))
3842 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3844 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3845 << SrcType << DestType;
3846 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3848 Diag(Target->getLocStart(), diag::note_declared_at);
3852 // Check for an existing class method with the given selector name.
3853 if (CfToNs && CMId) {
3854 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3855 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3857 Diag(Loc, diag::err_objc_bridged_related_known_method)
3858 << SrcType << DestType << Sel << false;
3859 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3864 // Check for an existing instance method with the given selector name.
3865 if (!CfToNs && IMId) {
3866 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3867 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3868 if (!InstanceMethod) {
3869 Diag(Loc, diag::err_objc_bridged_related_known_method)
3870 << SrcType << DestType << Sel << true;
3871 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3879 Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
3880 QualType DestType, QualType SrcType,
3882 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3883 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3884 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3885 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3886 if (!CfToNs && !NsToCf)
3889 ObjCInterfaceDecl *RelatedClass;
3890 ObjCMethodDecl *ClassMethod = nullptr;
3891 ObjCMethodDecl *InstanceMethod = nullptr;
3892 TypedefNameDecl *TDNDecl = nullptr;
3893 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3894 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3898 // Implicit conversion from CF to ObjC object is needed.
3900 std::string ExpressionString = "[";
3901 ExpressionString += RelatedClass->getNameAsString();
3902 ExpressionString += " ";
3903 ExpressionString += ClassMethod->getSelector().getAsString();
3904 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3905 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
3906 Diag(Loc, diag::err_objc_bridged_related_known_method)
3907 << SrcType << DestType << ClassMethod->getSelector() << false
3908 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3909 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
3910 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3911 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3913 QualType receiverType =
3914 Context.getObjCInterfaceType(RelatedClass);
3916 Expr *args[] = { SrcExpr };
3917 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3918 ClassMethod->getLocation(),
3919 ClassMethod->getSelector(), ClassMethod,
3920 MultiExprArg(args, 1));
3921 SrcExpr = msg.get();
3926 // Implicit conversion from ObjC type to CF object is needed.
3927 if (InstanceMethod) {
3928 std::string ExpressionString;
3929 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3930 if (InstanceMethod->isPropertyAccessor())
3931 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3932 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3933 ExpressionString = ".";
3934 ExpressionString += PDecl->getNameAsString();
3935 Diag(Loc, diag::err_objc_bridged_related_known_method)
3936 << SrcType << DestType << InstanceMethod->getSelector() << true
3937 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3939 if (ExpressionString.empty()) {
3940 // Provide a fixit: [ObjectExpr InstanceMethod]
3941 ExpressionString = " ";
3942 ExpressionString += InstanceMethod->getSelector().getAsString();
3943 ExpressionString += "]";
3945 Diag(Loc, diag::err_objc_bridged_related_known_method)
3946 << SrcType << DestType << InstanceMethod->getSelector() << true
3947 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3948 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3950 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3951 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3954 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3955 InstanceMethod->getLocation(),
3956 InstanceMethod->getSelector(),
3957 InstanceMethod, None);
3958 SrcExpr = msg.get();
3965 Sema::ARCConversionResult
3966 Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
3967 Expr *&castExpr, CheckedConversionKind CCK,
3968 bool DiagnoseCFAudited,
3969 BinaryOperatorKind Opc) {
3970 QualType castExprType = castExpr->getType();
3972 // For the purposes of the classification, we assume reference types
3973 // will bind to temporaries.
3974 QualType effCastType = castType;
3975 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3976 effCastType = ref->getPointeeType();
3978 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3979 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
3980 if (exprACTC == castACTC) {
3981 // check for viablity and report error if casting an rvalue to a
3982 // life-time qualifier.
3983 if ((castACTC == ACTC_retainable) &&
3984 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
3985 (castType != castExprType)) {
3986 const Type *DT = castType.getTypePtr();
3987 QualType QDT = castType;
3988 // We desugar some types but not others. We ignore those
3989 // that cannot happen in a cast; i.e. auto, and those which
3990 // should not be de-sugared; i.e typedef.
3991 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3992 QDT = PT->desugar();
3993 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3994 QDT = TP->desugar();
3995 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3996 QDT = AT->desugar();
3997 if (QDT != castType &&
3998 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3999 SourceLocation loc =
4000 (castRange.isValid() ? castRange.getBegin()
4001 : castExpr->getExprLoc());
4002 Diag(loc, diag::err_arc_nolifetime_behavior);
4008 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4010 // Allow all of these types to be cast to integer types (but not
4012 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4015 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4016 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4017 // must be explicit.
4018 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4020 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
4021 CCK != CCK_ImplicitConversion)
4024 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
4025 // For invalid casts, fall through.
4029 // Do nothing for both bottom and +0.
4034 // If the result is +1, consume it here.
4036 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4037 CK_ARCConsumeObject, castExpr,
4038 nullptr, VK_RValue);
4039 ExprNeedsCleanups = true;
4043 // If this is a non-implicit cast from id or block type to a
4044 // CoreFoundation type, delay complaining in case the cast is used
4045 // in an acceptable context.
4046 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
4047 CCK != CCK_ImplicitConversion)
4048 return ACR_unbridged;
4050 // Do not issue bridge cast" diagnostic when implicit casting a cstring
4051 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
4053 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
4054 ConversionToObjCStringLiteralCheck(castType, castExpr))
4057 // Do not issue "bridge cast" diagnostic when implicit casting
4058 // a retainable object to a CF type parameter belonging to an audited
4059 // CF API function. Let caller issue a normal type mismatched diagnostic
4061 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4062 castACTC != ACTC_coreFoundation)
4063 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4064 (Opc == BO_NE || Opc == BO_EQ)))
4065 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4066 castExpr, castExpr, exprACTC, CCK);
4070 /// Given that we saw an expression with the ARCUnbridgedCastTy
4071 /// placeholder type, complain bitterly.
4072 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4073 // We expect the spurious ImplicitCastExpr to already have been stripped.
4074 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4075 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4077 SourceRange castRange;
4079 CheckedConversionKind CCK;
4081 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4082 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4083 castType = cast->getTypeAsWritten();
4084 CCK = CCK_CStyleCast;
4085 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4086 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4087 castType = cast->getTypeAsWritten();
4088 CCK = CCK_OtherCast;
4090 castType = cast->getType();
4091 CCK = CCK_ImplicitConversion;
4094 ARCConversionTypeClass castACTC =
4095 classifyTypeForARCConversion(castType.getNonReferenceType());
4097 Expr *castExpr = realCast->getSubExpr();
4098 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4100 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4101 castExpr, realCast, ACTC_retainable, CCK);
4104 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4105 /// type, remove the placeholder cast.
4106 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4107 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4109 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4110 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4111 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4112 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4113 assert(uo->getOpcode() == UO_Extension);
4114 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4115 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
4116 sub->getValueKind(), sub->getObjectKind(),
4117 uo->getOperatorLoc());
4118 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4119 assert(!gse->isResultDependent());
4121 unsigned n = gse->getNumAssocs();
4122 SmallVector<Expr*, 4> subExprs(n);
4123 SmallVector<TypeSourceInfo*, 4> subTypes(n);
4124 for (unsigned i = 0; i != n; ++i) {
4125 subTypes[i] = gse->getAssocTypeSourceInfo(i);
4126 Expr *sub = gse->getAssocExpr(i);
4127 if (i == gse->getResultIndex())
4128 sub = stripARCUnbridgedCast(sub);
4132 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
4133 gse->getControllingExpr(),
4135 gse->getDefaultLoc(),
4136 gse->getRParenLoc(),
4137 gse->containsUnexpandedParameterPack(),
4138 gse->getResultIndex());
4140 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4141 return cast<ImplicitCastExpr>(e)->getSubExpr();
4145 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4146 QualType exprType) {
4147 QualType canCastType =
4148 Context.getCanonicalType(castType).getUnqualifiedType();
4149 QualType canExprType =
4150 Context.getCanonicalType(exprType).getUnqualifiedType();
4151 if (isa<ObjCObjectPointerType>(canCastType) &&
4152 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4153 canExprType->isObjCObjectPointerType()) {
4154 if (const ObjCObjectPointerType *ObjT =
4155 canExprType->getAs<ObjCObjectPointerType>())
4156 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4157 return !ObjI->isArcWeakrefUnavailable();
4162 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
4163 static Expr *maybeUndoReclaimObject(Expr *e) {
4164 // For now, we just undo operands that are *immediately* reclaim
4165 // expressions, which prevents the vast majority of potential
4166 // problems here. To catch them all, we'd need to rebuild arbitrary
4167 // value-propagating subexpressions --- we can't reliably rebuild
4168 // in-place because of expression sharing.
4169 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4170 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
4171 return ice->getSubExpr();
4176 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4177 ObjCBridgeCastKind Kind,
4178 SourceLocation BridgeKeywordLoc,
4179 TypeSourceInfo *TSInfo,
4181 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4182 if (SubResult.isInvalid()) return ExprError();
4183 SubExpr = SubResult.get();
4185 QualType T = TSInfo->getType();
4186 QualType FromType = SubExpr->getType();
4190 bool MustConsume = false;
4191 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4192 // Okay: we'll build a dependent expression type.
4194 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4196 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4197 : CK_CPointerToObjCPointerCast);
4202 case OBC_BridgeRetained: {
4203 bool br = isKnownName("CFBridgingRelease");
4204 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4207 << (T->isBlockPointerType()? 1 : 0)
4209 << SubExpr->getSourceRange()
4211 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4212 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4213 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
4215 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4216 br ? "CFBridgingRelease "
4217 : "__bridge_transfer ");
4223 case OBC_BridgeTransfer:
4224 // We must consume the Objective-C object produced by the cast.
4228 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4233 // Reclaiming a value that's going to be __bridge-casted to CF
4234 // is very dangerous, so we don't do it.
4235 SubExpr = maybeUndoReclaimObject(SubExpr);
4238 case OBC_BridgeRetained:
4239 // Produce the object before casting it.
4240 SubExpr = ImplicitCastExpr::Create(Context, FromType,
4241 CK_ARCProduceObject,
4242 SubExpr, nullptr, VK_RValue);
4245 case OBC_BridgeTransfer: {
4246 bool br = isKnownName("CFBridgingRetain");
4247 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4248 << (FromType->isBlockPointerType()? 1 : 0)
4252 << SubExpr->getSourceRange()
4255 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4256 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4257 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
4259 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4260 br ? "CFBridgingRetain " : "__bridge_retained");
4267 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4268 << FromType << T << Kind
4269 << SubExpr->getSourceRange()
4270 << TSInfo->getTypeLoc().getSourceRange();
4274 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
4279 ExprNeedsCleanups = true;
4280 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
4281 nullptr, VK_RValue);
4287 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4288 SourceLocation LParenLoc,
4289 ObjCBridgeCastKind Kind,
4290 SourceLocation BridgeKeywordLoc,
4292 SourceLocation RParenLoc,
4294 TypeSourceInfo *TSInfo = nullptr;
4295 QualType T = GetTypeFromParser(Type, &TSInfo);
4296 if (Kind == OBC_Bridge)
4297 CheckTollFreeBridgeCast(T, SubExpr);
4299 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4300 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,