1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for Objective-C expressions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21 #include "clang/Edit/Commit.h"
22 #include "clang/Edit/Rewriters.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Sema/Initialization.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "llvm/ADT/SmallString.h"
30 using namespace clang;
32 using llvm::makeArrayRef;
34 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
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->getLocStart(), 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->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
111 << 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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
403 = InitializationKind::CreateCopy(Element->getLocStart(),
405 InitializationSequence Seq(S, Entity, Kind, Element);
407 return Seq.Perform(S, Entity, Kind, Element);
410 Expr *OrigElement = Element;
412 // Perform lvalue-to-rvalue conversion.
413 Result = S.DefaultLvalueConversion(Element);
414 if (Result.isInvalid())
416 Element = Result.get();
418 // Make sure that we have an Objective-C pointer type or block.
419 if (!Element->getType()->isObjCObjectPointerType() &&
420 !Element->getType()->isBlockPointerType()) {
421 bool Recovered = false;
423 // If this is potentially an Objective-C numeric literal, add the '@'.
424 if (isa<IntegerLiteral>(OrigElement) ||
425 isa<CharacterLiteral>(OrigElement) ||
426 isa<FloatingLiteral>(OrigElement) ||
427 isa<ObjCBoolLiteralExpr>(OrigElement) ||
428 isa<CXXBoolLiteralExpr>(OrigElement)) {
429 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
430 int Which = isa<CharacterLiteral>(OrigElement) ? 1
431 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
432 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
435 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
436 << Which << OrigElement->getSourceRange()
437 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
439 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
441 if (Result.isInvalid())
444 Element = Result.get();
448 // If this is potentially an Objective-C string literal, add the '@'.
449 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
450 if (String->isAscii()) {
451 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
452 << 0 << OrigElement->getSourceRange()
453 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
455 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
456 if (Result.isInvalid())
459 Element = Result.get();
465 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
466 << Element->getType();
471 if (ObjCStringLiteral *getString =
472 dyn_cast<ObjCStringLiteral>(OrigElement)) {
473 if (StringLiteral *SL = getString->getString()) {
474 unsigned numConcat = SL->getNumConcatenated();
476 // Only warn if the concatenated string doesn't come from a macro.
477 bool hasMacro = false;
478 for (unsigned i = 0; i < numConcat ; ++i)
479 if (SL->getStrTokenLoc(i).isMacroID()) {
484 S.Diag(Element->getLocStart(),
485 diag::warn_concatenated_nsarray_literal)
486 << Element->getType();
491 // Make sure that the element has the type that the container factory
493 return S.PerformCopyInitialization(
494 InitializedEntity::InitializeParameter(S.Context, T,
496 Element->getLocStart(), Element);
499 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
500 if (ValueExpr->isTypeDependent()) {
501 ObjCBoxedExpr *BoxedExpr =
502 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
505 ObjCMethodDecl *BoxingMethod = nullptr;
507 // Convert the expression to an RValue, so we can check for pointer types...
508 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
509 if (RValue.isInvalid()) {
512 SourceLocation Loc = SR.getBegin();
513 ValueExpr = RValue.get();
514 QualType ValueType(ValueExpr->getType());
515 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
516 QualType PointeeType = PT->getPointeeType();
517 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
520 NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
525 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
526 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
529 if (!StringWithUTF8StringMethod) {
530 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
531 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
533 // Look for the appropriate method within NSString.
534 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
535 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
536 // Debugger needs to work even if NSString hasn't been defined.
537 TypeSourceInfo *ReturnTInfo = nullptr;
538 ObjCMethodDecl *M = ObjCMethodDecl::Create(
539 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
540 NSStringPointer, ReturnTInfo, NSStringDecl,
541 /*isInstance=*/false, /*isVariadic=*/false,
542 /*isPropertyAccessor=*/false,
543 /*isImplicitlyDeclared=*/true,
544 /*isDefined=*/false, ObjCMethodDecl::Required,
545 /*HasRelatedResultType=*/false);
546 QualType ConstCharType = Context.CharTy.withConst();
548 ParmVarDecl::Create(Context, M,
549 SourceLocation(), SourceLocation(),
550 &Context.Idents.get("value"),
551 Context.getPointerType(ConstCharType),
554 M->setMethodParams(Context, value, None);
558 if (!validateBoxingMethod(*this, Loc, NSStringDecl,
559 stringWithUTF8String, BoxingMethod))
562 StringWithUTF8StringMethod = BoxingMethod;
565 BoxingMethod = StringWithUTF8StringMethod;
566 BoxedType = NSStringPointer;
568 } else if (ValueType->isBuiltinType()) {
569 // The other types we support are numeric, char and BOOL/bool. We could also
570 // provide limited support for structure types, such as NSRange, NSRect, and
571 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
574 // Check for a top-level character literal.
575 if (const CharacterLiteral *Char =
576 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
577 // In C, character literals have type 'int'. That's not the type we want
578 // to use to determine the Objective-c literal kind.
579 switch (Char->getKind()) {
580 case CharacterLiteral::Ascii:
581 case CharacterLiteral::UTF8:
582 ValueType = Context.CharTy;
585 case CharacterLiteral::Wide:
586 ValueType = Context.getWideCharType();
589 case CharacterLiteral::UTF16:
590 ValueType = Context.Char16Ty;
593 case CharacterLiteral::UTF32:
594 ValueType = Context.Char32Ty;
598 // FIXME: Do I need to do anything special with BoolTy expressions?
600 // Look for the appropriate method within NSNumber.
601 BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
602 BoxedType = NSNumberPointer;
603 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
604 if (!ET->getDecl()->isComplete()) {
605 Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
606 << ValueType << ValueExpr->getSourceRange();
610 BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
611 ET->getDecl()->getIntegerType());
612 BoxedType = NSNumberPointer;
613 } else if (ValueType->isObjCBoxableRecordType()) {
614 // Support for structure types, that marked as objc_boxable
615 // struct __attribute__((objc_boxable)) s { ... };
617 // Look up the NSValue class, if we haven't done so already. It's cached
618 // in the Sema instance.
620 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
626 // generate the pointer to NSValue type.
627 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
628 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
631 if (!ValueWithBytesObjCTypeMethod) {
632 IdentifierInfo *II[] = {
633 &Context.Idents.get("valueWithBytes"),
634 &Context.Idents.get("objCType")
636 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
638 // Look for the appropriate method within NSValue.
639 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
640 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
641 // Debugger needs to work even if NSValue hasn't been defined.
642 TypeSourceInfo *ReturnTInfo = nullptr;
643 ObjCMethodDecl *M = ObjCMethodDecl::Create(
647 ValueWithBytesObjCType,
651 /*isInstance=*/false,
652 /*isVariadic=*/false,
653 /*isPropertyAccessor=*/false,
654 /*isImplicitlyDeclared=*/true,
656 ObjCMethodDecl::Required,
657 /*HasRelatedResultType=*/false);
659 SmallVector<ParmVarDecl *, 2> Params;
662 ParmVarDecl::Create(Context, M,
663 SourceLocation(), SourceLocation(),
664 &Context.Idents.get("bytes"),
665 Context.VoidPtrTy.withConst(),
668 Params.push_back(bytes);
670 QualType ConstCharType = Context.CharTy.withConst();
672 ParmVarDecl::Create(Context, M,
673 SourceLocation(), SourceLocation(),
674 &Context.Idents.get("type"),
675 Context.getPointerType(ConstCharType),
678 Params.push_back(type);
680 M->setMethodParams(Context, Params, None);
684 if (!validateBoxingMethod(*this, Loc, NSValueDecl,
685 ValueWithBytesObjCType, BoxingMethod))
688 ValueWithBytesObjCTypeMethod = BoxingMethod;
691 if (!ValueType.isTriviallyCopyableType(Context)) {
692 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
693 << ValueType << ValueExpr->getSourceRange();
697 BoxingMethod = ValueWithBytesObjCTypeMethod;
698 BoxedType = NSValuePointer;
702 Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
703 << ValueType << ValueExpr->getSourceRange();
707 DiagnoseUseOfDecl(BoxingMethod, Loc);
709 ExprResult ConvertedValueExpr;
710 if (ValueType->isObjCBoxableRecordType()) {
711 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
712 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
715 // Convert the expression to the type that the parameter requires.
716 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
717 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
719 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
723 if (ConvertedValueExpr.isInvalid())
725 ValueExpr = ConvertedValueExpr.get();
727 ObjCBoxedExpr *BoxedExpr =
728 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
730 return MaybeBindToTemporary(BoxedExpr);
733 /// Build an ObjC subscript pseudo-object expression, given that
734 /// that's supported by the runtime.
735 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
737 ObjCMethodDecl *getterMethod,
738 ObjCMethodDecl *setterMethod) {
739 assert(!LangOpts.isSubscriptPointerArithmetic());
741 // We can't get dependent types here; our callers should have
742 // filtered them out.
743 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
744 "base or index cannot have dependent type here");
746 // Filter out placeholders in the index. In theory, overloads could
747 // be preserved here, although that might not actually work correctly.
748 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
749 if (Result.isInvalid())
751 IndexExpr = Result.get();
753 // Perform lvalue-to-rvalue conversion on the base.
754 Result = DefaultLvalueConversion(BaseExpr);
755 if (Result.isInvalid())
757 BaseExpr = Result.get();
759 // Build the pseudo-object expression.
760 return new (Context) ObjCSubscriptRefExpr(
761 BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
762 getterMethod, setterMethod, RB);
765 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
766 SourceLocation Loc = SR.getBegin();
769 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
776 // Find the arrayWithObjects:count: method, if we haven't done so already.
777 QualType IdT = Context.getObjCIdType();
778 if (!ArrayWithObjectsMethod) {
780 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
781 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
782 if (!Method && getLangOpts().DebuggerObjCLiteral) {
783 TypeSourceInfo *ReturnTInfo = nullptr;
784 Method = ObjCMethodDecl::Create(
785 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
786 Context.getTranslationUnitDecl(), false /*Instance*/,
787 false /*isVariadic*/,
788 /*isPropertyAccessor=*/false,
789 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
790 ObjCMethodDecl::Required, false);
791 SmallVector<ParmVarDecl *, 2> Params;
792 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
795 &Context.Idents.get("objects"),
796 Context.getPointerType(IdT),
799 Params.push_back(objects);
800 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
803 &Context.Idents.get("cnt"),
804 Context.UnsignedLongTy,
805 /*TInfo=*/nullptr, SC_None,
807 Params.push_back(cnt);
808 Method->setMethodParams(Context, Params, None);
811 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
814 // Dig out the type that all elements should be converted to.
815 QualType T = Method->parameters()[0]->getType();
816 const PointerType *PtrT = T->getAs<PointerType>();
818 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
819 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
821 Diag(Method->parameters()[0]->getLocation(),
822 diag::note_objc_literal_method_param)
824 << Context.getPointerType(IdT.withConst());
828 // Check that the 'count' parameter is integral.
829 if (!Method->parameters()[1]->getType()->isIntegerType()) {
830 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
832 Diag(Method->parameters()[1]->getLocation(),
833 diag::note_objc_literal_method_param)
835 << Method->parameters()[1]->getType()
840 // We've found a good +arrayWithObjects:count: method. Save it!
841 ArrayWithObjectsMethod = Method;
844 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
845 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
847 // Check that each of the elements provided is valid in a collection literal,
848 // performing conversions as necessary.
849 Expr **ElementsBuffer = Elements.data();
850 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
851 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
854 if (Converted.isInvalid())
857 ElementsBuffer[I] = Converted.get();
861 = Context.getObjCObjectPointerType(
862 Context.getObjCInterfaceType(NSArrayDecl));
864 return MaybeBindToTemporary(
865 ObjCArrayLiteral::Create(Context, Elements, Ty,
866 ArrayWithObjectsMethod, SR));
869 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
870 MutableArrayRef<ObjCDictionaryElement> Elements) {
871 SourceLocation Loc = SR.getBegin();
873 if (!NSDictionaryDecl) {
874 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
875 Sema::LK_Dictionary);
876 if (!NSDictionaryDecl) {
881 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
883 QualType IdT = Context.getObjCIdType();
884 if (!DictionaryWithObjectsMethod) {
885 Selector Sel = NSAPIObj->getNSDictionarySelector(
886 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
887 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
888 if (!Method && getLangOpts().DebuggerObjCLiteral) {
889 Method = ObjCMethodDecl::Create(Context,
890 SourceLocation(), SourceLocation(), Sel,
892 nullptr /*TypeSourceInfo */,
893 Context.getTranslationUnitDecl(),
894 false /*Instance*/, false/*isVariadic*/,
895 /*isPropertyAccessor=*/false,
896 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
897 ObjCMethodDecl::Required,
899 SmallVector<ParmVarDecl *, 3> Params;
900 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
903 &Context.Idents.get("objects"),
904 Context.getPointerType(IdT),
905 /*TInfo=*/nullptr, SC_None,
907 Params.push_back(objects);
908 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
911 &Context.Idents.get("keys"),
912 Context.getPointerType(IdT),
913 /*TInfo=*/nullptr, SC_None,
915 Params.push_back(keys);
916 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
919 &Context.Idents.get("cnt"),
920 Context.UnsignedLongTy,
921 /*TInfo=*/nullptr, SC_None,
923 Params.push_back(cnt);
924 Method->setMethodParams(Context, Params, None);
927 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
931 // Dig out the type that all values should be converted to.
932 QualType ValueT = Method->parameters()[0]->getType();
933 const PointerType *PtrValue = ValueT->getAs<PointerType>();
935 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
936 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
938 Diag(Method->parameters()[0]->getLocation(),
939 diag::note_objc_literal_method_param)
941 << Context.getPointerType(IdT.withConst());
945 // Dig out the type that all keys should be converted to.
946 QualType KeyT = Method->parameters()[1]->getType();
947 const PointerType *PtrKey = KeyT->getAs<PointerType>();
949 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
953 if (QIDNSCopying.isNull()) {
954 // key argument of selector is id<NSCopying>?
955 if (ObjCProtocolDecl *NSCopyingPDecl =
956 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
957 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
959 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
961 (ObjCProtocolDecl**) PQ,
964 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
967 if (!QIDNSCopying.isNull())
968 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
973 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
975 Diag(Method->parameters()[1]->getLocation(),
976 diag::note_objc_literal_method_param)
978 << Context.getPointerType(IdT.withConst());
983 // Check that the 'count' parameter is integral.
984 QualType CountType = Method->parameters()[2]->getType();
985 if (!CountType->isIntegerType()) {
986 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
988 Diag(Method->parameters()[2]->getLocation(),
989 diag::note_objc_literal_method_param)
995 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
996 DictionaryWithObjectsMethod = Method;
999 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
1000 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
1001 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
1002 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1004 // Check that each of the keys and values provided is valid in a collection
1005 // literal, performing conversions as necessary.
1006 bool HasPackExpansions = false;
1007 for (ObjCDictionaryElement &Element : Elements) {
1009 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
1011 if (Key.isInvalid())
1016 = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
1017 if (Value.isInvalid())
1020 Element.Key = Key.get();
1021 Element.Value = Value.get();
1023 if (Element.EllipsisLoc.isInvalid())
1026 if (!Element.Key->containsUnexpandedParameterPack() &&
1027 !Element.Value->containsUnexpandedParameterPack()) {
1028 Diag(Element.EllipsisLoc,
1029 diag::err_pack_expansion_without_parameter_packs)
1030 << SourceRange(Element.Key->getLocStart(),
1031 Element.Value->getLocEnd());
1035 HasPackExpansions = true;
1039 = Context.getObjCObjectPointerType(
1040 Context.getObjCInterfaceType(NSDictionaryDecl));
1041 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
1042 Context, Elements, HasPackExpansions, Ty,
1043 DictionaryWithObjectsMethod, SR));
1046 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
1047 TypeSourceInfo *EncodedTypeInfo,
1048 SourceLocation RParenLoc) {
1049 QualType EncodedType = EncodedTypeInfo->getType();
1051 if (EncodedType->isDependentType())
1052 StrTy = Context.DependentTy;
1054 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1055 !EncodedType->isVoidType()) // void is handled too.
1056 if (RequireCompleteType(AtLoc, EncodedType,
1057 diag::err_incomplete_type_objc_at_encode,
1058 EncodedTypeInfo->getTypeLoc()))
1062 QualType NotEncodedT;
1063 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1064 if (!NotEncodedT.isNull())
1065 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1066 << EncodedType << NotEncodedT;
1068 // The type of @encode is the same as the type of the corresponding string,
1069 // which is an array type.
1070 StrTy = Context.CharTy;
1071 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1072 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1074 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
1075 ArrayType::Normal, 0);
1078 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
1081 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1082 SourceLocation EncodeLoc,
1083 SourceLocation LParenLoc,
1085 SourceLocation RParenLoc) {
1086 // FIXME: Preserve type source info ?
1087 TypeSourceInfo *TInfo;
1088 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1090 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1091 getLocForEndOfToken(LParenLoc));
1093 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
1096 static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1097 SourceLocation AtLoc,
1098 SourceLocation LParenLoc,
1099 SourceLocation RParenLoc,
1100 ObjCMethodDecl *Method,
1101 ObjCMethodList &MethList) {
1102 ObjCMethodList *M = &MethList;
1103 bool Warned = false;
1104 for (M = M->getNext(); M; M=M->getNext()) {
1105 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
1106 if (MatchingMethodDecl == Method ||
1107 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1108 MatchingMethodDecl->getSelector() != Method->getSelector())
1110 if (!S.MatchTwoMethodDeclarations(Method,
1111 MatchingMethodDecl, Sema::MMS_loose)) {
1114 S.Diag(AtLoc, diag::warn_multiple_selectors)
1115 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1116 << FixItHint::CreateInsertion(RParenLoc, ")");
1117 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1118 << Method->getDeclName();
1120 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1121 << MatchingMethodDecl->getDeclName();
1127 static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1128 ObjCMethodDecl *Method,
1129 SourceLocation LParenLoc,
1130 SourceLocation RParenLoc,
1131 bool WarnMultipleSelectors) {
1132 if (!WarnMultipleSelectors ||
1133 S.Diags.isIgnored(diag::warn_multiple_selectors, SourceLocation()))
1135 bool Warned = false;
1136 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1137 e = S.MethodPool.end(); b != e; b++) {
1138 // first, instance methods
1139 ObjCMethodList &InstMethList = b->second.first;
1140 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1141 Method, InstMethList))
1144 // second, class methods
1145 ObjCMethodList &ClsMethList = b->second.second;
1146 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1147 Method, ClsMethList) || Warned)
1152 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1153 SourceLocation AtLoc,
1154 SourceLocation SelLoc,
1155 SourceLocation LParenLoc,
1156 SourceLocation RParenLoc,
1157 bool WarnMultipleSelectors) {
1158 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1159 SourceRange(LParenLoc, RParenLoc));
1161 Method = LookupFactoryMethodInGlobalPool(Sel,
1162 SourceRange(LParenLoc, RParenLoc));
1164 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1165 Selector MatchedSel = OM->getSelector();
1166 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1167 RParenLoc.getLocWithOffset(-1));
1168 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1169 << Sel << MatchedSel
1170 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1173 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
1175 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1176 WarnMultipleSelectors);
1179 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1180 !getSourceManager().isInSystemHeader(Method->getLocation()))
1181 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
1183 // In ARC, forbid the user from using @selector for
1184 // retain/release/autorelease/dealloc/retainCount.
1185 if (getLangOpts().ObjCAutoRefCount) {
1186 switch (Sel.getMethodFamily()) {
1189 case OMF_autorelease:
1190 case OMF_retainCount:
1192 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1193 Sel << SourceRange(LParenLoc, RParenLoc);
1201 case OMF_mutableCopy:
1204 case OMF_initialize:
1205 case OMF_performSelector:
1209 QualType Ty = Context.getObjCSelType();
1210 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1213 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1214 SourceLocation AtLoc,
1215 SourceLocation ProtoLoc,
1216 SourceLocation LParenLoc,
1217 SourceLocation ProtoIdLoc,
1218 SourceLocation RParenLoc) {
1219 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
1221 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
1224 if (PDecl->hasDefinition())
1225 PDecl = PDecl->getDefinition();
1227 QualType Ty = Context.getObjCProtoType();
1230 Ty = Context.getObjCObjectPointerType(Ty);
1231 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1234 /// Try to capture an implicit reference to 'self'.
1235 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1236 DeclContext *DC = getFunctionLevelDeclContext();
1238 // If we're not in an ObjC method, error out. Note that, unlike the
1239 // C++ case, we don't require an instance method --- class methods
1240 // still have a 'self', and we really do still need to capture it!
1241 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1245 tryCaptureVariable(method->getSelfDecl(), Loc);
1250 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1251 QualType origType = T;
1252 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1253 if (T == Context.getObjCInstanceType()) {
1254 return Context.getAttributedType(
1255 AttributedType::getNullabilityAttrKind(*nullability),
1256 Context.getObjCIdType(),
1257 Context.getObjCIdType());
1263 if (T == Context.getObjCInstanceType())
1264 return Context.getObjCIdType();
1269 /// Determine the result type of a message send based on the receiver type,
1270 /// method, and the kind of message send.
1272 /// This is the "base" result type, which will still need to be adjusted
1273 /// to account for nullability.
1274 static QualType getBaseMessageSendResultType(Sema &S,
1275 QualType ReceiverType,
1276 ObjCMethodDecl *Method,
1277 bool isClassMessage,
1278 bool isSuperMessage) {
1279 assert(Method && "Must have a method");
1280 if (!Method->hasRelatedResultType())
1281 return Method->getSendResultType(ReceiverType);
1283 ASTContext &Context = S.Context;
1285 // Local function that transfers the nullability of the method's
1286 // result type to the returned result.
1287 auto transferNullability = [&](QualType type) -> QualType {
1288 // If the method's result type has nullability, extract it.
1289 if (auto nullability = Method->getSendResultType(ReceiverType)
1290 ->getNullability(Context)){
1291 // Strip off any outer nullability sugar from the provided type.
1292 (void)AttributedType::stripOuterNullability(type);
1294 // Form a new attributed type using the method result type's nullability.
1295 return Context.getAttributedType(
1296 AttributedType::getNullabilityAttrKind(*nullability),
1304 // If a method has a related return type:
1305 // - if the method found is an instance method, but the message send
1306 // was a class message send, T is the declared return type of the method
1308 if (Method->isInstanceMethod() && isClassMessage)
1309 return stripObjCInstanceType(Context,
1310 Method->getSendResultType(ReceiverType));
1312 // - if the receiver is super, T is a pointer to the class of the
1313 // enclosing method definition
1314 if (isSuperMessage) {
1315 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1316 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1317 return transferNullability(
1318 Context.getObjCObjectPointerType(
1319 Context.getObjCInterfaceType(Class)));
1323 // - if the receiver is the name of a class U, T is a pointer to U
1324 if (ReceiverType->getAsObjCInterfaceType())
1325 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1326 // - if the receiver is of type Class or qualified Class type,
1327 // T is the declared return type of the method.
1328 if (ReceiverType->isObjCClassType() ||
1329 ReceiverType->isObjCQualifiedClassType())
1330 return stripObjCInstanceType(Context,
1331 Method->getSendResultType(ReceiverType));
1333 // - if the receiver is id, qualified id, Class, or qualified Class, T
1334 // is the receiver type, otherwise
1335 // - T is the type of the receiver expression.
1336 return transferNullability(ReceiverType);
1339 QualType Sema::getMessageSendResultType(QualType ReceiverType,
1340 ObjCMethodDecl *Method,
1341 bool isClassMessage,
1342 bool isSuperMessage) {
1343 // Produce the result type.
1344 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1349 // If this is a class message, ignore the nullability of the receiver.
1353 // Map the nullability of the result into a table index.
1354 unsigned receiverNullabilityIdx = 0;
1355 if (auto nullability = ReceiverType->getNullability(Context))
1356 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1358 unsigned resultNullabilityIdx = 0;
1359 if (auto nullability = resultType->getNullability(Context))
1360 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1362 // The table of nullability mappings, indexed by the receiver's nullability
1363 // and then the result type's nullability.
1364 static const uint8_t None = 0;
1365 static const uint8_t NonNull = 1;
1366 static const uint8_t Nullable = 2;
1367 static const uint8_t Unspecified = 3;
1368 static const uint8_t nullabilityMap[4][4] = {
1369 // None NonNull Nullable Unspecified
1370 /* None */ { None, None, Nullable, None },
1371 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1372 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1373 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1376 unsigned newResultNullabilityIdx
1377 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1378 if (newResultNullabilityIdx == resultNullabilityIdx)
1381 // Strip off the existing nullability. This removes as little type sugar as
1384 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1385 resultType = attributed->getModifiedType();
1387 resultType = resultType.getDesugaredType(Context);
1389 } while (resultType->getNullability(Context));
1391 // Add nullability back if needed.
1392 if (newResultNullabilityIdx > 0) {
1394 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1395 return Context.getAttributedType(
1396 AttributedType::getNullabilityAttrKind(newNullability),
1397 resultType, resultType);
1403 /// Look for an ObjC method whose result type exactly matches the given type.
1404 static const ObjCMethodDecl *
1405 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1406 QualType instancetype) {
1407 if (MD->getReturnType() == instancetype)
1410 // For these purposes, a method in an @implementation overrides a
1411 // declaration in the @interface.
1412 if (const ObjCImplDecl *impl =
1413 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1414 const ObjCContainerDecl *iface;
1415 if (const ObjCCategoryImplDecl *catImpl =
1416 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1417 iface = catImpl->getCategoryDecl();
1419 iface = impl->getClassInterface();
1422 const ObjCMethodDecl *ifaceMD =
1423 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1424 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1427 SmallVector<const ObjCMethodDecl *, 4> overrides;
1428 MD->getOverriddenMethods(overrides);
1429 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1430 if (const ObjCMethodDecl *result =
1431 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1438 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1439 // Only complain if we're in an ObjC method and the required return
1440 // type doesn't match the method's declared return type.
1441 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1442 if (!MD || !MD->hasRelatedResultType() ||
1443 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
1446 // Look for a method overridden by this method which explicitly uses
1448 if (const ObjCMethodDecl *overridden =
1449 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1450 SourceRange range = overridden->getReturnTypeSourceRange();
1451 SourceLocation loc = range.getBegin();
1452 if (loc.isInvalid())
1453 loc = overridden->getLocation();
1454 Diag(loc, diag::note_related_result_type_explicit)
1455 << /*current method*/ 1 << range;
1459 // Otherwise, if we have an interesting method family, note that.
1460 // This should always trigger if the above didn't.
1461 if (ObjCMethodFamily family = MD->getMethodFamily())
1462 Diag(MD->getLocation(), diag::note_related_result_type_family)
1463 << /*current method*/ 1
1467 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1468 E = E->IgnoreParenImpCasts();
1469 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1473 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1477 if (!Method->hasRelatedResultType())
1480 if (Context.hasSameUnqualifiedType(
1481 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
1484 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
1485 Context.getObjCInstanceType()))
1488 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1489 << Method->isInstanceMethod() << Method->getSelector()
1490 << MsgSend->getType();
1493 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
1496 ArrayRef<SourceLocation> SelectorLocs,
1497 ObjCMethodDecl *Method,
1498 bool isClassMessage, bool isSuperMessage,
1499 SourceLocation lbrac, SourceLocation rbrac,
1500 SourceRange RecRange,
1501 QualType &ReturnType, ExprValueKind &VK) {
1502 SourceLocation SelLoc;
1503 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1504 SelLoc = SelectorLocs.front();
1509 // Apply default argument promotion as for (C99 6.5.2.2p6).
1510 for (unsigned i = 0, e = Args.size(); i != e; i++) {
1511 if (Args[i]->isTypeDependent())
1515 if (getLangOpts().DebuggerSupport) {
1516 QualType paramTy; // ignored
1517 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
1519 result = DefaultArgumentPromotion(Args[i]);
1521 if (result.isInvalid())
1523 Args[i] = result.get();
1527 if (getLangOpts().ObjCAutoRefCount)
1528 DiagID = diag::err_arc_method_not_found;
1530 DiagID = isClassMessage ? diag::warn_class_method_not_found
1531 : diag::warn_inst_method_not_found;
1532 if (!getLangOpts().DebuggerSupport) {
1533 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
1534 if (OMD && !OMD->isInvalidDecl()) {
1535 if (getLangOpts().ObjCAutoRefCount)
1536 DiagID = diag::err_method_not_found_with_typo;
1538 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1539 : diag::warn_instance_method_not_found_with_typo;
1540 Selector MatchedSel = OMD->getSelector();
1541 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
1542 if (MatchedSel.isUnarySelector())
1543 Diag(SelLoc, DiagID)
1544 << Sel<< isClassMessage << MatchedSel
1545 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1547 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
1550 Diag(SelLoc, DiagID)
1551 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
1552 SelectorLocs.back());
1553 // Find the class to which we are sending this message.
1554 if (ReceiverType->isObjCObjectPointerType()) {
1555 if (ObjCInterfaceDecl *ThisClass =
1556 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1557 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1558 if (!RecRange.isInvalid())
1559 if (ThisClass->lookupClassMethod(Sel))
1560 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1561 << FixItHint::CreateReplacement(RecRange,
1562 ThisClass->getNameAsString());
1567 // In debuggers, we want to use __unknown_anytype for these
1568 // results so that clients can cast them.
1569 if (getLangOpts().DebuggerSupport) {
1570 ReturnType = Context.UnknownAnyTy;
1572 ReturnType = Context.getObjCIdType();
1578 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1580 VK = Expr::getValueKindForType(Method->getReturnType());
1582 unsigned NumNamedArgs = Sel.getNumArgs();
1583 // Method might have more arguments than selector indicates. This is due
1584 // to addition of c-style arguments in method.
1585 if (Method->param_size() > Sel.getNumArgs())
1586 NumNamedArgs = Method->param_size();
1587 // FIXME. This need be cleaned up.
1588 if (Args.size() < NumNamedArgs) {
1589 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
1590 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
1594 // Compute the set of type arguments to be substituted into each parameter
1596 Optional<ArrayRef<QualType>> typeArgs
1597 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
1598 bool IsError = false;
1599 for (unsigned i = 0; i < NumNamedArgs; i++) {
1600 // We can't do any type-checking on a type-dependent argument.
1601 if (Args[i]->isTypeDependent())
1604 Expr *argExpr = Args[i];
1606 ParmVarDecl *param = Method->parameters()[i];
1607 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1609 // Strip the unbridged-cast placeholder expression off unless it's
1610 // a consumed argument.
1611 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1612 !param->hasAttr<CFConsumedAttr>())
1613 argExpr = stripARCUnbridgedCast(argExpr);
1615 // If the parameter is __unknown_anytype, infer its type
1616 // from the argument.
1617 if (param->getType() == Context.UnknownAnyTy) {
1619 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
1620 if (argE.isInvalid()) {
1623 Args[i] = argE.get();
1625 // Update the parameter type in-place.
1626 param->setType(paramType);
1631 QualType origParamType = param->getType();
1632 QualType paramType = param->getType();
1634 paramType = paramType.substObjCTypeArgs(
1637 ObjCSubstitutionContext::Parameter);
1639 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1641 diag::err_call_incomplete_argument, argExpr))
1644 InitializedEntity Entity
1645 = InitializedEntity::InitializeParameter(Context, param, paramType);
1646 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
1647 if (ArgE.isInvalid())
1650 Args[i] = ArgE.getAs<Expr>();
1652 // If we are type-erasing a block to a block-compatible
1653 // Objective-C pointer type, we may need to extend the lifetime
1654 // of the block object.
1655 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
1656 Args[i]->getType()->isBlockPointerType() &&
1657 origParamType->isObjCObjectPointerType()) {
1658 ExprResult arg = Args[i];
1659 maybeExtendBlockObject(arg);
1660 Args[i] = arg.get();
1665 // Promote additional arguments to variadic methods.
1666 if (Method->isVariadic()) {
1667 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
1668 if (Args[i]->isTypeDependent())
1671 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1673 IsError |= Arg.isInvalid();
1674 Args[i] = Arg.get();
1677 // Check for extra arguments to non-variadic methods.
1678 if (Args.size() != NumNamedArgs) {
1679 Diag(Args[NumNamedArgs]->getLocStart(),
1680 diag::err_typecheck_call_too_many_args)
1681 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1682 << Method->getSourceRange()
1683 << SourceRange(Args[NumNamedArgs]->getLocStart(),
1684 Args.back()->getLocEnd());
1688 DiagnoseSentinelCalls(Method, SelLoc, Args);
1690 // Do additional checkings on method.
1691 IsError |= CheckObjCMethodCall(
1692 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
1697 bool Sema::isSelfExpr(Expr *RExpr) {
1698 // 'self' is objc 'self' in an objc method only.
1699 ObjCMethodDecl *Method =
1700 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1701 return isSelfExpr(RExpr, Method);
1704 bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
1705 if (!method) return false;
1707 receiver = receiver->IgnoreParenLValueCasts();
1708 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1709 if (DRE->getDecl() == method->getSelfDecl())
1714 /// LookupMethodInType - Look up a method in an ObjCObjectType.
1715 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1717 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1718 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1719 // Look it up in the main interface (and categories, etc.)
1720 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1723 // Okay, look for "private" methods declared in any
1724 // @implementations we've seen.
1725 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1729 // Check qualifiers.
1730 for (const auto *I : objType->quals())
1731 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
1737 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1738 /// list of a qualified objective pointer type.
1739 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1740 const ObjCObjectPointerType *OPT,
1743 ObjCMethodDecl *MD = nullptr;
1744 for (const auto *PROTO : OPT->quals()) {
1745 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1752 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1753 /// objective C interface. This is a property reference expression.
1755 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1756 Expr *BaseExpr, SourceLocation OpLoc,
1757 DeclarationName MemberName,
1758 SourceLocation MemberLoc,
1759 SourceLocation SuperLoc, QualType SuperType,
1761 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1762 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1764 if (!MemberName.isIdentifier()) {
1765 Diag(MemberLoc, diag::err_invalid_property_name)
1766 << MemberName << QualType(OPT, 0);
1770 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1772 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1773 : BaseExpr->getSourceRange();
1774 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1775 diag::err_property_not_found_forward_class,
1776 MemberName, BaseRange))
1779 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
1780 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1781 // Check whether we can reference this property.
1782 if (DiagnoseUseOfDecl(PD, MemberLoc))
1785 return new (Context)
1786 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1787 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1789 return new (Context)
1790 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1791 OK_ObjCProperty, MemberLoc, BaseExpr);
1793 // Check protocols on qualified interfaces.
1794 for (const auto *I : OPT->quals())
1795 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
1796 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1797 // Check whether we can reference this property.
1798 if (DiagnoseUseOfDecl(PD, MemberLoc))
1802 return new (Context) ObjCPropertyRefExpr(
1803 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1804 SuperLoc, SuperType);
1806 return new (Context)
1807 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1808 OK_ObjCProperty, MemberLoc, BaseExpr);
1810 // If that failed, look for an "implicit" property by seeing if the nullary
1811 // selector is implemented.
1813 // FIXME: The logic for looking up nullary and unary selectors should be
1814 // shared with the code in ActOnInstanceMessage.
1816 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1817 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1819 // May be found in property's qualified list.
1821 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
1823 // If this reference is in an @implementation, check for 'private' methods.
1825 Getter = IFace->lookupPrivateMethod(Sel);
1828 // Check if we can reference this property.
1829 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1832 // If we found a getter then this may be a valid dot-reference, we
1833 // will look for the matching setter, in case it is needed.
1834 Selector SetterSel =
1835 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1836 PP.getSelectorTable(), Member);
1837 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1839 // May be found in property's qualified list.
1841 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1844 // If this reference is in an @implementation, also check for 'private'
1846 Setter = IFace->lookupPrivateMethod(SetterSel);
1849 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1852 // Special warning if member name used in a property-dot for a setter accessor
1853 // does not use a property with same name; e.g. obj.X = ... for a property with
1855 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() &&
1856 !IFace->FindPropertyDeclaration(
1857 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1858 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1859 // Do not warn if user is using property-dot syntax to make call to
1860 // user named setter.
1861 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
1863 diag::warn_property_access_suggest)
1864 << MemberName << QualType(OPT, 0) << PDecl->getName()
1865 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
1869 if (Getter || Setter) {
1871 return new (Context)
1872 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1873 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1875 return new (Context)
1876 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1877 OK_ObjCProperty, MemberLoc, BaseExpr);
1881 // Attempt to correct for typos in property names.
1882 if (TypoCorrection Corrected =
1883 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1884 LookupOrdinaryName, nullptr, nullptr,
1885 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1886 CTK_ErrorRecovery, IFace, false, OPT)) {
1887 DeclarationName TypoResult = Corrected.getCorrection();
1888 if (TypoResult.isIdentifier() &&
1889 TypoResult.getAsIdentifierInfo() == Member) {
1890 // There is no need to try the correction if it is the same.
1891 NamedDecl *ChosenDecl =
1892 Corrected.isKeyword() ? nullptr : Corrected.getFoundDecl();
1893 if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
1894 if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
1895 // This is a class property, we should not use the instance to
1897 Diag(MemberLoc, diag::err_class_property_found) << MemberName
1898 << OPT->getInterfaceDecl()->getName()
1899 << FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
1900 OPT->getInterfaceDecl()->getName());
1904 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1905 << MemberName << QualType(OPT, 0));
1906 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1907 TypoResult, MemberLoc,
1908 SuperLoc, SuperType, Super);
1911 ObjCInterfaceDecl *ClassDeclared;
1912 if (ObjCIvarDecl *Ivar =
1913 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1914 QualType T = Ivar->getType();
1915 if (const ObjCObjectPointerType * OBJPT =
1916 T->getAsObjCInterfacePointerType()) {
1917 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1918 diag::err_property_not_as_forward_class,
1919 MemberName, BaseExpr))
1923 diag::err_ivar_access_using_property_syntax_suggest)
1924 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1925 << FixItHint::CreateReplacement(OpLoc, "->");
1929 Diag(MemberLoc, diag::err_property_not_found)
1930 << MemberName << QualType(OPT, 0);
1932 Diag(Setter->getLocation(), diag::note_getter_unavailable)
1933 << MemberName << BaseExpr->getSourceRange();
1938 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1939 IdentifierInfo &propertyName,
1940 SourceLocation receiverNameLoc,
1941 SourceLocation propertyNameLoc) {
1943 IdentifierInfo *receiverNamePtr = &receiverName;
1944 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1949 // If the "receiver" is 'super' in a method, handle it as an expression-like
1950 // property reference.
1951 if (receiverNamePtr->isStr("super")) {
1952 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
1953 if (auto classDecl = CurMethod->getClassInterface()) {
1954 SuperType = QualType(classDecl->getSuperClassType(), 0);
1955 if (CurMethod->isInstanceMethod()) {
1956 if (SuperType.isNull()) {
1957 // The current class does not have a superclass.
1958 Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
1959 << CurMethod->getClassInterface()->getIdentifier();
1962 QualType T = Context.getObjCObjectPointerType(SuperType);
1964 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
1965 /*BaseExpr*/nullptr,
1966 SourceLocation()/*OpLoc*/,
1969 receiverNameLoc, T, true);
1972 // Otherwise, if this is a class method, try dispatching to our
1974 IFace = CurMethod->getClassInterface()->getSuperClass();
1980 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1988 if (auto PD = IFace->FindPropertyDeclaration(
1989 &propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) {
1990 GetterSel = PD->getGetterName();
1991 SetterSel = PD->getSetterName();
1993 GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName);
1994 SetterSel = SelectorTable::constructSetterSelector(
1995 PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName);
1998 // Search for a declared property first.
1999 ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel);
2001 // If this reference is in an @implementation, check for 'private' methods.
2003 Getter = IFace->lookupPrivateClassMethod(GetterSel);
2006 // FIXME: refactor/share with ActOnMemberReference().
2007 // Check if we can reference this property.
2008 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
2012 // Look for the matching setter, in case it is needed.
2013 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2015 // If this reference is in an @implementation, also check for 'private'
2017 Setter = IFace->lookupPrivateClassMethod(SetterSel);
2019 // Look through local category implementations associated with the class.
2021 Setter = IFace->getCategoryClassMethod(SetterSel);
2023 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2026 if (Getter || Setter) {
2027 if (!SuperType.isNull())
2028 return new (Context)
2029 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2030 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
2033 return new (Context) ObjCPropertyRefExpr(
2034 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2035 propertyNameLoc, receiverNameLoc, IFace);
2037 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2038 << &propertyName << Context.getObjCInterfaceType(IFace));
2043 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
2045 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2046 // Determine whether "super" is acceptable in the current context.
2047 if (Method && Method->getClassInterface())
2048 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2051 bool ValidateCandidate(const TypoCorrection &candidate) override {
2052 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2053 candidate.isKeyword("super");
2057 } // end anonymous namespace
2059 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
2060 IdentifierInfo *Name,
2061 SourceLocation NameLoc,
2063 bool HasTrailingDot,
2064 ParsedType &ReceiverType) {
2065 ReceiverType = nullptr;
2067 // If the identifier is "super" and there is no trailing dot, we're
2068 // messaging super. If the identifier is "super" and there is a
2069 // trailing dot, it's an instance message.
2070 if (IsSuper && S->isInObjcMethodScope())
2071 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
2073 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2074 LookupName(Result, S);
2076 switch (Result.getResultKind()) {
2077 case LookupResult::NotFound:
2078 // Normal name lookup didn't find anything. If we're in an
2079 // Objective-C method, look for ivars. If we find one, we're done!
2080 // FIXME: This is a hack. Ivar lookup should be part of normal
2082 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
2083 if (!Method->getClassInterface()) {
2084 // Fall back: let the parser try to parse it as an instance message.
2085 return ObjCInstanceMessage;
2088 ObjCInterfaceDecl *ClassDeclared;
2089 if (Method->getClassInterface()->lookupInstanceVariable(Name,
2091 return ObjCInstanceMessage;
2094 // Break out; we'll perform typo correction below.
2097 case LookupResult::NotFoundInCurrentInstantiation:
2098 case LookupResult::FoundOverloaded:
2099 case LookupResult::FoundUnresolvedValue:
2100 case LookupResult::Ambiguous:
2101 Result.suppressDiagnostics();
2102 return ObjCInstanceMessage;
2104 case LookupResult::Found: {
2105 // If the identifier is a class or not, and there is a trailing dot,
2106 // it's an instance message.
2108 return ObjCInstanceMessage;
2109 // We found something. If it's a type, then we have a class
2110 // message. Otherwise, it's an instance message.
2111 NamedDecl *ND = Result.getFoundDecl();
2113 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2114 T = Context.getObjCInterfaceType(Class);
2115 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
2116 T = Context.getTypeDeclType(Type);
2117 DiagnoseUseOfDecl(Type, NameLoc);
2120 return ObjCInstanceMessage;
2122 // We have a class message, and T is the type we're
2123 // messaging. Build source-location information for it.
2124 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2125 ReceiverType = CreateParsedType(T, TSInfo);
2126 return ObjCClassMessage;
2130 if (TypoCorrection Corrected = CorrectTypo(
2131 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
2132 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
2133 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
2134 if (Corrected.isKeyword()) {
2135 // If we've found the keyword "super" (the only keyword that would be
2136 // returned by CorrectTypo), this is a send to super.
2137 diagnoseTypo(Corrected,
2138 PDiag(diag::err_unknown_receiver_suggest) << Name);
2139 return ObjCSuperMessage;
2140 } else if (ObjCInterfaceDecl *Class =
2141 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2142 // If we found a declaration, correct when it refers to an Objective-C
2144 diagnoseTypo(Corrected,
2145 PDiag(diag::err_unknown_receiver_suggest) << Name);
2146 QualType T = Context.getObjCInterfaceType(Class);
2147 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2148 ReceiverType = CreateParsedType(T, TSInfo);
2149 return ObjCClassMessage;
2153 // Fall back: let the parser try to parse it as an instance message.
2154 return ObjCInstanceMessage;
2157 ExprResult Sema::ActOnSuperMessage(Scope *S,
2158 SourceLocation SuperLoc,
2160 SourceLocation LBracLoc,
2161 ArrayRef<SourceLocation> SelectorLocs,
2162 SourceLocation RBracLoc,
2163 MultiExprArg Args) {
2164 // Determine whether we are inside a method or not.
2165 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
2167 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2171 ObjCInterfaceDecl *Class = Method->getClassInterface();
2173 Diag(SuperLoc, diag::err_no_super_class_message)
2174 << Method->getDeclName();
2178 QualType SuperTy(Class->getSuperClassType(), 0);
2179 if (SuperTy.isNull()) {
2180 // The current class does not have a superclass.
2181 Diag(SuperLoc, diag::err_root_class_cannot_use_super)
2182 << Class->getIdentifier();
2186 // We are in a method whose class has a superclass, so 'super'
2187 // is acting as a keyword.
2188 if (Method->getSelector() == Sel)
2189 getCurFunction()->ObjCShouldCallSuper = false;
2191 if (Method->isInstanceMethod()) {
2192 // Since we are in an instance method, this is an instance
2193 // message to the superclass instance.
2194 SuperTy = Context.getObjCObjectPointerType(SuperTy);
2195 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2196 Sel, /*Method=*/nullptr,
2197 LBracLoc, SelectorLocs, RBracLoc, Args);
2200 // Since we are in a class method, this is a class message to
2202 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
2204 SuperLoc, Sel, /*Method=*/nullptr,
2205 LBracLoc, SelectorLocs, RBracLoc, Args);
2208 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2209 bool isSuperReceiver,
2212 ObjCMethodDecl *Method,
2213 MultiExprArg Args) {
2214 TypeSourceInfo *receiverTypeInfo = nullptr;
2215 if (!ReceiverType.isNull())
2216 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2218 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2219 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2220 Sel, Method, Loc, Loc, Loc, Args,
2221 /*isImplicit=*/true);
2224 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2226 bool (*refactor)(const ObjCMessageExpr *,
2227 const NSAPI &, edit::Commit &)) {
2228 SourceLocation MsgLoc = Msg->getExprLoc();
2229 if (S.Diags.isIgnored(DiagID, MsgLoc))
2232 SourceManager &SM = S.SourceMgr;
2233 edit::Commit ECommit(SM, S.LangOpts);
2234 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2235 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2236 << Msg->getSelector() << Msg->getSourceRange();
2237 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2238 if (!ECommit.isCommitable())
2240 for (edit::Commit::edit_iterator
2241 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2242 const edit::Commit::Edit &Edit = *I;
2243 switch (Edit.Kind) {
2244 case edit::Commit::Act_Insert:
2245 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2249 case edit::Commit::Act_InsertFromRange:
2250 Builder.AddFixItHint(
2251 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2252 Edit.getInsertFromRange(SM),
2255 case edit::Commit::Act_Remove:
2256 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2263 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2264 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2265 edit::rewriteObjCRedundantCallWithLiteral);
2268 static void checkFoundationAPI(Sema &S, SourceLocation Loc,
2269 const ObjCMethodDecl *Method,
2270 ArrayRef<Expr *> Args, QualType ReceiverType,
2271 bool IsClassObjectCall) {
2272 // Check if this is a performSelector method that uses a selector that returns
2273 // a record or a vector type.
2274 if (Method->getSelector().getMethodFamily() != OMF_performSelector ||
2277 const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens());
2280 ObjCMethodDecl *ImpliedMethod;
2281 if (!IsClassObjectCall) {
2282 const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>();
2283 if (!OPT || !OPT->getInterfaceDecl())
2286 OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector());
2289 OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector());
2291 const auto *IT = ReceiverType->getAs<ObjCInterfaceType>();
2294 ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector());
2297 IT->getDecl()->lookupPrivateClassMethod(SE->getSelector());
2301 QualType Ret = ImpliedMethod->getReturnType();
2302 if (Ret->isRecordType() || Ret->isVectorType() || Ret->isExtVectorType()) {
2303 QualType Ret = ImpliedMethod->getReturnType();
2304 S.Diag(Loc, diag::warn_objc_unsafe_perform_selector)
2305 << Method->getSelector()
2306 << (!Ret->isRecordType()
2308 : Ret->isUnionType() ? /*Union*/ 1 : /*Struct*/ 0);
2309 S.Diag(ImpliedMethod->getLocStart(),
2310 diag::note_objc_unsafe_perform_selector_method_declared_here)
2311 << ImpliedMethod->getSelector() << Ret;
2315 /// \brief Diagnose use of %s directive in an NSString which is being passed
2316 /// as formatting string to formatting method.
2318 DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2319 ObjCMethodDecl *Method,
2321 Expr **Args, unsigned NumArgs) {
2323 bool Format = false;
2324 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2325 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
2330 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2331 if (S.GetFormatNSStringIdx(I, Idx)) {
2337 if (!Format || NumArgs <= Idx)
2340 Expr *FormatExpr = Args[Idx];
2341 if (ObjCStringLiteral *OSL =
2342 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2343 StringLiteral *FormatString = OSL->getString();
2344 if (S.FormatStringHasSArg(FormatString)) {
2345 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2348 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2349 << Method->getDeclName();
2354 /// \brief Build an Objective-C class message expression.
2356 /// This routine takes care of both normal class messages and
2357 /// class messages to the superclass.
2359 /// \param ReceiverTypeInfo Type source information that describes the
2360 /// receiver of this message. This may be NULL, in which case we are
2361 /// sending to the superclass and \p SuperLoc must be a valid source
2364 /// \param ReceiverType The type of the object receiving the
2365 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2366 /// type as that refers to. For a superclass send, this is the type of
2369 /// \param SuperLoc The location of the "super" keyword in a
2370 /// superclass message.
2372 /// \param Sel The selector to which the message is being sent.
2374 /// \param Method The method that this class message is invoking, if
2377 /// \param LBracLoc The location of the opening square bracket ']'.
2379 /// \param RBracLoc The location of the closing square bracket ']'.
2381 /// \param ArgsIn The message arguments.
2382 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
2383 QualType ReceiverType,
2384 SourceLocation SuperLoc,
2386 ObjCMethodDecl *Method,
2387 SourceLocation LBracLoc,
2388 ArrayRef<SourceLocation> SelectorLocs,
2389 SourceLocation RBracLoc,
2390 MultiExprArg ArgsIn,
2392 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
2393 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
2394 if (LBracLoc.isInvalid()) {
2395 Diag(Loc, diag::err_missing_open_square_message_send)
2396 << FixItHint::CreateInsertion(Loc, "[");
2399 SourceLocation SelLoc;
2400 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2401 SelLoc = SelectorLocs.front();
2405 if (ReceiverType->isDependentType()) {
2406 // If the receiver type is dependent, we can't type-check anything
2407 // at this point. Build a dependent expression.
2408 unsigned NumArgs = ArgsIn.size();
2409 Expr **Args = ArgsIn.data();
2410 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2411 return ObjCMessageExpr::Create(
2412 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2413 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2417 // Find the class to which we are sending this message.
2418 ObjCInterfaceDecl *Class = nullptr;
2419 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2420 if (!ClassType || !(Class = ClassType->getInterface())) {
2421 Diag(Loc, diag::err_invalid_receiver_class_message)
2425 assert(Class && "We don't know which class we're messaging?");
2426 // objc++ diagnoses during typename annotation.
2427 if (!getLangOpts().CPlusPlus)
2428 (void)DiagnoseUseOfDecl(Class, SelLoc);
2429 // Find the method we are messaging.
2431 SourceRange TypeRange
2432 = SuperLoc.isValid()? SourceRange(SuperLoc)
2433 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
2434 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
2435 (getLangOpts().ObjCAutoRefCount
2436 ? diag::err_arc_receiver_forward_class
2437 : diag::warn_receiver_forward_class),
2439 // A forward class used in messaging is treated as a 'Class'
2440 Method = LookupFactoryMethodInGlobalPool(Sel,
2441 SourceRange(LBracLoc, RBracLoc));
2442 if (Method && !getLangOpts().ObjCAutoRefCount)
2443 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2444 << Method->getDeclName();
2447 Method = Class->lookupClassMethod(Sel);
2449 // If we have an implementation in scope, check "private" methods.
2451 Method = Class->lookupPrivateClassMethod(Sel);
2453 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2457 // Check the argument types and determine the result type.
2458 QualType ReturnType;
2459 ExprValueKind VK = VK_RValue;
2461 unsigned NumArgs = ArgsIn.size();
2462 Expr **Args = ArgsIn.data();
2463 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2466 SuperLoc.isValid(), LBracLoc, RBracLoc,
2471 if (Method && !Method->getReturnType()->isVoidType() &&
2472 RequireCompleteType(LBracLoc, Method->getReturnType(),
2473 diag::err_illegal_message_expr_incomplete_type))
2476 // Warn about explicit call of +initialize on its own class. But not on 'super'.
2477 if (Method && Method->getMethodFamily() == OMF_initialize) {
2478 if (!SuperLoc.isValid()) {
2479 const ObjCInterfaceDecl *ID =
2480 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2482 Diag(Loc, diag::warn_direct_initialize_call);
2483 Diag(Method->getLocation(), diag::note_method_declared_at)
2484 << Method->getDeclName();
2487 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2488 // [super initialize] is allowed only within an +initialize implementation
2489 if (CurMeth->getMethodFamily() != OMF_initialize) {
2490 Diag(Loc, diag::warn_direct_super_initialize_call);
2491 Diag(Method->getLocation(), diag::note_method_declared_at)
2492 << Method->getDeclName();
2493 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2494 << CurMeth->getDeclName();
2499 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2501 // Construct the appropriate ObjCMessageExpr.
2502 ObjCMessageExpr *Result;
2503 if (SuperLoc.isValid())
2504 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2505 SuperLoc, /*IsInstanceSuper=*/false,
2506 ReceiverType, Sel, SelectorLocs,
2507 Method, makeArrayRef(Args, NumArgs),
2508 RBracLoc, isImplicit);
2510 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2511 ReceiverTypeInfo, Sel, SelectorLocs,
2512 Method, makeArrayRef(Args, NumArgs),
2513 RBracLoc, isImplicit);
2515 checkCocoaAPI(*this, Result);
2518 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
2519 ReceiverType, /*IsClassObjectCall=*/true);
2520 return MaybeBindToTemporary(Result);
2523 // ActOnClassMessage - used for both unary and keyword messages.
2524 // ArgExprs is optional - if it is present, the number of expressions
2525 // is obtained from Sel.getNumArgs().
2526 ExprResult Sema::ActOnClassMessage(Scope *S,
2527 ParsedType Receiver,
2529 SourceLocation LBracLoc,
2530 ArrayRef<SourceLocation> SelectorLocs,
2531 SourceLocation RBracLoc,
2532 MultiExprArg Args) {
2533 TypeSourceInfo *ReceiverTypeInfo;
2534 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2535 if (ReceiverType.isNull())
2538 if (!ReceiverTypeInfo)
2539 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2541 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
2542 /*SuperLoc=*/SourceLocation(), Sel,
2543 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2547 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2548 QualType ReceiverType,
2551 ObjCMethodDecl *Method,
2552 MultiExprArg Args) {
2553 return BuildInstanceMessage(Receiver, ReceiverType,
2554 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2555 Sel, Method, Loc, Loc, Loc, Args,
2556 /*isImplicit=*/true);
2559 static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) {
2562 const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext());
2565 const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
2566 if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>(
2567 S.LookupSingleName(S.TUScope, II, Protocol->getLocStart(),
2568 Sema::LookupOrdinaryName))) {
2569 for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) {
2570 if (P->getCanonicalDecl() == Protocol->getCanonicalDecl())
2577 /// \brief Build an Objective-C instance message expression.
2579 /// This routine takes care of both normal instance messages and
2580 /// instance messages to the superclass instance.
2582 /// \param Receiver The expression that computes the object that will
2583 /// receive this message. This may be empty, in which case we are
2584 /// sending to the superclass instance and \p SuperLoc must be a valid
2585 /// source location.
2587 /// \param ReceiverType The (static) type of the object receiving the
2588 /// message. When a \p Receiver expression is provided, this is the
2589 /// same type as that expression. For a superclass instance send, this
2590 /// is a pointer to the type of the superclass.
2592 /// \param SuperLoc The location of the "super" keyword in a
2593 /// superclass instance message.
2595 /// \param Sel The selector to which the message is being sent.
2597 /// \param Method The method that this instance message is invoking, if
2600 /// \param LBracLoc The location of the opening square bracket ']'.
2602 /// \param RBracLoc The location of the closing square bracket ']'.
2604 /// \param ArgsIn The message arguments.
2605 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2606 QualType ReceiverType,
2607 SourceLocation SuperLoc,
2609 ObjCMethodDecl *Method,
2610 SourceLocation LBracLoc,
2611 ArrayRef<SourceLocation> SelectorLocs,
2612 SourceLocation RBracLoc,
2613 MultiExprArg ArgsIn,
2615 assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
2616 "SuperLoc must be valid so we can "
2619 // The location of the receiver.
2620 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
2621 SourceRange RecRange =
2622 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2623 SourceLocation SelLoc;
2624 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2625 SelLoc = SelectorLocs.front();
2629 if (LBracLoc.isInvalid()) {
2630 Diag(Loc, diag::err_missing_open_square_message_send)
2631 << FixItHint::CreateInsertion(Loc, "[");
2635 // If we have a receiver expression, perform appropriate promotions
2636 // and determine receiver type.
2638 if (Receiver->hasPlaceholderType()) {
2640 if (Receiver->getType() == Context.UnknownAnyTy)
2641 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2643 Result = CheckPlaceholderExpr(Receiver);
2644 if (Result.isInvalid()) return ExprError();
2645 Receiver = Result.get();
2648 if (Receiver->isTypeDependent()) {
2649 // If the receiver is type-dependent, we can't type-check anything
2650 // at this point. Build a dependent expression.
2651 unsigned NumArgs = ArgsIn.size();
2652 Expr **Args = ArgsIn.data();
2653 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2654 return ObjCMessageExpr::Create(
2655 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2656 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2657 RBracLoc, isImplicit);
2660 // If necessary, apply function/array conversion to the receiver.
2661 // C99 6.7.5.3p[7,8].
2662 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2663 if (Result.isInvalid())
2665 Receiver = Result.get();
2666 ReceiverType = Receiver->getType();
2668 // If the receiver is an ObjC pointer, a block pointer, or an
2669 // __attribute__((NSObject)) pointer, we don't need to do any
2670 // special conversion in order to look up a receiver.
2671 if (ReceiverType->isObjCRetainableType()) {
2673 } else if (!getLangOpts().ObjCAutoRefCount &&
2674 !Context.getObjCIdType().isNull() &&
2675 (ReceiverType->isPointerType() ||
2676 ReceiverType->isIntegerType())) {
2677 // Implicitly convert integers and pointers to 'id' but emit a warning.
2679 Diag(Loc, diag::warn_bad_receiver_type)
2681 << Receiver->getSourceRange();
2682 if (ReceiverType->isPointerType()) {
2683 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2684 CK_CPointerToObjCPointerCast).get();
2686 // TODO: specialized warning on null receivers?
2687 bool IsNull = Receiver->isNullPointerConstant(Context,
2688 Expr::NPC_ValueDependentIsNull);
2689 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2690 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2693 ReceiverType = Receiver->getType();
2694 } else if (getLangOpts().CPlusPlus) {
2695 // The receiver must be a complete type.
2696 if (RequireCompleteType(Loc, Receiver->getType(),
2697 diag::err_incomplete_receiver_type))
2700 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2701 if (result.isUsable()) {
2702 Receiver = result.get();
2703 ReceiverType = Receiver->getType();
2708 // There's a somewhat weird interaction here where we assume that we
2709 // won't actually have a method unless we also don't need to do some
2710 // of the more detailed type-checking on the receiver.
2713 // Handle messages to id and __kindof types (where we use the
2714 // global method pool).
2715 const ObjCObjectType *typeBound = nullptr;
2716 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2718 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
2719 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2720 SmallVector<ObjCMethodDecl*, 4> Methods;
2721 // If we have a type bound, further filter the methods.
2722 CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
2723 true/*CheckTheOther*/, typeBound);
2724 if (!Methods.empty()) {
2725 // We choose the first method as the initial candidate, then try to
2726 // select a better one.
2727 Method = Methods[0];
2729 if (ObjCMethodDecl *BestMethod =
2730 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
2731 Method = BestMethod;
2733 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2734 SourceRange(LBracLoc, RBracLoc),
2735 receiverIsIdLike, Methods))
2736 DiagnoseUseOfDecl(Method, SelLoc);
2738 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
2739 ReceiverType->isObjCQualifiedClassType()) {
2740 // Handle messages to Class.
2741 // We allow sending a message to a qualified Class ("Class<foo>"), which
2742 // is ok as long as one of the protocols implements the selector (if not,
2744 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2745 const ObjCObjectPointerType *QClassTy
2746 = ReceiverType->getAsObjCQualifiedClassType();
2747 // Search protocols for class methods.
2748 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2750 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2751 // warn if instance method found for a Class message.
2752 if (Method && !isMethodDeclaredInRootProtocol(*this, Method)) {
2753 Diag(SelLoc, diag::warn_instance_method_on_class_found)
2754 << Method->getSelector() << Sel;
2755 Diag(Method->getLocation(), diag::note_method_declared_at)
2756 << Method->getDeclName();
2760 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2761 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2762 // First check the public methods in the class interface.
2763 Method = ClassDecl->lookupClassMethod(Sel);
2766 Method = ClassDecl->lookupPrivateClassMethod(Sel);
2768 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2772 // If not messaging 'self', look for any factory method named 'Sel'.
2773 if (!Receiver || !isSelfExpr(Receiver)) {
2774 // If no class (factory) method was found, check if an _instance_
2775 // method of the same name exists in the root class only.
2776 SmallVector<ObjCMethodDecl*, 4> Methods;
2777 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2778 false/*InstanceFirst*/,
2779 true/*CheckTheOther*/);
2780 if (!Methods.empty()) {
2781 // We choose the first method as the initial candidate, then try
2782 // to select a better one.
2783 Method = Methods[0];
2785 // If we find an instance method, emit waring.
2786 if (Method->isInstanceMethod()) {
2787 if (const ObjCInterfaceDecl *ID =
2788 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2789 if (ID->getSuperClass())
2790 Diag(SelLoc, diag::warn_root_inst_method_not_found)
2791 << Sel << SourceRange(LBracLoc, RBracLoc);
2795 if (ObjCMethodDecl *BestMethod =
2796 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2798 Method = BestMethod;
2804 ObjCInterfaceDecl *ClassDecl = nullptr;
2806 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2807 // long as one of the protocols implements the selector (if not, warn).
2808 // And as long as message is not deprecated/unavailable (warn if it is).
2809 if (const ObjCObjectPointerType *QIdTy
2810 = ReceiverType->getAsObjCQualifiedIdType()) {
2811 // Search protocols for instance methods.
2812 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2814 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2815 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2817 } else if (const ObjCObjectPointerType *OCIType
2818 = ReceiverType->getAsObjCInterfacePointerType()) {
2819 // We allow sending a message to a pointer to an interface (an object).
2820 ClassDecl = OCIType->getInterfaceDecl();
2822 // Try to complete the type. Under ARC, this is a hard error from which
2823 // we don't try to recover.
2824 // FIXME: In the non-ARC case, this will still be a hard error if the
2825 // definition is found in a module that's not visible.
2826 const ObjCInterfaceDecl *forwardClass = nullptr;
2827 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
2828 getLangOpts().ObjCAutoRefCount
2829 ? diag::err_arc_receiver_forward_instance
2830 : diag::warn_receiver_forward_instance,
2831 Receiver? Receiver->getSourceRange()
2832 : SourceRange(SuperLoc))) {
2833 if (getLangOpts().ObjCAutoRefCount)
2836 forwardClass = OCIType->getInterfaceDecl();
2837 Diag(Receiver ? Receiver->getLocStart()
2838 : SuperLoc, diag::note_receiver_is_id);
2841 Method = ClassDecl->lookupInstanceMethod(Sel);
2845 // Search protocol qualifiers.
2846 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2849 // If we have implementations in scope, check "private" methods.
2850 Method = ClassDecl->lookupPrivateMethod(Sel);
2852 if (!Method && getLangOpts().ObjCAutoRefCount) {
2853 Diag(SelLoc, diag::err_arc_may_not_respond)
2854 << OCIType->getPointeeType() << Sel << RecRange
2855 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
2859 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2860 // If we still haven't found a method, look in the global pool. This
2861 // behavior isn't very desirable, however we need it for GCC
2862 // compatibility. FIXME: should we deviate??
2863 if (OCIType->qual_empty()) {
2864 SmallVector<ObjCMethodDecl*, 4> Methods;
2865 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2866 true/*InstanceFirst*/,
2867 false/*CheckTheOther*/);
2868 if (!Methods.empty()) {
2869 // We choose the first method as the initial candidate, then try
2870 // to select a better one.
2871 Method = Methods[0];
2873 if (ObjCMethodDecl *BestMethod =
2874 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2876 Method = BestMethod;
2878 AreMultipleMethodsInGlobalPool(Sel, Method,
2879 SourceRange(LBracLoc, RBracLoc),
2880 true/*receiverIdOrClass*/,
2883 if (Method && !forwardClass)
2884 Diag(SelLoc, diag::warn_maynot_respond)
2885 << OCIType->getInterfaceDecl()->getIdentifier()
2890 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
2893 // Reject other random receiver types (e.g. structs).
2894 Diag(Loc, diag::err_bad_receiver_type)
2895 << ReceiverType << Receiver->getSourceRange();
2901 FunctionScopeInfo *DIFunctionScopeInfo =
2902 (Method && Method->getMethodFamily() == OMF_init)
2903 ? getEnclosingFunction() : nullptr;
2905 if (DIFunctionScopeInfo &&
2906 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
2907 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2908 bool isDesignatedInitChain = false;
2909 if (SuperLoc.isValid()) {
2910 if (const ObjCObjectPointerType *
2911 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2912 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
2913 // Either we know this is a designated initializer or we
2914 // conservatively assume it because we don't know for sure.
2915 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2916 ID->isDesignatedInitializer(Sel)) {
2917 isDesignatedInitChain = true;
2918 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
2923 if (!isDesignatedInitChain) {
2924 const ObjCMethodDecl *InitMethod = nullptr;
2926 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2927 assert(isDesignated && InitMethod);
2929 Diag(SelLoc, SuperLoc.isValid() ?
2930 diag::warn_objc_designated_init_non_designated_init_call :
2931 diag::warn_objc_designated_init_non_super_designated_init_call);
2932 Diag(InitMethod->getLocation(),
2933 diag::note_objc_designated_init_marked_here);
2937 if (DIFunctionScopeInfo &&
2938 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
2939 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2940 if (SuperLoc.isValid()) {
2941 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2943 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
2947 // Check the message arguments.
2948 unsigned NumArgs = ArgsIn.size();
2949 Expr **Args = ArgsIn.data();
2950 QualType ReturnType;
2951 ExprValueKind VK = VK_RValue;
2952 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2953 ReceiverType->isObjCQualifiedClassType());
2954 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2955 Sel, SelectorLocs, Method,
2956 ClassMessage, SuperLoc.isValid(),
2957 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
2960 if (Method && !Method->getReturnType()->isVoidType() &&
2961 RequireCompleteType(LBracLoc, Method->getReturnType(),
2962 diag::err_illegal_message_expr_incomplete_type))
2965 // In ARC, forbid the user from sending messages to
2966 // retain/release/autorelease/dealloc/retainCount explicitly.
2967 if (getLangOpts().ObjCAutoRefCount) {
2968 ObjCMethodFamily family =
2969 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2973 checkInitMethod(Method, ReceiverType);
2979 case OMF_mutableCopy:
2982 case OMF_initialize:
2988 case OMF_autorelease:
2989 case OMF_retainCount:
2990 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2994 case OMF_performSelector:
2995 if (Method && NumArgs >= 1) {
2996 if (const auto *SelExp =
2997 dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
2998 Selector ArgSel = SelExp->getSelector();
2999 ObjCMethodDecl *SelMethod =
3000 LookupInstanceMethodInGlobalPool(ArgSel,
3001 SelExp->getSourceRange());
3004 LookupFactoryMethodInGlobalPool(ArgSel,
3005 SelExp->getSourceRange());
3007 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
3008 switch (SelFamily) {
3011 case OMF_mutableCopy:
3014 // Issue error, unless ns_returns_not_retained.
3015 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
3016 // selector names a +1 method
3018 diag::err_arc_perform_selector_retains);
3019 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3020 << SelMethod->getDeclName();
3024 // +0 call. OK. unless ns_returns_retained.
3025 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
3026 // selector names a +1 method
3028 diag::err_arc_perform_selector_retains);
3029 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3030 << SelMethod->getDeclName();
3036 // error (may leak).
3037 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
3038 Diag(Args[0]->getExprLoc(), diag::note_used_here);
3045 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
3047 // Construct the appropriate ObjCMessageExpr instance.
3048 ObjCMessageExpr *Result;
3049 if (SuperLoc.isValid())
3050 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3051 SuperLoc, /*IsInstanceSuper=*/true,
3052 ReceiverType, Sel, SelectorLocs, Method,
3053 makeArrayRef(Args, NumArgs), RBracLoc,
3056 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3057 Receiver, Sel, SelectorLocs, Method,
3058 makeArrayRef(Args, NumArgs), RBracLoc,
3061 checkCocoaAPI(*this, Result);
3064 bool IsClassObjectCall = ClassMessage;
3065 // 'self' message receivers in class methods should be treated as message
3066 // sends to the class object in order for the semantic checks to be
3067 // performed correctly. Messages to 'super' already count as class messages,
3068 // so they don't need to be handled here.
3069 if (Receiver && isSelfExpr(Receiver)) {
3070 if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
3071 if (OPT->getObjectType()->isObjCClass()) {
3072 if (const auto *CurMeth = getCurMethodDecl()) {
3073 IsClassObjectCall = true;
3075 Context.getObjCInterfaceType(CurMeth->getClassInterface());
3080 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
3081 ReceiverType, IsClassObjectCall);
3084 if (getLangOpts().ObjCAutoRefCount) {
3085 // In ARC, annotate delegate init calls.
3086 if (Result->getMethodFamily() == OMF_init &&
3087 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
3088 // Only consider init calls *directly* in init implementations,
3089 // not within blocks.
3090 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
3091 if (method && method->getMethodFamily() == OMF_init) {
3092 // The implicit assignment to self means we also don't want to
3093 // consume the result.
3094 Result->setDelegateInitCall(true);
3099 // In ARC, check for message sends which are likely to introduce
3101 checkRetainCycles(Result);
3104 if (getLangOpts().ObjCWeak) {
3105 if (!isImplicit && Method) {
3106 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
3108 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
3109 if (!IsWeak && Sel.isUnarySelector())
3110 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
3112 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
3113 getCurFunction()->recordUseOfWeak(Result, Prop);
3118 CheckObjCCircularContainer(Result);
3120 return MaybeBindToTemporary(Result);
3123 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
3124 if (ObjCSelectorExpr *OSE =
3125 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
3126 Selector Sel = OSE->getSelector();
3127 SourceLocation Loc = OSE->getAtLoc();
3128 auto Pos = S.ReferencedSelectors.find(Sel);
3129 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3130 S.ReferencedSelectors.erase(Pos);
3134 // ActOnInstanceMessage - used for both unary and keyword messages.
3135 // ArgExprs is optional - if it is present, the number of expressions
3136 // is obtained from Sel.getNumArgs().
3137 ExprResult Sema::ActOnInstanceMessage(Scope *S,
3140 SourceLocation LBracLoc,
3141 ArrayRef<SourceLocation> SelectorLocs,
3142 SourceLocation RBracLoc,
3143 MultiExprArg Args) {
3147 // A ParenListExpr can show up while doing error recovery with invalid code.
3148 if (isa<ParenListExpr>(Receiver)) {
3149 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3150 if (Result.isInvalid()) return ExprError();
3151 Receiver = Result.get();
3154 if (RespondsToSelectorSel.isNull()) {
3155 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3156 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3158 if (Sel == RespondsToSelectorSel)
3159 RemoveSelectorFromWarningCache(*this, Args[0]);
3161 return BuildInstanceMessage(Receiver, Receiver->getType(),
3162 /*SuperLoc=*/SourceLocation(), Sel,
3163 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3167 enum ARCConversionTypeClass {
3168 /// int, void, struct A
3174 /// id*, id***, void (^*)(),
3175 ACTC_indirectRetainable,
3177 /// void* might be a normal C type, or it might a CF type.
3184 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3185 return (ACTC == ACTC_retainable ||
3186 ACTC == ACTC_coreFoundation ||
3187 ACTC == ACTC_voidPtr);
3190 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3191 return ACTC == ACTC_none ||
3192 ACTC == ACTC_voidPtr ||
3193 ACTC == ACTC_coreFoundation;
3196 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
3197 bool isIndirect = false;
3199 // Ignore an outermost reference type.
3200 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
3201 type = ref->getPointeeType();
3205 // Drill through pointers and arrays recursively.
3207 if (const PointerType *ptr = type->getAs<PointerType>()) {
3208 type = ptr->getPointeeType();
3210 // The first level of pointer may be the innermost pointer on a CF type.
3212 if (type->isVoidType()) return ACTC_voidPtr;
3213 if (type->isRecordType()) return ACTC_coreFoundation;
3215 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3216 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3224 if (type->isObjCARCBridgableType())
3225 return ACTC_indirectRetainable;
3229 if (type->isObjCARCBridgableType())
3230 return ACTC_retainable;
3236 /// A result from the cast checker.
3238 /// Cannot be casted.
3241 /// Can be safely retained or not retained.
3244 /// Can be casted at +0.
3247 /// Can be casted at +1.
3250 ACCResult merge(ACCResult left, ACCResult right) {
3251 if (left == right) return left;
3252 if (left == ACC_bottom) return right;
3253 if (right == ACC_bottom) return left;
3257 /// A checker which white-lists certain expressions whose conversion
3258 /// to or from retainable type would otherwise be forbidden in ARC.
3259 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3260 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3262 ASTContext &Context;
3263 ARCConversionTypeClass SourceClass;
3264 ARCConversionTypeClass TargetClass;
3267 static bool isCFType(QualType type) {
3268 // Someday this can use ns_bridged. For now, it has to do this.
3269 return type->isCARCBridgableType();
3273 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
3274 ARCConversionTypeClass target, bool diagnose)
3275 : Context(Context), SourceClass(source), TargetClass(target),
3276 Diagnose(diagnose) {}
3279 ACCResult Visit(Expr *e) {
3280 return super::Visit(e->IgnoreParens());
3283 ACCResult VisitStmt(Stmt *s) {
3287 /// Null pointer constants can be casted however you please.
3288 ACCResult VisitExpr(Expr *e) {
3289 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3294 /// Objective-C string literals can be safely casted.
3295 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3296 // If we're casting to any retainable type, go ahead. Global
3297 // strings are immune to retains, so this is bottom.
3298 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3303 /// Look through certain implicit and explicit casts.
3304 ACCResult VisitCastExpr(CastExpr *e) {
3305 switch (e->getCastKind()) {
3306 case CK_NullToPointer:
3310 case CK_LValueToRValue:
3312 case CK_CPointerToObjCPointerCast:
3313 case CK_BlockPointerToObjCPointerCast:
3314 case CK_AnyPointerToBlockPointerCast:
3315 return Visit(e->getSubExpr());
3322 /// Look through unary extension.
3323 ACCResult VisitUnaryExtension(UnaryOperator *e) {
3324 return Visit(e->getSubExpr());
3327 /// Ignore the LHS of a comma operator.
3328 ACCResult VisitBinComma(BinaryOperator *e) {
3329 return Visit(e->getRHS());
3332 /// Conditional operators are okay if both sides are okay.
3333 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3334 ACCResult left = Visit(e->getTrueExpr());
3335 if (left == ACC_invalid) return ACC_invalid;
3336 return merge(left, Visit(e->getFalseExpr()));
3339 /// Look through pseudo-objects.
3340 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3341 // If we're getting here, we should always have a result.
3342 return Visit(e->getResultExpr());
3345 /// Statement expressions are okay if their result expression is okay.
3346 ACCResult VisitStmtExpr(StmtExpr *e) {
3347 return Visit(e->getSubStmt()->body_back());
3350 /// Some declaration references are okay.
3351 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
3352 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
3353 // References to global constants are okay.
3354 if (isAnyRetainable(TargetClass) &&
3355 isAnyRetainable(SourceClass) &&
3357 !var->hasDefinition(Context) &&
3358 var->getType().isConstQualified()) {
3360 // In system headers, they can also be assumed to be immune to retains.
3361 // These are things like 'kCFStringTransformToLatin'.
3362 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3365 return ACC_plusZero;
3372 /// Some calls are okay.
3373 ACCResult VisitCallExpr(CallExpr *e) {
3374 if (FunctionDecl *fn = e->getDirectCallee())
3375 if (ACCResult result = checkCallToFunction(fn))
3378 return super::VisitCallExpr(e);
3381 ACCResult checkCallToFunction(FunctionDecl *fn) {
3382 // Require a CF*Ref return type.
3383 if (!isCFType(fn->getReturnType()))
3386 if (!isAnyRetainable(TargetClass))
3389 // Honor an explicit 'not retained' attribute.
3390 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3391 return ACC_plusZero;
3393 // Honor an explicit 'retained' attribute, except that for
3394 // now we're not going to permit implicit handling of +1 results,
3395 // because it's a bit frightening.
3396 if (fn->hasAttr<CFReturnsRetainedAttr>())
3397 return Diagnose ? ACC_plusOne
3398 : ACC_invalid; // ACC_plusOne if we start accepting this
3400 // Recognize this specific builtin function, which is used by CFSTR.
3401 unsigned builtinID = fn->getBuiltinID();
3402 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3405 // Otherwise, don't do anything implicit with an unaudited function.
3406 if (!fn->hasAttr<CFAuditedTransferAttr>())
3409 // Otherwise, it's +0 unless it follows the create convention.
3410 if (ento::coreFoundation::followsCreateRule(fn))
3411 return Diagnose ? ACC_plusOne
3412 : ACC_invalid; // ACC_plusOne if we start accepting this
3414 return ACC_plusZero;
3417 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3418 return checkCallToMethod(e->getMethodDecl());
3421 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3422 ObjCMethodDecl *method;
3423 if (e->isExplicitProperty())
3424 method = e->getExplicitProperty()->getGetterMethodDecl();
3426 method = e->getImplicitPropertyGetter();
3427 return checkCallToMethod(method);
3430 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3431 if (!method) return ACC_invalid;
3433 // Check for message sends to functions returning CF types. We
3434 // just obey the Cocoa conventions with these, even though the
3435 // return type is CF.
3436 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
3439 // If the method is explicitly marked not-retained, it's +0.
3440 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3441 return ACC_plusZero;
3443 // If the method is explicitly marked as returning retained, or its
3444 // selector follows a +1 Cocoa convention, treat it as +1.
3445 if (method->hasAttr<CFReturnsRetainedAttr>())
3448 switch (method->getSelector().getMethodFamily()) {
3451 case OMF_mutableCopy:
3456 // Otherwise, treat it as +0.
3457 return ACC_plusZero;
3461 } // end anonymous namespace
3463 bool Sema::isKnownName(StringRef name) {
3466 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
3467 Sema::LookupOrdinaryName);
3468 return LookupName(R, TUScope, false);
3471 static void addFixitForObjCARCConversion(Sema &S,
3472 DiagnosticBuilder &DiagB,
3473 Sema::CheckedConversionKind CCK,
3474 SourceLocation afterLParen,
3478 const char *bridgeKeyword,
3479 const char *CFBridgeName) {
3480 // We handle C-style and implicit casts here.
3482 case Sema::CCK_ImplicitConversion:
3483 case Sema::CCK_CStyleCast:
3484 case Sema::CCK_OtherCast:
3486 case Sema::CCK_FunctionalCast:
3491 if (CCK == Sema::CCK_OtherCast) {
3492 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3493 SourceRange range(NCE->getOperatorLoc(),
3494 NCE->getAngleBrackets().getEnd());
3495 SmallString<32> BridgeCall;
3497 SourceManager &SM = S.getSourceManager();
3498 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3499 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3502 BridgeCall += CFBridgeName;
3503 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3507 Expr *castedE = castExpr;
3508 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3509 castedE = CCE->getSubExpr();
3510 castedE = castedE->IgnoreImpCasts();
3511 SourceRange range = castedE->getSourceRange();
3513 SmallString<32> BridgeCall;
3515 SourceManager &SM = S.getSourceManager();
3516 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3517 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3520 BridgeCall += CFBridgeName;
3522 if (isa<ParenExpr>(castedE)) {
3523 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3527 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3529 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3530 S.getLocForEndOfToken(range.getEnd()),
3536 if (CCK == Sema::CCK_CStyleCast) {
3537 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
3538 } else if (CCK == Sema::CCK_OtherCast) {
3539 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3540 std::string castCode = "(";
3541 castCode += bridgeKeyword;
3542 castCode += castType.getAsString();
3544 SourceRange Range(NCE->getOperatorLoc(),
3545 NCE->getAngleBrackets().getEnd());
3546 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3549 std::string castCode = "(";
3550 castCode += bridgeKeyword;
3551 castCode += castType.getAsString();
3553 Expr *castedE = castExpr->IgnoreImpCasts();
3554 SourceRange range = castedE->getSourceRange();
3555 if (isa<ParenExpr>(castedE)) {
3556 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3560 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3562 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3563 S.getLocForEndOfToken(range.getEnd()),
3569 template <typename T>
3570 static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3571 TypedefNameDecl *TDNDecl = TD->getDecl();
3572 QualType QT = TDNDecl->getUnderlyingType();
3573 if (QT->isPointerType()) {
3574 QT = QT->getPointeeType();
3575 if (const RecordType *RT = QT->getAs<RecordType>())
3576 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
3577 return RD->getAttr<T>();
3582 static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3583 TypedefNameDecl *&TDNDecl) {
3584 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3585 TDNDecl = TD->getDecl();
3586 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3587 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3589 T = TDNDecl->getUnderlyingType();
3595 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3596 QualType castType, ARCConversionTypeClass castACTC,
3597 Expr *castExpr, Expr *realCast,
3598 ARCConversionTypeClass exprACTC,
3599 Sema::CheckedConversionKind CCK) {
3600 SourceLocation loc =
3601 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
3603 if (S.makeUnavailableInSystemHeader(loc,
3604 UnavailableAttr::IR_ARCForbiddenConversion))
3607 QualType castExprType = castExpr->getType();
3608 // Defer emitting a diagnostic for bridge-related casts; that will be
3609 // handled by CheckObjCBridgeRelatedConversions.
3610 TypedefNameDecl *TDNDecl = nullptr;
3611 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3612 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3613 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3614 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3617 unsigned srcKind = 0;
3620 case ACTC_coreFoundation:
3622 srcKind = (castExprType->isPointerType() ? 1 : 0);
3624 case ACTC_retainable:
3625 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3627 case ACTC_indirectRetainable:
3632 // Check whether this could be fixed with a bridge cast.
3633 SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
3634 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
3636 // Bridge from an ARC type to a CF type.
3637 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
3639 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3640 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3641 << 2 // of C pointer type
3643 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3646 << castExpr->getSourceRange();
3647 bool br = S.isKnownName("CFBridgingRelease");
3648 ACCResult CreateRule =
3649 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3650 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3651 if (CreateRule != ACC_plusOne)
3653 DiagnosticBuilder DiagB =
3654 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3655 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3657 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3658 castType, castExpr, realCast, "__bridge ",
3661 if (CreateRule != ACC_plusZero)
3663 DiagnosticBuilder DiagB =
3664 (CCK == Sema::CCK_OtherCast && !br) ?
3665 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3666 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3667 diag::note_arc_bridge_transfer)
3668 << castExprType << br;
3670 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3671 castType, castExpr, realCast, "__bridge_transfer ",
3672 br ? "CFBridgingRelease" : nullptr);
3678 // Bridge from a CF type to an ARC type.
3679 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
3680 bool br = S.isKnownName("CFBridgingRetain");
3681 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3682 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3683 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3685 << 2 // to C pointer type
3688 << castExpr->getSourceRange();
3689 ACCResult CreateRule =
3690 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3691 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3692 if (CreateRule != ACC_plusOne)
3694 DiagnosticBuilder DiagB =
3695 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3696 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3697 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3698 castType, castExpr, realCast, "__bridge ",
3701 if (CreateRule != ACC_plusZero)
3703 DiagnosticBuilder DiagB =
3704 (CCK == Sema::CCK_OtherCast && !br) ?
3705 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3706 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3707 diag::note_arc_bridge_retained)
3710 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3711 castType, castExpr, realCast, "__bridge_retained ",
3712 br ? "CFBridgingRetain" : nullptr);
3718 S.Diag(loc, diag::err_arc_mismatched_cast)
3719 << (CCK != Sema::CCK_ImplicitConversion)
3720 << srcKind << castExprType << castType
3721 << castRange << castExpr->getSourceRange();
3724 template <typename TB>
3725 static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3726 bool &HadTheAttribute, bool warn) {
3727 QualType T = castExpr->getType();
3728 HadTheAttribute = false;
3729 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3730 TypedefNameDecl *TDNDecl = TD->getDecl();
3731 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3732 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3733 HadTheAttribute = true;
3734 if (Parm->isStr("id"))
3737 NamedDecl *Target = nullptr;
3738 // Check for an existing type with this name.
3739 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3740 Sema::LookupOrdinaryName);
3741 if (S.LookupName(R, S.TUScope)) {
3742 Target = R.getFoundDecl();
3743 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3744 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3745 if (const ObjCObjectPointerType *InterfacePointerType =
3746 castType->getAsObjCInterfacePointerType()) {
3747 ObjCInterfaceDecl *CastClass
3748 = InterfacePointerType->getObjectType()->getInterface();
3749 if ((CastClass == ExprClass) ||
3750 (CastClass && CastClass->isSuperClassOf(ExprClass)))
3753 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3754 << T << Target->getName() << castType->getPointeeType();
3756 } else if (castType->isObjCIdType() ||
3757 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3758 castType, ExprClass)))
3759 // ok to cast to 'id'.
3760 // casting to id<p-list> is ok if bridge type adopts all of
3761 // p-list protocols.
3765 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3766 << T << Target->getName() << castType;
3767 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3768 S.Diag(Target->getLocStart(), diag::note_declared_at);
3773 } else if (!castType->isObjCIdType()) {
3774 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
3775 << castExpr->getType() << Parm;
3776 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3778 S.Diag(Target->getLocStart(), diag::note_declared_at);
3784 T = TDNDecl->getUnderlyingType();
3789 template <typename TB>
3790 static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3791 bool &HadTheAttribute, bool warn) {
3792 QualType T = castType;
3793 HadTheAttribute = false;
3794 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3795 TypedefNameDecl *TDNDecl = TD->getDecl();
3796 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3797 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3798 HadTheAttribute = true;
3799 if (Parm->isStr("id"))
3802 NamedDecl *Target = nullptr;
3803 // Check for an existing type with this name.
3804 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3805 Sema::LookupOrdinaryName);
3806 if (S.LookupName(R, S.TUScope)) {
3807 Target = R.getFoundDecl();
3808 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3809 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3810 if (const ObjCObjectPointerType *InterfacePointerType =
3811 castExpr->getType()->getAsObjCInterfacePointerType()) {
3812 ObjCInterfaceDecl *ExprClass
3813 = InterfacePointerType->getObjectType()->getInterface();
3814 if ((CastClass == ExprClass) ||
3815 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
3818 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3819 << castExpr->getType()->getPointeeType() << T;
3820 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3823 } else if (castExpr->getType()->isObjCIdType() ||
3824 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3825 castExpr->getType(), CastClass)))
3826 // ok to cast an 'id' expression to a CFtype.
3827 // ok to cast an 'id<plist>' expression to CFtype provided plist
3828 // adopts all of CFtype's ObjetiveC's class plist.
3832 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3833 << castExpr->getType() << castType;
3834 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3835 S.Diag(Target->getLocStart(), diag::note_declared_at);
3841 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3842 << castExpr->getType() << castType;
3843 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3845 S.Diag(Target->getLocStart(), diag::note_declared_at);
3850 T = TDNDecl->getUnderlyingType();
3855 void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
3856 if (!getLangOpts().ObjC1)
3858 // warn in presence of __bridge casting to or from a toll free bridge cast.
3859 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3860 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3861 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
3862 bool HasObjCBridgeAttr;
3863 bool ObjCBridgeAttrWillNotWarn =
3864 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3866 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3868 bool HasObjCBridgeMutableAttr;
3869 bool ObjCBridgeMutableAttrWillNotWarn =
3870 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3871 HasObjCBridgeMutableAttr, false);
3872 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3875 if (HasObjCBridgeAttr)
3876 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3878 else if (HasObjCBridgeMutableAttr)
3879 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3880 HasObjCBridgeMutableAttr, true);
3882 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
3883 bool HasObjCBridgeAttr;
3884 bool ObjCBridgeAttrWillNotWarn =
3885 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3887 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3889 bool HasObjCBridgeMutableAttr;
3890 bool ObjCBridgeMutableAttrWillNotWarn =
3891 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3892 HasObjCBridgeMutableAttr, false);
3893 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3896 if (HasObjCBridgeAttr)
3897 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3899 else if (HasObjCBridgeMutableAttr)
3900 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3901 HasObjCBridgeMutableAttr, true);
3905 void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3906 QualType SrcType = castExpr->getType();
3907 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3908 if (PRE->isExplicitProperty()) {
3909 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3910 SrcType = PDecl->getType();
3912 else if (PRE->isImplicitProperty()) {
3913 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3914 SrcType = Getter->getReturnType();
3918 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3919 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3920 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3922 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3923 castType, SrcType, castExpr);
3926 bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3928 if (!getLangOpts().ObjC1)
3930 ARCConversionTypeClass exprACTC =
3931 classifyTypeForARCConversion(castExpr->getType());
3932 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3933 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3934 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3935 CheckTollFreeBridgeCast(castType, castExpr);
3936 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3937 : CK_CPointerToObjCPointerCast;
3943 bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3944 QualType DestType, QualType SrcType,
3945 ObjCInterfaceDecl *&RelatedClass,
3946 ObjCMethodDecl *&ClassMethod,
3947 ObjCMethodDecl *&InstanceMethod,
3948 TypedefNameDecl *&TDNDecl,
3949 bool CfToNs, bool Diagnose) {
3950 QualType T = CfToNs ? SrcType : DestType;
3951 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3955 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3956 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3957 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3960 NamedDecl *Target = nullptr;
3961 // Check for an existing type with this name.
3962 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3963 Sema::LookupOrdinaryName);
3964 if (!LookupName(R, TUScope)) {
3966 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
3967 << SrcType << DestType;
3968 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3972 Target = R.getFoundDecl();
3973 if (Target && isa<ObjCInterfaceDecl>(Target))
3974 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3977 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3978 << SrcType << DestType;
3979 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3981 Diag(Target->getLocStart(), diag::note_declared_at);
3986 // Check for an existing class method with the given selector name.
3987 if (CfToNs && CMId) {
3988 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3989 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3992 Diag(Loc, diag::err_objc_bridged_related_known_method)
3993 << SrcType << DestType << Sel << false;
3994 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
4000 // Check for an existing instance method with the given selector name.
4001 if (!CfToNs && IMId) {
4002 Selector Sel = Context.Selectors.getNullarySelector(IMId);
4003 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
4004 if (!InstanceMethod) {
4006 Diag(Loc, diag::err_objc_bridged_related_known_method)
4007 << SrcType << DestType << Sel << true;
4008 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
4017 Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
4018 QualType DestType, QualType SrcType,
4019 Expr *&SrcExpr, bool Diagnose) {
4020 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
4021 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
4022 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
4023 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
4024 if (!CfToNs && !NsToCf)
4027 ObjCInterfaceDecl *RelatedClass;
4028 ObjCMethodDecl *ClassMethod = nullptr;
4029 ObjCMethodDecl *InstanceMethod = nullptr;
4030 TypedefNameDecl *TDNDecl = nullptr;
4031 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
4032 ClassMethod, InstanceMethod, TDNDecl,
4037 // Implicit conversion from CF to ObjC object is needed.
4040 std::string ExpressionString = "[";
4041 ExpressionString += RelatedClass->getNameAsString();
4042 ExpressionString += " ";
4043 ExpressionString += ClassMethod->getSelector().getAsString();
4044 SourceLocation SrcExprEndLoc = getLocForEndOfToken(SrcExpr->getLocEnd());
4045 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
4046 Diag(Loc, diag::err_objc_bridged_related_known_method)
4047 << SrcType << DestType << ClassMethod->getSelector() << false
4048 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
4049 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
4050 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
4051 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
4053 QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
4055 Expr *args[] = { SrcExpr };
4056 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
4057 ClassMethod->getLocation(),
4058 ClassMethod->getSelector(), ClassMethod,
4059 MultiExprArg(args, 1));
4060 SrcExpr = msg.get();
4066 // Implicit conversion from ObjC type to CF object is needed.
4067 if (InstanceMethod) {
4069 std::string ExpressionString;
4070 SourceLocation SrcExprEndLoc =
4071 getLocForEndOfToken(SrcExpr->getLocEnd());
4072 if (InstanceMethod->isPropertyAccessor())
4073 if (const ObjCPropertyDecl *PDecl =
4074 InstanceMethod->findPropertyDecl()) {
4075 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
4076 ExpressionString = ".";
4077 ExpressionString += PDecl->getNameAsString();
4078 Diag(Loc, diag::err_objc_bridged_related_known_method)
4079 << SrcType << DestType << InstanceMethod->getSelector() << true
4080 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4082 if (ExpressionString.empty()) {
4083 // Provide a fixit: [ObjectExpr InstanceMethod]
4084 ExpressionString = " ";
4085 ExpressionString += InstanceMethod->getSelector().getAsString();
4086 ExpressionString += "]";
4088 Diag(Loc, diag::err_objc_bridged_related_known_method)
4089 << SrcType << DestType << InstanceMethod->getSelector() << true
4090 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
4091 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4093 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
4094 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
4097 BuildInstanceMessageImplicit(SrcExpr, SrcType,
4098 InstanceMethod->getLocation(),
4099 InstanceMethod->getSelector(),
4100 InstanceMethod, None);
4101 SrcExpr = msg.get();
4109 Sema::ARCConversionResult
4110 Sema::CheckObjCConversion(SourceRange castRange, QualType castType,
4111 Expr *&castExpr, CheckedConversionKind CCK,
4112 bool Diagnose, bool DiagnoseCFAudited,
4113 BinaryOperatorKind Opc) {
4114 QualType castExprType = castExpr->getType();
4116 // For the purposes of the classification, we assume reference types
4117 // will bind to temporaries.
4118 QualType effCastType = castType;
4119 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
4120 effCastType = ref->getPointeeType();
4122 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
4123 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
4124 if (exprACTC == castACTC) {
4125 // Check for viability and report error if casting an rvalue to a
4126 // life-time qualifier.
4127 if (castACTC == ACTC_retainable &&
4128 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
4129 castType != castExprType) {
4130 const Type *DT = castType.getTypePtr();
4131 QualType QDT = castType;
4132 // We desugar some types but not others. We ignore those
4133 // that cannot happen in a cast; i.e. auto, and those which
4134 // should not be de-sugared; i.e typedef.
4135 if (const ParenType *PT = dyn_cast<ParenType>(DT))
4136 QDT = PT->desugar();
4137 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
4138 QDT = TP->desugar();
4139 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
4140 QDT = AT->desugar();
4141 if (QDT != castType &&
4142 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
4144 SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
4145 : castExpr->getExprLoc());
4146 Diag(loc, diag::err_arc_nolifetime_behavior);
4154 // The life-time qualifier cast check above is all we need for ObjCWeak.
4155 // ObjCAutoRefCount has more restrictions on what is legal.
4156 if (!getLangOpts().ObjCAutoRefCount)
4159 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4161 // Allow all of these types to be cast to integer types (but not
4163 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4166 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4167 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4168 // must be explicit.
4169 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4171 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
4172 CCK != CCK_ImplicitConversion)
4175 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
4176 // For invalid casts, fall through.
4180 // Do nothing for both bottom and +0.
4185 // If the result is +1, consume it here.
4187 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4188 CK_ARCConsumeObject, castExpr,
4189 nullptr, VK_RValue);
4190 Cleanup.setExprNeedsCleanups(true);
4194 // If this is a non-implicit cast from id or block type to a
4195 // CoreFoundation type, delay complaining in case the cast is used
4196 // in an acceptable context.
4197 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
4198 CCK != CCK_ImplicitConversion)
4199 return ACR_unbridged;
4201 // Issue a diagnostic about a missing @-sign when implicit casting a cstring
4202 // to 'NSString *', instead of falling through to report a "bridge cast"
4204 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
4205 ConversionToObjCStringLiteralCheck(castType, castExpr, Diagnose))
4208 // Do not issue "bridge cast" diagnostic when implicit casting
4209 // a retainable object to a CF type parameter belonging to an audited
4210 // CF API function. Let caller issue a normal type mismatched diagnostic
4212 if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4213 castACTC != ACTC_coreFoundation) &&
4214 !(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4215 (Opc == BO_NE || Opc == BO_EQ))) {
4217 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
4218 castExpr, exprACTC, CCK);
4224 /// Given that we saw an expression with the ARCUnbridgedCastTy
4225 /// placeholder type, complain bitterly.
4226 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4227 // We expect the spurious ImplicitCastExpr to already have been stripped.
4228 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4229 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4231 SourceRange castRange;
4233 CheckedConversionKind CCK;
4235 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4236 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4237 castType = cast->getTypeAsWritten();
4238 CCK = CCK_CStyleCast;
4239 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4240 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4241 castType = cast->getTypeAsWritten();
4242 CCK = CCK_OtherCast;
4244 llvm_unreachable("Unexpected ImplicitCastExpr");
4247 ARCConversionTypeClass castACTC =
4248 classifyTypeForARCConversion(castType.getNonReferenceType());
4250 Expr *castExpr = realCast->getSubExpr();
4251 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4253 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4254 castExpr, realCast, ACTC_retainable, CCK);
4257 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4258 /// type, remove the placeholder cast.
4259 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4260 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4262 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4263 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4264 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4265 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4266 assert(uo->getOpcode() == UO_Extension);
4267 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4268 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
4269 sub->getValueKind(), sub->getObjectKind(),
4270 uo->getOperatorLoc());
4271 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4272 assert(!gse->isResultDependent());
4274 unsigned n = gse->getNumAssocs();
4275 SmallVector<Expr*, 4> subExprs(n);
4276 SmallVector<TypeSourceInfo*, 4> subTypes(n);
4277 for (unsigned i = 0; i != n; ++i) {
4278 subTypes[i] = gse->getAssocTypeSourceInfo(i);
4279 Expr *sub = gse->getAssocExpr(i);
4280 if (i == gse->getResultIndex())
4281 sub = stripARCUnbridgedCast(sub);
4285 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
4286 gse->getControllingExpr(),
4288 gse->getDefaultLoc(),
4289 gse->getRParenLoc(),
4290 gse->containsUnexpandedParameterPack(),
4291 gse->getResultIndex());
4293 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4294 return cast<ImplicitCastExpr>(e)->getSubExpr();
4298 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4299 QualType exprType) {
4300 QualType canCastType =
4301 Context.getCanonicalType(castType).getUnqualifiedType();
4302 QualType canExprType =
4303 Context.getCanonicalType(exprType).getUnqualifiedType();
4304 if (isa<ObjCObjectPointerType>(canCastType) &&
4305 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4306 canExprType->isObjCObjectPointerType()) {
4307 if (const ObjCObjectPointerType *ObjT =
4308 canExprType->getAs<ObjCObjectPointerType>())
4309 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4310 return !ObjI->isArcWeakrefUnavailable();
4315 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
4316 static Expr *maybeUndoReclaimObject(Expr *e) {
4317 // For now, we just undo operands that are *immediately* reclaim
4318 // expressions, which prevents the vast majority of potential
4319 // problems here. To catch them all, we'd need to rebuild arbitrary
4320 // value-propagating subexpressions --- we can't reliably rebuild
4321 // in-place because of expression sharing.
4322 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4323 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
4324 return ice->getSubExpr();
4329 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4330 ObjCBridgeCastKind Kind,
4331 SourceLocation BridgeKeywordLoc,
4332 TypeSourceInfo *TSInfo,
4334 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4335 if (SubResult.isInvalid()) return ExprError();
4336 SubExpr = SubResult.get();
4338 QualType T = TSInfo->getType();
4339 QualType FromType = SubExpr->getType();
4343 bool MustConsume = false;
4344 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4345 // Okay: we'll build a dependent expression type.
4347 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4349 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4350 : CK_CPointerToObjCPointerCast);
4355 case OBC_BridgeRetained: {
4356 bool br = isKnownName("CFBridgingRelease");
4357 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4360 << (T->isBlockPointerType()? 1 : 0)
4362 << SubExpr->getSourceRange()
4364 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4365 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4366 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
4368 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4369 br ? "CFBridgingRelease "
4370 : "__bridge_transfer ");
4376 case OBC_BridgeTransfer:
4377 // We must consume the Objective-C object produced by the cast.
4381 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4386 // Reclaiming a value that's going to be __bridge-casted to CF
4387 // is very dangerous, so we don't do it.
4388 SubExpr = maybeUndoReclaimObject(SubExpr);
4391 case OBC_BridgeRetained:
4392 // Produce the object before casting it.
4393 SubExpr = ImplicitCastExpr::Create(Context, FromType,
4394 CK_ARCProduceObject,
4395 SubExpr, nullptr, VK_RValue);
4398 case OBC_BridgeTransfer: {
4399 bool br = isKnownName("CFBridgingRetain");
4400 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4401 << (FromType->isBlockPointerType()? 1 : 0)
4405 << SubExpr->getSourceRange()
4408 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4409 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4410 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
4412 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4413 br ? "CFBridgingRetain " : "__bridge_retained");
4420 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4421 << FromType << T << Kind
4422 << SubExpr->getSourceRange()
4423 << TSInfo->getTypeLoc().getSourceRange();
4427 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
4432 Cleanup.setExprNeedsCleanups(true);
4433 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
4434 nullptr, VK_RValue);
4440 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4441 SourceLocation LParenLoc,
4442 ObjCBridgeCastKind Kind,
4443 SourceLocation BridgeKeywordLoc,
4445 SourceLocation RParenLoc,
4447 TypeSourceInfo *TSInfo = nullptr;
4448 QualType T = GetTypeFromParser(Type, &TSInfo);
4449 if (Kind == OBC_Bridge)
4450 CheckTollFreeBridgeCast(T, SubExpr);
4452 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4453 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,