1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for Objective-C expressions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21 #include "clang/Edit/Commit.h"
22 #include "clang/Edit/Rewriters.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Sema/Initialization.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "llvm/ADT/SmallString.h"
30 using namespace clang;
32 using llvm::makeArrayRef;
34 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
36 unsigned NumStrings) {
37 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
39 // Most ObjC strings are formed out of a single piece. However, we *can*
40 // have strings formed out of multiple @ strings with multiple pptokens in
41 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
42 // StringLiteral for ObjCStringLiteral to hold onto.
43 StringLiteral *S = Strings[0];
45 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
47 // Concatenate objc strings.
48 SmallString<128> StrBuf;
49 SmallVector<SourceLocation, 8> StrLocs;
51 for (unsigned i = 0; i != NumStrings; ++i) {
54 // ObjC strings can't be wide or UTF.
56 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
62 StrBuf += S->getString();
64 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
68 // Create the aggregate string with the appropriate content and location
70 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
71 assert(CAT && "String literal not of constant array type!");
72 QualType StrTy = Context.getConstantArrayType(
73 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
74 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
75 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
76 /*Pascal=*/false, StrTy, &StrLocs[0],
80 return BuildObjCStringLiteral(AtLocs[0], S);
83 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
84 // Verify that this composite string is acceptable for ObjC strings.
85 if (CheckObjCString(S))
88 // Initialize the constant string interface lazily. This assumes
89 // the NSString interface is seen in this translation unit. Note: We
90 // don't use NSConstantString, since the runtime team considers this
91 // interface private (even though it appears in the header files).
92 QualType Ty = Context.getObjCConstantStringInterface();
94 Ty = Context.getObjCObjectPointerType(Ty);
95 } else if (getLangOpts().NoConstantCFStrings) {
96 IdentifierInfo *NSIdent=nullptr;
97 std::string StringClass(getLangOpts().ObjCConstantStringClass);
99 if (StringClass.empty())
100 NSIdent = &Context.Idents.get("NSConstantString");
102 NSIdent = &Context.Idents.get(StringClass);
104 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
106 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
107 Context.setObjCConstantStringInterface(StrIF);
108 Ty = Context.getObjCConstantStringInterface();
109 Ty = Context.getObjCObjectPointerType(Ty);
111 // If there is no NSConstantString interface defined then treat this
112 // as error and recover from it.
113 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
114 << S->getSourceRange();
115 Ty = Context.getObjCIdType();
118 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
119 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
121 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
122 Context.setObjCConstantStringInterface(StrIF);
123 Ty = Context.getObjCConstantStringInterface();
124 Ty = Context.getObjCObjectPointerType(Ty);
126 // If there is no NSString interface defined, implicitly declare
127 // a @class NSString; and use that instead. This is to make sure
128 // type of an NSString literal is represented correctly, instead of
129 // being an 'id' type.
130 Ty = Context.getObjCNSStringType();
132 ObjCInterfaceDecl *NSStringIDecl =
133 ObjCInterfaceDecl::Create (Context,
134 Context.getTranslationUnitDecl(),
135 SourceLocation(), NSIdent,
136 nullptr, SourceLocation());
137 Ty = Context.getObjCInterfaceType(NSStringIDecl);
138 Context.setObjCNSStringType(Ty);
140 Ty = Context.getObjCObjectPointerType(Ty);
144 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
147 /// \brief Emits an error if the given method does not exist, or if the return
148 /// type is not an Objective-C object.
149 static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
150 const ObjCInterfaceDecl *Class,
151 Selector Sel, const ObjCMethodDecl *Method) {
153 // FIXME: Is there a better way to avoid quotes than using getName()?
154 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
158 // Make sure the return type is reasonable.
159 QualType ReturnType = Method->getReturnType();
160 if (!ReturnType->isObjCObjectPointerType()) {
161 S.Diag(Loc, diag::err_objc_literal_method_sig)
163 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
171 /// \brief Retrieve the NSNumber factory method that should be used to create
172 /// an Objective-C literal for the given type.
173 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
175 bool isLiteral = false,
176 SourceRange R = SourceRange()) {
177 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
178 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
182 S.Diag(Loc, diag::err_invalid_nsnumber_type)
188 // If we already looked up this method, we're done.
189 if (S.NSNumberLiteralMethods[*Kind])
190 return S.NSNumberLiteralMethods[*Kind];
192 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
195 ASTContext &CX = S.Context;
197 // Look up the NSNumber class, if we haven't done so already. It's cached
198 // in the Sema instance.
199 if (!S.NSNumberDecl) {
200 IdentifierInfo *NSNumberId =
201 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
202 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
203 Loc, Sema::LookupOrdinaryName);
204 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
205 if (!S.NSNumberDecl) {
206 if (S.getLangOpts().DebuggerObjCLiteral) {
207 // Create a stub definition of NSNumber.
208 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
209 CX.getTranslationUnitDecl(),
210 SourceLocation(), NSNumberId,
211 nullptr, SourceLocation());
213 // Otherwise, require a declaration of NSNumber.
214 S.Diag(Loc, diag::err_undeclared_nsnumber);
217 } else if (!S.NSNumberDecl->hasDefinition()) {
218 S.Diag(Loc, diag::err_undeclared_nsnumber);
222 // generate the pointer to NSNumber type.
223 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
224 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
227 // Look for the appropriate method within NSNumber.
228 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
229 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
230 // create a stub definition this NSNumber factory method.
231 TypeSourceInfo *ReturnTInfo = nullptr;
233 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
234 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
235 /*isInstance=*/false, /*isVariadic=*/false,
236 /*isPropertyAccessor=*/false,
237 /*isImplicitlyDeclared=*/true,
238 /*isDefined=*/false, ObjCMethodDecl::Required,
239 /*HasRelatedResultType=*/false);
240 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
241 SourceLocation(), SourceLocation(),
242 &CX.Idents.get("value"),
243 NumberType, /*TInfo=*/nullptr,
245 Method->setMethodParams(S.Context, value, None);
248 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
251 // Note: if the parameter type is out-of-line, we'll catch it later in the
252 // implicit conversion.
254 S.NSNumberLiteralMethods[*Kind] = Method;
258 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
259 /// numeric literal expression. Type of the expression will be "NSNumber *".
260 ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
261 // Determine the type of the literal.
262 QualType NumberType = Number->getType();
263 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
264 // In C, character literals have type 'int'. That's not the type we want
265 // to use to determine the Objective-c literal kind.
266 switch (Char->getKind()) {
267 case CharacterLiteral::Ascii:
268 NumberType = Context.CharTy;
271 case CharacterLiteral::Wide:
272 NumberType = Context.getWideCharType();
275 case CharacterLiteral::UTF16:
276 NumberType = Context.Char16Ty;
279 case CharacterLiteral::UTF32:
280 NumberType = Context.Char32Ty;
285 // Look for the appropriate method within NSNumber.
286 // Construct the literal.
287 SourceRange NR(Number->getSourceRange());
288 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
293 // Convert the number to the type that the parameter expects.
294 ParmVarDecl *ParamDecl = Method->parameters()[0];
295 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
297 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
300 if (ConvertedNumber.isInvalid())
302 Number = ConvertedNumber.get();
304 // Use the effective source range of the literal, including the leading '@'.
305 return MaybeBindToTemporary(
306 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
307 SourceRange(AtLoc, NR.getEnd())));
310 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
311 SourceLocation ValueLoc,
314 if (getLangOpts().CPlusPlus) {
315 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
317 // C doesn't actually have a way to represent literal values of type
318 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
319 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
320 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
321 CK_IntegralToBoolean);
324 return BuildObjCNumericLiteral(AtLoc, Inner.get());
327 /// \brief Check that the given expression is a valid element of an Objective-C
328 /// collection literal.
329 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
331 bool ArrayLiteral = false) {
332 // If the expression is type-dependent, there's nothing for us to do.
333 if (Element->isTypeDependent())
336 ExprResult Result = S.CheckPlaceholderExpr(Element);
337 if (Result.isInvalid())
339 Element = Result.get();
341 // In C++, check for an implicit conversion to an Objective-C object pointer
343 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
344 InitializedEntity Entity
345 = InitializedEntity::InitializeParameter(S.Context, T,
347 InitializationKind Kind
348 = InitializationKind::CreateCopy(Element->getLocStart(),
350 InitializationSequence Seq(S, Entity, Kind, Element);
352 return Seq.Perform(S, Entity, Kind, Element);
355 Expr *OrigElement = Element;
357 // Perform lvalue-to-rvalue conversion.
358 Result = S.DefaultLvalueConversion(Element);
359 if (Result.isInvalid())
361 Element = Result.get();
363 // Make sure that we have an Objective-C pointer type or block.
364 if (!Element->getType()->isObjCObjectPointerType() &&
365 !Element->getType()->isBlockPointerType()) {
366 bool Recovered = false;
368 // If this is potentially an Objective-C numeric literal, add the '@'.
369 if (isa<IntegerLiteral>(OrigElement) ||
370 isa<CharacterLiteral>(OrigElement) ||
371 isa<FloatingLiteral>(OrigElement) ||
372 isa<ObjCBoolLiteralExpr>(OrigElement) ||
373 isa<CXXBoolLiteralExpr>(OrigElement)) {
374 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
375 int Which = isa<CharacterLiteral>(OrigElement) ? 1
376 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
377 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
380 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
381 << Which << OrigElement->getSourceRange()
382 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
384 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
386 if (Result.isInvalid())
389 Element = Result.get();
393 // If this is potentially an Objective-C string literal, add the '@'.
394 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
395 if (String->isAscii()) {
396 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
397 << 0 << OrigElement->getSourceRange()
398 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
400 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
401 if (Result.isInvalid())
404 Element = Result.get();
410 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
411 << Element->getType();
416 if (ObjCStringLiteral *getString =
417 dyn_cast<ObjCStringLiteral>(OrigElement)) {
418 if (StringLiteral *SL = getString->getString()) {
419 unsigned numConcat = SL->getNumConcatenated();
421 // Only warn if the concatenated string doesn't come from a macro.
422 bool hasMacro = false;
423 for (unsigned i = 0; i < numConcat ; ++i)
424 if (SL->getStrTokenLoc(i).isMacroID()) {
429 S.Diag(Element->getLocStart(),
430 diag::warn_concatenated_nsarray_literal)
431 << Element->getType();
436 // Make sure that the element has the type that the container factory
438 return S.PerformCopyInitialization(
439 InitializedEntity::InitializeParameter(S.Context, T,
441 Element->getLocStart(), Element);
444 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
445 if (ValueExpr->isTypeDependent()) {
446 ObjCBoxedExpr *BoxedExpr =
447 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
450 ObjCMethodDecl *BoxingMethod = nullptr;
452 // Convert the expression to an RValue, so we can check for pointer types...
453 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
454 if (RValue.isInvalid()) {
457 ValueExpr = RValue.get();
458 QualType ValueType(ValueExpr->getType());
459 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
460 QualType PointeeType = PT->getPointeeType();
461 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
464 IdentifierInfo *NSStringId =
465 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
466 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
467 SR.getBegin(), LookupOrdinaryName);
468 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
470 if (getLangOpts().DebuggerObjCLiteral) {
471 // Support boxed expressions in the debugger w/o NSString declaration.
472 DeclContext *TU = Context.getTranslationUnitDecl();
473 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
476 nullptr, SourceLocation());
478 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
481 } else if (!NSStringDecl->hasDefinition()) {
482 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
485 assert(NSStringDecl && "NSStringDecl should not be NULL");
486 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
487 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
490 if (!StringWithUTF8StringMethod) {
491 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
492 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
494 // Look for the appropriate method within NSString.
495 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
496 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
497 // Debugger needs to work even if NSString hasn't been defined.
498 TypeSourceInfo *ReturnTInfo = nullptr;
499 ObjCMethodDecl *M = ObjCMethodDecl::Create(
500 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
501 NSStringPointer, ReturnTInfo, NSStringDecl,
502 /*isInstance=*/false, /*isVariadic=*/false,
503 /*isPropertyAccessor=*/false,
504 /*isImplicitlyDeclared=*/true,
505 /*isDefined=*/false, ObjCMethodDecl::Required,
506 /*HasRelatedResultType=*/false);
507 QualType ConstCharType = Context.CharTy.withConst();
509 ParmVarDecl::Create(Context, M,
510 SourceLocation(), SourceLocation(),
511 &Context.Idents.get("value"),
512 Context.getPointerType(ConstCharType),
515 M->setMethodParams(Context, value, None);
519 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
520 stringWithUTF8String, BoxingMethod))
523 StringWithUTF8StringMethod = BoxingMethod;
526 BoxingMethod = StringWithUTF8StringMethod;
527 BoxedType = NSStringPointer;
529 } else if (ValueType->isBuiltinType()) {
530 // The other types we support are numeric, char and BOOL/bool. We could also
531 // provide limited support for structure types, such as NSRange, NSRect, and
532 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
535 // Check for a top-level character literal.
536 if (const CharacterLiteral *Char =
537 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
538 // In C, character literals have type 'int'. That's not the type we want
539 // to use to determine the Objective-c literal kind.
540 switch (Char->getKind()) {
541 case CharacterLiteral::Ascii:
542 ValueType = Context.CharTy;
545 case CharacterLiteral::Wide:
546 ValueType = Context.getWideCharType();
549 case CharacterLiteral::UTF16:
550 ValueType = Context.Char16Ty;
553 case CharacterLiteral::UTF32:
554 ValueType = Context.Char32Ty;
558 CheckForIntOverflow(ValueExpr);
559 // FIXME: Do I need to do anything special with BoolTy expressions?
561 // Look for the appropriate method within NSNumber.
562 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
563 BoxedType = NSNumberPointer;
565 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
566 if (!ET->getDecl()->isComplete()) {
567 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
568 << ValueType << ValueExpr->getSourceRange();
572 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
573 ET->getDecl()->getIntegerType());
574 BoxedType = NSNumberPointer;
578 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
579 << ValueType << ValueExpr->getSourceRange();
583 // Convert the expression to the type that the parameter requires.
584 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
585 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
587 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
590 if (ConvertedValueExpr.isInvalid())
592 ValueExpr = ConvertedValueExpr.get();
594 ObjCBoxedExpr *BoxedExpr =
595 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
597 return MaybeBindToTemporary(BoxedExpr);
600 /// Build an ObjC subscript pseudo-object expression, given that
601 /// that's supported by the runtime.
602 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
604 ObjCMethodDecl *getterMethod,
605 ObjCMethodDecl *setterMethod) {
606 assert(!LangOpts.isSubscriptPointerArithmetic());
608 // We can't get dependent types here; our callers should have
609 // filtered them out.
610 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
611 "base or index cannot have dependent type here");
613 // Filter out placeholders in the index. In theory, overloads could
614 // be preserved here, although that might not actually work correctly.
615 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
616 if (Result.isInvalid())
618 IndexExpr = Result.get();
620 // Perform lvalue-to-rvalue conversion on the base.
621 Result = DefaultLvalueConversion(BaseExpr);
622 if (Result.isInvalid())
624 BaseExpr = Result.get();
626 // Build the pseudo-object expression.
627 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
628 Context.PseudoObjectTy, getterMethod,
632 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
633 // Look up the NSArray class, if we haven't done so already.
635 NamedDecl *IF = LookupSingleName(TUScope,
636 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
639 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
640 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
641 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
642 Context.getTranslationUnitDecl(),
644 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
645 nullptr, SourceLocation());
648 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
653 // Find the arrayWithObjects:count: method, if we haven't done so already.
654 QualType IdT = Context.getObjCIdType();
655 if (!ArrayWithObjectsMethod) {
657 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
658 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
659 if (!Method && getLangOpts().DebuggerObjCLiteral) {
660 TypeSourceInfo *ReturnTInfo = nullptr;
661 Method = ObjCMethodDecl::Create(
662 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
663 Context.getTranslationUnitDecl(), false /*Instance*/,
664 false /*isVariadic*/,
665 /*isPropertyAccessor=*/false,
666 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
667 ObjCMethodDecl::Required, false);
668 SmallVector<ParmVarDecl *, 2> Params;
669 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
672 &Context.Idents.get("objects"),
673 Context.getPointerType(IdT),
676 Params.push_back(objects);
677 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
680 &Context.Idents.get("cnt"),
681 Context.UnsignedLongTy,
682 /*TInfo=*/nullptr, SC_None,
684 Params.push_back(cnt);
685 Method->setMethodParams(Context, Params, None);
688 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
691 // Dig out the type that all elements should be converted to.
692 QualType T = Method->parameters()[0]->getType();
693 const PointerType *PtrT = T->getAs<PointerType>();
695 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
696 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
698 Diag(Method->parameters()[0]->getLocation(),
699 diag::note_objc_literal_method_param)
701 << Context.getPointerType(IdT.withConst());
705 // Check that the 'count' parameter is integral.
706 if (!Method->parameters()[1]->getType()->isIntegerType()) {
707 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
709 Diag(Method->parameters()[1]->getLocation(),
710 diag::note_objc_literal_method_param)
712 << Method->parameters()[1]->getType()
717 // We've found a good +arrayWithObjects:count: method. Save it!
718 ArrayWithObjectsMethod = Method;
721 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
722 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
724 // Check that each of the elements provided is valid in a collection literal,
725 // performing conversions as necessary.
726 Expr **ElementsBuffer = Elements.data();
727 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
728 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
731 if (Converted.isInvalid())
734 ElementsBuffer[I] = Converted.get();
738 = Context.getObjCObjectPointerType(
739 Context.getObjCInterfaceType(NSArrayDecl));
741 return MaybeBindToTemporary(
742 ObjCArrayLiteral::Create(Context, Elements, Ty,
743 ArrayWithObjectsMethod, SR));
746 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
747 ObjCDictionaryElement *Elements,
748 unsigned NumElements) {
749 // Look up the NSDictionary class, if we haven't done so already.
750 if (!NSDictionaryDecl) {
751 NamedDecl *IF = LookupSingleName(TUScope,
752 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
753 SR.getBegin(), LookupOrdinaryName);
754 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
755 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
756 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
757 Context.getTranslationUnitDecl(),
759 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
760 nullptr, SourceLocation());
762 if (!NSDictionaryDecl) {
763 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
768 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
770 QualType IdT = Context.getObjCIdType();
771 if (!DictionaryWithObjectsMethod) {
772 Selector Sel = NSAPIObj->getNSDictionarySelector(
773 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
774 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
775 if (!Method && getLangOpts().DebuggerObjCLiteral) {
776 Method = ObjCMethodDecl::Create(Context,
777 SourceLocation(), SourceLocation(), Sel,
779 nullptr /*TypeSourceInfo */,
780 Context.getTranslationUnitDecl(),
781 false /*Instance*/, false/*isVariadic*/,
782 /*isPropertyAccessor=*/false,
783 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
784 ObjCMethodDecl::Required,
786 SmallVector<ParmVarDecl *, 3> Params;
787 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
790 &Context.Idents.get("objects"),
791 Context.getPointerType(IdT),
792 /*TInfo=*/nullptr, SC_None,
794 Params.push_back(objects);
795 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
798 &Context.Idents.get("keys"),
799 Context.getPointerType(IdT),
800 /*TInfo=*/nullptr, SC_None,
802 Params.push_back(keys);
803 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
806 &Context.Idents.get("cnt"),
807 Context.UnsignedLongTy,
808 /*TInfo=*/nullptr, SC_None,
810 Params.push_back(cnt);
811 Method->setMethodParams(Context, Params, None);
814 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
818 // Dig out the type that all values should be converted to.
819 QualType ValueT = Method->parameters()[0]->getType();
820 const PointerType *PtrValue = ValueT->getAs<PointerType>();
822 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
823 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
825 Diag(Method->parameters()[0]->getLocation(),
826 diag::note_objc_literal_method_param)
828 << Context.getPointerType(IdT.withConst());
832 // Dig out the type that all keys should be converted to.
833 QualType KeyT = Method->parameters()[1]->getType();
834 const PointerType *PtrKey = KeyT->getAs<PointerType>();
836 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
840 if (QIDNSCopying.isNull()) {
841 // key argument of selector is id<NSCopying>?
842 if (ObjCProtocolDecl *NSCopyingPDecl =
843 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
844 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
846 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
847 (ObjCProtocolDecl**) PQ,1);
848 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
851 if (!QIDNSCopying.isNull())
852 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
857 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
859 Diag(Method->parameters()[1]->getLocation(),
860 diag::note_objc_literal_method_param)
862 << Context.getPointerType(IdT.withConst());
867 // Check that the 'count' parameter is integral.
868 QualType CountType = Method->parameters()[2]->getType();
869 if (!CountType->isIntegerType()) {
870 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
872 Diag(Method->parameters()[2]->getLocation(),
873 diag::note_objc_literal_method_param)
879 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
880 DictionaryWithObjectsMethod = Method;
883 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
884 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
885 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
886 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
888 // Check that each of the keys and values provided is valid in a collection
889 // literal, performing conversions as necessary.
890 bool HasPackExpansions = false;
891 for (unsigned I = 0, N = NumElements; I != N; ++I) {
893 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
900 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
901 if (Value.isInvalid())
904 Elements[I].Key = Key.get();
905 Elements[I].Value = Value.get();
907 if (Elements[I].EllipsisLoc.isInvalid())
910 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
911 !Elements[I].Value->containsUnexpandedParameterPack()) {
912 Diag(Elements[I].EllipsisLoc,
913 diag::err_pack_expansion_without_parameter_packs)
914 << SourceRange(Elements[I].Key->getLocStart(),
915 Elements[I].Value->getLocEnd());
919 HasPackExpansions = true;
924 = Context.getObjCObjectPointerType(
925 Context.getObjCInterfaceType(NSDictionaryDecl));
926 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
927 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
928 DictionaryWithObjectsMethod, SR));
931 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
932 TypeSourceInfo *EncodedTypeInfo,
933 SourceLocation RParenLoc) {
934 QualType EncodedType = EncodedTypeInfo->getType();
936 if (EncodedType->isDependentType())
937 StrTy = Context.DependentTy;
939 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
940 !EncodedType->isVoidType()) // void is handled too.
941 if (RequireCompleteType(AtLoc, EncodedType,
942 diag::err_incomplete_type_objc_at_encode,
943 EncodedTypeInfo->getTypeLoc()))
947 QualType NotEncodedT;
948 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
949 if (!NotEncodedT.isNull())
950 Diag(AtLoc, diag::warn_incomplete_encoded_type)
951 << EncodedType << NotEncodedT;
953 // The type of @encode is the same as the type of the corresponding string,
954 // which is an array type.
955 StrTy = Context.CharTy;
956 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
957 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
959 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
960 ArrayType::Normal, 0);
963 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
966 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
967 SourceLocation EncodeLoc,
968 SourceLocation LParenLoc,
970 SourceLocation RParenLoc) {
971 // FIXME: Preserve type source info ?
972 TypeSourceInfo *TInfo;
973 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
975 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
976 PP.getLocForEndOfToken(LParenLoc));
978 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
981 static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
982 SourceLocation AtLoc,
983 SourceLocation LParenLoc,
984 SourceLocation RParenLoc,
985 ObjCMethodDecl *Method,
986 ObjCMethodList &MethList) {
987 ObjCMethodList *M = &MethList;
989 for (M = M->getNext(); M; M=M->getNext()) {
990 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
991 if (MatchingMethodDecl == Method ||
992 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
993 MatchingMethodDecl->getSelector() != Method->getSelector())
995 if (!S.MatchTwoMethodDeclarations(Method,
996 MatchingMethodDecl, Sema::MMS_loose)) {
999 S.Diag(AtLoc, diag::warning_multiple_selectors)
1000 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1001 << FixItHint::CreateInsertion(RParenLoc, ")");
1002 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1003 << Method->getDeclName();
1005 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1006 << MatchingMethodDecl->getDeclName();
1012 static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1013 ObjCMethodDecl *Method,
1014 SourceLocation LParenLoc,
1015 SourceLocation RParenLoc,
1016 bool WarnMultipleSelectors) {
1017 if (!WarnMultipleSelectors ||
1018 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
1020 bool Warned = false;
1021 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1022 e = S.MethodPool.end(); b != e; b++) {
1023 // first, instance methods
1024 ObjCMethodList &InstMethList = b->second.first;
1025 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1026 Method, InstMethList))
1029 // second, class methods
1030 ObjCMethodList &ClsMethList = b->second.second;
1031 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1032 Method, ClsMethList) || Warned)
1037 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1038 SourceLocation AtLoc,
1039 SourceLocation SelLoc,
1040 SourceLocation LParenLoc,
1041 SourceLocation RParenLoc,
1042 bool WarnMultipleSelectors) {
1043 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1044 SourceRange(LParenLoc, RParenLoc), false, false);
1046 Method = LookupFactoryMethodInGlobalPool(Sel,
1047 SourceRange(LParenLoc, RParenLoc));
1049 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1050 Selector MatchedSel = OM->getSelector();
1051 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1052 RParenLoc.getLocWithOffset(-1));
1053 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1054 << Sel << MatchedSel
1055 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1058 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
1060 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1061 WarnMultipleSelectors);
1064 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1065 !getSourceManager().isInSystemHeader(Method->getLocation())) {
1066 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
1067 = ReferencedSelectors.find(Sel);
1068 if (Pos == ReferencedSelectors.end())
1069 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
1072 // In ARC, forbid the user from using @selector for
1073 // retain/release/autorelease/dealloc/retainCount.
1074 if (getLangOpts().ObjCAutoRefCount) {
1075 switch (Sel.getMethodFamily()) {
1078 case OMF_autorelease:
1079 case OMF_retainCount:
1081 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1082 Sel << SourceRange(LParenLoc, RParenLoc);
1090 case OMF_mutableCopy:
1093 case OMF_initialize:
1094 case OMF_performSelector:
1098 QualType Ty = Context.getObjCSelType();
1099 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1102 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1103 SourceLocation AtLoc,
1104 SourceLocation ProtoLoc,
1105 SourceLocation LParenLoc,
1106 SourceLocation ProtoIdLoc,
1107 SourceLocation RParenLoc) {
1108 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
1110 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
1113 if (PDecl->hasDefinition())
1114 PDecl = PDecl->getDefinition();
1116 QualType Ty = Context.getObjCProtoType();
1119 Ty = Context.getObjCObjectPointerType(Ty);
1120 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1123 /// Try to capture an implicit reference to 'self'.
1124 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1125 DeclContext *DC = getFunctionLevelDeclContext();
1127 // If we're not in an ObjC method, error out. Note that, unlike the
1128 // C++ case, we don't require an instance method --- class methods
1129 // still have a 'self', and we really do still need to capture it!
1130 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1134 tryCaptureVariable(method->getSelfDecl(), Loc);
1139 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1140 if (T == Context.getObjCInstanceType())
1141 return Context.getObjCIdType();
1146 QualType Sema::getMessageSendResultType(QualType ReceiverType,
1147 ObjCMethodDecl *Method,
1148 bool isClassMessage, bool isSuperMessage) {
1149 assert(Method && "Must have a method");
1150 if (!Method->hasRelatedResultType())
1151 return Method->getSendResultType();
1153 // If a method has a related return type:
1154 // - if the method found is an instance method, but the message send
1155 // was a class message send, T is the declared return type of the method
1157 if (Method->isInstanceMethod() && isClassMessage)
1158 return stripObjCInstanceType(Context, Method->getSendResultType());
1160 // - if the receiver is super, T is a pointer to the class of the
1161 // enclosing method definition
1162 if (isSuperMessage) {
1163 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1164 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1165 return Context.getObjCObjectPointerType(
1166 Context.getObjCInterfaceType(Class));
1169 // - if the receiver is the name of a class U, T is a pointer to U
1170 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1171 ReceiverType->isObjCQualifiedInterfaceType())
1172 return Context.getObjCObjectPointerType(ReceiverType);
1173 // - if the receiver is of type Class or qualified Class type,
1174 // T is the declared return type of the method.
1175 if (ReceiverType->isObjCClassType() ||
1176 ReceiverType->isObjCQualifiedClassType())
1177 return stripObjCInstanceType(Context, Method->getSendResultType());
1179 // - if the receiver is id, qualified id, Class, or qualified Class, T
1180 // is the receiver type, otherwise
1181 // - T is the type of the receiver expression.
1182 return ReceiverType;
1185 /// Look for an ObjC method whose result type exactly matches the given type.
1186 static const ObjCMethodDecl *
1187 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1188 QualType instancetype) {
1189 if (MD->getReturnType() == instancetype)
1192 // For these purposes, a method in an @implementation overrides a
1193 // declaration in the @interface.
1194 if (const ObjCImplDecl *impl =
1195 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1196 const ObjCContainerDecl *iface;
1197 if (const ObjCCategoryImplDecl *catImpl =
1198 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1199 iface = catImpl->getCategoryDecl();
1201 iface = impl->getClassInterface();
1204 const ObjCMethodDecl *ifaceMD =
1205 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1206 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1209 SmallVector<const ObjCMethodDecl *, 4> overrides;
1210 MD->getOverriddenMethods(overrides);
1211 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1212 if (const ObjCMethodDecl *result =
1213 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1220 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1221 // Only complain if we're in an ObjC method and the required return
1222 // type doesn't match the method's declared return type.
1223 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1224 if (!MD || !MD->hasRelatedResultType() ||
1225 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
1228 // Look for a method overridden by this method which explicitly uses
1230 if (const ObjCMethodDecl *overridden =
1231 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1232 SourceRange range = overridden->getReturnTypeSourceRange();
1233 SourceLocation loc = range.getBegin();
1234 if (loc.isInvalid())
1235 loc = overridden->getLocation();
1236 Diag(loc, diag::note_related_result_type_explicit)
1237 << /*current method*/ 1 << range;
1241 // Otherwise, if we have an interesting method family, note that.
1242 // This should always trigger if the above didn't.
1243 if (ObjCMethodFamily family = MD->getMethodFamily())
1244 Diag(MD->getLocation(), diag::note_related_result_type_family)
1245 << /*current method*/ 1
1249 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1250 E = E->IgnoreParenImpCasts();
1251 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1255 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1259 if (!Method->hasRelatedResultType())
1262 if (Context.hasSameUnqualifiedType(
1263 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
1266 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
1267 Context.getObjCInstanceType()))
1270 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1271 << Method->isInstanceMethod() << Method->getSelector()
1272 << MsgSend->getType();
1275 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
1278 ArrayRef<SourceLocation> SelectorLocs,
1279 ObjCMethodDecl *Method,
1280 bool isClassMessage, bool isSuperMessage,
1281 SourceLocation lbrac, SourceLocation rbrac,
1282 SourceRange RecRange,
1283 QualType &ReturnType, ExprValueKind &VK) {
1284 SourceLocation SelLoc;
1285 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1286 SelLoc = SelectorLocs.front();
1291 // Apply default argument promotion as for (C99 6.5.2.2p6).
1292 for (unsigned i = 0, e = Args.size(); i != e; i++) {
1293 if (Args[i]->isTypeDependent())
1297 if (getLangOpts().DebuggerSupport) {
1298 QualType paramTy; // ignored
1299 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
1301 result = DefaultArgumentPromotion(Args[i]);
1303 if (result.isInvalid())
1305 Args[i] = result.get();
1309 if (getLangOpts().ObjCAutoRefCount)
1310 DiagID = diag::err_arc_method_not_found;
1312 DiagID = isClassMessage ? diag::warn_class_method_not_found
1313 : diag::warn_inst_method_not_found;
1314 if (!getLangOpts().DebuggerSupport) {
1315 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
1316 if (OMD && !OMD->isInvalidDecl()) {
1317 if (getLangOpts().ObjCAutoRefCount)
1318 DiagID = diag::error_method_not_found_with_typo;
1320 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1321 : diag::warn_instance_method_not_found_with_typo;
1322 Selector MatchedSel = OMD->getSelector();
1323 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
1324 if (MatchedSel.isUnarySelector())
1325 Diag(SelLoc, DiagID)
1326 << Sel<< isClassMessage << MatchedSel
1327 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1329 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
1332 Diag(SelLoc, DiagID)
1333 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
1334 SelectorLocs.back());
1335 // Find the class to which we are sending this message.
1336 if (ReceiverType->isObjCObjectPointerType()) {
1337 if (ObjCInterfaceDecl *ThisClass =
1338 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1339 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1340 if (!RecRange.isInvalid())
1341 if (ThisClass->lookupClassMethod(Sel))
1342 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1343 << FixItHint::CreateReplacement(RecRange,
1344 ThisClass->getNameAsString());
1349 // In debuggers, we want to use __unknown_anytype for these
1350 // results so that clients can cast them.
1351 if (getLangOpts().DebuggerSupport) {
1352 ReturnType = Context.UnknownAnyTy;
1354 ReturnType = Context.getObjCIdType();
1360 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1362 VK = Expr::getValueKindForType(Method->getReturnType());
1364 unsigned NumNamedArgs = Sel.getNumArgs();
1365 // Method might have more arguments than selector indicates. This is due
1366 // to addition of c-style arguments in method.
1367 if (Method->param_size() > Sel.getNumArgs())
1368 NumNamedArgs = Method->param_size();
1369 // FIXME. This need be cleaned up.
1370 if (Args.size() < NumNamedArgs) {
1371 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
1372 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
1376 bool IsError = false;
1377 for (unsigned i = 0; i < NumNamedArgs; i++) {
1378 // We can't do any type-checking on a type-dependent argument.
1379 if (Args[i]->isTypeDependent())
1382 Expr *argExpr = Args[i];
1384 ParmVarDecl *param = Method->parameters()[i];
1385 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1387 // Strip the unbridged-cast placeholder expression off unless it's
1388 // a consumed argument.
1389 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1390 !param->hasAttr<CFConsumedAttr>())
1391 argExpr = stripARCUnbridgedCast(argExpr);
1393 // If the parameter is __unknown_anytype, infer its type
1394 // from the argument.
1395 if (param->getType() == Context.UnknownAnyTy) {
1397 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
1398 if (argE.isInvalid()) {
1401 Args[i] = argE.get();
1403 // Update the parameter type in-place.
1404 param->setType(paramType);
1409 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1411 diag::err_call_incomplete_argument, argExpr))
1414 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1416 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
1417 if (ArgE.isInvalid())
1420 Args[i] = ArgE.getAs<Expr>();
1423 // Promote additional arguments to variadic methods.
1424 if (Method->isVariadic()) {
1425 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
1426 if (Args[i]->isTypeDependent())
1429 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1431 IsError |= Arg.isInvalid();
1432 Args[i] = Arg.get();
1435 // Check for extra arguments to non-variadic methods.
1436 if (Args.size() != NumNamedArgs) {
1437 Diag(Args[NumNamedArgs]->getLocStart(),
1438 diag::err_typecheck_call_too_many_args)
1439 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1440 << Method->getSourceRange()
1441 << SourceRange(Args[NumNamedArgs]->getLocStart(),
1442 Args.back()->getLocEnd());
1446 DiagnoseSentinelCalls(Method, SelLoc, Args);
1448 // Do additional checkings on method.
1449 IsError |= CheckObjCMethodCall(
1450 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
1455 bool Sema::isSelfExpr(Expr *RExpr) {
1456 // 'self' is objc 'self' in an objc method only.
1457 ObjCMethodDecl *Method =
1458 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1459 return isSelfExpr(RExpr, Method);
1462 bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
1463 if (!method) return false;
1465 receiver = receiver->IgnoreParenLValueCasts();
1466 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1467 if (DRE->getDecl() == method->getSelfDecl())
1472 /// LookupMethodInType - Look up a method in an ObjCObjectType.
1473 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1475 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1476 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1477 // Look it up in the main interface (and categories, etc.)
1478 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1481 // Okay, look for "private" methods declared in any
1482 // @implementations we've seen.
1483 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1487 // Check qualifiers.
1488 for (const auto *I : objType->quals())
1489 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
1495 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1496 /// list of a qualified objective pointer type.
1497 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1498 const ObjCObjectPointerType *OPT,
1501 ObjCMethodDecl *MD = nullptr;
1502 for (const auto *PROTO : OPT->quals()) {
1503 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1510 static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1514 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1515 Receiver = OVE->getSourceExpr();
1517 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1518 SourceLocation Loc = RExpr->getLocStart();
1519 QualType T = RExpr->getType();
1520 const ObjCPropertyDecl *PDecl = nullptr;
1521 const ObjCMethodDecl *GDecl = nullptr;
1522 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1523 RExpr = POE->getSyntacticForm();
1524 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1525 if (PRE->isImplicitProperty()) {
1526 GDecl = PRE->getImplicitPropertyGetter();
1528 T = GDecl->getReturnType();
1532 PDecl = PRE->getExplicitProperty();
1534 T = PDecl->getType();
1539 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1540 // See if receiver is a method which envokes a synthesized getter
1541 // backing a 'weak' property.
1542 ObjCMethodDecl *Method = ME->getMethodDecl();
1543 if (Method && Method->getSelector().getNumArgs() == 0) {
1544 PDecl = Method->findPropertyDecl();
1546 T = PDecl->getType();
1550 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1553 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1557 S.Diag(Loc, diag::warn_receiver_is_weak)
1558 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1561 S.Diag(PDecl->getLocation(), diag::note_property_declare);
1563 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1565 S.Diag(Loc, diag::note_arc_assign_to_strong);
1568 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1569 /// objective C interface. This is a property reference expression.
1571 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1572 Expr *BaseExpr, SourceLocation OpLoc,
1573 DeclarationName MemberName,
1574 SourceLocation MemberLoc,
1575 SourceLocation SuperLoc, QualType SuperType,
1577 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1578 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1580 if (!MemberName.isIdentifier()) {
1581 Diag(MemberLoc, diag::err_invalid_property_name)
1582 << MemberName << QualType(OPT, 0);
1586 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1588 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1589 : BaseExpr->getSourceRange();
1590 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1591 diag::err_property_not_found_forward_class,
1592 MemberName, BaseRange))
1595 // Search for a declared property first.
1596 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1597 // Check whether we can reference this property.
1598 if (DiagnoseUseOfDecl(PD, MemberLoc))
1601 return new (Context)
1602 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1603 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1605 return new (Context)
1606 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1607 OK_ObjCProperty, MemberLoc, BaseExpr);
1609 // Check protocols on qualified interfaces.
1610 for (const auto *I : OPT->quals())
1611 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
1612 // Check whether we can reference this property.
1613 if (DiagnoseUseOfDecl(PD, MemberLoc))
1617 return new (Context) ObjCPropertyRefExpr(
1618 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1619 SuperLoc, SuperType);
1621 return new (Context)
1622 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1623 OK_ObjCProperty, MemberLoc, BaseExpr);
1625 // If that failed, look for an "implicit" property by seeing if the nullary
1626 // selector is implemented.
1628 // FIXME: The logic for looking up nullary and unary selectors should be
1629 // shared with the code in ActOnInstanceMessage.
1631 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1632 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1634 // May be founf in property's qualified list.
1636 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
1638 // If this reference is in an @implementation, check for 'private' methods.
1640 Getter = IFace->lookupPrivateMethod(Sel);
1643 // Check if we can reference this property.
1644 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1647 // If we found a getter then this may be a valid dot-reference, we
1648 // will look for the matching setter, in case it is needed.
1649 Selector SetterSel =
1650 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1651 PP.getSelectorTable(), Member);
1652 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1654 // May be founf in property's qualified list.
1656 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1659 // If this reference is in an @implementation, also check for 'private'
1661 Setter = IFace->lookupPrivateMethod(SetterSel);
1664 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1667 // Special warning if member name used in a property-dot for a setter accessor
1668 // does not use a property with same name; e.g. obj.X = ... for a property with
1670 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor()
1671 && !IFace->FindPropertyDeclaration(Member)) {
1672 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1673 // Do not warn if user is using property-dot syntax to make call to
1674 // user named setter.
1675 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
1677 diag::warn_property_access_suggest)
1678 << MemberName << QualType(OPT, 0) << PDecl->getName()
1679 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
1683 if (Getter || Setter) {
1685 return new (Context)
1686 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1687 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1689 return new (Context)
1690 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1691 OK_ObjCProperty, MemberLoc, BaseExpr);
1695 // Attempt to correct for typos in property names.
1696 if (TypoCorrection Corrected =
1697 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1698 LookupOrdinaryName, nullptr, nullptr,
1699 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1700 CTK_ErrorRecovery, IFace, false, OPT)) {
1701 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1702 << MemberName << QualType(OPT, 0));
1703 DeclarationName TypoResult = Corrected.getCorrection();
1704 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1705 TypoResult, MemberLoc,
1706 SuperLoc, SuperType, Super);
1708 ObjCInterfaceDecl *ClassDeclared;
1709 if (ObjCIvarDecl *Ivar =
1710 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1711 QualType T = Ivar->getType();
1712 if (const ObjCObjectPointerType * OBJPT =
1713 T->getAsObjCInterfacePointerType()) {
1714 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1715 diag::err_property_not_as_forward_class,
1716 MemberName, BaseExpr))
1720 diag::err_ivar_access_using_property_syntax_suggest)
1721 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1722 << FixItHint::CreateReplacement(OpLoc, "->");
1726 Diag(MemberLoc, diag::err_property_not_found)
1727 << MemberName << QualType(OPT, 0);
1729 Diag(Setter->getLocation(), diag::note_getter_unavailable)
1730 << MemberName << BaseExpr->getSourceRange();
1737 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1738 IdentifierInfo &propertyName,
1739 SourceLocation receiverNameLoc,
1740 SourceLocation propertyNameLoc) {
1742 IdentifierInfo *receiverNamePtr = &receiverName;
1743 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1746 bool IsSuper = false;
1748 // If the "receiver" is 'super' in a method, handle it as an expression-like
1749 // property reference.
1750 if (receiverNamePtr->isStr("super")) {
1753 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
1754 if (CurMethod->isInstanceMethod()) {
1755 ObjCInterfaceDecl *Super =
1756 CurMethod->getClassInterface()->getSuperClass();
1758 // The current class does not have a superclass.
1759 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1760 << CurMethod->getClassInterface()->getIdentifier();
1763 QualType T = Context.getObjCInterfaceType(Super);
1764 T = Context.getObjCObjectPointerType(T);
1766 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
1767 /*BaseExpr*/nullptr,
1768 SourceLocation()/*OpLoc*/,
1771 receiverNameLoc, T, true);
1774 // Otherwise, if this is a class method, try dispatching to our
1776 IFace = CurMethod->getClassInterface()->getSuperClass();
1781 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1787 // Search for a declared property first.
1788 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
1789 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
1791 // If this reference is in an @implementation, check for 'private' methods.
1793 Getter = IFace->lookupPrivateClassMethod(Sel);
1796 // FIXME: refactor/share with ActOnMemberReference().
1797 // Check if we can reference this property.
1798 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1802 // Look for the matching setter, in case it is needed.
1803 Selector SetterSel =
1804 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1805 PP.getSelectorTable(),
1808 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1810 // If this reference is in an @implementation, also check for 'private'
1812 Setter = IFace->lookupPrivateClassMethod(SetterSel);
1814 // Look through local category implementations associated with the class.
1816 Setter = IFace->getCategoryClassMethod(SetterSel);
1818 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1821 if (Getter || Setter) {
1823 return new (Context)
1824 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1825 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
1826 Context.getObjCInterfaceType(IFace));
1828 return new (Context) ObjCPropertyRefExpr(
1829 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
1830 propertyNameLoc, receiverNameLoc, IFace);
1832 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1833 << &propertyName << Context.getObjCInterfaceType(IFace));
1838 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1840 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1841 // Determine whether "super" is acceptable in the current context.
1842 if (Method && Method->getClassInterface())
1843 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1846 bool ValidateCandidate(const TypoCorrection &candidate) override {
1847 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1848 candidate.isKeyword("super");
1854 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
1855 IdentifierInfo *Name,
1856 SourceLocation NameLoc,
1858 bool HasTrailingDot,
1859 ParsedType &ReceiverType) {
1860 ReceiverType = ParsedType();
1862 // If the identifier is "super" and there is no trailing dot, we're
1863 // messaging super. If the identifier is "super" and there is a
1864 // trailing dot, it's an instance message.
1865 if (IsSuper && S->isInObjcMethodScope())
1866 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
1868 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1869 LookupName(Result, S);
1871 switch (Result.getResultKind()) {
1872 case LookupResult::NotFound:
1873 // Normal name lookup didn't find anything. If we're in an
1874 // Objective-C method, look for ivars. If we find one, we're done!
1875 // FIXME: This is a hack. Ivar lookup should be part of normal
1877 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
1878 if (!Method->getClassInterface()) {
1879 // Fall back: let the parser try to parse it as an instance message.
1880 return ObjCInstanceMessage;
1883 ObjCInterfaceDecl *ClassDeclared;
1884 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1886 return ObjCInstanceMessage;
1889 // Break out; we'll perform typo correction below.
1892 case LookupResult::NotFoundInCurrentInstantiation:
1893 case LookupResult::FoundOverloaded:
1894 case LookupResult::FoundUnresolvedValue:
1895 case LookupResult::Ambiguous:
1896 Result.suppressDiagnostics();
1897 return ObjCInstanceMessage;
1899 case LookupResult::Found: {
1900 // If the identifier is a class or not, and there is a trailing dot,
1901 // it's an instance message.
1903 return ObjCInstanceMessage;
1904 // We found something. If it's a type, then we have a class
1905 // message. Otherwise, it's an instance message.
1906 NamedDecl *ND = Result.getFoundDecl();
1908 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1909 T = Context.getObjCInterfaceType(Class);
1910 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
1911 T = Context.getTypeDeclType(Type);
1912 DiagnoseUseOfDecl(Type, NameLoc);
1915 return ObjCInstanceMessage;
1917 // We have a class message, and T is the type we're
1918 // messaging. Build source-location information for it.
1919 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1920 ReceiverType = CreateParsedType(T, TSInfo);
1921 return ObjCClassMessage;
1925 if (TypoCorrection Corrected = CorrectTypo(
1926 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
1927 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
1928 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
1929 if (Corrected.isKeyword()) {
1930 // If we've found the keyword "super" (the only keyword that would be
1931 // returned by CorrectTypo), this is a send to super.
1932 diagnoseTypo(Corrected,
1933 PDiag(diag::err_unknown_receiver_suggest) << Name);
1934 return ObjCSuperMessage;
1935 } else if (ObjCInterfaceDecl *Class =
1936 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1937 // If we found a declaration, correct when it refers to an Objective-C
1939 diagnoseTypo(Corrected,
1940 PDiag(diag::err_unknown_receiver_suggest) << Name);
1941 QualType T = Context.getObjCInterfaceType(Class);
1942 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1943 ReceiverType = CreateParsedType(T, TSInfo);
1944 return ObjCClassMessage;
1948 // Fall back: let the parser try to parse it as an instance message.
1949 return ObjCInstanceMessage;
1952 ExprResult Sema::ActOnSuperMessage(Scope *S,
1953 SourceLocation SuperLoc,
1955 SourceLocation LBracLoc,
1956 ArrayRef<SourceLocation> SelectorLocs,
1957 SourceLocation RBracLoc,
1958 MultiExprArg Args) {
1959 // Determine whether we are inside a method or not.
1960 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
1962 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1966 ObjCInterfaceDecl *Class = Method->getClassInterface();
1968 Diag(SuperLoc, diag::error_no_super_class_message)
1969 << Method->getDeclName();
1973 ObjCInterfaceDecl *Super = Class->getSuperClass();
1975 // The current class does not have a superclass.
1976 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1977 << Class->getIdentifier();
1981 // We are in a method whose class has a superclass, so 'super'
1982 // is acting as a keyword.
1983 if (Method->getSelector() == Sel)
1984 getCurFunction()->ObjCShouldCallSuper = false;
1986 if (Method->isInstanceMethod()) {
1987 // Since we are in an instance method, this is an instance
1988 // message to the superclass instance.
1989 QualType SuperTy = Context.getObjCInterfaceType(Super);
1990 SuperTy = Context.getObjCObjectPointerType(SuperTy);
1991 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
1992 Sel, /*Method=*/nullptr,
1993 LBracLoc, SelectorLocs, RBracLoc, Args);
1996 // Since we are in a class method, this is a class message to
1998 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
1999 Context.getObjCInterfaceType(Super),
2000 SuperLoc, Sel, /*Method=*/nullptr,
2001 LBracLoc, SelectorLocs, RBracLoc, Args);
2005 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2006 bool isSuperReceiver,
2009 ObjCMethodDecl *Method,
2010 MultiExprArg Args) {
2011 TypeSourceInfo *receiverTypeInfo = nullptr;
2012 if (!ReceiverType.isNull())
2013 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2015 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2016 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2017 Sel, Method, Loc, Loc, Loc, Args,
2018 /*isImplicit=*/true);
2022 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2024 bool (*refactor)(const ObjCMessageExpr *,
2025 const NSAPI &, edit::Commit &)) {
2026 SourceLocation MsgLoc = Msg->getExprLoc();
2027 if (S.Diags.isIgnored(DiagID, MsgLoc))
2030 SourceManager &SM = S.SourceMgr;
2031 edit::Commit ECommit(SM, S.LangOpts);
2032 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2033 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2034 << Msg->getSelector() << Msg->getSourceRange();
2035 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2036 if (!ECommit.isCommitable())
2038 for (edit::Commit::edit_iterator
2039 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2040 const edit::Commit::Edit &Edit = *I;
2041 switch (Edit.Kind) {
2042 case edit::Commit::Act_Insert:
2043 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2047 case edit::Commit::Act_InsertFromRange:
2048 Builder.AddFixItHint(
2049 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2050 Edit.getInsertFromRange(SM),
2053 case edit::Commit::Act_Remove:
2054 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2061 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2062 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2063 edit::rewriteObjCRedundantCallWithLiteral);
2066 /// \brief Diagnose use of %s directive in an NSString which is being passed
2067 /// as formatting string to formatting method.
2069 DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2070 ObjCMethodDecl *Method,
2072 Expr **Args, unsigned NumArgs) {
2074 bool Format = false;
2075 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2076 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
2081 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2082 if (S.GetFormatNSStringIdx(I, Idx)) {
2088 if (!Format || NumArgs <= Idx)
2091 Expr *FormatExpr = Args[Idx];
2092 if (ObjCStringLiteral *OSL =
2093 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2094 StringLiteral *FormatString = OSL->getString();
2095 if (S.FormatStringHasSArg(FormatString)) {
2096 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2099 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2100 << Method->getDeclName();
2105 /// \brief Build an Objective-C class message expression.
2107 /// This routine takes care of both normal class messages and
2108 /// class messages to the superclass.
2110 /// \param ReceiverTypeInfo Type source information that describes the
2111 /// receiver of this message. This may be NULL, in which case we are
2112 /// sending to the superclass and \p SuperLoc must be a valid source
2115 /// \param ReceiverType The type of the object receiving the
2116 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2117 /// type as that refers to. For a superclass send, this is the type of
2120 /// \param SuperLoc The location of the "super" keyword in a
2121 /// superclass message.
2123 /// \param Sel The selector to which the message is being sent.
2125 /// \param Method The method that this class message is invoking, if
2128 /// \param LBracLoc The location of the opening square bracket ']'.
2130 /// \param RBracLoc The location of the closing square bracket ']'.
2132 /// \param ArgsIn The message arguments.
2133 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
2134 QualType ReceiverType,
2135 SourceLocation SuperLoc,
2137 ObjCMethodDecl *Method,
2138 SourceLocation LBracLoc,
2139 ArrayRef<SourceLocation> SelectorLocs,
2140 SourceLocation RBracLoc,
2141 MultiExprArg ArgsIn,
2143 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
2144 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
2145 if (LBracLoc.isInvalid()) {
2146 Diag(Loc, diag::err_missing_open_square_message_send)
2147 << FixItHint::CreateInsertion(Loc, "[");
2150 SourceLocation SelLoc;
2151 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2152 SelLoc = SelectorLocs.front();
2156 if (ReceiverType->isDependentType()) {
2157 // If the receiver type is dependent, we can't type-check anything
2158 // at this point. Build a dependent expression.
2159 unsigned NumArgs = ArgsIn.size();
2160 Expr **Args = ArgsIn.data();
2161 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2162 return ObjCMessageExpr::Create(
2163 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2164 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2168 // Find the class to which we are sending this message.
2169 ObjCInterfaceDecl *Class = nullptr;
2170 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2171 if (!ClassType || !(Class = ClassType->getInterface())) {
2172 Diag(Loc, diag::err_invalid_receiver_class_message)
2176 assert(Class && "We don't know which class we're messaging?");
2177 // objc++ diagnoses during typename annotation.
2178 if (!getLangOpts().CPlusPlus)
2179 (void)DiagnoseUseOfDecl(Class, SelLoc);
2180 // Find the method we are messaging.
2182 SourceRange TypeRange
2183 = SuperLoc.isValid()? SourceRange(SuperLoc)
2184 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
2185 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
2186 (getLangOpts().ObjCAutoRefCount
2187 ? diag::err_arc_receiver_forward_class
2188 : diag::warn_receiver_forward_class),
2190 // A forward class used in messaging is treated as a 'Class'
2191 Method = LookupFactoryMethodInGlobalPool(Sel,
2192 SourceRange(LBracLoc, RBracLoc));
2193 if (Method && !getLangOpts().ObjCAutoRefCount)
2194 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2195 << Method->getDeclName();
2198 Method = Class->lookupClassMethod(Sel);
2200 // If we have an implementation in scope, check "private" methods.
2202 Method = Class->lookupPrivateClassMethod(Sel);
2204 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2208 // Check the argument types and determine the result type.
2209 QualType ReturnType;
2210 ExprValueKind VK = VK_RValue;
2212 unsigned NumArgs = ArgsIn.size();
2213 Expr **Args = ArgsIn.data();
2214 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2217 SuperLoc.isValid(), LBracLoc, RBracLoc,
2222 if (Method && !Method->getReturnType()->isVoidType() &&
2223 RequireCompleteType(LBracLoc, Method->getReturnType(),
2224 diag::err_illegal_message_expr_incomplete_type))
2227 // Warn about explicit call of +initialize on its own class. But not on 'super'.
2228 if (Method && Method->getMethodFamily() == OMF_initialize) {
2229 if (!SuperLoc.isValid()) {
2230 const ObjCInterfaceDecl *ID =
2231 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2233 Diag(Loc, diag::warn_direct_initialize_call);
2234 Diag(Method->getLocation(), diag::note_method_declared_at)
2235 << Method->getDeclName();
2238 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2239 // [super initialize] is allowed only within an +initialize implementation
2240 if (CurMeth->getMethodFamily() != OMF_initialize) {
2241 Diag(Loc, diag::warn_direct_super_initialize_call);
2242 Diag(Method->getLocation(), diag::note_method_declared_at)
2243 << Method->getDeclName();
2244 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2245 << CurMeth->getDeclName();
2250 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2252 // Construct the appropriate ObjCMessageExpr.
2253 ObjCMessageExpr *Result;
2254 if (SuperLoc.isValid())
2255 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2256 SuperLoc, /*IsInstanceSuper=*/false,
2257 ReceiverType, Sel, SelectorLocs,
2258 Method, makeArrayRef(Args, NumArgs),
2259 RBracLoc, isImplicit);
2261 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2262 ReceiverTypeInfo, Sel, SelectorLocs,
2263 Method, makeArrayRef(Args, NumArgs),
2264 RBracLoc, isImplicit);
2266 checkCocoaAPI(*this, Result);
2268 return MaybeBindToTemporary(Result);
2271 // ActOnClassMessage - used for both unary and keyword messages.
2272 // ArgExprs is optional - if it is present, the number of expressions
2273 // is obtained from Sel.getNumArgs().
2274 ExprResult Sema::ActOnClassMessage(Scope *S,
2275 ParsedType Receiver,
2277 SourceLocation LBracLoc,
2278 ArrayRef<SourceLocation> SelectorLocs,
2279 SourceLocation RBracLoc,
2280 MultiExprArg Args) {
2281 TypeSourceInfo *ReceiverTypeInfo;
2282 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2283 if (ReceiverType.isNull())
2287 if (!ReceiverTypeInfo)
2288 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2290 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
2291 /*SuperLoc=*/SourceLocation(), Sel,
2292 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2296 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2297 QualType ReceiverType,
2300 ObjCMethodDecl *Method,
2301 MultiExprArg Args) {
2302 return BuildInstanceMessage(Receiver, ReceiverType,
2303 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2304 Sel, Method, Loc, Loc, Loc, Args,
2305 /*isImplicit=*/true);
2308 /// \brief Build an Objective-C instance message expression.
2310 /// This routine takes care of both normal instance messages and
2311 /// instance messages to the superclass instance.
2313 /// \param Receiver The expression that computes the object that will
2314 /// receive this message. This may be empty, in which case we are
2315 /// sending to the superclass instance and \p SuperLoc must be a valid
2316 /// source location.
2318 /// \param ReceiverType The (static) type of the object receiving the
2319 /// message. When a \p Receiver expression is provided, this is the
2320 /// same type as that expression. For a superclass instance send, this
2321 /// is a pointer to the type of the superclass.
2323 /// \param SuperLoc The location of the "super" keyword in a
2324 /// superclass instance message.
2326 /// \param Sel The selector to which the message is being sent.
2328 /// \param Method The method that this instance message is invoking, if
2331 /// \param LBracLoc The location of the opening square bracket ']'.
2333 /// \param RBracLoc The location of the closing square bracket ']'.
2335 /// \param ArgsIn The message arguments.
2336 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2337 QualType ReceiverType,
2338 SourceLocation SuperLoc,
2340 ObjCMethodDecl *Method,
2341 SourceLocation LBracLoc,
2342 ArrayRef<SourceLocation> SelectorLocs,
2343 SourceLocation RBracLoc,
2344 MultiExprArg ArgsIn,
2346 // The location of the receiver.
2347 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
2348 SourceRange RecRange =
2349 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2350 SourceLocation SelLoc;
2351 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2352 SelLoc = SelectorLocs.front();
2356 if (LBracLoc.isInvalid()) {
2357 Diag(Loc, diag::err_missing_open_square_message_send)
2358 << FixItHint::CreateInsertion(Loc, "[");
2362 // If we have a receiver expression, perform appropriate promotions
2363 // and determine receiver type.
2365 if (Receiver->hasPlaceholderType()) {
2367 if (Receiver->getType() == Context.UnknownAnyTy)
2368 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2370 Result = CheckPlaceholderExpr(Receiver);
2371 if (Result.isInvalid()) return ExprError();
2372 Receiver = Result.get();
2375 if (Receiver->isTypeDependent()) {
2376 // If the receiver is type-dependent, we can't type-check anything
2377 // at this point. Build a dependent expression.
2378 unsigned NumArgs = ArgsIn.size();
2379 Expr **Args = ArgsIn.data();
2380 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2381 return ObjCMessageExpr::Create(
2382 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2383 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2384 RBracLoc, isImplicit);
2387 // If necessary, apply function/array conversion to the receiver.
2388 // C99 6.7.5.3p[7,8].
2389 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2390 if (Result.isInvalid())
2392 Receiver = Result.get();
2393 ReceiverType = Receiver->getType();
2395 // If the receiver is an ObjC pointer, a block pointer, or an
2396 // __attribute__((NSObject)) pointer, we don't need to do any
2397 // special conversion in order to look up a receiver.
2398 if (ReceiverType->isObjCRetainableType()) {
2400 } else if (!getLangOpts().ObjCAutoRefCount &&
2401 !Context.getObjCIdType().isNull() &&
2402 (ReceiverType->isPointerType() ||
2403 ReceiverType->isIntegerType())) {
2404 // Implicitly convert integers and pointers to 'id' but emit a warning.
2406 Diag(Loc, diag::warn_bad_receiver_type)
2408 << Receiver->getSourceRange();
2409 if (ReceiverType->isPointerType()) {
2410 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2411 CK_CPointerToObjCPointerCast).get();
2413 // TODO: specialized warning on null receivers?
2414 bool IsNull = Receiver->isNullPointerConstant(Context,
2415 Expr::NPC_ValueDependentIsNull);
2416 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2417 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2420 ReceiverType = Receiver->getType();
2421 } else if (getLangOpts().CPlusPlus) {
2422 // The receiver must be a complete type.
2423 if (RequireCompleteType(Loc, Receiver->getType(),
2424 diag::err_incomplete_receiver_type))
2427 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2428 if (result.isUsable()) {
2429 Receiver = result.get();
2430 ReceiverType = Receiver->getType();
2435 // There's a somewhat weird interaction here where we assume that we
2436 // won't actually have a method unless we also don't need to do some
2437 // of the more detailed type-checking on the receiver.
2440 // Handle messages to id.
2441 bool receiverIsId = ReceiverType->isObjCIdType();
2442 if (receiverIsId || ReceiverType->isBlockPointerType() ||
2443 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2444 Method = LookupInstanceMethodInGlobalPool(Sel,
2445 SourceRange(LBracLoc, RBracLoc),
2448 Method = LookupFactoryMethodInGlobalPool(Sel,
2449 SourceRange(LBracLoc,RBracLoc),
2452 if (ObjCMethodDecl *BestMethod =
2453 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2454 Method = BestMethod;
2455 if (!AreMultipleMethodsInGlobalPool(Sel, Method->isInstanceMethod()))
2456 DiagnoseUseOfDecl(Method, SelLoc);
2458 } else if (ReceiverType->isObjCClassType() ||
2459 ReceiverType->isObjCQualifiedClassType()) {
2460 // Handle messages to Class.
2461 // We allow sending a message to a qualified Class ("Class<foo>"), which
2462 // is ok as long as one of the protocols implements the selector (if not,
2464 if (const ObjCObjectPointerType *QClassTy
2465 = ReceiverType->getAsObjCQualifiedClassType()) {
2466 // Search protocols for class methods.
2467 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2469 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2470 // warn if instance method found for a Class message.
2472 Diag(SelLoc, diag::warn_instance_method_on_class_found)
2473 << Method->getSelector() << Sel;
2474 Diag(Method->getLocation(), diag::note_method_declared_at)
2475 << Method->getDeclName();
2479 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2480 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2481 // First check the public methods in the class interface.
2482 Method = ClassDecl->lookupClassMethod(Sel);
2485 Method = ClassDecl->lookupPrivateClassMethod(Sel);
2487 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2491 // If not messaging 'self', look for any factory method named 'Sel'.
2492 if (!Receiver || !isSelfExpr(Receiver)) {
2493 Method = LookupFactoryMethodInGlobalPool(Sel,
2494 SourceRange(LBracLoc, RBracLoc),
2497 // If no class (factory) method was found, check if an _instance_
2498 // method of the same name exists in the root class only.
2499 Method = LookupInstanceMethodInGlobalPool(Sel,
2500 SourceRange(LBracLoc, RBracLoc),
2503 if (const ObjCInterfaceDecl *ID =
2504 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2505 if (ID->getSuperClass())
2506 Diag(SelLoc, diag::warn_root_inst_method_not_found)
2507 << Sel << SourceRange(LBracLoc, RBracLoc);
2511 if (ObjCMethodDecl *BestMethod =
2512 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2513 Method = BestMethod;
2518 ObjCInterfaceDecl *ClassDecl = nullptr;
2520 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2521 // long as one of the protocols implements the selector (if not, warn).
2522 // And as long as message is not deprecated/unavailable (warn if it is).
2523 if (const ObjCObjectPointerType *QIdTy
2524 = ReceiverType->getAsObjCQualifiedIdType()) {
2525 // Search protocols for instance methods.
2526 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2528 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2529 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2531 } else if (const ObjCObjectPointerType *OCIType
2532 = ReceiverType->getAsObjCInterfacePointerType()) {
2533 // We allow sending a message to a pointer to an interface (an object).
2534 ClassDecl = OCIType->getInterfaceDecl();
2536 // Try to complete the type. Under ARC, this is a hard error from which
2537 // we don't try to recover.
2538 const ObjCInterfaceDecl *forwardClass = nullptr;
2539 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
2540 getLangOpts().ObjCAutoRefCount
2541 ? diag::err_arc_receiver_forward_instance
2542 : diag::warn_receiver_forward_instance,
2543 Receiver? Receiver->getSourceRange()
2544 : SourceRange(SuperLoc))) {
2545 if (getLangOpts().ObjCAutoRefCount)
2548 forwardClass = OCIType->getInterfaceDecl();
2549 Diag(Receiver ? Receiver->getLocStart()
2550 : SuperLoc, diag::note_receiver_is_id);
2553 Method = ClassDecl->lookupInstanceMethod(Sel);
2557 // Search protocol qualifiers.
2558 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2561 // If we have implementations in scope, check "private" methods.
2562 Method = ClassDecl->lookupPrivateMethod(Sel);
2564 if (!Method && getLangOpts().ObjCAutoRefCount) {
2565 Diag(SelLoc, diag::err_arc_may_not_respond)
2566 << OCIType->getPointeeType() << Sel << RecRange
2567 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
2571 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2572 // If we still haven't found a method, look in the global pool. This
2573 // behavior isn't very desirable, however we need it for GCC
2574 // compatibility. FIXME: should we deviate??
2575 if (OCIType->qual_empty()) {
2576 Method = LookupInstanceMethodInGlobalPool(Sel,
2577 SourceRange(LBracLoc, RBracLoc));
2578 if (Method && !forwardClass)
2579 Diag(SelLoc, diag::warn_maynot_respond)
2580 << OCIType->getInterfaceDecl()->getIdentifier()
2585 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
2588 // Reject other random receiver types (e.g. structs).
2589 Diag(Loc, diag::err_bad_receiver_type)
2590 << ReceiverType << Receiver->getSourceRange();
2596 FunctionScopeInfo *DIFunctionScopeInfo =
2597 (Method && Method->getMethodFamily() == OMF_init)
2598 ? getEnclosingFunction() : nullptr;
2600 if (DIFunctionScopeInfo &&
2601 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
2602 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2603 bool isDesignatedInitChain = false;
2604 if (SuperLoc.isValid()) {
2605 if (const ObjCObjectPointerType *
2606 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2607 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
2608 // Either we know this is a designated initializer or we
2609 // conservatively assume it because we don't know for sure.
2610 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2611 ID->isDesignatedInitializer(Sel)) {
2612 isDesignatedInitChain = true;
2613 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
2618 if (!isDesignatedInitChain) {
2619 const ObjCMethodDecl *InitMethod = nullptr;
2621 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2622 assert(isDesignated && InitMethod);
2624 Diag(SelLoc, SuperLoc.isValid() ?
2625 diag::warn_objc_designated_init_non_designated_init_call :
2626 diag::warn_objc_designated_init_non_super_designated_init_call);
2627 Diag(InitMethod->getLocation(),
2628 diag::note_objc_designated_init_marked_here);
2632 if (DIFunctionScopeInfo &&
2633 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
2634 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2635 if (SuperLoc.isValid()) {
2636 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2638 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
2642 // Check the message arguments.
2643 unsigned NumArgs = ArgsIn.size();
2644 Expr **Args = ArgsIn.data();
2645 QualType ReturnType;
2646 ExprValueKind VK = VK_RValue;
2647 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2648 ReceiverType->isObjCQualifiedClassType());
2649 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2650 Sel, SelectorLocs, Method,
2651 ClassMessage, SuperLoc.isValid(),
2652 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
2655 if (Method && !Method->getReturnType()->isVoidType() &&
2656 RequireCompleteType(LBracLoc, Method->getReturnType(),
2657 diag::err_illegal_message_expr_incomplete_type))
2660 // In ARC, forbid the user from sending messages to
2661 // retain/release/autorelease/dealloc/retainCount explicitly.
2662 if (getLangOpts().ObjCAutoRefCount) {
2663 ObjCMethodFamily family =
2664 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2668 checkInitMethod(Method, ReceiverType);
2674 case OMF_mutableCopy:
2677 case OMF_initialize:
2683 case OMF_autorelease:
2684 case OMF_retainCount:
2685 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2689 case OMF_performSelector:
2690 if (Method && NumArgs >= 1) {
2691 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2692 Selector ArgSel = SelExp->getSelector();
2693 ObjCMethodDecl *SelMethod =
2694 LookupInstanceMethodInGlobalPool(ArgSel,
2695 SelExp->getSourceRange());
2698 LookupFactoryMethodInGlobalPool(ArgSel,
2699 SelExp->getSourceRange());
2701 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2702 switch (SelFamily) {
2705 case OMF_mutableCopy:
2709 // Issue error, unless ns_returns_not_retained.
2710 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2711 // selector names a +1 method
2713 diag::err_arc_perform_selector_retains);
2714 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2715 << SelMethod->getDeclName();
2719 // +0 call. OK. unless ns_returns_retained.
2720 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2721 // selector names a +1 method
2723 diag::err_arc_perform_selector_retains);
2724 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2725 << SelMethod->getDeclName();
2731 // error (may leak).
2732 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
2733 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2740 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2742 // Construct the appropriate ObjCMessageExpr instance.
2743 ObjCMessageExpr *Result;
2744 if (SuperLoc.isValid())
2745 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2746 SuperLoc, /*IsInstanceSuper=*/true,
2747 ReceiverType, Sel, SelectorLocs, Method,
2748 makeArrayRef(Args, NumArgs), RBracLoc,
2751 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2752 Receiver, Sel, SelectorLocs, Method,
2753 makeArrayRef(Args, NumArgs), RBracLoc,
2756 checkCocoaAPI(*this, Result);
2759 if (getLangOpts().ObjCAutoRefCount) {
2760 // Do not warn about IBOutlet weak property receivers being set to null
2761 // as this cannot asynchronously happen.
2762 bool WarnWeakReceiver = true;
2763 if (isImplicit && Method)
2764 if (const ObjCPropertyDecl *PropertyDecl = Method->findPropertyDecl())
2765 WarnWeakReceiver = !PropertyDecl->hasAttr<IBOutletAttr>();
2766 if (WarnWeakReceiver)
2767 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
2769 // In ARC, annotate delegate init calls.
2770 if (Result->getMethodFamily() == OMF_init &&
2771 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2772 // Only consider init calls *directly* in init implementations,
2773 // not within blocks.
2774 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2775 if (method && method->getMethodFamily() == OMF_init) {
2776 // The implicit assignment to self means we also don't want to
2777 // consume the result.
2778 Result->setDelegateInitCall(true);
2783 // In ARC, check for message sends which are likely to introduce
2785 checkRetainCycles(Result);
2787 if (!isImplicit && Method) {
2788 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2790 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2791 if (!IsWeak && Sel.isUnarySelector())
2792 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
2794 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
2795 getCurFunction()->recordUseOfWeak(Result, Prop);
2800 return MaybeBindToTemporary(Result);
2803 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2804 if (ObjCSelectorExpr *OSE =
2805 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2806 Selector Sel = OSE->getSelector();
2807 SourceLocation Loc = OSE->getAtLoc();
2808 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2809 = S.ReferencedSelectors.find(Sel);
2810 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2811 S.ReferencedSelectors.erase(Pos);
2815 // ActOnInstanceMessage - used for both unary and keyword messages.
2816 // ArgExprs is optional - if it is present, the number of expressions
2817 // is obtained from Sel.getNumArgs().
2818 ExprResult Sema::ActOnInstanceMessage(Scope *S,
2821 SourceLocation LBracLoc,
2822 ArrayRef<SourceLocation> SelectorLocs,
2823 SourceLocation RBracLoc,
2824 MultiExprArg Args) {
2828 // A ParenListExpr can show up while doing error recovery with invalid code.
2829 if (isa<ParenListExpr>(Receiver)) {
2830 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2831 if (Result.isInvalid()) return ExprError();
2832 Receiver = Result.get();
2835 if (RespondsToSelectorSel.isNull()) {
2836 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2837 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2839 if (Sel == RespondsToSelectorSel)
2840 RemoveSelectorFromWarningCache(*this, Args[0]);
2842 return BuildInstanceMessage(Receiver, Receiver->getType(),
2843 /*SuperLoc=*/SourceLocation(), Sel,
2844 /*Method=*/nullptr, LBracLoc, SelectorLocs,
2848 enum ARCConversionTypeClass {
2849 /// int, void, struct A
2855 /// id*, id***, void (^*)(),
2856 ACTC_indirectRetainable,
2858 /// void* might be a normal C type, or it might a CF type.
2864 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2865 return (ACTC == ACTC_retainable ||
2866 ACTC == ACTC_coreFoundation ||
2867 ACTC == ACTC_voidPtr);
2869 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2870 return ACTC == ACTC_none ||
2871 ACTC == ACTC_voidPtr ||
2872 ACTC == ACTC_coreFoundation;
2875 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
2876 bool isIndirect = false;
2878 // Ignore an outermost reference type.
2879 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
2880 type = ref->getPointeeType();
2884 // Drill through pointers and arrays recursively.
2886 if (const PointerType *ptr = type->getAs<PointerType>()) {
2887 type = ptr->getPointeeType();
2889 // The first level of pointer may be the innermost pointer on a CF type.
2891 if (type->isVoidType()) return ACTC_voidPtr;
2892 if (type->isRecordType()) return ACTC_coreFoundation;
2894 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2895 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2903 if (type->isObjCARCBridgableType())
2904 return ACTC_indirectRetainable;
2908 if (type->isObjCARCBridgableType())
2909 return ACTC_retainable;
2915 /// A result from the cast checker.
2917 /// Cannot be casted.
2920 /// Can be safely retained or not retained.
2923 /// Can be casted at +0.
2926 /// Can be casted at +1.
2929 ACCResult merge(ACCResult left, ACCResult right) {
2930 if (left == right) return left;
2931 if (left == ACC_bottom) return right;
2932 if (right == ACC_bottom) return left;
2936 /// A checker which white-lists certain expressions whose conversion
2937 /// to or from retainable type would otherwise be forbidden in ARC.
2938 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2939 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2941 ASTContext &Context;
2942 ARCConversionTypeClass SourceClass;
2943 ARCConversionTypeClass TargetClass;
2946 static bool isCFType(QualType type) {
2947 // Someday this can use ns_bridged. For now, it has to do this.
2948 return type->isCARCBridgableType();
2952 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
2953 ARCConversionTypeClass target, bool diagnose)
2954 : Context(Context), SourceClass(source), TargetClass(target),
2955 Diagnose(diagnose) {}
2958 ACCResult Visit(Expr *e) {
2959 return super::Visit(e->IgnoreParens());
2962 ACCResult VisitStmt(Stmt *s) {
2966 /// Null pointer constants can be casted however you please.
2967 ACCResult VisitExpr(Expr *e) {
2968 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2973 /// Objective-C string literals can be safely casted.
2974 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2975 // If we're casting to any retainable type, go ahead. Global
2976 // strings are immune to retains, so this is bottom.
2977 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2982 /// Look through certain implicit and explicit casts.
2983 ACCResult VisitCastExpr(CastExpr *e) {
2984 switch (e->getCastKind()) {
2985 case CK_NullToPointer:
2989 case CK_LValueToRValue:
2991 case CK_CPointerToObjCPointerCast:
2992 case CK_BlockPointerToObjCPointerCast:
2993 case CK_AnyPointerToBlockPointerCast:
2994 return Visit(e->getSubExpr());
3001 /// Look through unary extension.
3002 ACCResult VisitUnaryExtension(UnaryOperator *e) {
3003 return Visit(e->getSubExpr());
3006 /// Ignore the LHS of a comma operator.
3007 ACCResult VisitBinComma(BinaryOperator *e) {
3008 return Visit(e->getRHS());
3011 /// Conditional operators are okay if both sides are okay.
3012 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3013 ACCResult left = Visit(e->getTrueExpr());
3014 if (left == ACC_invalid) return ACC_invalid;
3015 return merge(left, Visit(e->getFalseExpr()));
3018 /// Look through pseudo-objects.
3019 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3020 // If we're getting here, we should always have a result.
3021 return Visit(e->getResultExpr());
3024 /// Statement expressions are okay if their result expression is okay.
3025 ACCResult VisitStmtExpr(StmtExpr *e) {
3026 return Visit(e->getSubStmt()->body_back());
3029 /// Some declaration references are okay.
3030 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
3031 // References to global constants from system headers are okay.
3032 // These are things like 'kCFStringTransformToLatin'. They are
3033 // can also be assumed to be immune to retains.
3034 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
3035 if (isAnyRetainable(TargetClass) &&
3036 isAnyRetainable(SourceClass) &&
3038 var->getStorageClass() == SC_Extern &&
3039 var->getType().isConstQualified() &&
3040 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
3048 /// Some calls are okay.
3049 ACCResult VisitCallExpr(CallExpr *e) {
3050 if (FunctionDecl *fn = e->getDirectCallee())
3051 if (ACCResult result = checkCallToFunction(fn))
3054 return super::VisitCallExpr(e);
3057 ACCResult checkCallToFunction(FunctionDecl *fn) {
3058 // Require a CF*Ref return type.
3059 if (!isCFType(fn->getReturnType()))
3062 if (!isAnyRetainable(TargetClass))
3065 // Honor an explicit 'not retained' attribute.
3066 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3067 return ACC_plusZero;
3069 // Honor an explicit 'retained' attribute, except that for
3070 // now we're not going to permit implicit handling of +1 results,
3071 // because it's a bit frightening.
3072 if (fn->hasAttr<CFReturnsRetainedAttr>())
3073 return Diagnose ? ACC_plusOne
3074 : ACC_invalid; // ACC_plusOne if we start accepting this
3076 // Recognize this specific builtin function, which is used by CFSTR.
3077 unsigned builtinID = fn->getBuiltinID();
3078 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3081 // Otherwise, don't do anything implicit with an unaudited function.
3082 if (!fn->hasAttr<CFAuditedTransferAttr>())
3085 // Otherwise, it's +0 unless it follows the create convention.
3086 if (ento::coreFoundation::followsCreateRule(fn))
3087 return Diagnose ? ACC_plusOne
3088 : ACC_invalid; // ACC_plusOne if we start accepting this
3090 return ACC_plusZero;
3093 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3094 return checkCallToMethod(e->getMethodDecl());
3097 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3098 ObjCMethodDecl *method;
3099 if (e->isExplicitProperty())
3100 method = e->getExplicitProperty()->getGetterMethodDecl();
3102 method = e->getImplicitPropertyGetter();
3103 return checkCallToMethod(method);
3106 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3107 if (!method) return ACC_invalid;
3109 // Check for message sends to functions returning CF types. We
3110 // just obey the Cocoa conventions with these, even though the
3111 // return type is CF.
3112 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
3115 // If the method is explicitly marked not-retained, it's +0.
3116 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3117 return ACC_plusZero;
3119 // If the method is explicitly marked as returning retained, or its
3120 // selector follows a +1 Cocoa convention, treat it as +1.
3121 if (method->hasAttr<CFReturnsRetainedAttr>())
3124 switch (method->getSelector().getMethodFamily()) {
3127 case OMF_mutableCopy:
3132 // Otherwise, treat it as +0.
3133 return ACC_plusZero;
3139 bool Sema::isKnownName(StringRef name) {
3142 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
3143 Sema::LookupOrdinaryName);
3144 return LookupName(R, TUScope, false);
3147 static void addFixitForObjCARCConversion(Sema &S,
3148 DiagnosticBuilder &DiagB,
3149 Sema::CheckedConversionKind CCK,
3150 SourceLocation afterLParen,
3154 const char *bridgeKeyword,
3155 const char *CFBridgeName) {
3156 // We handle C-style and implicit casts here.
3158 case Sema::CCK_ImplicitConversion:
3159 case Sema::CCK_CStyleCast:
3160 case Sema::CCK_OtherCast:
3162 case Sema::CCK_FunctionalCast:
3167 if (CCK == Sema::CCK_OtherCast) {
3168 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3169 SourceRange range(NCE->getOperatorLoc(),
3170 NCE->getAngleBrackets().getEnd());
3171 SmallString<32> BridgeCall;
3173 SourceManager &SM = S.getSourceManager();
3174 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3175 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3178 BridgeCall += CFBridgeName;
3179 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3183 Expr *castedE = castExpr;
3184 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3185 castedE = CCE->getSubExpr();
3186 castedE = castedE->IgnoreImpCasts();
3187 SourceRange range = castedE->getSourceRange();
3189 SmallString<32> BridgeCall;
3191 SourceManager &SM = S.getSourceManager();
3192 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3193 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3196 BridgeCall += CFBridgeName;
3198 if (isa<ParenExpr>(castedE)) {
3199 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3203 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3205 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3206 S.PP.getLocForEndOfToken(range.getEnd()),
3212 if (CCK == Sema::CCK_CStyleCast) {
3213 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
3214 } else if (CCK == Sema::CCK_OtherCast) {
3215 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3216 std::string castCode = "(";
3217 castCode += bridgeKeyword;
3218 castCode += castType.getAsString();
3220 SourceRange Range(NCE->getOperatorLoc(),
3221 NCE->getAngleBrackets().getEnd());
3222 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3225 std::string castCode = "(";
3226 castCode += bridgeKeyword;
3227 castCode += castType.getAsString();
3229 Expr *castedE = castExpr->IgnoreImpCasts();
3230 SourceRange range = castedE->getSourceRange();
3231 if (isa<ParenExpr>(castedE)) {
3232 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3236 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3238 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3239 S.PP.getLocForEndOfToken(range.getEnd()),
3245 template <typename T>
3246 static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3247 TypedefNameDecl *TDNDecl = TD->getDecl();
3248 QualType QT = TDNDecl->getUnderlyingType();
3249 if (QT->isPointerType()) {
3250 QT = QT->getPointeeType();
3251 if (const RecordType *RT = QT->getAs<RecordType>())
3252 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
3253 return RD->getAttr<T>();
3258 static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3259 TypedefNameDecl *&TDNDecl) {
3260 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3261 TDNDecl = TD->getDecl();
3262 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3263 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3265 T = TDNDecl->getUnderlyingType();
3271 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3272 QualType castType, ARCConversionTypeClass castACTC,
3273 Expr *castExpr, Expr *realCast,
3274 ARCConversionTypeClass exprACTC,
3275 Sema::CheckedConversionKind CCK) {
3276 SourceLocation loc =
3277 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
3279 if (S.makeUnavailableInSystemHeader(loc,
3280 "converts between Objective-C and C pointers in -fobjc-arc"))
3283 QualType castExprType = castExpr->getType();
3284 TypedefNameDecl *TDNDecl = nullptr;
3285 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3286 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3287 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3288 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3291 unsigned srcKind = 0;
3294 case ACTC_coreFoundation:
3296 srcKind = (castExprType->isPointerType() ? 1 : 0);
3298 case ACTC_retainable:
3299 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3301 case ACTC_indirectRetainable:
3306 // Check whether this could be fixed with a bridge cast.
3307 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3308 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
3310 // Bridge from an ARC type to a CF type.
3311 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
3313 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3314 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3315 << 2 // of C pointer type
3317 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3320 << castExpr->getSourceRange();
3321 bool br = S.isKnownName("CFBridgingRelease");
3322 ACCResult CreateRule =
3323 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3324 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3325 if (CreateRule != ACC_plusOne)
3327 DiagnosticBuilder DiagB =
3328 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3329 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3331 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3332 castType, castExpr, realCast, "__bridge ",
3335 if (CreateRule != ACC_plusZero)
3337 DiagnosticBuilder DiagB =
3338 (CCK == Sema::CCK_OtherCast && !br) ?
3339 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3340 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3341 diag::note_arc_bridge_transfer)
3342 << castExprType << br;
3344 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3345 castType, castExpr, realCast, "__bridge_transfer ",
3346 br ? "CFBridgingRelease" : nullptr);
3352 // Bridge from a CF type to an ARC type.
3353 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
3354 bool br = S.isKnownName("CFBridgingRetain");
3355 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3356 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3357 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3359 << 2 // to C pointer type
3362 << castExpr->getSourceRange();
3363 ACCResult CreateRule =
3364 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3365 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3366 if (CreateRule != ACC_plusOne)
3368 DiagnosticBuilder DiagB =
3369 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3370 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3371 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3372 castType, castExpr, realCast, "__bridge ",
3375 if (CreateRule != ACC_plusZero)
3377 DiagnosticBuilder DiagB =
3378 (CCK == Sema::CCK_OtherCast && !br) ?
3379 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3380 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3381 diag::note_arc_bridge_retained)
3384 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3385 castType, castExpr, realCast, "__bridge_retained ",
3386 br ? "CFBridgingRetain" : nullptr);
3392 S.Diag(loc, diag::err_arc_mismatched_cast)
3393 << (CCK != Sema::CCK_ImplicitConversion)
3394 << srcKind << castExprType << castType
3395 << castRange << castExpr->getSourceRange();
3398 template <typename TB>
3399 static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3400 bool &HadTheAttribute, bool warn) {
3401 QualType T = castExpr->getType();
3402 HadTheAttribute = false;
3403 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3404 TypedefNameDecl *TDNDecl = TD->getDecl();
3405 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3406 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3407 HadTheAttribute = true;
3408 if (Parm->isStr("id"))
3411 NamedDecl *Target = nullptr;
3412 // Check for an existing type with this name.
3413 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3414 Sema::LookupOrdinaryName);
3415 if (S.LookupName(R, S.TUScope)) {
3416 Target = R.getFoundDecl();
3417 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3418 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3419 if (const ObjCObjectPointerType *InterfacePointerType =
3420 castType->getAsObjCInterfacePointerType()) {
3421 ObjCInterfaceDecl *CastClass
3422 = InterfacePointerType->getObjectType()->getInterface();
3423 if ((CastClass == ExprClass) ||
3424 (CastClass && ExprClass->isSuperClassOf(CastClass)))
3427 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3428 << T << Target->getName() << castType->getPointeeType();
3430 } else if (castType->isObjCIdType() ||
3431 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3432 castType, ExprClass)))
3433 // ok to cast to 'id'.
3434 // casting to id<p-list> is ok if bridge type adopts all of
3435 // p-list protocols.
3439 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3440 << T << Target->getName() << castType;
3441 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3442 S.Diag(Target->getLocStart(), diag::note_declared_at);
3448 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
3449 << castExpr->getType() << Parm;
3450 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3452 S.Diag(Target->getLocStart(), diag::note_declared_at);
3457 T = TDNDecl->getUnderlyingType();
3462 template <typename TB>
3463 static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3464 bool &HadTheAttribute, bool warn) {
3465 QualType T = castType;
3466 HadTheAttribute = false;
3467 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3468 TypedefNameDecl *TDNDecl = TD->getDecl();
3469 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3470 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3471 HadTheAttribute = true;
3472 NamedDecl *Target = nullptr;
3473 // Check for an existing type with this name.
3474 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3475 Sema::LookupOrdinaryName);
3476 if (S.LookupName(R, S.TUScope)) {
3477 Target = R.getFoundDecl();
3478 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3479 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3480 if (const ObjCObjectPointerType *InterfacePointerType =
3481 castExpr->getType()->getAsObjCInterfacePointerType()) {
3482 ObjCInterfaceDecl *ExprClass
3483 = InterfacePointerType->getObjectType()->getInterface();
3484 if ((CastClass == ExprClass) ||
3485 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
3488 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3489 << castExpr->getType()->getPointeeType() << T;
3490 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3493 } else if (castExpr->getType()->isObjCIdType() ||
3494 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3495 castExpr->getType(), CastClass)))
3496 // ok to cast an 'id' expression to a CFtype.
3497 // ok to cast an 'id<plist>' expression to CFtype provided plist
3498 // adopts all of CFtype's ObjetiveC's class plist.
3502 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3503 << castExpr->getType() << castType;
3504 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3505 S.Diag(Target->getLocStart(), diag::note_declared_at);
3511 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3512 << castExpr->getType() << castType;
3513 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3515 S.Diag(Target->getLocStart(), diag::note_declared_at);
3520 T = TDNDecl->getUnderlyingType();
3525 void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
3526 if (!getLangOpts().ObjC1)
3528 // warn in presence of __bridge casting to or from a toll free bridge cast.
3529 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3530 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3531 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
3532 bool HasObjCBridgeAttr;
3533 bool ObjCBridgeAttrWillNotWarn =
3534 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3536 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3538 bool HasObjCBridgeMutableAttr;
3539 bool ObjCBridgeMutableAttrWillNotWarn =
3540 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3541 HasObjCBridgeMutableAttr, false);
3542 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3545 if (HasObjCBridgeAttr)
3546 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3548 else if (HasObjCBridgeMutableAttr)
3549 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3550 HasObjCBridgeMutableAttr, true);
3552 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
3553 bool HasObjCBridgeAttr;
3554 bool ObjCBridgeAttrWillNotWarn =
3555 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3557 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3559 bool HasObjCBridgeMutableAttr;
3560 bool ObjCBridgeMutableAttrWillNotWarn =
3561 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3562 HasObjCBridgeMutableAttr, false);
3563 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3566 if (HasObjCBridgeAttr)
3567 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3569 else if (HasObjCBridgeMutableAttr)
3570 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3571 HasObjCBridgeMutableAttr, true);
3575 void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3576 QualType SrcType = castExpr->getType();
3577 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3578 if (PRE->isExplicitProperty()) {
3579 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3580 SrcType = PDecl->getType();
3582 else if (PRE->isImplicitProperty()) {
3583 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3584 SrcType = Getter->getReturnType();
3589 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3590 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3591 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3593 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3594 castType, SrcType, castExpr);
3598 bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3600 if (!getLangOpts().ObjC1)
3602 ARCConversionTypeClass exprACTC =
3603 classifyTypeForARCConversion(castExpr->getType());
3604 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3605 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3606 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3607 CheckTollFreeBridgeCast(castType, castExpr);
3608 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3609 : CK_CPointerToObjCPointerCast;
3615 bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3616 QualType DestType, QualType SrcType,
3617 ObjCInterfaceDecl *&RelatedClass,
3618 ObjCMethodDecl *&ClassMethod,
3619 ObjCMethodDecl *&InstanceMethod,
3620 TypedefNameDecl *&TDNDecl,
3622 QualType T = CfToNs ? SrcType : DestType;
3623 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3627 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3628 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3629 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3632 NamedDecl *Target = nullptr;
3633 // Check for an existing type with this name.
3634 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3635 Sema::LookupOrdinaryName);
3636 if (!LookupName(R, TUScope)) {
3637 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
3638 << SrcType << DestType;
3639 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3642 Target = R.getFoundDecl();
3643 if (Target && isa<ObjCInterfaceDecl>(Target))
3644 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3646 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3647 << SrcType << DestType;
3648 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3650 Diag(Target->getLocStart(), diag::note_declared_at);
3654 // Check for an existing class method with the given selector name.
3655 if (CfToNs && CMId) {
3656 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3657 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3659 Diag(Loc, diag::err_objc_bridged_related_known_method)
3660 << SrcType << DestType << Sel << false;
3661 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3666 // Check for an existing instance method with the given selector name.
3667 if (!CfToNs && IMId) {
3668 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3669 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3670 if (!InstanceMethod) {
3671 Diag(Loc, diag::err_objc_bridged_related_known_method)
3672 << SrcType << DestType << Sel << true;
3673 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3681 Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
3682 QualType DestType, QualType SrcType,
3684 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3685 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3686 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3687 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3688 if (!CfToNs && !NsToCf)
3691 ObjCInterfaceDecl *RelatedClass;
3692 ObjCMethodDecl *ClassMethod = nullptr;
3693 ObjCMethodDecl *InstanceMethod = nullptr;
3694 TypedefNameDecl *TDNDecl = nullptr;
3695 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3696 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3700 // Implicit conversion from CF to ObjC object is needed.
3702 std::string ExpressionString = "[";
3703 ExpressionString += RelatedClass->getNameAsString();
3704 ExpressionString += " ";
3705 ExpressionString += ClassMethod->getSelector().getAsString();
3706 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3707 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
3708 Diag(Loc, diag::err_objc_bridged_related_known_method)
3709 << SrcType << DestType << ClassMethod->getSelector() << false
3710 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3711 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
3712 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3713 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3715 QualType receiverType =
3716 Context.getObjCInterfaceType(RelatedClass);
3718 Expr *args[] = { SrcExpr };
3719 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3720 ClassMethod->getLocation(),
3721 ClassMethod->getSelector(), ClassMethod,
3722 MultiExprArg(args, 1));
3723 SrcExpr = msg.get();
3728 // Implicit conversion from ObjC type to CF object is needed.
3729 if (InstanceMethod) {
3730 std::string ExpressionString;
3731 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3732 if (InstanceMethod->isPropertyAccessor())
3733 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3734 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3735 ExpressionString = ".";
3736 ExpressionString += PDecl->getNameAsString();
3737 Diag(Loc, diag::err_objc_bridged_related_known_method)
3738 << SrcType << DestType << InstanceMethod->getSelector() << true
3739 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3741 if (ExpressionString.empty()) {
3742 // Provide a fixit: [ObjectExpr InstanceMethod]
3743 ExpressionString = " ";
3744 ExpressionString += InstanceMethod->getSelector().getAsString();
3745 ExpressionString += "]";
3747 Diag(Loc, diag::err_objc_bridged_related_known_method)
3748 << SrcType << DestType << InstanceMethod->getSelector() << true
3749 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3750 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3752 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3753 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3756 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3757 InstanceMethod->getLocation(),
3758 InstanceMethod->getSelector(),
3759 InstanceMethod, None);
3760 SrcExpr = msg.get();
3767 Sema::ARCConversionResult
3768 Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
3769 Expr *&castExpr, CheckedConversionKind CCK,
3770 bool DiagnoseCFAudited,
3771 BinaryOperatorKind Opc) {
3772 QualType castExprType = castExpr->getType();
3774 // For the purposes of the classification, we assume reference types
3775 // will bind to temporaries.
3776 QualType effCastType = castType;
3777 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3778 effCastType = ref->getPointeeType();
3780 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3781 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
3782 if (exprACTC == castACTC) {
3783 // check for viablity and report error if casting an rvalue to a
3784 // life-time qualifier.
3785 if ((castACTC == ACTC_retainable) &&
3786 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
3787 (castType != castExprType)) {
3788 const Type *DT = castType.getTypePtr();
3789 QualType QDT = castType;
3790 // We desugar some types but not others. We ignore those
3791 // that cannot happen in a cast; i.e. auto, and those which
3792 // should not be de-sugared; i.e typedef.
3793 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3794 QDT = PT->desugar();
3795 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3796 QDT = TP->desugar();
3797 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3798 QDT = AT->desugar();
3799 if (QDT != castType &&
3800 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3801 SourceLocation loc =
3802 (castRange.isValid() ? castRange.getBegin()
3803 : castExpr->getExprLoc());
3804 Diag(loc, diag::err_arc_nolifetime_behavior);
3810 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3812 // Allow all of these types to be cast to integer types (but not
3814 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3817 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3818 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3819 // must be explicit.
3820 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3822 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3823 CCK != CCK_ImplicitConversion)
3826 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
3827 // For invalid casts, fall through.
3831 // Do nothing for both bottom and +0.
3836 // If the result is +1, consume it here.
3838 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3839 CK_ARCConsumeObject, castExpr,
3840 nullptr, VK_RValue);
3841 ExprNeedsCleanups = true;
3845 // If this is a non-implicit cast from id or block type to a
3846 // CoreFoundation type, delay complaining in case the cast is used
3847 // in an acceptable context.
3848 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3849 CCK != CCK_ImplicitConversion)
3850 return ACR_unbridged;
3852 // Do not issue bridge cast" diagnostic when implicit casting a cstring
3853 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3855 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3856 ConversionToObjCStringLiteralCheck(castType, castExpr))
3859 // Do not issue "bridge cast" diagnostic when implicit casting
3860 // a retainable object to a CF type parameter belonging to an audited
3861 // CF API function. Let caller issue a normal type mismatched diagnostic
3863 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3864 castACTC != ACTC_coreFoundation)
3865 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
3866 (Opc == BO_NE || Opc == BO_EQ)))
3867 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3868 castExpr, castExpr, exprACTC, CCK);
3872 /// Given that we saw an expression with the ARCUnbridgedCastTy
3873 /// placeholder type, complain bitterly.
3874 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3875 // We expect the spurious ImplicitCastExpr to already have been stripped.
3876 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3877 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3879 SourceRange castRange;
3881 CheckedConversionKind CCK;
3883 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3884 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3885 castType = cast->getTypeAsWritten();
3886 CCK = CCK_CStyleCast;
3887 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3888 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3889 castType = cast->getTypeAsWritten();
3890 CCK = CCK_OtherCast;
3892 castType = cast->getType();
3893 CCK = CCK_ImplicitConversion;
3896 ARCConversionTypeClass castACTC =
3897 classifyTypeForARCConversion(castType.getNonReferenceType());
3899 Expr *castExpr = realCast->getSubExpr();
3900 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3902 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3903 castExpr, realCast, ACTC_retainable, CCK);
3906 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3907 /// type, remove the placeholder cast.
3908 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3909 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3911 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3912 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3913 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3914 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3915 assert(uo->getOpcode() == UO_Extension);
3916 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3917 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3918 sub->getValueKind(), sub->getObjectKind(),
3919 uo->getOperatorLoc());
3920 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3921 assert(!gse->isResultDependent());
3923 unsigned n = gse->getNumAssocs();
3924 SmallVector<Expr*, 4> subExprs(n);
3925 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3926 for (unsigned i = 0; i != n; ++i) {
3927 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3928 Expr *sub = gse->getAssocExpr(i);
3929 if (i == gse->getResultIndex())
3930 sub = stripARCUnbridgedCast(sub);
3934 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3935 gse->getControllingExpr(),
3937 gse->getDefaultLoc(),
3938 gse->getRParenLoc(),
3939 gse->containsUnexpandedParameterPack(),
3940 gse->getResultIndex());
3942 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3943 return cast<ImplicitCastExpr>(e)->getSubExpr();
3947 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3948 QualType exprType) {
3949 QualType canCastType =
3950 Context.getCanonicalType(castType).getUnqualifiedType();
3951 QualType canExprType =
3952 Context.getCanonicalType(exprType).getUnqualifiedType();
3953 if (isa<ObjCObjectPointerType>(canCastType) &&
3954 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3955 canExprType->isObjCObjectPointerType()) {
3956 if (const ObjCObjectPointerType *ObjT =
3957 canExprType->getAs<ObjCObjectPointerType>())
3958 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3959 return !ObjI->isArcWeakrefUnavailable();
3964 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
3965 static Expr *maybeUndoReclaimObject(Expr *e) {
3966 // For now, we just undo operands that are *immediately* reclaim
3967 // expressions, which prevents the vast majority of potential
3968 // problems here. To catch them all, we'd need to rebuild arbitrary
3969 // value-propagating subexpressions --- we can't reliably rebuild
3970 // in-place because of expression sharing.
3971 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3972 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
3973 return ice->getSubExpr();
3978 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3979 ObjCBridgeCastKind Kind,
3980 SourceLocation BridgeKeywordLoc,
3981 TypeSourceInfo *TSInfo,
3983 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3984 if (SubResult.isInvalid()) return ExprError();
3985 SubExpr = SubResult.get();
3987 QualType T = TSInfo->getType();
3988 QualType FromType = SubExpr->getType();
3992 bool MustConsume = false;
3993 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3994 // Okay: we'll build a dependent expression type.
3996 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3998 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3999 : CK_CPointerToObjCPointerCast);
4004 case OBC_BridgeRetained: {
4005 bool br = isKnownName("CFBridgingRelease");
4006 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4009 << (T->isBlockPointerType()? 1 : 0)
4011 << SubExpr->getSourceRange()
4013 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4014 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4015 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
4017 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4018 br ? "CFBridgingRelease "
4019 : "__bridge_transfer ");
4025 case OBC_BridgeTransfer:
4026 // We must consume the Objective-C object produced by the cast.
4030 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4035 // Reclaiming a value that's going to be __bridge-casted to CF
4036 // is very dangerous, so we don't do it.
4037 SubExpr = maybeUndoReclaimObject(SubExpr);
4040 case OBC_BridgeRetained:
4041 // Produce the object before casting it.
4042 SubExpr = ImplicitCastExpr::Create(Context, FromType,
4043 CK_ARCProduceObject,
4044 SubExpr, nullptr, VK_RValue);
4047 case OBC_BridgeTransfer: {
4048 bool br = isKnownName("CFBridgingRetain");
4049 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4050 << (FromType->isBlockPointerType()? 1 : 0)
4054 << SubExpr->getSourceRange()
4057 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4058 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4059 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
4061 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4062 br ? "CFBridgingRetain " : "__bridge_retained");
4069 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4070 << FromType << T << Kind
4071 << SubExpr->getSourceRange()
4072 << TSInfo->getTypeLoc().getSourceRange();
4076 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
4081 ExprNeedsCleanups = true;
4082 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
4083 nullptr, VK_RValue);
4089 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4090 SourceLocation LParenLoc,
4091 ObjCBridgeCastKind Kind,
4092 SourceLocation BridgeKeywordLoc,
4094 SourceLocation RParenLoc,
4096 TypeSourceInfo *TSInfo = nullptr;
4097 QualType T = GetTypeFromParser(Type, &TSInfo);
4098 if (Kind == OBC_Bridge)
4099 CheckTollFreeBridgeCast(T, SubExpr);
4101 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4102 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,