1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for Objective-C expressions.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/SemaInternal.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/AST/StmtVisitor.h"
18 #include "clang/AST/TypeLoc.h"
19 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
20 #include "clang/Edit/Commit.h"
21 #include "clang/Edit/Rewriters.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Sema/Initialization.h"
24 #include "clang/Sema/Lookup.h"
25 #include "clang/Sema/Scope.h"
26 #include "clang/Sema/ScopeInfo.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/Support/ConvertUTF.h"
30 using namespace clang;
32 using llvm::makeArrayRef;
34 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35 ArrayRef<Expr *> Strings) {
36 // Most ObjC strings are formed out of a single piece. However, we *can*
37 // have strings formed out of multiple @ strings with multiple pptokens in
38 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
39 // StringLiteral for ObjCStringLiteral to hold onto.
40 StringLiteral *S = cast<StringLiteral>(Strings[0]);
42 // If we have a multi-part string, merge it all together.
43 if (Strings.size() != 1) {
44 // Concatenate objc strings.
45 SmallString<128> StrBuf;
46 SmallVector<SourceLocation, 8> StrLocs;
48 for (Expr *E : Strings) {
49 S = cast<StringLiteral>(E);
51 // ObjC strings can't be wide or UTF.
53 Diag(S->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
54 << S->getSourceRange();
59 StrBuf += S->getString();
61 // Get the locations of the string tokens.
62 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
65 // Create the aggregate string with the appropriate content and location
67 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
68 assert(CAT && "String literal not of constant array type!");
69 QualType StrTy = Context.getConstantArrayType(
70 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
71 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
72 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
73 /*Pascal=*/false, StrTy, &StrLocs[0],
77 return BuildObjCStringLiteral(AtLocs[0], S);
80 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
81 // Verify that this composite string is acceptable for ObjC strings.
82 if (CheckObjCString(S))
85 // Initialize the constant string interface lazily. This assumes
86 // the NSString interface is seen in this translation unit. Note: We
87 // don't use NSConstantString, since the runtime team considers this
88 // interface private (even though it appears in the header files).
89 QualType Ty = Context.getObjCConstantStringInterface();
91 Ty = Context.getObjCObjectPointerType(Ty);
92 } else if (getLangOpts().NoConstantCFStrings) {
93 IdentifierInfo *NSIdent=nullptr;
94 std::string StringClass(getLangOpts().ObjCConstantStringClass);
96 if (StringClass.empty())
97 NSIdent = &Context.Idents.get("NSConstantString");
99 NSIdent = &Context.Idents.get(StringClass);
101 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
103 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
104 Context.setObjCConstantStringInterface(StrIF);
105 Ty = Context.getObjCConstantStringInterface();
106 Ty = Context.getObjCObjectPointerType(Ty);
108 // If there is no NSConstantString interface defined then treat this
109 // as error and recover from it.
110 Diag(S->getBeginLoc(), diag::err_no_nsconstant_string_class)
111 << NSIdent << S->getSourceRange();
112 Ty = Context.getObjCIdType();
115 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
116 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
118 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
119 Context.setObjCConstantStringInterface(StrIF);
120 Ty = Context.getObjCConstantStringInterface();
121 Ty = Context.getObjCObjectPointerType(Ty);
123 // If there is no NSString interface defined, implicitly declare
124 // a @class NSString; and use that instead. This is to make sure
125 // type of an NSString literal is represented correctly, instead of
126 // being an 'id' type.
127 Ty = Context.getObjCNSStringType();
129 ObjCInterfaceDecl *NSStringIDecl =
130 ObjCInterfaceDecl::Create (Context,
131 Context.getTranslationUnitDecl(),
132 SourceLocation(), NSIdent,
133 nullptr, nullptr, SourceLocation());
134 Ty = Context.getObjCInterfaceType(NSStringIDecl);
135 Context.setObjCNSStringType(Ty);
137 Ty = Context.getObjCObjectPointerType(Ty);
141 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
144 /// Emits an error if the given method does not exist, or if the return
145 /// type is not an Objective-C object.
146 static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
147 const ObjCInterfaceDecl *Class,
148 Selector Sel, const ObjCMethodDecl *Method) {
150 // FIXME: Is there a better way to avoid quotes than using getName()?
151 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
155 // Make sure the return type is reasonable.
156 QualType ReturnType = Method->getReturnType();
157 if (!ReturnType->isObjCObjectPointerType()) {
158 S.Diag(Loc, diag::err_objc_literal_method_sig)
160 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
168 /// Maps ObjCLiteralKind to NSClassIdKindKind
169 static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(
170 Sema::ObjCLiteralKind LiteralKind) {
171 switch (LiteralKind) {
173 return NSAPI::ClassId_NSArray;
174 case Sema::LK_Dictionary:
175 return NSAPI::ClassId_NSDictionary;
176 case Sema::LK_Numeric:
177 return NSAPI::ClassId_NSNumber;
178 case Sema::LK_String:
179 return NSAPI::ClassId_NSString;
181 return NSAPI::ClassId_NSValue;
183 // there is no corresponding matching
184 // between LK_None/LK_Block and NSClassIdKindKind
189 llvm_unreachable("LiteralKind can't be converted into a ClassKind");
192 /// Validates ObjCInterfaceDecl availability.
193 /// ObjCInterfaceDecl, used to create ObjC literals, should be defined
194 /// if clang not in a debugger mode.
195 static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl,
197 Sema::ObjCLiteralKind LiteralKind) {
199 NSAPI::NSClassIdKindKind Kind = ClassKindFromLiteralKind(LiteralKind);
200 IdentifierInfo *II = S.NSAPIObj->getNSClassId(Kind);
201 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
202 << II->getName() << LiteralKind;
204 } else if (!Decl->hasDefinition() && !S.getLangOpts().DebuggerObjCLiteral) {
205 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
206 << Decl->getName() << LiteralKind;
207 S.Diag(Decl->getLocation(), diag::note_forward_class);
214 /// Looks up ObjCInterfaceDecl of a given NSClassIdKindKind.
215 /// Used to create ObjC literals, such as NSDictionary (@{}),
216 /// NSArray (@[]) and Boxed Expressions (@())
217 static ObjCInterfaceDecl *LookupObjCInterfaceDeclForLiteral(Sema &S,
219 Sema::ObjCLiteralKind LiteralKind) {
220 NSAPI::NSClassIdKindKind ClassKind = ClassKindFromLiteralKind(LiteralKind);
221 IdentifierInfo *II = S.NSAPIObj->getNSClassId(ClassKind);
222 NamedDecl *IF = S.LookupSingleName(S.TUScope, II, Loc,
223 Sema::LookupOrdinaryName);
224 ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
225 if (!ID && S.getLangOpts().DebuggerObjCLiteral) {
226 ASTContext &Context = S.Context;
227 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
228 ID = ObjCInterfaceDecl::Create (Context, TU, SourceLocation(), II,
229 nullptr, nullptr, SourceLocation());
232 if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) {
239 /// Retrieve the NSNumber factory method that should be used to create
240 /// an Objective-C literal for the given type.
241 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
243 bool isLiteral = false,
244 SourceRange R = SourceRange()) {
245 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
246 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
250 S.Diag(Loc, diag::err_invalid_nsnumber_type)
256 // If we already looked up this method, we're done.
257 if (S.NSNumberLiteralMethods[*Kind])
258 return S.NSNumberLiteralMethods[*Kind];
260 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
263 ASTContext &CX = S.Context;
265 // Look up the NSNumber class, if we haven't done so already. It's cached
266 // in the Sema instance.
267 if (!S.NSNumberDecl) {
268 S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc,
270 if (!S.NSNumberDecl) {
275 if (S.NSNumberPointer.isNull()) {
276 // generate the pointer to NSNumber type.
277 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
278 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
281 // Look for the appropriate method within NSNumber.
282 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
283 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
284 // create a stub definition this NSNumber factory method.
285 TypeSourceInfo *ReturnTInfo = nullptr;
287 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
288 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
289 /*isInstance=*/false, /*isVariadic=*/false,
290 /*isPropertyAccessor=*/false,
291 /*isImplicitlyDeclared=*/true,
292 /*isDefined=*/false, ObjCMethodDecl::Required,
293 /*HasRelatedResultType=*/false);
294 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
295 SourceLocation(), SourceLocation(),
296 &CX.Idents.get("value"),
297 NumberType, /*TInfo=*/nullptr,
299 Method->setMethodParams(S.Context, value, None);
302 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
305 // Note: if the parameter type is out-of-line, we'll catch it later in the
306 // implicit conversion.
308 S.NSNumberLiteralMethods[*Kind] = Method;
312 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
313 /// numeric literal expression. Type of the expression will be "NSNumber *".
314 ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
315 // Determine the type of the literal.
316 QualType NumberType = Number->getType();
317 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
318 // In C, character literals have type 'int'. That's not the type we want
319 // to use to determine the Objective-c literal kind.
320 switch (Char->getKind()) {
321 case CharacterLiteral::Ascii:
322 case CharacterLiteral::UTF8:
323 NumberType = Context.CharTy;
326 case CharacterLiteral::Wide:
327 NumberType = Context.getWideCharType();
330 case CharacterLiteral::UTF16:
331 NumberType = Context.Char16Ty;
334 case CharacterLiteral::UTF32:
335 NumberType = Context.Char32Ty;
340 // Look for the appropriate method within NSNumber.
341 // Construct the literal.
342 SourceRange NR(Number->getSourceRange());
343 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
348 // Convert the number to the type that the parameter expects.
349 ParmVarDecl *ParamDecl = Method->parameters()[0];
350 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
352 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
355 if (ConvertedNumber.isInvalid())
357 Number = ConvertedNumber.get();
359 // Use the effective source range of the literal, including the leading '@'.
360 return MaybeBindToTemporary(
361 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
362 SourceRange(AtLoc, NR.getEnd())));
365 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
366 SourceLocation ValueLoc,
369 if (getLangOpts().CPlusPlus) {
370 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
372 // C doesn't actually have a way to represent literal values of type
373 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
374 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
375 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
376 CK_IntegralToBoolean);
379 return BuildObjCNumericLiteral(AtLoc, Inner.get());
382 /// Check that the given expression is a valid element of an Objective-C
383 /// collection literal.
384 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
386 bool ArrayLiteral = false) {
387 // If the expression is type-dependent, there's nothing for us to do.
388 if (Element->isTypeDependent())
391 ExprResult Result = S.CheckPlaceholderExpr(Element);
392 if (Result.isInvalid())
394 Element = Result.get();
396 // In C++, check for an implicit conversion to an Objective-C object pointer
398 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
399 InitializedEntity Entity
400 = InitializedEntity::InitializeParameter(S.Context, T,
402 InitializationKind Kind = InitializationKind::CreateCopy(
403 Element->getBeginLoc(), SourceLocation());
404 InitializationSequence Seq(S, Entity, Kind, Element);
406 return Seq.Perform(S, Entity, Kind, Element);
409 Expr *OrigElement = Element;
411 // Perform lvalue-to-rvalue conversion.
412 Result = S.DefaultLvalueConversion(Element);
413 if (Result.isInvalid())
415 Element = Result.get();
417 // Make sure that we have an Objective-C pointer type or block.
418 if (!Element->getType()->isObjCObjectPointerType() &&
419 !Element->getType()->isBlockPointerType()) {
420 bool Recovered = false;
422 // If this is potentially an Objective-C numeric literal, add the '@'.
423 if (isa<IntegerLiteral>(OrigElement) ||
424 isa<CharacterLiteral>(OrigElement) ||
425 isa<FloatingLiteral>(OrigElement) ||
426 isa<ObjCBoolLiteralExpr>(OrigElement) ||
427 isa<CXXBoolLiteralExpr>(OrigElement)) {
428 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
429 int Which = isa<CharacterLiteral>(OrigElement) ? 1
430 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
431 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
434 S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
435 << Which << OrigElement->getSourceRange()
436 << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
439 S.BuildObjCNumericLiteral(OrigElement->getBeginLoc(), OrigElement);
440 if (Result.isInvalid())
443 Element = Result.get();
447 // If this is potentially an Objective-C string literal, add the '@'.
448 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
449 if (String->isAscii()) {
450 S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
451 << 0 << OrigElement->getSourceRange()
452 << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
454 Result = S.BuildObjCStringLiteral(OrigElement->getBeginLoc(), String);
455 if (Result.isInvalid())
458 Element = Result.get();
464 S.Diag(Element->getBeginLoc(), diag::err_invalid_collection_element)
465 << Element->getType();
470 if (ObjCStringLiteral *getString =
471 dyn_cast<ObjCStringLiteral>(OrigElement)) {
472 if (StringLiteral *SL = getString->getString()) {
473 unsigned numConcat = SL->getNumConcatenated();
475 // Only warn if the concatenated string doesn't come from a macro.
476 bool hasMacro = false;
477 for (unsigned i = 0; i < numConcat ; ++i)
478 if (SL->getStrTokenLoc(i).isMacroID()) {
483 S.Diag(Element->getBeginLoc(),
484 diag::warn_concatenated_nsarray_literal)
485 << Element->getType();
490 // Make sure that the element has the type that the container factory
492 return S.PerformCopyInitialization(
493 InitializedEntity::InitializeParameter(S.Context, T,
495 Element->getBeginLoc(), Element);
498 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
499 if (ValueExpr->isTypeDependent()) {
500 ObjCBoxedExpr *BoxedExpr =
501 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
504 ObjCMethodDecl *BoxingMethod = nullptr;
506 // Convert the expression to an RValue, so we can check for pointer types...
507 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
508 if (RValue.isInvalid()) {
511 SourceLocation Loc = SR.getBegin();
512 ValueExpr = RValue.get();
513 QualType ValueType(ValueExpr->getType());
514 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
515 QualType PointeeType = PT->getPointeeType();
516 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
519 NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
524 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
525 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
528 // The boxed expression can be emitted as a compile time constant if it is
529 // a string literal whose character encoding is compatible with UTF-8.
530 if (auto *CE = dyn_cast<ImplicitCastExpr>(ValueExpr))
531 if (CE->getCastKind() == CK_ArrayToPointerDecay)
533 dyn_cast<StringLiteral>(CE->getSubExpr()->IgnoreParens())) {
534 assert((SL->isAscii() || SL->isUTF8()) &&
535 "unexpected character encoding");
536 StringRef Str = SL->getString();
537 const llvm::UTF8 *StrBegin = Str.bytes_begin();
538 const llvm::UTF8 *StrEnd = Str.bytes_end();
539 // Check that this is a valid UTF-8 string.
540 if (llvm::isLegalUTF8String(&StrBegin, StrEnd)) {
541 BoxedType = Context.getAttributedType(
542 AttributedType::getNullabilityAttrKind(
543 NullabilityKind::NonNull),
544 NSStringPointer, NSStringPointer);
545 return new (Context) ObjCBoxedExpr(CE, BoxedType, nullptr, SR);
548 Diag(SL->getBeginLoc(), diag::warn_objc_boxing_invalid_utf8_string)
549 << NSStringPointer << SL->getSourceRange();
552 if (!StringWithUTF8StringMethod) {
553 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
554 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
556 // Look for the appropriate method within NSString.
557 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
558 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
559 // Debugger needs to work even if NSString hasn't been defined.
560 TypeSourceInfo *ReturnTInfo = nullptr;
561 ObjCMethodDecl *M = ObjCMethodDecl::Create(
562 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
563 NSStringPointer, ReturnTInfo, NSStringDecl,
564 /*isInstance=*/false, /*isVariadic=*/false,
565 /*isPropertyAccessor=*/false,
566 /*isImplicitlyDeclared=*/true,
567 /*isDefined=*/false, ObjCMethodDecl::Required,
568 /*HasRelatedResultType=*/false);
569 QualType ConstCharType = Context.CharTy.withConst();
571 ParmVarDecl::Create(Context, M,
572 SourceLocation(), SourceLocation(),
573 &Context.Idents.get("value"),
574 Context.getPointerType(ConstCharType),
577 M->setMethodParams(Context, value, None);
581 if (!validateBoxingMethod(*this, Loc, NSStringDecl,
582 stringWithUTF8String, BoxingMethod))
585 StringWithUTF8StringMethod = BoxingMethod;
588 BoxingMethod = StringWithUTF8StringMethod;
589 BoxedType = NSStringPointer;
590 // Transfer the nullability from method's return type.
591 Optional<NullabilityKind> Nullability =
592 BoxingMethod->getReturnType()->getNullability(Context);
594 BoxedType = Context.getAttributedType(
595 AttributedType::getNullabilityAttrKind(*Nullability), BoxedType,
598 } else if (ValueType->isBuiltinType()) {
599 // The other types we support are numeric, char and BOOL/bool. We could also
600 // provide limited support for structure types, such as NSRange, NSRect, and
601 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
604 // Check for a top-level character literal.
605 if (const CharacterLiteral *Char =
606 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
607 // In C, character literals have type 'int'. That's not the type we want
608 // to use to determine the Objective-c literal kind.
609 switch (Char->getKind()) {
610 case CharacterLiteral::Ascii:
611 case CharacterLiteral::UTF8:
612 ValueType = Context.CharTy;
615 case CharacterLiteral::Wide:
616 ValueType = Context.getWideCharType();
619 case CharacterLiteral::UTF16:
620 ValueType = Context.Char16Ty;
623 case CharacterLiteral::UTF32:
624 ValueType = Context.Char32Ty;
628 // FIXME: Do I need to do anything special with BoolTy expressions?
630 // Look for the appropriate method within NSNumber.
631 BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
632 BoxedType = NSNumberPointer;
633 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
634 if (!ET->getDecl()->isComplete()) {
635 Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
636 << ValueType << ValueExpr->getSourceRange();
640 BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
641 ET->getDecl()->getIntegerType());
642 BoxedType = NSNumberPointer;
643 } else if (ValueType->isObjCBoxableRecordType()) {
644 // Support for structure types, that marked as objc_boxable
645 // struct __attribute__((objc_boxable)) s { ... };
647 // Look up the NSValue class, if we haven't done so already. It's cached
648 // in the Sema instance.
650 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
656 // generate the pointer to NSValue type.
657 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
658 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
661 if (!ValueWithBytesObjCTypeMethod) {
662 IdentifierInfo *II[] = {
663 &Context.Idents.get("valueWithBytes"),
664 &Context.Idents.get("objCType")
666 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
668 // Look for the appropriate method within NSValue.
669 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
670 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
671 // Debugger needs to work even if NSValue hasn't been defined.
672 TypeSourceInfo *ReturnTInfo = nullptr;
673 ObjCMethodDecl *M = ObjCMethodDecl::Create(
677 ValueWithBytesObjCType,
681 /*isInstance=*/false,
682 /*isVariadic=*/false,
683 /*isPropertyAccessor=*/false,
684 /*isImplicitlyDeclared=*/true,
686 ObjCMethodDecl::Required,
687 /*HasRelatedResultType=*/false);
689 SmallVector<ParmVarDecl *, 2> Params;
692 ParmVarDecl::Create(Context, M,
693 SourceLocation(), SourceLocation(),
694 &Context.Idents.get("bytes"),
695 Context.VoidPtrTy.withConst(),
698 Params.push_back(bytes);
700 QualType ConstCharType = Context.CharTy.withConst();
702 ParmVarDecl::Create(Context, M,
703 SourceLocation(), SourceLocation(),
704 &Context.Idents.get("type"),
705 Context.getPointerType(ConstCharType),
708 Params.push_back(type);
710 M->setMethodParams(Context, Params, None);
714 if (!validateBoxingMethod(*this, Loc, NSValueDecl,
715 ValueWithBytesObjCType, BoxingMethod))
718 ValueWithBytesObjCTypeMethod = BoxingMethod;
721 if (!ValueType.isTriviallyCopyableType(Context)) {
722 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
723 << ValueType << ValueExpr->getSourceRange();
727 BoxingMethod = ValueWithBytesObjCTypeMethod;
728 BoxedType = NSValuePointer;
732 Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
733 << ValueType << ValueExpr->getSourceRange();
737 DiagnoseUseOfDecl(BoxingMethod, Loc);
739 ExprResult ConvertedValueExpr;
740 if (ValueType->isObjCBoxableRecordType()) {
741 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
742 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
745 // Convert the expression to the type that the parameter requires.
746 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
747 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
749 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
753 if (ConvertedValueExpr.isInvalid())
755 ValueExpr = ConvertedValueExpr.get();
757 ObjCBoxedExpr *BoxedExpr =
758 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
760 return MaybeBindToTemporary(BoxedExpr);
763 /// Build an ObjC subscript pseudo-object expression, given that
764 /// that's supported by the runtime.
765 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
767 ObjCMethodDecl *getterMethod,
768 ObjCMethodDecl *setterMethod) {
769 assert(!LangOpts.isSubscriptPointerArithmetic());
771 // We can't get dependent types here; our callers should have
772 // filtered them out.
773 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
774 "base or index cannot have dependent type here");
776 // Filter out placeholders in the index. In theory, overloads could
777 // be preserved here, although that might not actually work correctly.
778 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
779 if (Result.isInvalid())
781 IndexExpr = Result.get();
783 // Perform lvalue-to-rvalue conversion on the base.
784 Result = DefaultLvalueConversion(BaseExpr);
785 if (Result.isInvalid())
787 BaseExpr = Result.get();
789 // Build the pseudo-object expression.
790 return new (Context) ObjCSubscriptRefExpr(
791 BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
792 getterMethod, setterMethod, RB);
795 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
796 SourceLocation Loc = SR.getBegin();
799 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
806 // Find the arrayWithObjects:count: method, if we haven't done so already.
807 QualType IdT = Context.getObjCIdType();
808 if (!ArrayWithObjectsMethod) {
810 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
811 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
812 if (!Method && getLangOpts().DebuggerObjCLiteral) {
813 TypeSourceInfo *ReturnTInfo = nullptr;
814 Method = ObjCMethodDecl::Create(
815 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
816 Context.getTranslationUnitDecl(), false /*Instance*/,
817 false /*isVariadic*/,
818 /*isPropertyAccessor=*/false,
819 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
820 ObjCMethodDecl::Required, false);
821 SmallVector<ParmVarDecl *, 2> Params;
822 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
825 &Context.Idents.get("objects"),
826 Context.getPointerType(IdT),
829 Params.push_back(objects);
830 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
833 &Context.Idents.get("cnt"),
834 Context.UnsignedLongTy,
835 /*TInfo=*/nullptr, SC_None,
837 Params.push_back(cnt);
838 Method->setMethodParams(Context, Params, None);
841 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
844 // Dig out the type that all elements should be converted to.
845 QualType T = Method->parameters()[0]->getType();
846 const PointerType *PtrT = T->getAs<PointerType>();
848 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
849 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
851 Diag(Method->parameters()[0]->getLocation(),
852 diag::note_objc_literal_method_param)
854 << Context.getPointerType(IdT.withConst());
858 // Check that the 'count' parameter is integral.
859 if (!Method->parameters()[1]->getType()->isIntegerType()) {
860 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
862 Diag(Method->parameters()[1]->getLocation(),
863 diag::note_objc_literal_method_param)
865 << Method->parameters()[1]->getType()
870 // We've found a good +arrayWithObjects:count: method. Save it!
871 ArrayWithObjectsMethod = Method;
874 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
875 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
877 // Check that each of the elements provided is valid in a collection literal,
878 // performing conversions as necessary.
879 Expr **ElementsBuffer = Elements.data();
880 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
881 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
884 if (Converted.isInvalid())
887 ElementsBuffer[I] = Converted.get();
891 = Context.getObjCObjectPointerType(
892 Context.getObjCInterfaceType(NSArrayDecl));
894 return MaybeBindToTemporary(
895 ObjCArrayLiteral::Create(Context, Elements, Ty,
896 ArrayWithObjectsMethod, SR));
899 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
900 MutableArrayRef<ObjCDictionaryElement> Elements) {
901 SourceLocation Loc = SR.getBegin();
903 if (!NSDictionaryDecl) {
904 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
905 Sema::LK_Dictionary);
906 if (!NSDictionaryDecl) {
911 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
913 QualType IdT = Context.getObjCIdType();
914 if (!DictionaryWithObjectsMethod) {
915 Selector Sel = NSAPIObj->getNSDictionarySelector(
916 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
917 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
918 if (!Method && getLangOpts().DebuggerObjCLiteral) {
919 Method = ObjCMethodDecl::Create(Context,
920 SourceLocation(), SourceLocation(), Sel,
922 nullptr /*TypeSourceInfo */,
923 Context.getTranslationUnitDecl(),
924 false /*Instance*/, false/*isVariadic*/,
925 /*isPropertyAccessor=*/false,
926 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
927 ObjCMethodDecl::Required,
929 SmallVector<ParmVarDecl *, 3> Params;
930 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
933 &Context.Idents.get("objects"),
934 Context.getPointerType(IdT),
935 /*TInfo=*/nullptr, SC_None,
937 Params.push_back(objects);
938 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
941 &Context.Idents.get("keys"),
942 Context.getPointerType(IdT),
943 /*TInfo=*/nullptr, SC_None,
945 Params.push_back(keys);
946 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
949 &Context.Idents.get("cnt"),
950 Context.UnsignedLongTy,
951 /*TInfo=*/nullptr, SC_None,
953 Params.push_back(cnt);
954 Method->setMethodParams(Context, Params, None);
957 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
961 // Dig out the type that all values should be converted to.
962 QualType ValueT = Method->parameters()[0]->getType();
963 const PointerType *PtrValue = ValueT->getAs<PointerType>();
965 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
966 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
968 Diag(Method->parameters()[0]->getLocation(),
969 diag::note_objc_literal_method_param)
971 << Context.getPointerType(IdT.withConst());
975 // Dig out the type that all keys should be converted to.
976 QualType KeyT = Method->parameters()[1]->getType();
977 const PointerType *PtrKey = KeyT->getAs<PointerType>();
979 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
983 if (QIDNSCopying.isNull()) {
984 // key argument of selector is id<NSCopying>?
985 if (ObjCProtocolDecl *NSCopyingPDecl =
986 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
987 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
989 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
991 (ObjCProtocolDecl**) PQ,
994 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
997 if (!QIDNSCopying.isNull())
998 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
1003 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
1005 Diag(Method->parameters()[1]->getLocation(),
1006 diag::note_objc_literal_method_param)
1008 << Context.getPointerType(IdT.withConst());
1013 // Check that the 'count' parameter is integral.
1014 QualType CountType = Method->parameters()[2]->getType();
1015 if (!CountType->isIntegerType()) {
1016 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
1018 Diag(Method->parameters()[2]->getLocation(),
1019 diag::note_objc_literal_method_param)
1025 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
1026 DictionaryWithObjectsMethod = Method;
1029 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
1030 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
1031 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
1032 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1034 // Check that each of the keys and values provided is valid in a collection
1035 // literal, performing conversions as necessary.
1036 bool HasPackExpansions = false;
1037 for (ObjCDictionaryElement &Element : Elements) {
1039 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
1041 if (Key.isInvalid())
1046 = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
1047 if (Value.isInvalid())
1050 Element.Key = Key.get();
1051 Element.Value = Value.get();
1053 if (Element.EllipsisLoc.isInvalid())
1056 if (!Element.Key->containsUnexpandedParameterPack() &&
1057 !Element.Value->containsUnexpandedParameterPack()) {
1058 Diag(Element.EllipsisLoc,
1059 diag::err_pack_expansion_without_parameter_packs)
1060 << SourceRange(Element.Key->getBeginLoc(),
1061 Element.Value->getEndLoc());
1065 HasPackExpansions = true;
1069 = Context.getObjCObjectPointerType(
1070 Context.getObjCInterfaceType(NSDictionaryDecl));
1071 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
1072 Context, Elements, HasPackExpansions, Ty,
1073 DictionaryWithObjectsMethod, SR));
1076 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
1077 TypeSourceInfo *EncodedTypeInfo,
1078 SourceLocation RParenLoc) {
1079 QualType EncodedType = EncodedTypeInfo->getType();
1081 if (EncodedType->isDependentType())
1082 StrTy = Context.DependentTy;
1084 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1085 !EncodedType->isVoidType()) // void is handled too.
1086 if (RequireCompleteType(AtLoc, EncodedType,
1087 diag::err_incomplete_type_objc_at_encode,
1088 EncodedTypeInfo->getTypeLoc()))
1092 QualType NotEncodedT;
1093 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1094 if (!NotEncodedT.isNull())
1095 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1096 << EncodedType << NotEncodedT;
1098 // The type of @encode is the same as the type of the corresponding string,
1099 // which is an array type.
1100 StrTy = Context.getStringLiteralArrayType(Context.CharTy, Str.size());
1103 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
1106 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1107 SourceLocation EncodeLoc,
1108 SourceLocation LParenLoc,
1110 SourceLocation RParenLoc) {
1111 // FIXME: Preserve type source info ?
1112 TypeSourceInfo *TInfo;
1113 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1115 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1116 getLocForEndOfToken(LParenLoc));
1118 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
1121 static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1122 SourceLocation AtLoc,
1123 SourceLocation LParenLoc,
1124 SourceLocation RParenLoc,
1125 ObjCMethodDecl *Method,
1126 ObjCMethodList &MethList) {
1127 ObjCMethodList *M = &MethList;
1128 bool Warned = false;
1129 for (M = M->getNext(); M; M=M->getNext()) {
1130 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
1131 if (MatchingMethodDecl == Method ||
1132 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1133 MatchingMethodDecl->getSelector() != Method->getSelector())
1135 if (!S.MatchTwoMethodDeclarations(Method,
1136 MatchingMethodDecl, Sema::MMS_loose)) {
1139 S.Diag(AtLoc, diag::warn_multiple_selectors)
1140 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1141 << FixItHint::CreateInsertion(RParenLoc, ")");
1142 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1143 << Method->getDeclName();
1145 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1146 << MatchingMethodDecl->getDeclName();
1152 static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1153 ObjCMethodDecl *Method,
1154 SourceLocation LParenLoc,
1155 SourceLocation RParenLoc,
1156 bool WarnMultipleSelectors) {
1157 if (!WarnMultipleSelectors ||
1158 S.Diags.isIgnored(diag::warn_multiple_selectors, SourceLocation()))
1160 bool Warned = false;
1161 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1162 e = S.MethodPool.end(); b != e; b++) {
1163 // first, instance methods
1164 ObjCMethodList &InstMethList = b->second.first;
1165 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1166 Method, InstMethList))
1169 // second, class methods
1170 ObjCMethodList &ClsMethList = b->second.second;
1171 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1172 Method, ClsMethList) || Warned)
1177 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1178 SourceLocation AtLoc,
1179 SourceLocation SelLoc,
1180 SourceLocation LParenLoc,
1181 SourceLocation RParenLoc,
1182 bool WarnMultipleSelectors) {
1183 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1184 SourceRange(LParenLoc, RParenLoc));
1186 Method = LookupFactoryMethodInGlobalPool(Sel,
1187 SourceRange(LParenLoc, RParenLoc));
1189 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1190 Selector MatchedSel = OM->getSelector();
1191 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1192 RParenLoc.getLocWithOffset(-1));
1193 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1194 << Sel << MatchedSel
1195 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1198 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
1200 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1201 WarnMultipleSelectors);
1204 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1205 !getSourceManager().isInSystemHeader(Method->getLocation()))
1206 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
1208 // In ARC, forbid the user from using @selector for
1209 // retain/release/autorelease/dealloc/retainCount.
1210 if (getLangOpts().ObjCAutoRefCount) {
1211 switch (Sel.getMethodFamily()) {
1214 case OMF_autorelease:
1215 case OMF_retainCount:
1217 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1218 Sel << SourceRange(LParenLoc, RParenLoc);
1226 case OMF_mutableCopy:
1229 case OMF_initialize:
1230 case OMF_performSelector:
1234 QualType Ty = Context.getObjCSelType();
1235 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1238 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1239 SourceLocation AtLoc,
1240 SourceLocation ProtoLoc,
1241 SourceLocation LParenLoc,
1242 SourceLocation ProtoIdLoc,
1243 SourceLocation RParenLoc) {
1244 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
1246 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
1249 if (!PDecl->hasDefinition()) {
1250 Diag(ProtoLoc, diag::err_atprotocol_protocol) << PDecl;
1251 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
1253 PDecl = PDecl->getDefinition();
1256 QualType Ty = Context.getObjCProtoType();
1259 Ty = Context.getObjCObjectPointerType(Ty);
1260 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1263 /// Try to capture an implicit reference to 'self'.
1264 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1265 DeclContext *DC = getFunctionLevelDeclContext();
1267 // If we're not in an ObjC method, error out. Note that, unlike the
1268 // C++ case, we don't require an instance method --- class methods
1269 // still have a 'self', and we really do still need to capture it!
1270 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1274 tryCaptureVariable(method->getSelfDecl(), Loc);
1279 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1280 QualType origType = T;
1281 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1282 if (T == Context.getObjCInstanceType()) {
1283 return Context.getAttributedType(
1284 AttributedType::getNullabilityAttrKind(*nullability),
1285 Context.getObjCIdType(),
1286 Context.getObjCIdType());
1292 if (T == Context.getObjCInstanceType())
1293 return Context.getObjCIdType();
1298 /// Determine the result type of a message send based on the receiver type,
1299 /// method, and the kind of message send.
1301 /// This is the "base" result type, which will still need to be adjusted
1302 /// to account for nullability.
1303 static QualType getBaseMessageSendResultType(Sema &S,
1304 QualType ReceiverType,
1305 ObjCMethodDecl *Method,
1306 bool isClassMessage,
1307 bool isSuperMessage) {
1308 assert(Method && "Must have a method");
1309 if (!Method->hasRelatedResultType())
1310 return Method->getSendResultType(ReceiverType);
1312 ASTContext &Context = S.Context;
1314 // Local function that transfers the nullability of the method's
1315 // result type to the returned result.
1316 auto transferNullability = [&](QualType type) -> QualType {
1317 // If the method's result type has nullability, extract it.
1318 if (auto nullability = Method->getSendResultType(ReceiverType)
1319 ->getNullability(Context)){
1320 // Strip off any outer nullability sugar from the provided type.
1321 (void)AttributedType::stripOuterNullability(type);
1323 // Form a new attributed type using the method result type's nullability.
1324 return Context.getAttributedType(
1325 AttributedType::getNullabilityAttrKind(*nullability),
1333 // If a method has a related return type:
1334 // - if the method found is an instance method, but the message send
1335 // was a class message send, T is the declared return type of the method
1337 if (Method->isInstanceMethod() && isClassMessage)
1338 return stripObjCInstanceType(Context,
1339 Method->getSendResultType(ReceiverType));
1341 // - if the receiver is super, T is a pointer to the class of the
1342 // enclosing method definition
1343 if (isSuperMessage) {
1344 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1345 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1346 return transferNullability(
1347 Context.getObjCObjectPointerType(
1348 Context.getObjCInterfaceType(Class)));
1352 // - if the receiver is the name of a class U, T is a pointer to U
1353 if (ReceiverType->getAsObjCInterfaceType())
1354 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1355 // - if the receiver is of type Class or qualified Class type,
1356 // T is the declared return type of the method.
1357 if (ReceiverType->isObjCClassType() ||
1358 ReceiverType->isObjCQualifiedClassType())
1359 return stripObjCInstanceType(Context,
1360 Method->getSendResultType(ReceiverType));
1362 // - if the receiver is id, qualified id, Class, or qualified Class, T
1363 // is the receiver type, otherwise
1364 // - T is the type of the receiver expression.
1365 return transferNullability(ReceiverType);
1368 QualType Sema::getMessageSendResultType(const Expr *Receiver,
1369 QualType ReceiverType,
1370 ObjCMethodDecl *Method,
1371 bool isClassMessage,
1372 bool isSuperMessage) {
1373 // Produce the result type.
1374 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1379 // If this is a class message, ignore the nullability of the receiver.
1380 if (isClassMessage) {
1381 // In a class method, class messages to 'self' that return instancetype can
1382 // be typed as the current class. We can safely do this in ARC because self
1383 // can't be reassigned, and we do it unsafely outside of ARC because in
1384 // practice people never reassign self in class methods and there's some
1385 // virtue in not being aggressively pedantic.
1386 if (Receiver && Receiver->isObjCSelfExpr()) {
1387 assert(ReceiverType->isObjCClassType() && "expected a Class self");
1388 QualType T = Method->getSendResultType(ReceiverType);
1389 AttributedType::stripOuterNullability(T);
1390 if (T == Context.getObjCInstanceType()) {
1391 const ObjCMethodDecl *MD = cast<ObjCMethodDecl>(
1392 cast<ImplicitParamDecl>(
1393 cast<DeclRefExpr>(Receiver->IgnoreParenImpCasts())->getDecl())
1394 ->getDeclContext());
1395 assert(MD->isClassMethod() && "expected a class method");
1396 QualType NewResultType = Context.getObjCObjectPointerType(
1397 Context.getObjCInterfaceType(MD->getClassInterface()));
1398 if (auto Nullability = resultType->getNullability(Context))
1399 NewResultType = Context.getAttributedType(
1400 AttributedType::getNullabilityAttrKind(*Nullability),
1401 NewResultType, NewResultType);
1402 return NewResultType;
1408 // There is nothing left to do if the result type cannot have a nullability
1410 if (!resultType->canHaveNullability())
1413 // Map the nullability of the result into a table index.
1414 unsigned receiverNullabilityIdx = 0;
1415 if (auto nullability = ReceiverType->getNullability(Context))
1416 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1418 unsigned resultNullabilityIdx = 0;
1419 if (auto nullability = resultType->getNullability(Context))
1420 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1422 // The table of nullability mappings, indexed by the receiver's nullability
1423 // and then the result type's nullability.
1424 static const uint8_t None = 0;
1425 static const uint8_t NonNull = 1;
1426 static const uint8_t Nullable = 2;
1427 static const uint8_t Unspecified = 3;
1428 static const uint8_t nullabilityMap[4][4] = {
1429 // None NonNull Nullable Unspecified
1430 /* None */ { None, None, Nullable, None },
1431 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1432 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1433 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1436 unsigned newResultNullabilityIdx
1437 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1438 if (newResultNullabilityIdx == resultNullabilityIdx)
1441 // Strip off the existing nullability. This removes as little type sugar as
1444 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1445 resultType = attributed->getModifiedType();
1447 resultType = resultType.getDesugaredType(Context);
1449 } while (resultType->getNullability(Context));
1451 // Add nullability back if needed.
1452 if (newResultNullabilityIdx > 0) {
1454 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1455 return Context.getAttributedType(
1456 AttributedType::getNullabilityAttrKind(newNullability),
1457 resultType, resultType);
1463 /// Look for an ObjC method whose result type exactly matches the given type.
1464 static const ObjCMethodDecl *
1465 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1466 QualType instancetype) {
1467 if (MD->getReturnType() == instancetype)
1470 // For these purposes, a method in an @implementation overrides a
1471 // declaration in the @interface.
1472 if (const ObjCImplDecl *impl =
1473 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1474 const ObjCContainerDecl *iface;
1475 if (const ObjCCategoryImplDecl *catImpl =
1476 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1477 iface = catImpl->getCategoryDecl();
1479 iface = impl->getClassInterface();
1482 const ObjCMethodDecl *ifaceMD =
1483 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1484 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1487 SmallVector<const ObjCMethodDecl *, 4> overrides;
1488 MD->getOverriddenMethods(overrides);
1489 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1490 if (const ObjCMethodDecl *result =
1491 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1498 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1499 // Only complain if we're in an ObjC method and the required return
1500 // type doesn't match the method's declared return type.
1501 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1502 if (!MD || !MD->hasRelatedResultType() ||
1503 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
1506 // Look for a method overridden by this method which explicitly uses
1508 if (const ObjCMethodDecl *overridden =
1509 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1510 SourceRange range = overridden->getReturnTypeSourceRange();
1511 SourceLocation loc = range.getBegin();
1512 if (loc.isInvalid())
1513 loc = overridden->getLocation();
1514 Diag(loc, diag::note_related_result_type_explicit)
1515 << /*current method*/ 1 << range;
1519 // Otherwise, if we have an interesting method family, note that.
1520 // This should always trigger if the above didn't.
1521 if (ObjCMethodFamily family = MD->getMethodFamily())
1522 Diag(MD->getLocation(), diag::note_related_result_type_family)
1523 << /*current method*/ 1
1527 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1528 E = E->IgnoreParenImpCasts();
1529 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1533 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1537 if (!Method->hasRelatedResultType())
1540 if (Context.hasSameUnqualifiedType(
1541 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
1544 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
1545 Context.getObjCInstanceType()))
1548 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1549 << Method->isInstanceMethod() << Method->getSelector()
1550 << MsgSend->getType();
1553 bool Sema::CheckMessageArgumentTypes(
1554 const Expr *Receiver, QualType ReceiverType, MultiExprArg Args,
1555 Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method,
1556 bool isClassMessage, bool isSuperMessage, SourceLocation lbrac,
1557 SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType,
1558 ExprValueKind &VK) {
1559 SourceLocation SelLoc;
1560 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1561 SelLoc = SelectorLocs.front();
1566 // Apply default argument promotion as for (C99 6.5.2.2p6).
1567 for (unsigned i = 0, e = Args.size(); i != e; i++) {
1568 if (Args[i]->isTypeDependent())
1572 if (getLangOpts().DebuggerSupport) {
1573 QualType paramTy; // ignored
1574 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
1576 result = DefaultArgumentPromotion(Args[i]);
1578 if (result.isInvalid())
1580 Args[i] = result.get();
1584 if (getLangOpts().ObjCAutoRefCount)
1585 DiagID = diag::err_arc_method_not_found;
1587 DiagID = isClassMessage ? diag::warn_class_method_not_found
1588 : diag::warn_inst_method_not_found;
1589 if (!getLangOpts().DebuggerSupport) {
1590 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
1591 if (OMD && !OMD->isInvalidDecl()) {
1592 if (getLangOpts().ObjCAutoRefCount)
1593 DiagID = diag::err_method_not_found_with_typo;
1595 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1596 : diag::warn_instance_method_not_found_with_typo;
1597 Selector MatchedSel = OMD->getSelector();
1598 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
1599 if (MatchedSel.isUnarySelector())
1600 Diag(SelLoc, DiagID)
1601 << Sel<< isClassMessage << MatchedSel
1602 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1604 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
1607 Diag(SelLoc, DiagID)
1608 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
1609 SelectorLocs.back());
1610 // Find the class to which we are sending this message.
1611 if (ReceiverType->isObjCObjectPointerType()) {
1612 if (ObjCInterfaceDecl *ThisClass =
1613 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1614 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1615 if (!RecRange.isInvalid())
1616 if (ThisClass->lookupClassMethod(Sel))
1617 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1618 << FixItHint::CreateReplacement(RecRange,
1619 ThisClass->getNameAsString());
1624 // In debuggers, we want to use __unknown_anytype for these
1625 // results so that clients can cast them.
1626 if (getLangOpts().DebuggerSupport) {
1627 ReturnType = Context.UnknownAnyTy;
1629 ReturnType = Context.getObjCIdType();
1635 ReturnType = getMessageSendResultType(Receiver, ReceiverType, Method,
1636 isClassMessage, isSuperMessage);
1637 VK = Expr::getValueKindForType(Method->getReturnType());
1639 unsigned NumNamedArgs = Sel.getNumArgs();
1640 // Method might have more arguments than selector indicates. This is due
1641 // to addition of c-style arguments in method.
1642 if (Method->param_size() > Sel.getNumArgs())
1643 NumNamedArgs = Method->param_size();
1644 // FIXME. This need be cleaned up.
1645 if (Args.size() < NumNamedArgs) {
1646 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
1647 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
1651 // Compute the set of type arguments to be substituted into each parameter
1653 Optional<ArrayRef<QualType>> typeArgs
1654 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
1655 bool IsError = false;
1656 for (unsigned i = 0; i < NumNamedArgs; i++) {
1657 // We can't do any type-checking on a type-dependent argument.
1658 if (Args[i]->isTypeDependent())
1661 Expr *argExpr = Args[i];
1663 ParmVarDecl *param = Method->parameters()[i];
1664 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1666 if (param->hasAttr<NoEscapeAttr>())
1667 if (auto *BE = dyn_cast<BlockExpr>(
1668 argExpr->IgnoreParenNoopCasts(Context)))
1669 BE->getBlockDecl()->setDoesNotEscape();
1671 // Strip the unbridged-cast placeholder expression off unless it's
1672 // a consumed argument.
1673 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1674 !param->hasAttr<CFConsumedAttr>())
1675 argExpr = stripARCUnbridgedCast(argExpr);
1677 // If the parameter is __unknown_anytype, infer its type
1678 // from the argument.
1679 if (param->getType() == Context.UnknownAnyTy) {
1681 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
1682 if (argE.isInvalid()) {
1685 Args[i] = argE.get();
1687 // Update the parameter type in-place.
1688 param->setType(paramType);
1693 QualType origParamType = param->getType();
1694 QualType paramType = param->getType();
1696 paramType = paramType.substObjCTypeArgs(
1699 ObjCSubstitutionContext::Parameter);
1701 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1703 diag::err_call_incomplete_argument, argExpr))
1706 InitializedEntity Entity
1707 = InitializedEntity::InitializeParameter(Context, param, paramType);
1708 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
1709 if (ArgE.isInvalid())
1712 Args[i] = ArgE.getAs<Expr>();
1714 // If we are type-erasing a block to a block-compatible
1715 // Objective-C pointer type, we may need to extend the lifetime
1716 // of the block object.
1717 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
1718 Args[i]->getType()->isBlockPointerType() &&
1719 origParamType->isObjCObjectPointerType()) {
1720 ExprResult arg = Args[i];
1721 maybeExtendBlockObject(arg);
1722 Args[i] = arg.get();
1727 // Promote additional arguments to variadic methods.
1728 if (Method->isVariadic()) {
1729 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
1730 if (Args[i]->isTypeDependent())
1733 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1735 IsError |= Arg.isInvalid();
1736 Args[i] = Arg.get();
1739 // Check for extra arguments to non-variadic methods.
1740 if (Args.size() != NumNamedArgs) {
1741 Diag(Args[NumNamedArgs]->getBeginLoc(),
1742 diag::err_typecheck_call_too_many_args)
1743 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1744 << Method->getSourceRange()
1745 << SourceRange(Args[NumNamedArgs]->getBeginLoc(),
1746 Args.back()->getEndLoc());
1750 DiagnoseSentinelCalls(Method, SelLoc, Args);
1752 // Do additional checkings on method.
1753 IsError |= CheckObjCMethodCall(
1754 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
1759 bool Sema::isSelfExpr(Expr *RExpr) {
1760 // 'self' is objc 'self' in an objc method only.
1761 ObjCMethodDecl *Method =
1762 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1763 return isSelfExpr(RExpr, Method);
1766 bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
1767 if (!method) return false;
1769 receiver = receiver->IgnoreParenLValueCasts();
1770 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1771 if (DRE->getDecl() == method->getSelfDecl())
1776 /// LookupMethodInType - Look up a method in an ObjCObjectType.
1777 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1779 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1780 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1781 // Look it up in the main interface (and categories, etc.)
1782 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1785 // Okay, look for "private" methods declared in any
1786 // @implementations we've seen.
1787 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1791 // Check qualifiers.
1792 for (const auto *I : objType->quals())
1793 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
1799 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1800 /// list of a qualified objective pointer type.
1801 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1802 const ObjCObjectPointerType *OPT,
1805 ObjCMethodDecl *MD = nullptr;
1806 for (const auto *PROTO : OPT->quals()) {
1807 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1814 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1815 /// objective C interface. This is a property reference expression.
1817 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1818 Expr *BaseExpr, SourceLocation OpLoc,
1819 DeclarationName MemberName,
1820 SourceLocation MemberLoc,
1821 SourceLocation SuperLoc, QualType SuperType,
1823 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1824 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1826 if (!MemberName.isIdentifier()) {
1827 Diag(MemberLoc, diag::err_invalid_property_name)
1828 << MemberName << QualType(OPT, 0);
1832 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1834 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1835 : BaseExpr->getSourceRange();
1836 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1837 diag::err_property_not_found_forward_class,
1838 MemberName, BaseRange))
1841 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
1842 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1843 // Check whether we can reference this property.
1844 if (DiagnoseUseOfDecl(PD, MemberLoc))
1847 return new (Context)
1848 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1849 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1851 return new (Context)
1852 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1853 OK_ObjCProperty, MemberLoc, BaseExpr);
1855 // Check protocols on qualified interfaces.
1856 for (const auto *I : OPT->quals())
1857 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
1858 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1859 // Check whether we can reference this property.
1860 if (DiagnoseUseOfDecl(PD, MemberLoc))
1864 return new (Context) ObjCPropertyRefExpr(
1865 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1866 SuperLoc, SuperType);
1868 return new (Context)
1869 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1870 OK_ObjCProperty, MemberLoc, BaseExpr);
1872 // If that failed, look for an "implicit" property by seeing if the nullary
1873 // selector is implemented.
1875 // FIXME: The logic for looking up nullary and unary selectors should be
1876 // shared with the code in ActOnInstanceMessage.
1878 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1879 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1881 // May be found in property's qualified list.
1883 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
1885 // If this reference is in an @implementation, check for 'private' methods.
1887 Getter = IFace->lookupPrivateMethod(Sel);
1890 // Check if we can reference this property.
1891 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1894 // If we found a getter then this may be a valid dot-reference, we
1895 // will look for the matching setter, in case it is needed.
1896 Selector SetterSel =
1897 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1898 PP.getSelectorTable(), Member);
1899 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1901 // May be found in property's qualified list.
1903 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1906 // If this reference is in an @implementation, also check for 'private'
1908 Setter = IFace->lookupPrivateMethod(SetterSel);
1911 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1914 // Special warning if member name used in a property-dot for a setter accessor
1915 // does not use a property with same name; e.g. obj.X = ... for a property with
1917 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() &&
1918 !IFace->FindPropertyDeclaration(
1919 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1920 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1921 // Do not warn if user is using property-dot syntax to make call to
1922 // user named setter.
1923 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
1925 diag::warn_property_access_suggest)
1926 << MemberName << QualType(OPT, 0) << PDecl->getName()
1927 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
1931 if (Getter || Setter) {
1933 return new (Context)
1934 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1935 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1937 return new (Context)
1938 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1939 OK_ObjCProperty, MemberLoc, BaseExpr);
1943 // Attempt to correct for typos in property names.
1944 DeclFilterCCC<ObjCPropertyDecl> CCC{};
1945 if (TypoCorrection Corrected = CorrectTypo(
1946 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName,
1947 nullptr, nullptr, CCC, CTK_ErrorRecovery, IFace, false, OPT)) {
1948 DeclarationName TypoResult = Corrected.getCorrection();
1949 if (TypoResult.isIdentifier() &&
1950 TypoResult.getAsIdentifierInfo() == Member) {
1951 // There is no need to try the correction if it is the same.
1952 NamedDecl *ChosenDecl =
1953 Corrected.isKeyword() ? nullptr : Corrected.getFoundDecl();
1954 if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
1955 if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
1956 // This is a class property, we should not use the instance to
1958 Diag(MemberLoc, diag::err_class_property_found) << MemberName
1959 << OPT->getInterfaceDecl()->getName()
1960 << FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
1961 OPT->getInterfaceDecl()->getName());
1965 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1966 << MemberName << QualType(OPT, 0));
1967 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1968 TypoResult, MemberLoc,
1969 SuperLoc, SuperType, Super);
1972 ObjCInterfaceDecl *ClassDeclared;
1973 if (ObjCIvarDecl *Ivar =
1974 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1975 QualType T = Ivar->getType();
1976 if (const ObjCObjectPointerType * OBJPT =
1977 T->getAsObjCInterfacePointerType()) {
1978 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1979 diag::err_property_not_as_forward_class,
1980 MemberName, BaseExpr))
1984 diag::err_ivar_access_using_property_syntax_suggest)
1985 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1986 << FixItHint::CreateReplacement(OpLoc, "->");
1990 Diag(MemberLoc, diag::err_property_not_found)
1991 << MemberName << QualType(OPT, 0);
1993 Diag(Setter->getLocation(), diag::note_getter_unavailable)
1994 << MemberName << BaseExpr->getSourceRange();
1999 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
2000 IdentifierInfo &propertyName,
2001 SourceLocation receiverNameLoc,
2002 SourceLocation propertyNameLoc) {
2004 IdentifierInfo *receiverNamePtr = &receiverName;
2005 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
2010 // If the "receiver" is 'super' in a method, handle it as an expression-like
2011 // property reference.
2012 if (receiverNamePtr->isStr("super")) {
2013 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
2014 if (auto classDecl = CurMethod->getClassInterface()) {
2015 SuperType = QualType(classDecl->getSuperClassType(), 0);
2016 if (CurMethod->isInstanceMethod()) {
2017 if (SuperType.isNull()) {
2018 // The current class does not have a superclass.
2019 Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
2020 << CurMethod->getClassInterface()->getIdentifier();
2023 QualType T = Context.getObjCObjectPointerType(SuperType);
2025 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
2026 /*BaseExpr*/nullptr,
2027 SourceLocation()/*OpLoc*/,
2030 receiverNameLoc, T, true);
2033 // Otherwise, if this is a class method, try dispatching to our
2035 IFace = CurMethod->getClassInterface()->getSuperClass();
2041 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
2049 if (auto PD = IFace->FindPropertyDeclaration(
2050 &propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) {
2051 GetterSel = PD->getGetterName();
2052 SetterSel = PD->getSetterName();
2054 GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName);
2055 SetterSel = SelectorTable::constructSetterSelector(
2056 PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName);
2059 // Search for a declared property first.
2060 ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel);
2062 // If this reference is in an @implementation, check for 'private' methods.
2064 Getter = IFace->lookupPrivateClassMethod(GetterSel);
2067 // FIXME: refactor/share with ActOnMemberReference().
2068 // Check if we can reference this property.
2069 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
2073 // Look for the matching setter, in case it is needed.
2074 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2076 // If this reference is in an @implementation, also check for 'private'
2078 Setter = IFace->lookupPrivateClassMethod(SetterSel);
2080 // Look through local category implementations associated with the class.
2082 Setter = IFace->getCategoryClassMethod(SetterSel);
2084 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2087 if (Getter || Setter) {
2088 if (!SuperType.isNull())
2089 return new (Context)
2090 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2091 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
2094 return new (Context) ObjCPropertyRefExpr(
2095 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2096 propertyNameLoc, receiverNameLoc, IFace);
2098 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2099 << &propertyName << Context.getObjCInterfaceType(IFace));
2104 class ObjCInterfaceOrSuperCCC final : public CorrectionCandidateCallback {
2106 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2107 // Determine whether "super" is acceptable in the current context.
2108 if (Method && Method->getClassInterface())
2109 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2112 bool ValidateCandidate(const TypoCorrection &candidate) override {
2113 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2114 candidate.isKeyword("super");
2117 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2118 return llvm::make_unique<ObjCInterfaceOrSuperCCC>(*this);
2122 } // end anonymous namespace
2124 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
2125 IdentifierInfo *Name,
2126 SourceLocation NameLoc,
2128 bool HasTrailingDot,
2129 ParsedType &ReceiverType) {
2130 ReceiverType = nullptr;
2132 // If the identifier is "super" and there is no trailing dot, we're
2133 // messaging super. If the identifier is "super" and there is a
2134 // trailing dot, it's an instance message.
2135 if (IsSuper && S->isInObjcMethodScope())
2136 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
2138 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2139 LookupName(Result, S);
2141 switch (Result.getResultKind()) {
2142 case LookupResult::NotFound:
2143 // Normal name lookup didn't find anything. If we're in an
2144 // Objective-C method, look for ivars. If we find one, we're done!
2145 // FIXME: This is a hack. Ivar lookup should be part of normal
2147 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
2148 if (!Method->getClassInterface()) {
2149 // Fall back: let the parser try to parse it as an instance message.
2150 return ObjCInstanceMessage;
2153 ObjCInterfaceDecl *ClassDeclared;
2154 if (Method->getClassInterface()->lookupInstanceVariable(Name,
2156 return ObjCInstanceMessage;
2159 // Break out; we'll perform typo correction below.
2162 case LookupResult::NotFoundInCurrentInstantiation:
2163 case LookupResult::FoundOverloaded:
2164 case LookupResult::FoundUnresolvedValue:
2165 case LookupResult::Ambiguous:
2166 Result.suppressDiagnostics();
2167 return ObjCInstanceMessage;
2169 case LookupResult::Found: {
2170 // If the identifier is a class or not, and there is a trailing dot,
2171 // it's an instance message.
2173 return ObjCInstanceMessage;
2174 // We found something. If it's a type, then we have a class
2175 // message. Otherwise, it's an instance message.
2176 NamedDecl *ND = Result.getFoundDecl();
2178 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2179 T = Context.getObjCInterfaceType(Class);
2180 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
2181 T = Context.getTypeDeclType(Type);
2182 DiagnoseUseOfDecl(Type, NameLoc);
2185 return ObjCInstanceMessage;
2187 // We have a class message, and T is the type we're
2188 // messaging. Build source-location information for it.
2189 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2190 ReceiverType = CreateParsedType(T, TSInfo);
2191 return ObjCClassMessage;
2195 ObjCInterfaceOrSuperCCC CCC(getCurMethodDecl());
2196 if (TypoCorrection Corrected = CorrectTypo(
2197 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr, CCC,
2198 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
2199 if (Corrected.isKeyword()) {
2200 // If we've found the keyword "super" (the only keyword that would be
2201 // returned by CorrectTypo), this is a send to super.
2202 diagnoseTypo(Corrected,
2203 PDiag(diag::err_unknown_receiver_suggest) << Name);
2204 return ObjCSuperMessage;
2205 } else if (ObjCInterfaceDecl *Class =
2206 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2207 // If we found a declaration, correct when it refers to an Objective-C
2209 diagnoseTypo(Corrected,
2210 PDiag(diag::err_unknown_receiver_suggest) << Name);
2211 QualType T = Context.getObjCInterfaceType(Class);
2212 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2213 ReceiverType = CreateParsedType(T, TSInfo);
2214 return ObjCClassMessage;
2218 // Fall back: let the parser try to parse it as an instance message.
2219 return ObjCInstanceMessage;
2222 ExprResult Sema::ActOnSuperMessage(Scope *S,
2223 SourceLocation SuperLoc,
2225 SourceLocation LBracLoc,
2226 ArrayRef<SourceLocation> SelectorLocs,
2227 SourceLocation RBracLoc,
2228 MultiExprArg Args) {
2229 // Determine whether we are inside a method or not.
2230 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
2232 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2236 ObjCInterfaceDecl *Class = Method->getClassInterface();
2238 Diag(SuperLoc, diag::err_no_super_class_message)
2239 << Method->getDeclName();
2243 QualType SuperTy(Class->getSuperClassType(), 0);
2244 if (SuperTy.isNull()) {
2245 // The current class does not have a superclass.
2246 Diag(SuperLoc, diag::err_root_class_cannot_use_super)
2247 << Class->getIdentifier();
2251 // We are in a method whose class has a superclass, so 'super'
2252 // is acting as a keyword.
2253 if (Method->getSelector() == Sel)
2254 getCurFunction()->ObjCShouldCallSuper = false;
2256 if (Method->isInstanceMethod()) {
2257 // Since we are in an instance method, this is an instance
2258 // message to the superclass instance.
2259 SuperTy = Context.getObjCObjectPointerType(SuperTy);
2260 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2261 Sel, /*Method=*/nullptr,
2262 LBracLoc, SelectorLocs, RBracLoc, Args);
2265 // Since we are in a class method, this is a class message to
2267 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
2269 SuperLoc, Sel, /*Method=*/nullptr,
2270 LBracLoc, SelectorLocs, RBracLoc, Args);
2273 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2274 bool isSuperReceiver,
2277 ObjCMethodDecl *Method,
2278 MultiExprArg Args) {
2279 TypeSourceInfo *receiverTypeInfo = nullptr;
2280 if (!ReceiverType.isNull())
2281 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2283 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2284 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2285 Sel, Method, Loc, Loc, Loc, Args,
2286 /*isImplicit=*/true);
2289 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2291 bool (*refactor)(const ObjCMessageExpr *,
2292 const NSAPI &, edit::Commit &)) {
2293 SourceLocation MsgLoc = Msg->getExprLoc();
2294 if (S.Diags.isIgnored(DiagID, MsgLoc))
2297 SourceManager &SM = S.SourceMgr;
2298 edit::Commit ECommit(SM, S.LangOpts);
2299 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2300 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2301 << Msg->getSelector() << Msg->getSourceRange();
2302 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2303 if (!ECommit.isCommitable())
2305 for (edit::Commit::edit_iterator
2306 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2307 const edit::Commit::Edit &Edit = *I;
2308 switch (Edit.Kind) {
2309 case edit::Commit::Act_Insert:
2310 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2314 case edit::Commit::Act_InsertFromRange:
2315 Builder.AddFixItHint(
2316 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2317 Edit.getInsertFromRange(SM),
2320 case edit::Commit::Act_Remove:
2321 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2328 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2329 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2330 edit::rewriteObjCRedundantCallWithLiteral);
2333 static void checkFoundationAPI(Sema &S, SourceLocation Loc,
2334 const ObjCMethodDecl *Method,
2335 ArrayRef<Expr *> Args, QualType ReceiverType,
2336 bool IsClassObjectCall) {
2337 // Check if this is a performSelector method that uses a selector that returns
2338 // a record or a vector type.
2339 if (Method->getSelector().getMethodFamily() != OMF_performSelector ||
2342 const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens());
2345 ObjCMethodDecl *ImpliedMethod;
2346 if (!IsClassObjectCall) {
2347 const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>();
2348 if (!OPT || !OPT->getInterfaceDecl())
2351 OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector());
2354 OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector());
2356 const auto *IT = ReceiverType->getAs<ObjCInterfaceType>();
2359 ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector());
2362 IT->getDecl()->lookupPrivateClassMethod(SE->getSelector());
2366 QualType Ret = ImpliedMethod->getReturnType();
2367 if (Ret->isRecordType() || Ret->isVectorType() || Ret->isExtVectorType()) {
2368 QualType Ret = ImpliedMethod->getReturnType();
2369 S.Diag(Loc, diag::warn_objc_unsafe_perform_selector)
2370 << Method->getSelector()
2371 << (!Ret->isRecordType()
2373 : Ret->isUnionType() ? /*Union*/ 1 : /*Struct*/ 0);
2374 S.Diag(ImpliedMethod->getBeginLoc(),
2375 diag::note_objc_unsafe_perform_selector_method_declared_here)
2376 << ImpliedMethod->getSelector() << Ret;
2380 /// Diagnose use of %s directive in an NSString which is being passed
2381 /// as formatting string to formatting method.
2383 DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2384 ObjCMethodDecl *Method,
2386 Expr **Args, unsigned NumArgs) {
2388 bool Format = false;
2389 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2390 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
2395 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2396 if (S.GetFormatNSStringIdx(I, Idx)) {
2402 if (!Format || NumArgs <= Idx)
2405 Expr *FormatExpr = Args[Idx];
2406 if (ObjCStringLiteral *OSL =
2407 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2408 StringLiteral *FormatString = OSL->getString();
2409 if (S.FormatStringHasSArg(FormatString)) {
2410 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2413 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2414 << Method->getDeclName();
2419 /// Build an Objective-C class message expression.
2421 /// This routine takes care of both normal class messages and
2422 /// class messages to the superclass.
2424 /// \param ReceiverTypeInfo Type source information that describes the
2425 /// receiver of this message. This may be NULL, in which case we are
2426 /// sending to the superclass and \p SuperLoc must be a valid source
2429 /// \param ReceiverType The type of the object receiving the
2430 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2431 /// type as that refers to. For a superclass send, this is the type of
2434 /// \param SuperLoc The location of the "super" keyword in a
2435 /// superclass message.
2437 /// \param Sel The selector to which the message is being sent.
2439 /// \param Method The method that this class message is invoking, if
2442 /// \param LBracLoc The location of the opening square bracket ']'.
2444 /// \param RBracLoc The location of the closing square bracket ']'.
2446 /// \param ArgsIn The message arguments.
2447 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
2448 QualType ReceiverType,
2449 SourceLocation SuperLoc,
2451 ObjCMethodDecl *Method,
2452 SourceLocation LBracLoc,
2453 ArrayRef<SourceLocation> SelectorLocs,
2454 SourceLocation RBracLoc,
2455 MultiExprArg ArgsIn,
2457 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
2458 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
2459 if (LBracLoc.isInvalid()) {
2460 Diag(Loc, diag::err_missing_open_square_message_send)
2461 << FixItHint::CreateInsertion(Loc, "[");
2464 ArrayRef<SourceLocation> SelectorSlotLocs;
2465 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2466 SelectorSlotLocs = SelectorLocs;
2468 SelectorSlotLocs = Loc;
2469 SourceLocation SelLoc = SelectorSlotLocs.front();
2471 if (ReceiverType->isDependentType()) {
2472 // If the receiver type is dependent, we can't type-check anything
2473 // at this point. Build a dependent expression.
2474 unsigned NumArgs = ArgsIn.size();
2475 Expr **Args = ArgsIn.data();
2476 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2477 return ObjCMessageExpr::Create(
2478 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2479 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2483 // Find the class to which we are sending this message.
2484 ObjCInterfaceDecl *Class = nullptr;
2485 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2486 if (!ClassType || !(Class = ClassType->getInterface())) {
2487 Diag(Loc, diag::err_invalid_receiver_class_message)
2491 assert(Class && "We don't know which class we're messaging?");
2492 // objc++ diagnoses during typename annotation.
2493 if (!getLangOpts().CPlusPlus)
2494 (void)DiagnoseUseOfDecl(Class, SelectorSlotLocs);
2495 // Find the method we are messaging.
2497 SourceRange TypeRange
2498 = SuperLoc.isValid()? SourceRange(SuperLoc)
2499 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
2500 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
2501 (getLangOpts().ObjCAutoRefCount
2502 ? diag::err_arc_receiver_forward_class
2503 : diag::warn_receiver_forward_class),
2505 // A forward class used in messaging is treated as a 'Class'
2506 Method = LookupFactoryMethodInGlobalPool(Sel,
2507 SourceRange(LBracLoc, RBracLoc));
2508 if (Method && !getLangOpts().ObjCAutoRefCount)
2509 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2510 << Method->getDeclName();
2513 Method = Class->lookupClassMethod(Sel);
2515 // If we have an implementation in scope, check "private" methods.
2517 Method = Class->lookupPrivateClassMethod(Sel);
2519 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs,
2520 nullptr, false, false, Class))
2524 // Check the argument types and determine the result type.
2525 QualType ReturnType;
2526 ExprValueKind VK = VK_RValue;
2528 unsigned NumArgs = ArgsIn.size();
2529 Expr **Args = ArgsIn.data();
2530 if (CheckMessageArgumentTypes(/*Receiver=*/nullptr, ReceiverType,
2531 MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
2532 Method, true, SuperLoc.isValid(), LBracLoc,
2533 RBracLoc, SourceRange(), ReturnType, VK))
2536 if (Method && !Method->getReturnType()->isVoidType() &&
2537 RequireCompleteType(LBracLoc, Method->getReturnType(),
2538 diag::err_illegal_message_expr_incomplete_type))
2541 // Warn about explicit call of +initialize on its own class. But not on 'super'.
2542 if (Method && Method->getMethodFamily() == OMF_initialize) {
2543 if (!SuperLoc.isValid()) {
2544 const ObjCInterfaceDecl *ID =
2545 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2547 Diag(Loc, diag::warn_direct_initialize_call);
2548 Diag(Method->getLocation(), diag::note_method_declared_at)
2549 << Method->getDeclName();
2552 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2553 // [super initialize] is allowed only within an +initialize implementation
2554 if (CurMeth->getMethodFamily() != OMF_initialize) {
2555 Diag(Loc, diag::warn_direct_super_initialize_call);
2556 Diag(Method->getLocation(), diag::note_method_declared_at)
2557 << Method->getDeclName();
2558 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2559 << CurMeth->getDeclName();
2564 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2566 // Construct the appropriate ObjCMessageExpr.
2567 ObjCMessageExpr *Result;
2568 if (SuperLoc.isValid())
2569 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2570 SuperLoc, /*IsInstanceSuper=*/false,
2571 ReceiverType, Sel, SelectorLocs,
2572 Method, makeArrayRef(Args, NumArgs),
2573 RBracLoc, isImplicit);
2575 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2576 ReceiverTypeInfo, Sel, SelectorLocs,
2577 Method, makeArrayRef(Args, NumArgs),
2578 RBracLoc, isImplicit);
2580 checkCocoaAPI(*this, Result);
2583 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
2584 ReceiverType, /*IsClassObjectCall=*/true);
2585 return MaybeBindToTemporary(Result);
2588 // ActOnClassMessage - used for both unary and keyword messages.
2589 // ArgExprs is optional - if it is present, the number of expressions
2590 // is obtained from Sel.getNumArgs().
2591 ExprResult Sema::ActOnClassMessage(Scope *S,
2592 ParsedType Receiver,
2594 SourceLocation LBracLoc,
2595 ArrayRef<SourceLocation> SelectorLocs,
2596 SourceLocation RBracLoc,
2597 MultiExprArg Args) {
2598 TypeSourceInfo *ReceiverTypeInfo;
2599 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2600 if (ReceiverType.isNull())
2603 if (!ReceiverTypeInfo)
2604 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2606 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
2607 /*SuperLoc=*/SourceLocation(), Sel,
2608 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2612 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2613 QualType ReceiverType,
2616 ObjCMethodDecl *Method,
2617 MultiExprArg Args) {
2618 return BuildInstanceMessage(Receiver, ReceiverType,
2619 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2620 Sel, Method, Loc, Loc, Loc, Args,
2621 /*isImplicit=*/true);
2624 static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) {
2627 const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext());
2630 const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
2631 if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>(
2632 S.LookupSingleName(S.TUScope, II, Protocol->getBeginLoc(),
2633 Sema::LookupOrdinaryName))) {
2634 for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) {
2635 if (P->getCanonicalDecl() == Protocol->getCanonicalDecl())
2642 /// Build an Objective-C instance message expression.
2644 /// This routine takes care of both normal instance messages and
2645 /// instance messages to the superclass instance.
2647 /// \param Receiver The expression that computes the object that will
2648 /// receive this message. This may be empty, in which case we are
2649 /// sending to the superclass instance and \p SuperLoc must be a valid
2650 /// source location.
2652 /// \param ReceiverType The (static) type of the object receiving the
2653 /// message. When a \p Receiver expression is provided, this is the
2654 /// same type as that expression. For a superclass instance send, this
2655 /// is a pointer to the type of the superclass.
2657 /// \param SuperLoc The location of the "super" keyword in a
2658 /// superclass instance message.
2660 /// \param Sel The selector to which the message is being sent.
2662 /// \param Method The method that this instance message is invoking, if
2665 /// \param LBracLoc The location of the opening square bracket ']'.
2667 /// \param RBracLoc The location of the closing square bracket ']'.
2669 /// \param ArgsIn The message arguments.
2670 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2671 QualType ReceiverType,
2672 SourceLocation SuperLoc,
2674 ObjCMethodDecl *Method,
2675 SourceLocation LBracLoc,
2676 ArrayRef<SourceLocation> SelectorLocs,
2677 SourceLocation RBracLoc,
2678 MultiExprArg ArgsIn,
2680 assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
2681 "SuperLoc must be valid so we can "
2684 // The location of the receiver.
2685 SourceLocation Loc = SuperLoc.isValid() ? SuperLoc : Receiver->getBeginLoc();
2686 SourceRange RecRange =
2687 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2688 ArrayRef<SourceLocation> SelectorSlotLocs;
2689 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2690 SelectorSlotLocs = SelectorLocs;
2692 SelectorSlotLocs = Loc;
2693 SourceLocation SelLoc = SelectorSlotLocs.front();
2695 if (LBracLoc.isInvalid()) {
2696 Diag(Loc, diag::err_missing_open_square_message_send)
2697 << FixItHint::CreateInsertion(Loc, "[");
2701 // If we have a receiver expression, perform appropriate promotions
2702 // and determine receiver type.
2704 if (Receiver->hasPlaceholderType()) {
2706 if (Receiver->getType() == Context.UnknownAnyTy)
2707 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2709 Result = CheckPlaceholderExpr(Receiver);
2710 if (Result.isInvalid()) return ExprError();
2711 Receiver = Result.get();
2714 if (Receiver->isTypeDependent()) {
2715 // If the receiver is type-dependent, we can't type-check anything
2716 // at this point. Build a dependent expression.
2717 unsigned NumArgs = ArgsIn.size();
2718 Expr **Args = ArgsIn.data();
2719 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2720 return ObjCMessageExpr::Create(
2721 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2722 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2723 RBracLoc, isImplicit);
2726 // If necessary, apply function/array conversion to the receiver.
2727 // C99 6.7.5.3p[7,8].
2728 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2729 if (Result.isInvalid())
2731 Receiver = Result.get();
2732 ReceiverType = Receiver->getType();
2734 // If the receiver is an ObjC pointer, a block pointer, or an
2735 // __attribute__((NSObject)) pointer, we don't need to do any
2736 // special conversion in order to look up a receiver.
2737 if (ReceiverType->isObjCRetainableType()) {
2739 } else if (!getLangOpts().ObjCAutoRefCount &&
2740 !Context.getObjCIdType().isNull() &&
2741 (ReceiverType->isPointerType() ||
2742 ReceiverType->isIntegerType())) {
2743 // Implicitly convert integers and pointers to 'id' but emit a warning.
2745 Diag(Loc, diag::warn_bad_receiver_type)
2747 << Receiver->getSourceRange();
2748 if (ReceiverType->isPointerType()) {
2749 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2750 CK_CPointerToObjCPointerCast).get();
2752 // TODO: specialized warning on null receivers?
2753 bool IsNull = Receiver->isNullPointerConstant(Context,
2754 Expr::NPC_ValueDependentIsNull);
2755 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2756 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2759 ReceiverType = Receiver->getType();
2760 } else if (getLangOpts().CPlusPlus) {
2761 // The receiver must be a complete type.
2762 if (RequireCompleteType(Loc, Receiver->getType(),
2763 diag::err_incomplete_receiver_type))
2766 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2767 if (result.isUsable()) {
2768 Receiver = result.get();
2769 ReceiverType = Receiver->getType();
2774 if (ReceiverType->isObjCIdType() && !isImplicit)
2775 Diag(Receiver->getExprLoc(), diag::warn_messaging_unqualified_id);
2777 // There's a somewhat weird interaction here where we assume that we
2778 // won't actually have a method unless we also don't need to do some
2779 // of the more detailed type-checking on the receiver.
2782 // Handle messages to id and __kindof types (where we use the
2783 // global method pool).
2784 const ObjCObjectType *typeBound = nullptr;
2785 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2787 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
2788 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2789 SmallVector<ObjCMethodDecl*, 4> Methods;
2790 // If we have a type bound, further filter the methods.
2791 CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
2792 true/*CheckTheOther*/, typeBound);
2793 if (!Methods.empty()) {
2794 // We choose the first method as the initial candidate, then try to
2795 // select a better one.
2796 Method = Methods[0];
2798 if (ObjCMethodDecl *BestMethod =
2799 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
2800 Method = BestMethod;
2802 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2803 SourceRange(LBracLoc, RBracLoc),
2804 receiverIsIdLike, Methods))
2805 DiagnoseUseOfDecl(Method, SelectorSlotLocs);
2807 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
2808 ReceiverType->isObjCQualifiedClassType()) {
2809 // Handle messages to Class.
2810 // We allow sending a message to a qualified Class ("Class<foo>"), which
2811 // is ok as long as one of the protocols implements the selector (if not,
2813 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2814 const ObjCObjectPointerType *QClassTy
2815 = ReceiverType->getAsObjCQualifiedClassType();
2816 // Search protocols for class methods.
2817 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2819 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2820 // warn if instance method found for a Class message.
2821 if (Method && !isMethodDeclaredInRootProtocol(*this, Method)) {
2822 Diag(SelLoc, diag::warn_instance_method_on_class_found)
2823 << Method->getSelector() << Sel;
2824 Diag(Method->getLocation(), diag::note_method_declared_at)
2825 << Method->getDeclName();
2829 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2830 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2831 // As a guess, try looking for the method in the current interface.
2832 // This very well may not produce the "right" method.
2834 // First check the public methods in the class interface.
2835 Method = ClassDecl->lookupClassMethod(Sel);
2838 Method = ClassDecl->lookupPrivateClassMethod(Sel);
2840 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
2845 // If not messaging 'self', look for any factory method named 'Sel'.
2846 if (!Receiver || !isSelfExpr(Receiver)) {
2847 // If no class (factory) method was found, check if an _instance_
2848 // method of the same name exists in the root class only.
2849 SmallVector<ObjCMethodDecl*, 4> Methods;
2850 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2851 false/*InstanceFirst*/,
2852 true/*CheckTheOther*/);
2853 if (!Methods.empty()) {
2854 // We choose the first method as the initial candidate, then try
2855 // to select a better one.
2856 Method = Methods[0];
2858 // If we find an instance method, emit warning.
2859 if (Method->isInstanceMethod()) {
2860 if (const ObjCInterfaceDecl *ID =
2861 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2862 if (ID->getSuperClass())
2863 Diag(SelLoc, diag::warn_root_inst_method_not_found)
2864 << Sel << SourceRange(LBracLoc, RBracLoc);
2868 if (ObjCMethodDecl *BestMethod =
2869 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2871 Method = BestMethod;
2877 ObjCInterfaceDecl *ClassDecl = nullptr;
2879 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2880 // long as one of the protocols implements the selector (if not, warn).
2881 // And as long as message is not deprecated/unavailable (warn if it is).
2882 if (const ObjCObjectPointerType *QIdTy
2883 = ReceiverType->getAsObjCQualifiedIdType()) {
2884 // Search protocols for instance methods.
2885 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2887 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2888 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
2890 } else if (const ObjCObjectPointerType *OCIType
2891 = ReceiverType->getAsObjCInterfacePointerType()) {
2892 // We allow sending a message to a pointer to an interface (an object).
2893 ClassDecl = OCIType->getInterfaceDecl();
2895 // Try to complete the type. Under ARC, this is a hard error from which
2896 // we don't try to recover.
2897 // FIXME: In the non-ARC case, this will still be a hard error if the
2898 // definition is found in a module that's not visible.
2899 const ObjCInterfaceDecl *forwardClass = nullptr;
2900 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
2901 getLangOpts().ObjCAutoRefCount
2902 ? diag::err_arc_receiver_forward_instance
2903 : diag::warn_receiver_forward_instance,
2904 Receiver? Receiver->getSourceRange()
2905 : SourceRange(SuperLoc))) {
2906 if (getLangOpts().ObjCAutoRefCount)
2909 forwardClass = OCIType->getInterfaceDecl();
2910 Diag(Receiver ? Receiver->getBeginLoc() : SuperLoc,
2911 diag::note_receiver_is_id);
2914 Method = ClassDecl->lookupInstanceMethod(Sel);
2918 // Search protocol qualifiers.
2919 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2922 // If we have implementations in scope, check "private" methods.
2923 Method = ClassDecl->lookupPrivateMethod(Sel);
2925 if (!Method && getLangOpts().ObjCAutoRefCount) {
2926 Diag(SelLoc, diag::err_arc_may_not_respond)
2927 << OCIType->getPointeeType() << Sel << RecRange
2928 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
2932 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2933 // If we still haven't found a method, look in the global pool. This
2934 // behavior isn't very desirable, however we need it for GCC
2935 // compatibility. FIXME: should we deviate??
2936 if (OCIType->qual_empty()) {
2937 SmallVector<ObjCMethodDecl*, 4> Methods;
2938 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2939 true/*InstanceFirst*/,
2940 false/*CheckTheOther*/);
2941 if (!Methods.empty()) {
2942 // We choose the first method as the initial candidate, then try
2943 // to select a better one.
2944 Method = Methods[0];
2946 if (ObjCMethodDecl *BestMethod =
2947 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2949 Method = BestMethod;
2951 AreMultipleMethodsInGlobalPool(Sel, Method,
2952 SourceRange(LBracLoc, RBracLoc),
2953 true/*receiverIdOrClass*/,
2956 if (Method && !forwardClass)
2957 Diag(SelLoc, diag::warn_maynot_respond)
2958 << OCIType->getInterfaceDecl()->getIdentifier()
2963 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs, forwardClass))
2966 // Reject other random receiver types (e.g. structs).
2967 Diag(Loc, diag::err_bad_receiver_type)
2968 << ReceiverType << Receiver->getSourceRange();
2974 FunctionScopeInfo *DIFunctionScopeInfo =
2975 (Method && Method->getMethodFamily() == OMF_init)
2976 ? getEnclosingFunction() : nullptr;
2978 if (DIFunctionScopeInfo &&
2979 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
2980 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2981 bool isDesignatedInitChain = false;
2982 if (SuperLoc.isValid()) {
2983 if (const ObjCObjectPointerType *
2984 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2985 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
2986 // Either we know this is a designated initializer or we
2987 // conservatively assume it because we don't know for sure.
2988 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2989 ID->isDesignatedInitializer(Sel)) {
2990 isDesignatedInitChain = true;
2991 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
2996 if (!isDesignatedInitChain) {
2997 const ObjCMethodDecl *InitMethod = nullptr;
2999 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
3000 assert(isDesignated && InitMethod);
3002 Diag(SelLoc, SuperLoc.isValid() ?
3003 diag::warn_objc_designated_init_non_designated_init_call :
3004 diag::warn_objc_designated_init_non_super_designated_init_call);
3005 Diag(InitMethod->getLocation(),
3006 diag::note_objc_designated_init_marked_here);
3010 if (DIFunctionScopeInfo &&
3011 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
3012 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
3013 if (SuperLoc.isValid()) {
3014 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
3016 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
3020 // Check the message arguments.
3021 unsigned NumArgs = ArgsIn.size();
3022 Expr **Args = ArgsIn.data();
3023 QualType ReturnType;
3024 ExprValueKind VK = VK_RValue;
3025 bool ClassMessage = (ReceiverType->isObjCClassType() ||
3026 ReceiverType->isObjCQualifiedClassType());
3027 if (CheckMessageArgumentTypes(Receiver, ReceiverType,
3028 MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
3029 Method, ClassMessage, SuperLoc.isValid(),
3030 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
3033 if (Method && !Method->getReturnType()->isVoidType() &&
3034 RequireCompleteType(LBracLoc, Method->getReturnType(),
3035 diag::err_illegal_message_expr_incomplete_type))
3038 // In ARC, forbid the user from sending messages to
3039 // retain/release/autorelease/dealloc/retainCount explicitly.
3040 if (getLangOpts().ObjCAutoRefCount) {
3041 ObjCMethodFamily family =
3042 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
3046 checkInitMethod(Method, ReceiverType);
3053 case OMF_mutableCopy:
3056 case OMF_initialize:
3062 case OMF_autorelease:
3063 case OMF_retainCount:
3064 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
3068 case OMF_performSelector:
3069 if (Method && NumArgs >= 1) {
3070 if (const auto *SelExp =
3071 dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
3072 Selector ArgSel = SelExp->getSelector();
3073 ObjCMethodDecl *SelMethod =
3074 LookupInstanceMethodInGlobalPool(ArgSel,
3075 SelExp->getSourceRange());
3078 LookupFactoryMethodInGlobalPool(ArgSel,
3079 SelExp->getSourceRange());
3081 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
3082 switch (SelFamily) {
3085 case OMF_mutableCopy:
3088 // Issue error, unless ns_returns_not_retained.
3089 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
3090 // selector names a +1 method
3092 diag::err_arc_perform_selector_retains);
3093 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3094 << SelMethod->getDeclName();
3098 // +0 call. OK. unless ns_returns_retained.
3099 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
3100 // selector names a +1 method
3102 diag::err_arc_perform_selector_retains);
3103 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3104 << SelMethod->getDeclName();
3110 // error (may leak).
3111 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
3112 Diag(Args[0]->getExprLoc(), diag::note_used_here);
3119 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
3121 // Construct the appropriate ObjCMessageExpr instance.
3122 ObjCMessageExpr *Result;
3123 if (SuperLoc.isValid())
3124 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3125 SuperLoc, /*IsInstanceSuper=*/true,
3126 ReceiverType, Sel, SelectorLocs, Method,
3127 makeArrayRef(Args, NumArgs), RBracLoc,
3130 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3131 Receiver, Sel, SelectorLocs, Method,
3132 makeArrayRef(Args, NumArgs), RBracLoc,
3135 checkCocoaAPI(*this, Result);
3138 bool IsClassObjectCall = ClassMessage;
3139 // 'self' message receivers in class methods should be treated as message
3140 // sends to the class object in order for the semantic checks to be
3141 // performed correctly. Messages to 'super' already count as class messages,
3142 // so they don't need to be handled here.
3143 if (Receiver && isSelfExpr(Receiver)) {
3144 if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
3145 if (OPT->getObjectType()->isObjCClass()) {
3146 if (const auto *CurMeth = getCurMethodDecl()) {
3147 IsClassObjectCall = true;
3149 Context.getObjCInterfaceType(CurMeth->getClassInterface());
3154 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
3155 ReceiverType, IsClassObjectCall);
3158 if (getLangOpts().ObjCAutoRefCount) {
3159 // In ARC, annotate delegate init calls.
3160 if (Result->getMethodFamily() == OMF_init &&
3161 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
3162 // Only consider init calls *directly* in init implementations,
3163 // not within blocks.
3164 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
3165 if (method && method->getMethodFamily() == OMF_init) {
3166 // The implicit assignment to self means we also don't want to
3167 // consume the result.
3168 Result->setDelegateInitCall(true);
3173 // In ARC, check for message sends which are likely to introduce
3175 checkRetainCycles(Result);
3178 if (getLangOpts().ObjCWeak) {
3179 if (!isImplicit && Method) {
3180 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
3182 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
3183 if (!IsWeak && Sel.isUnarySelector())
3184 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
3185 if (IsWeak && !isUnevaluatedContext() &&
3186 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
3187 getCurFunction()->recordUseOfWeak(Result, Prop);
3192 CheckObjCCircularContainer(Result);
3194 return MaybeBindToTemporary(Result);
3197 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
3198 if (ObjCSelectorExpr *OSE =
3199 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
3200 Selector Sel = OSE->getSelector();
3201 SourceLocation Loc = OSE->getAtLoc();
3202 auto Pos = S.ReferencedSelectors.find(Sel);
3203 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3204 S.ReferencedSelectors.erase(Pos);
3208 // ActOnInstanceMessage - used for both unary and keyword messages.
3209 // ArgExprs is optional - if it is present, the number of expressions
3210 // is obtained from Sel.getNumArgs().
3211 ExprResult Sema::ActOnInstanceMessage(Scope *S,
3214 SourceLocation LBracLoc,
3215 ArrayRef<SourceLocation> SelectorLocs,
3216 SourceLocation RBracLoc,
3217 MultiExprArg Args) {
3221 // A ParenListExpr can show up while doing error recovery with invalid code.
3222 if (isa<ParenListExpr>(Receiver)) {
3223 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3224 if (Result.isInvalid()) return ExprError();
3225 Receiver = Result.get();
3228 if (RespondsToSelectorSel.isNull()) {
3229 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3230 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3232 if (Sel == RespondsToSelectorSel)
3233 RemoveSelectorFromWarningCache(*this, Args[0]);
3235 return BuildInstanceMessage(Receiver, Receiver->getType(),
3236 /*SuperLoc=*/SourceLocation(), Sel,
3237 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3241 enum ARCConversionTypeClass {
3242 /// int, void, struct A
3248 /// id*, id***, void (^*)(),
3249 ACTC_indirectRetainable,
3251 /// void* might be a normal C type, or it might a CF type.
3258 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3259 return (ACTC == ACTC_retainable ||
3260 ACTC == ACTC_coreFoundation ||
3261 ACTC == ACTC_voidPtr);
3264 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3265 return ACTC == ACTC_none ||
3266 ACTC == ACTC_voidPtr ||
3267 ACTC == ACTC_coreFoundation;
3270 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
3271 bool isIndirect = false;
3273 // Ignore an outermost reference type.
3274 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
3275 type = ref->getPointeeType();
3279 // Drill through pointers and arrays recursively.
3281 if (const PointerType *ptr = type->getAs<PointerType>()) {
3282 type = ptr->getPointeeType();
3284 // The first level of pointer may be the innermost pointer on a CF type.
3286 if (type->isVoidType()) return ACTC_voidPtr;
3287 if (type->isRecordType()) return ACTC_coreFoundation;
3289 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3290 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3298 if (type->isObjCARCBridgableType())
3299 return ACTC_indirectRetainable;
3303 if (type->isObjCARCBridgableType())
3304 return ACTC_retainable;
3310 /// A result from the cast checker.
3312 /// Cannot be casted.
3315 /// Can be safely retained or not retained.
3318 /// Can be casted at +0.
3321 /// Can be casted at +1.
3324 ACCResult merge(ACCResult left, ACCResult right) {
3325 if (left == right) return left;
3326 if (left == ACC_bottom) return right;
3327 if (right == ACC_bottom) return left;
3331 /// A checker which white-lists certain expressions whose conversion
3332 /// to or from retainable type would otherwise be forbidden in ARC.
3333 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3334 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3336 ASTContext &Context;
3337 ARCConversionTypeClass SourceClass;
3338 ARCConversionTypeClass TargetClass;
3341 static bool isCFType(QualType type) {
3342 // Someday this can use ns_bridged. For now, it has to do this.
3343 return type->isCARCBridgableType();
3347 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
3348 ARCConversionTypeClass target, bool diagnose)
3349 : Context(Context), SourceClass(source), TargetClass(target),
3350 Diagnose(diagnose) {}
3353 ACCResult Visit(Expr *e) {
3354 return super::Visit(e->IgnoreParens());
3357 ACCResult VisitStmt(Stmt *s) {
3361 /// Null pointer constants can be casted however you please.
3362 ACCResult VisitExpr(Expr *e) {
3363 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3368 /// Objective-C string literals can be safely casted.
3369 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3370 // If we're casting to any retainable type, go ahead. Global
3371 // strings are immune to retains, so this is bottom.
3372 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3377 /// Look through certain implicit and explicit casts.
3378 ACCResult VisitCastExpr(CastExpr *e) {
3379 switch (e->getCastKind()) {
3380 case CK_NullToPointer:
3384 case CK_LValueToRValue:
3386 case CK_CPointerToObjCPointerCast:
3387 case CK_BlockPointerToObjCPointerCast:
3388 case CK_AnyPointerToBlockPointerCast:
3389 return Visit(e->getSubExpr());
3396 /// Look through unary extension.
3397 ACCResult VisitUnaryExtension(UnaryOperator *e) {
3398 return Visit(e->getSubExpr());
3401 /// Ignore the LHS of a comma operator.
3402 ACCResult VisitBinComma(BinaryOperator *e) {
3403 return Visit(e->getRHS());
3406 /// Conditional operators are okay if both sides are okay.
3407 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3408 ACCResult left = Visit(e->getTrueExpr());
3409 if (left == ACC_invalid) return ACC_invalid;
3410 return merge(left, Visit(e->getFalseExpr()));
3413 /// Look through pseudo-objects.
3414 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3415 // If we're getting here, we should always have a result.
3416 return Visit(e->getResultExpr());
3419 /// Statement expressions are okay if their result expression is okay.
3420 ACCResult VisitStmtExpr(StmtExpr *e) {
3421 return Visit(e->getSubStmt()->body_back());
3424 /// Some declaration references are okay.
3425 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
3426 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
3427 // References to global constants are okay.
3428 if (isAnyRetainable(TargetClass) &&
3429 isAnyRetainable(SourceClass) &&
3431 !var->hasDefinition(Context) &&
3432 var->getType().isConstQualified()) {
3434 // In system headers, they can also be assumed to be immune to retains.
3435 // These are things like 'kCFStringTransformToLatin'.
3436 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3439 return ACC_plusZero;
3446 /// Some calls are okay.
3447 ACCResult VisitCallExpr(CallExpr *e) {
3448 if (FunctionDecl *fn = e->getDirectCallee())
3449 if (ACCResult result = checkCallToFunction(fn))
3452 return super::VisitCallExpr(e);
3455 ACCResult checkCallToFunction(FunctionDecl *fn) {
3456 // Require a CF*Ref return type.
3457 if (!isCFType(fn->getReturnType()))
3460 if (!isAnyRetainable(TargetClass))
3463 // Honor an explicit 'not retained' attribute.
3464 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3465 return ACC_plusZero;
3467 // Honor an explicit 'retained' attribute, except that for
3468 // now we're not going to permit implicit handling of +1 results,
3469 // because it's a bit frightening.
3470 if (fn->hasAttr<CFReturnsRetainedAttr>())
3471 return Diagnose ? ACC_plusOne
3472 : ACC_invalid; // ACC_plusOne if we start accepting this
3474 // Recognize this specific builtin function, which is used by CFSTR.
3475 unsigned builtinID = fn->getBuiltinID();
3476 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3479 // Otherwise, don't do anything implicit with an unaudited function.
3480 if (!fn->hasAttr<CFAuditedTransferAttr>())
3483 // Otherwise, it's +0 unless it follows the create convention.
3484 if (ento::coreFoundation::followsCreateRule(fn))
3485 return Diagnose ? ACC_plusOne
3486 : ACC_invalid; // ACC_plusOne if we start accepting this
3488 return ACC_plusZero;
3491 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3492 return checkCallToMethod(e->getMethodDecl());
3495 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3496 ObjCMethodDecl *method;
3497 if (e->isExplicitProperty())
3498 method = e->getExplicitProperty()->getGetterMethodDecl();
3500 method = e->getImplicitPropertyGetter();
3501 return checkCallToMethod(method);
3504 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3505 if (!method) return ACC_invalid;
3507 // Check for message sends to functions returning CF types. We
3508 // just obey the Cocoa conventions with these, even though the
3509 // return type is CF.
3510 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
3513 // If the method is explicitly marked not-retained, it's +0.
3514 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3515 return ACC_plusZero;
3517 // If the method is explicitly marked as returning retained, or its
3518 // selector follows a +1 Cocoa convention, treat it as +1.
3519 if (method->hasAttr<CFReturnsRetainedAttr>())
3522 switch (method->getSelector().getMethodFamily()) {
3525 case OMF_mutableCopy:
3530 // Otherwise, treat it as +0.
3531 return ACC_plusZero;
3535 } // end anonymous namespace
3537 bool Sema::isKnownName(StringRef name) {
3540 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
3541 Sema::LookupOrdinaryName);
3542 return LookupName(R, TUScope, false);
3545 static void addFixitForObjCARCConversion(Sema &S,
3546 DiagnosticBuilder &DiagB,
3547 Sema::CheckedConversionKind CCK,
3548 SourceLocation afterLParen,
3552 const char *bridgeKeyword,
3553 const char *CFBridgeName) {
3554 // We handle C-style and implicit casts here.
3556 case Sema::CCK_ImplicitConversion:
3557 case Sema::CCK_ForBuiltinOverloadedOp:
3558 case Sema::CCK_CStyleCast:
3559 case Sema::CCK_OtherCast:
3561 case Sema::CCK_FunctionalCast:
3566 if (CCK == Sema::CCK_OtherCast) {
3567 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3568 SourceRange range(NCE->getOperatorLoc(),
3569 NCE->getAngleBrackets().getEnd());
3570 SmallString<32> BridgeCall;
3572 SourceManager &SM = S.getSourceManager();
3573 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3574 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3577 BridgeCall += CFBridgeName;
3578 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3582 Expr *castedE = castExpr;
3583 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3584 castedE = CCE->getSubExpr();
3585 castedE = castedE->IgnoreImpCasts();
3586 SourceRange range = castedE->getSourceRange();
3588 SmallString<32> BridgeCall;
3590 SourceManager &SM = S.getSourceManager();
3591 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3592 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3595 BridgeCall += CFBridgeName;
3597 if (isa<ParenExpr>(castedE)) {
3598 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3602 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3604 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3605 S.getLocForEndOfToken(range.getEnd()),
3611 if (CCK == Sema::CCK_CStyleCast) {
3612 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
3613 } else if (CCK == Sema::CCK_OtherCast) {
3614 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3615 std::string castCode = "(";
3616 castCode += bridgeKeyword;
3617 castCode += castType.getAsString();
3619 SourceRange Range(NCE->getOperatorLoc(),
3620 NCE->getAngleBrackets().getEnd());
3621 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3624 std::string castCode = "(";
3625 castCode += bridgeKeyword;
3626 castCode += castType.getAsString();
3628 Expr *castedE = castExpr->IgnoreImpCasts();
3629 SourceRange range = castedE->getSourceRange();
3630 if (isa<ParenExpr>(castedE)) {
3631 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3635 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3637 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3638 S.getLocForEndOfToken(range.getEnd()),
3644 template <typename T>
3645 static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3646 TypedefNameDecl *TDNDecl = TD->getDecl();
3647 QualType QT = TDNDecl->getUnderlyingType();
3648 if (QT->isPointerType()) {
3649 QT = QT->getPointeeType();
3650 if (const RecordType *RT = QT->getAs<RecordType>())
3651 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
3652 return RD->getAttr<T>();
3657 static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3658 TypedefNameDecl *&TDNDecl) {
3659 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3660 TDNDecl = TD->getDecl();
3661 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3662 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3664 T = TDNDecl->getUnderlyingType();
3670 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3671 QualType castType, ARCConversionTypeClass castACTC,
3672 Expr *castExpr, Expr *realCast,
3673 ARCConversionTypeClass exprACTC,
3674 Sema::CheckedConversionKind CCK) {
3675 SourceLocation loc =
3676 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
3678 if (S.makeUnavailableInSystemHeader(loc,
3679 UnavailableAttr::IR_ARCForbiddenConversion))
3682 QualType castExprType = castExpr->getType();
3683 // Defer emitting a diagnostic for bridge-related casts; that will be
3684 // handled by CheckObjCBridgeRelatedConversions.
3685 TypedefNameDecl *TDNDecl = nullptr;
3686 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3687 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3688 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3689 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3692 unsigned srcKind = 0;
3695 case ACTC_coreFoundation:
3697 srcKind = (castExprType->isPointerType() ? 1 : 0);
3699 case ACTC_retainable:
3700 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3702 case ACTC_indirectRetainable:
3707 // Check whether this could be fixed with a bridge cast.
3708 SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
3709 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
3711 unsigned convKindForDiag = Sema::isCast(CCK) ? 0 : 1;
3713 // Bridge from an ARC type to a CF type.
3714 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
3716 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3718 << 2 // of C pointer type
3720 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3723 << castExpr->getSourceRange();
3724 bool br = S.isKnownName("CFBridgingRelease");
3725 ACCResult CreateRule =
3726 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3727 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3728 if (CreateRule != ACC_plusOne)
3730 DiagnosticBuilder DiagB =
3731 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3732 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3734 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3735 castType, castExpr, realCast, "__bridge ",
3738 if (CreateRule != ACC_plusZero)
3740 DiagnosticBuilder DiagB =
3741 (CCK == Sema::CCK_OtherCast && !br) ?
3742 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3743 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3744 diag::note_arc_bridge_transfer)
3745 << castExprType << br;
3747 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3748 castType, castExpr, realCast, "__bridge_transfer ",
3749 br ? "CFBridgingRelease" : nullptr);
3755 // Bridge from a CF type to an ARC type.
3756 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
3757 bool br = S.isKnownName("CFBridgingRetain");
3758 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3760 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3762 << 2 // to C pointer type
3765 << castExpr->getSourceRange();
3766 ACCResult CreateRule =
3767 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3768 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3769 if (CreateRule != ACC_plusOne)
3771 DiagnosticBuilder DiagB =
3772 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3773 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3774 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3775 castType, castExpr, realCast, "__bridge ",
3778 if (CreateRule != ACC_plusZero)
3780 DiagnosticBuilder DiagB =
3781 (CCK == Sema::CCK_OtherCast && !br) ?
3782 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3783 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3784 diag::note_arc_bridge_retained)
3787 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3788 castType, castExpr, realCast, "__bridge_retained ",
3789 br ? "CFBridgingRetain" : nullptr);
3795 S.Diag(loc, diag::err_arc_mismatched_cast)
3797 << srcKind << castExprType << castType
3798 << castRange << castExpr->getSourceRange();
3801 template <typename TB>
3802 static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3803 bool &HadTheAttribute, bool warn) {
3804 QualType T = castExpr->getType();
3805 HadTheAttribute = false;
3806 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3807 TypedefNameDecl *TDNDecl = TD->getDecl();
3808 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3809 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3810 HadTheAttribute = true;
3811 if (Parm->isStr("id"))
3814 NamedDecl *Target = nullptr;
3815 // Check for an existing type with this name.
3816 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3817 Sema::LookupOrdinaryName);
3818 if (S.LookupName(R, S.TUScope)) {
3819 Target = R.getFoundDecl();
3820 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3821 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3822 if (const ObjCObjectPointerType *InterfacePointerType =
3823 castType->getAsObjCInterfacePointerType()) {
3824 ObjCInterfaceDecl *CastClass
3825 = InterfacePointerType->getObjectType()->getInterface();
3826 if ((CastClass == ExprClass) ||
3827 (CastClass && CastClass->isSuperClassOf(ExprClass)))
3830 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
3831 << T << Target->getName() << castType->getPointeeType();
3833 } else if (castType->isObjCIdType() ||
3834 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3835 castType, ExprClass)))
3836 // ok to cast to 'id'.
3837 // casting to id<p-list> is ok if bridge type adopts all of
3838 // p-list protocols.
3842 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
3843 << T << Target->getName() << castType;
3844 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3845 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
3850 } else if (!castType->isObjCIdType()) {
3851 S.Diag(castExpr->getBeginLoc(),
3852 diag::err_objc_cf_bridged_not_interface)
3853 << castExpr->getType() << Parm;
3854 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3856 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
3862 T = TDNDecl->getUnderlyingType();
3867 template <typename TB>
3868 static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3869 bool &HadTheAttribute, bool warn) {
3870 QualType T = castType;
3871 HadTheAttribute = false;
3872 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3873 TypedefNameDecl *TDNDecl = TD->getDecl();
3874 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3875 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3876 HadTheAttribute = true;
3877 if (Parm->isStr("id"))
3880 NamedDecl *Target = nullptr;
3881 // Check for an existing type with this name.
3882 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3883 Sema::LookupOrdinaryName);
3884 if (S.LookupName(R, S.TUScope)) {
3885 Target = R.getFoundDecl();
3886 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3887 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3888 if (const ObjCObjectPointerType *InterfacePointerType =
3889 castExpr->getType()->getAsObjCInterfacePointerType()) {
3890 ObjCInterfaceDecl *ExprClass
3891 = InterfacePointerType->getObjectType()->getInterface();
3892 if ((CastClass == ExprClass) ||
3893 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
3896 S.Diag(castExpr->getBeginLoc(),
3897 diag::warn_objc_invalid_bridge_to_cf)
3898 << castExpr->getType()->getPointeeType() << T;
3899 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3902 } else if (castExpr->getType()->isObjCIdType() ||
3903 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3904 castExpr->getType(), CastClass)))
3905 // ok to cast an 'id' expression to a CFtype.
3906 // ok to cast an 'id<plist>' expression to CFtype provided plist
3907 // adopts all of CFtype's ObjetiveC's class plist.
3911 S.Diag(castExpr->getBeginLoc(),
3912 diag::warn_objc_invalid_bridge_to_cf)
3913 << castExpr->getType() << castType;
3914 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3915 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
3921 S.Diag(castExpr->getBeginLoc(),
3922 diag::err_objc_ns_bridged_invalid_cfobject)
3923 << castExpr->getType() << castType;
3924 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3926 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
3931 T = TDNDecl->getUnderlyingType();
3936 void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
3937 if (!getLangOpts().ObjC)
3939 // warn in presence of __bridge casting to or from a toll free bridge cast.
3940 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3941 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3942 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
3943 bool HasObjCBridgeAttr;
3944 bool ObjCBridgeAttrWillNotWarn =
3945 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3947 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3949 bool HasObjCBridgeMutableAttr;
3950 bool ObjCBridgeMutableAttrWillNotWarn =
3951 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3952 HasObjCBridgeMutableAttr, false);
3953 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3956 if (HasObjCBridgeAttr)
3957 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3959 else if (HasObjCBridgeMutableAttr)
3960 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3961 HasObjCBridgeMutableAttr, true);
3963 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
3964 bool HasObjCBridgeAttr;
3965 bool ObjCBridgeAttrWillNotWarn =
3966 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3968 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3970 bool HasObjCBridgeMutableAttr;
3971 bool ObjCBridgeMutableAttrWillNotWarn =
3972 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3973 HasObjCBridgeMutableAttr, false);
3974 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3977 if (HasObjCBridgeAttr)
3978 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3980 else if (HasObjCBridgeMutableAttr)
3981 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3982 HasObjCBridgeMutableAttr, true);
3986 void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3987 QualType SrcType = castExpr->getType();
3988 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3989 if (PRE->isExplicitProperty()) {
3990 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3991 SrcType = PDecl->getType();
3993 else if (PRE->isImplicitProperty()) {
3994 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3995 SrcType = Getter->getReturnType();
3999 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
4000 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
4001 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
4003 CheckObjCBridgeRelatedConversions(castExpr->getBeginLoc(), castType, SrcType,
4007 bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
4009 if (!getLangOpts().ObjC)
4011 ARCConversionTypeClass exprACTC =
4012 classifyTypeForARCConversion(castExpr->getType());
4013 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
4014 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
4015 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
4016 CheckTollFreeBridgeCast(castType, castExpr);
4017 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
4018 : CK_CPointerToObjCPointerCast;
4024 bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
4025 QualType DestType, QualType SrcType,
4026 ObjCInterfaceDecl *&RelatedClass,
4027 ObjCMethodDecl *&ClassMethod,
4028 ObjCMethodDecl *&InstanceMethod,
4029 TypedefNameDecl *&TDNDecl,
4030 bool CfToNs, bool Diagnose) {
4031 QualType T = CfToNs ? SrcType : DestType;
4032 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
4036 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
4037 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
4038 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
4041 NamedDecl *Target = nullptr;
4042 // Check for an existing type with this name.
4043 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
4044 Sema::LookupOrdinaryName);
4045 if (!LookupName(R, TUScope)) {
4047 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
4048 << SrcType << DestType;
4049 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4053 Target = R.getFoundDecl();
4054 if (Target && isa<ObjCInterfaceDecl>(Target))
4055 RelatedClass = cast<ObjCInterfaceDecl>(Target);
4058 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
4059 << SrcType << DestType;
4060 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4062 Diag(Target->getBeginLoc(), diag::note_declared_at);
4067 // Check for an existing class method with the given selector name.
4068 if (CfToNs && CMId) {
4069 Selector Sel = Context.Selectors.getUnarySelector(CMId);
4070 ClassMethod = RelatedClass->lookupMethod(Sel, false);
4073 Diag(Loc, diag::err_objc_bridged_related_known_method)
4074 << SrcType << DestType << Sel << false;
4075 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4081 // Check for an existing instance method with the given selector name.
4082 if (!CfToNs && IMId) {
4083 Selector Sel = Context.Selectors.getNullarySelector(IMId);
4084 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
4085 if (!InstanceMethod) {
4087 Diag(Loc, diag::err_objc_bridged_related_known_method)
4088 << SrcType << DestType << Sel << true;
4089 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4098 Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
4099 QualType DestType, QualType SrcType,
4100 Expr *&SrcExpr, bool Diagnose) {
4101 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
4102 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
4103 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
4104 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
4105 if (!CfToNs && !NsToCf)
4108 ObjCInterfaceDecl *RelatedClass;
4109 ObjCMethodDecl *ClassMethod = nullptr;
4110 ObjCMethodDecl *InstanceMethod = nullptr;
4111 TypedefNameDecl *TDNDecl = nullptr;
4112 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
4113 ClassMethod, InstanceMethod, TDNDecl,
4118 // Implicit conversion from CF to ObjC object is needed.
4121 std::string ExpressionString = "[";
4122 ExpressionString += RelatedClass->getNameAsString();
4123 ExpressionString += " ";
4124 ExpressionString += ClassMethod->getSelector().getAsString();
4125 SourceLocation SrcExprEndLoc =
4126 getLocForEndOfToken(SrcExpr->getEndLoc());
4127 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
4128 Diag(Loc, diag::err_objc_bridged_related_known_method)
4129 << SrcType << DestType << ClassMethod->getSelector() << false
4130 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(),
4132 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
4133 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4134 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4136 QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
4138 Expr *args[] = { SrcExpr };
4139 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
4140 ClassMethod->getLocation(),
4141 ClassMethod->getSelector(), ClassMethod,
4142 MultiExprArg(args, 1));
4143 SrcExpr = msg.get();
4149 // Implicit conversion from ObjC type to CF object is needed.
4150 if (InstanceMethod) {
4152 std::string ExpressionString;
4153 SourceLocation SrcExprEndLoc =
4154 getLocForEndOfToken(SrcExpr->getEndLoc());
4155 if (InstanceMethod->isPropertyAccessor())
4156 if (const ObjCPropertyDecl *PDecl =
4157 InstanceMethod->findPropertyDecl()) {
4158 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
4159 ExpressionString = ".";
4160 ExpressionString += PDecl->getNameAsString();
4161 Diag(Loc, diag::err_objc_bridged_related_known_method)
4162 << SrcType << DestType << InstanceMethod->getSelector() << true
4163 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4165 if (ExpressionString.empty()) {
4166 // Provide a fixit: [ObjectExpr InstanceMethod]
4167 ExpressionString = " ";
4168 ExpressionString += InstanceMethod->getSelector().getAsString();
4169 ExpressionString += "]";
4171 Diag(Loc, diag::err_objc_bridged_related_known_method)
4172 << SrcType << DestType << InstanceMethod->getSelector() << true
4173 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "[")
4174 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4176 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4177 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4180 BuildInstanceMessageImplicit(SrcExpr, SrcType,
4181 InstanceMethod->getLocation(),
4182 InstanceMethod->getSelector(),
4183 InstanceMethod, None);
4184 SrcExpr = msg.get();
4192 Sema::ARCConversionResult
4193 Sema::CheckObjCConversion(SourceRange castRange, QualType castType,
4194 Expr *&castExpr, CheckedConversionKind CCK,
4195 bool Diagnose, bool DiagnoseCFAudited,
4196 BinaryOperatorKind Opc) {
4197 QualType castExprType = castExpr->getType();
4199 // For the purposes of the classification, we assume reference types
4200 // will bind to temporaries.
4201 QualType effCastType = castType;
4202 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
4203 effCastType = ref->getPointeeType();
4205 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
4206 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
4207 if (exprACTC == castACTC) {
4208 // Check for viability and report error if casting an rvalue to a
4209 // life-time qualifier.
4210 if (castACTC == ACTC_retainable &&
4211 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
4212 castType != castExprType) {
4213 const Type *DT = castType.getTypePtr();
4214 QualType QDT = castType;
4215 // We desugar some types but not others. We ignore those
4216 // that cannot happen in a cast; i.e. auto, and those which
4217 // should not be de-sugared; i.e typedef.
4218 if (const ParenType *PT = dyn_cast<ParenType>(DT))
4219 QDT = PT->desugar();
4220 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
4221 QDT = TP->desugar();
4222 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
4223 QDT = AT->desugar();
4224 if (QDT != castType &&
4225 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
4227 SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
4228 : castExpr->getExprLoc());
4229 Diag(loc, diag::err_arc_nolifetime_behavior);
4237 // The life-time qualifier cast check above is all we need for ObjCWeak.
4238 // ObjCAutoRefCount has more restrictions on what is legal.
4239 if (!getLangOpts().ObjCAutoRefCount)
4242 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4244 // Allow all of these types to be cast to integer types (but not
4246 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4249 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4250 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4251 // must be explicit.
4252 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4254 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
4258 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
4259 // For invalid casts, fall through.
4263 // Do nothing for both bottom and +0.
4268 // If the result is +1, consume it here.
4270 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4271 CK_ARCConsumeObject, castExpr,
4272 nullptr, VK_RValue);
4273 Cleanup.setExprNeedsCleanups(true);
4277 // If this is a non-implicit cast from id or block type to a
4278 // CoreFoundation type, delay complaining in case the cast is used
4279 // in an acceptable context.
4280 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && isCast(CCK))
4281 return ACR_unbridged;
4283 // Issue a diagnostic about a missing @-sign when implicit casting a cstring
4284 // to 'NSString *', instead of falling through to report a "bridge cast"
4286 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
4287 ConversionToObjCStringLiteralCheck(castType, castExpr, Diagnose))
4290 // Do not issue "bridge cast" diagnostic when implicit casting
4291 // a retainable object to a CF type parameter belonging to an audited
4292 // CF API function. Let caller issue a normal type mismatched diagnostic
4294 if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4295 castACTC != ACTC_coreFoundation) &&
4296 !(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4297 (Opc == BO_NE || Opc == BO_EQ))) {
4299 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
4300 castExpr, exprACTC, CCK);
4306 /// Given that we saw an expression with the ARCUnbridgedCastTy
4307 /// placeholder type, complain bitterly.
4308 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4309 // We expect the spurious ImplicitCastExpr to already have been stripped.
4310 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4311 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4313 SourceRange castRange;
4315 CheckedConversionKind CCK;
4317 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4318 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4319 castType = cast->getTypeAsWritten();
4320 CCK = CCK_CStyleCast;
4321 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4322 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4323 castType = cast->getTypeAsWritten();
4324 CCK = CCK_OtherCast;
4326 llvm_unreachable("Unexpected ImplicitCastExpr");
4329 ARCConversionTypeClass castACTC =
4330 classifyTypeForARCConversion(castType.getNonReferenceType());
4332 Expr *castExpr = realCast->getSubExpr();
4333 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4335 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4336 castExpr, realCast, ACTC_retainable, CCK);
4339 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4340 /// type, remove the placeholder cast.
4341 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4342 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4344 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4345 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4346 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4347 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4348 assert(uo->getOpcode() == UO_Extension);
4349 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4350 return new (Context)
4351 UnaryOperator(sub, UO_Extension, sub->getType(), sub->getValueKind(),
4352 sub->getObjectKind(), uo->getOperatorLoc(), false);
4353 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4354 assert(!gse->isResultDependent());
4356 unsigned n = gse->getNumAssocs();
4357 SmallVector<Expr *, 4> subExprs;
4358 SmallVector<TypeSourceInfo *, 4> subTypes;
4359 subExprs.reserve(n);
4360 subTypes.reserve(n);
4361 for (const GenericSelectionExpr::Association &assoc : gse->associations()) {
4362 subTypes.push_back(assoc.getTypeSourceInfo());
4363 Expr *sub = assoc.getAssociationExpr();
4364 if (assoc.isSelected())
4365 sub = stripARCUnbridgedCast(sub);
4366 subExprs.push_back(sub);
4369 return GenericSelectionExpr::Create(
4370 Context, gse->getGenericLoc(), gse->getControllingExpr(), subTypes,
4371 subExprs, gse->getDefaultLoc(), gse->getRParenLoc(),
4372 gse->containsUnexpandedParameterPack(), gse->getResultIndex());
4374 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4375 return cast<ImplicitCastExpr>(e)->getSubExpr();
4379 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4380 QualType exprType) {
4381 QualType canCastType =
4382 Context.getCanonicalType(castType).getUnqualifiedType();
4383 QualType canExprType =
4384 Context.getCanonicalType(exprType).getUnqualifiedType();
4385 if (isa<ObjCObjectPointerType>(canCastType) &&
4386 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4387 canExprType->isObjCObjectPointerType()) {
4388 if (const ObjCObjectPointerType *ObjT =
4389 canExprType->getAs<ObjCObjectPointerType>())
4390 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4391 return !ObjI->isArcWeakrefUnavailable();
4396 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
4397 static Expr *maybeUndoReclaimObject(Expr *e) {
4398 Expr *curExpr = e, *prevExpr = nullptr;
4400 // Walk down the expression until we hit an implicit cast of kind
4401 // ARCReclaimReturnedObject or an Expr that is neither a Paren nor a Cast.
4403 if (auto *pe = dyn_cast<ParenExpr>(curExpr)) {
4405 curExpr = pe->getSubExpr();
4409 if (auto *ce = dyn_cast<CastExpr>(curExpr)) {
4410 if (auto *ice = dyn_cast<ImplicitCastExpr>(ce))
4411 if (ice->getCastKind() == CK_ARCReclaimReturnedObject) {
4413 return ice->getSubExpr();
4414 if (auto *pe = dyn_cast<ParenExpr>(prevExpr))
4415 pe->setSubExpr(ice->getSubExpr());
4417 cast<CastExpr>(prevExpr)->setSubExpr(ice->getSubExpr());
4422 curExpr = ce->getSubExpr();
4426 // Break out of the loop if curExpr is neither a Paren nor a Cast.
4433 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4434 ObjCBridgeCastKind Kind,
4435 SourceLocation BridgeKeywordLoc,
4436 TypeSourceInfo *TSInfo,
4438 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4439 if (SubResult.isInvalid()) return ExprError();
4440 SubExpr = SubResult.get();
4442 QualType T = TSInfo->getType();
4443 QualType FromType = SubExpr->getType();
4447 bool MustConsume = false;
4448 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4449 // Okay: we'll build a dependent expression type.
4451 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4453 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4454 : CK_CPointerToObjCPointerCast);
4459 case OBC_BridgeRetained: {
4460 bool br = isKnownName("CFBridgingRelease");
4461 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4464 << (T->isBlockPointerType()? 1 : 0)
4466 << SubExpr->getSourceRange()
4468 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4469 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4470 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
4472 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4473 br ? "CFBridgingRelease "
4474 : "__bridge_transfer ");
4480 case OBC_BridgeTransfer:
4481 // We must consume the Objective-C object produced by the cast.
4485 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4490 // Reclaiming a value that's going to be __bridge-casted to CF
4491 // is very dangerous, so we don't do it.
4492 SubExpr = maybeUndoReclaimObject(SubExpr);
4495 case OBC_BridgeRetained:
4496 // Produce the object before casting it.
4497 SubExpr = ImplicitCastExpr::Create(Context, FromType,
4498 CK_ARCProduceObject,
4499 SubExpr, nullptr, VK_RValue);
4502 case OBC_BridgeTransfer: {
4503 bool br = isKnownName("CFBridgingRetain");
4504 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4505 << (FromType->isBlockPointerType()? 1 : 0)
4509 << SubExpr->getSourceRange()
4512 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4513 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4514 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
4516 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4517 br ? "CFBridgingRetain " : "__bridge_retained");
4524 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4525 << FromType << T << Kind
4526 << SubExpr->getSourceRange()
4527 << TSInfo->getTypeLoc().getSourceRange();
4531 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
4536 Cleanup.setExprNeedsCleanups(true);
4537 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
4538 nullptr, VK_RValue);
4544 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4545 SourceLocation LParenLoc,
4546 ObjCBridgeCastKind Kind,
4547 SourceLocation BridgeKeywordLoc,
4549 SourceLocation RParenLoc,
4551 TypeSourceInfo *TSInfo = nullptr;
4552 QualType T = GetTypeFromParser(Type, &TSInfo);
4553 if (Kind == OBC_Bridge)
4554 CheckTollFreeBridgeCast(T, SubExpr);
4556 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4557 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,