blob: fb91f0b7695bcded1dd6e2078cc974322bde1da6 [file] [log] [blame]
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnera3fc41d2008-01-04 22:32:30 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for Objective-C expressions.
10//
11//===----------------------------------------------------------------------===//
12
John McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Chris Lattnera3fc41d2008-01-04 22:32:30 +000014#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclObjC.h"
Steve Naroff021ca182008-05-29 21:12:08 +000016#include "clang/AST/ExprObjC.h"
John McCall31168b02011-06-15 23:02:42 +000017#include "clang/AST/StmtVisitor.h"
Douglas Gregor0c78ad92010-04-21 19:57:20 +000018#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
20#include "clang/Edit/Commit.h"
21#include "clang/Edit/Rewriters.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000022#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/Initialization.h"
24#include "clang/Sema/Lookup.h"
25#include "clang/Sema/Scope.h"
26#include "clang/Sema/ScopeInfo.h"
27#include "llvm/ADT/SmallString.h"
Akira Hatanaka1488ee42019-03-08 04:45:37 +000028#include "llvm/Support/ConvertUTF.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000029
Chris Lattnera3fc41d2008-01-04 22:32:30 +000030using namespace clang;
John McCall5f2d5562011-02-03 09:00:02 +000031using namespace sema;
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +000032using llvm::makeArrayRef;
Chris Lattnera3fc41d2008-01-04 22:32:30 +000033
John McCallfaf5fb42010-08-26 23:41:50 +000034ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
Craig Topper883dd332015-12-24 23:58:11 +000035 ArrayRef<Expr *> Strings) {
Chris Lattnerd7670d92009-02-18 06:13:04 +000036 // Most ObjC strings are formed out of a single piece. However, we *can*
37 // have strings formed out of multiple @ strings with multiple pptokens in
38 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
39 // StringLiteral for ObjCStringLiteral to hold onto.
Craig Topper883dd332015-12-24 23:58:11 +000040 StringLiteral *S = cast<StringLiteral>(Strings[0]);
Mike Stump11289f42009-09-09 15:08:12 +000041
Chris Lattnerd7670d92009-02-18 06:13:04 +000042 // If we have a multi-part string, merge it all together.
Craig Topper883dd332015-12-24 23:58:11 +000043 if (Strings.size() != 1) {
Chris Lattnera3fc41d2008-01-04 22:32:30 +000044 // Concatenate objc strings.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000045 SmallString<128> StrBuf;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000046 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump11289f42009-09-09 15:08:12 +000047
Craig Topper883dd332015-12-24 23:58:11 +000048 for (Expr *E : Strings) {
49 S = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +000050
Douglas Gregorfb65e592011-07-27 05:40:30 +000051 // ObjC strings can't be wide or UTF.
52 if (!S->isAscii()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000053 Diag(S->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
54 << S->getSourceRange();
Chris Lattnerd7670d92009-02-18 06:13:04 +000055 return true;
56 }
Mike Stump11289f42009-09-09 15:08:12 +000057
Benjamin Kramer35b077e2010-08-17 12:54:38 +000058 // Append the string.
59 StrBuf += S->getString();
Mike Stump11289f42009-09-09 15:08:12 +000060
Chris Lattner163ffd22009-02-18 06:48:40 +000061 // Get the locations of the string tokens.
62 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000063 }
Mike Stump11289f42009-09-09 15:08:12 +000064
Chris Lattner163ffd22009-02-18 06:48:40 +000065 // Create the aggregate string with the appropriate content and location
66 // information.
Benjamin Kramercdac7612014-02-25 12:26:20 +000067 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
68 assert(CAT && "String literal not of constant array type!");
69 QualType StrTy = Context.getConstantArrayType(
70 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
71 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
72 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
73 /*Pascal=*/false, StrTy, &StrLocs[0],
74 StrLocs.size());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000075 }
Fangrui Song6907ce22018-07-30 19:24:48 +000076
Ted Kremeneke65b0862012-03-06 20:05:56 +000077 return BuildObjCStringLiteral(AtLocs[0], S);
78}
Mike Stump11289f42009-09-09 15:08:12 +000079
Ted Kremeneke65b0862012-03-06 20:05:56 +000080ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner6436fb62009-02-18 06:01:06 +000081 // Verify that this composite string is acceptable for ObjC strings.
82 if (CheckObjCString(S))
Chris Lattnera3fc41d2008-01-04 22:32:30 +000083 return true;
Chris Lattnerfffd6a72009-02-18 06:06:56 +000084
85 // Initialize the constant string interface lazily. This assumes
Steve Naroff54e59452009-04-07 14:18:33 +000086 // the NSString interface is seen in this translation unit. Note: We
87 // don't use NSConstantString, since the runtime team considers this
88 // interface private (even though it appears in the header files).
Chris Lattnerfffd6a72009-02-18 06:06:56 +000089 QualType Ty = Context.getObjCConstantStringInterface();
90 if (!Ty.isNull()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +000091 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikiebbafb8a2012-03-11 07:00:24 +000092 } else if (getLangOpts().NoConstantCFStrings) {
Craig Topperc3ec1492014-05-26 06:22:03 +000093 IdentifierInfo *NSIdent=nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +000094 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fangrui Song6907ce22018-07-30 19:24:48 +000095
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000096 if (StringClass.empty())
97 NSIdent = &Context.Idents.get("NSConstantString");
98 else
99 NSIdent = &Context.Idents.get(StringClass);
Fangrui Song6907ce22018-07-30 19:24:48 +0000100
Ted Kremeneke65b0862012-03-06 20:05:56 +0000101 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian07317632010-04-23 23:19:04 +0000102 LookupOrdinaryName);
103 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
104 Context.setObjCConstantStringInterface(StrIF);
105 Ty = Context.getObjCConstantStringInterface();
106 Ty = Context.getObjCObjectPointerType(Ty);
107 } else {
108 // If there is no NSConstantString interface defined then treat this
109 // as error and recover from it.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000110 Diag(S->getBeginLoc(), diag::err_no_nsconstant_string_class)
111 << NSIdent << S->getSourceRange();
Fariborz Jahanian07317632010-04-23 23:19:04 +0000112 Ty = Context.getObjCIdType();
113 }
Chris Lattner091f6982008-06-21 21:44:18 +0000114 } else {
Patrick Beard0caa3942012-04-19 00:25:12 +0000115 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000116 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000117 LookupOrdinaryName);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000118 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
119 Context.setObjCConstantStringInterface(StrIF);
120 Ty = Context.getObjCConstantStringInterface();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000121 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000122 } else {
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000123 // If there is no NSString interface defined, implicitly declare
124 // a @class NSString; and use that instead. This is to make sure
125 // type of an NSString literal is represented correctly, instead of
126 // being an 'id' type.
127 Ty = Context.getObjCNSStringType();
128 if (Ty.isNull()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000129 ObjCInterfaceDecl *NSStringIDecl =
130 ObjCInterfaceDecl::Create (Context,
131 Context.getTranslationUnitDecl(),
132 SourceLocation(), NSIdent,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000133 nullptr, nullptr, SourceLocation());
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000134 Ty = Context.getObjCInterfaceType(NSStringIDecl);
135 Context.setObjCNSStringType(Ty);
136 }
137 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000138 }
Chris Lattner091f6982008-06-21 21:44:18 +0000139 }
Mike Stump11289f42009-09-09 15:08:12 +0000140
Ted Kremeneke65b0862012-03-06 20:05:56 +0000141 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
142}
143
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000144/// Emits an error if the given method does not exist, or if the return
Jordy Rose08e500c2012-05-12 17:32:44 +0000145/// type is not an Objective-C object.
146static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
147 const ObjCInterfaceDecl *Class,
148 Selector Sel, const ObjCMethodDecl *Method) {
149 if (!Method) {
150 // FIXME: Is there a better way to avoid quotes than using getName()?
151 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
152 return false;
153 }
154
155 // Make sure the return type is reasonable.
Alp Toker314cc812014-01-25 16:55:45 +0000156 QualType ReturnType = Method->getReturnType();
Jordy Rose08e500c2012-05-12 17:32:44 +0000157 if (!ReturnType->isObjCObjectPointerType()) {
158 S.Diag(Loc, diag::err_objc_literal_method_sig)
159 << Sel;
160 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
161 << ReturnType;
162 return false;
163 }
164
165 return true;
166}
167
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000168/// Maps ObjCLiteralKind to NSClassIdKindKind
Alex Denisovb7d85632015-07-24 05:09:40 +0000169static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(
170 Sema::ObjCLiteralKind LiteralKind) {
171 switch (LiteralKind) {
172 case Sema::LK_Array:
173 return NSAPI::ClassId_NSArray;
174 case Sema::LK_Dictionary:
175 return NSAPI::ClassId_NSDictionary;
176 case Sema::LK_Numeric:
177 return NSAPI::ClassId_NSNumber;
178 case Sema::LK_String:
179 return NSAPI::ClassId_NSString;
180 case Sema::LK_Boxed:
181 return NSAPI::ClassId_NSValue;
182
183 // there is no corresponding matching
184 // between LK_None/LK_Block and NSClassIdKindKind
185 case Sema::LK_Block:
186 case Sema::LK_None:
Aaron Ballman3e839de2015-07-24 12:47:27 +0000187 break;
Alex Denisovb7d85632015-07-24 05:09:40 +0000188 }
Aaron Ballman3e839de2015-07-24 12:47:27 +0000189 llvm_unreachable("LiteralKind can't be converted into a ClassKind");
Alex Denisovb7d85632015-07-24 05:09:40 +0000190}
191
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000192/// Validates ObjCInterfaceDecl availability.
Alex Denisovb7d85632015-07-24 05:09:40 +0000193/// ObjCInterfaceDecl, used to create ObjC literals, should be defined
194/// if clang not in a debugger mode.
195static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl,
196 SourceLocation Loc,
197 Sema::ObjCLiteralKind LiteralKind) {
198 if (!Decl) {
199 NSAPI::NSClassIdKindKind Kind = ClassKindFromLiteralKind(LiteralKind);
200 IdentifierInfo *II = S.NSAPIObj->getNSClassId(Kind);
201 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
202 << II->getName() << LiteralKind;
203 return false;
204 } else if (!Decl->hasDefinition() && !S.getLangOpts().DebuggerObjCLiteral) {
205 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
206 << Decl->getName() << LiteralKind;
207 S.Diag(Decl->getLocation(), diag::note_forward_class);
208 return false;
209 }
210
211 return true;
212}
213
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000214/// Looks up ObjCInterfaceDecl of a given NSClassIdKindKind.
Alex Denisovb7d85632015-07-24 05:09:40 +0000215/// Used to create ObjC literals, such as NSDictionary (@{}),
216/// NSArray (@[]) and Boxed Expressions (@())
217static ObjCInterfaceDecl *LookupObjCInterfaceDeclForLiteral(Sema &S,
218 SourceLocation Loc,
219 Sema::ObjCLiteralKind LiteralKind) {
220 NSAPI::NSClassIdKindKind ClassKind = ClassKindFromLiteralKind(LiteralKind);
221 IdentifierInfo *II = S.NSAPIObj->getNSClassId(ClassKind);
222 NamedDecl *IF = S.LookupSingleName(S.TUScope, II, Loc,
223 Sema::LookupOrdinaryName);
224 ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
225 if (!ID && S.getLangOpts().DebuggerObjCLiteral) {
226 ASTContext &Context = S.Context;
227 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
228 ID = ObjCInterfaceDecl::Create (Context, TU, SourceLocation(), II,
229 nullptr, nullptr, SourceLocation());
230 }
231
232 if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) {
233 ID = nullptr;
234 }
235
236 return ID;
237}
238
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000239/// Retrieve the NSNumber factory method that should be used to create
Ted Kremeneke65b0862012-03-06 20:05:56 +0000240/// an Objective-C literal for the given type.
241static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beard0caa3942012-04-19 00:25:12 +0000242 QualType NumberType,
243 bool isLiteral = false,
244 SourceRange R = SourceRange()) {
David Blaikie05785d12013-02-20 22:23:23 +0000245 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
246 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
247
Ted Kremeneke65b0862012-03-06 20:05:56 +0000248 if (!Kind) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000249 if (isLiteral) {
250 S.Diag(Loc, diag::err_invalid_nsnumber_type)
251 << NumberType << R;
252 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000253 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000254 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000255
Ted Kremeneke65b0862012-03-06 20:05:56 +0000256 // If we already looked up this method, we're done.
257 if (S.NSNumberLiteralMethods[*Kind])
258 return S.NSNumberLiteralMethods[*Kind];
Fangrui Song6907ce22018-07-30 19:24:48 +0000259
Ted Kremeneke65b0862012-03-06 20:05:56 +0000260 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
261 /*Instance=*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +0000262
Patrick Beard0caa3942012-04-19 00:25:12 +0000263 ASTContext &CX = S.Context;
Fangrui Song6907ce22018-07-30 19:24:48 +0000264
Patrick Beard0caa3942012-04-19 00:25:12 +0000265 // Look up the NSNumber class, if we haven't done so already. It's cached
266 // in the Sema instance.
267 if (!S.NSNumberDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000268 S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc,
269 Sema::LK_Numeric);
Patrick Beard0caa3942012-04-19 00:25:12 +0000270 if (!S.NSNumberDecl) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000271 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000272 }
Alex Denisove36748a2015-02-16 16:17:05 +0000273 }
274
275 if (S.NSNumberPointer.isNull()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000276 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000277 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
278 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000279 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000280
Ted Kremeneke65b0862012-03-06 20:05:56 +0000281 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000282 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000283 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000284 // create a stub definition this NSNumber factory method.
Craig Topperc3ec1492014-05-26 06:22:03 +0000285 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000286 Method =
287 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
288 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
289 /*isInstance=*/false, /*isVariadic=*/false,
290 /*isPropertyAccessor=*/false,
291 /*isImplicitlyDeclared=*/true,
292 /*isDefined=*/false, ObjCMethodDecl::Required,
293 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000294 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
295 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000296 &CX.Idents.get("value"),
Craig Topperc3ec1492014-05-26 06:22:03 +0000297 NumberType, /*TInfo=*/nullptr,
298 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000299 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000300 }
301
Jordy Rose08e500c2012-05-12 17:32:44 +0000302 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Craig Topperc3ec1492014-05-26 06:22:03 +0000303 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000304
305 // Note: if the parameter type is out-of-line, we'll catch it later in the
306 // implicit conversion.
Fangrui Song6907ce22018-07-30 19:24:48 +0000307
Ted Kremeneke65b0862012-03-06 20:05:56 +0000308 S.NSNumberLiteralMethods[*Kind] = Method;
309 return Method;
310}
311
Patrick Beard0caa3942012-04-19 00:25:12 +0000312/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
313/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000314ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000315 // Determine the type of the literal.
316 QualType NumberType = Number->getType();
317 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
318 // In C, character literals have type 'int'. That's not the type we want
319 // to use to determine the Objective-c literal kind.
320 switch (Char->getKind()) {
321 case CharacterLiteral::Ascii:
Aaron Ballman9a17c852016-01-07 20:59:26 +0000322 case CharacterLiteral::UTF8:
Ted Kremeneke65b0862012-03-06 20:05:56 +0000323 NumberType = Context.CharTy;
324 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000325
Ted Kremeneke65b0862012-03-06 20:05:56 +0000326 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000327 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000328 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000329
Ted Kremeneke65b0862012-03-06 20:05:56 +0000330 case CharacterLiteral::UTF16:
331 NumberType = Context.Char16Ty;
332 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000333
Ted Kremeneke65b0862012-03-06 20:05:56 +0000334 case CharacterLiteral::UTF32:
335 NumberType = Context.Char32Ty;
336 break;
337 }
338 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000339
Ted Kremeneke65b0862012-03-06 20:05:56 +0000340 // Look for the appropriate method within NSNumber.
341 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000342 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000343 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000344 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000345 if (!Method)
346 return ExprError();
347
348 // Convert the number to the type that the parameter expects.
Alp Toker03376dc2014-07-07 09:02:20 +0000349 ParmVarDecl *ParamDecl = Method->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000350 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
351 ParamDecl);
352 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
353 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000354 Number);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000355 if (ConvertedNumber.isInvalid())
356 return ExprError();
357 Number = ConvertedNumber.get();
Fangrui Song6907ce22018-07-30 19:24:48 +0000358
Patrick Beard2565c592012-05-01 21:47:19 +0000359 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000360 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000361 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
362 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000363}
364
Fangrui Song6907ce22018-07-30 19:24:48 +0000365ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000366 SourceLocation ValueLoc,
367 bool Value) {
368 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000369 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000370 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
371 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +0000372 // C doesn't actually have a way to represent literal values of type
Ted Kremeneke65b0862012-03-06 20:05:56 +0000373 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
374 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
Fangrui Song6907ce22018-07-30 19:24:48 +0000375 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000376 CK_IntegralToBoolean);
377 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000378
Ted Kremeneke65b0862012-03-06 20:05:56 +0000379 return BuildObjCNumericLiteral(AtLoc, Inner.get());
380}
381
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000382/// Check that the given expression is a valid element of an Objective-C
Ted Kremeneke65b0862012-03-06 20:05:56 +0000383/// collection literal.
Fangrui Song6907ce22018-07-30 19:24:48 +0000384static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000385 QualType T,
386 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000387 // If the expression is type-dependent, there's nothing for us to do.
388 if (Element->isTypeDependent())
389 return Element;
390
391 ExprResult Result = S.CheckPlaceholderExpr(Element);
392 if (Result.isInvalid())
393 return ExprError();
394 Element = Result.get();
395
Fangrui Song6907ce22018-07-30 19:24:48 +0000396 // In C++, check for an implicit conversion to an Objective-C object pointer
Ted Kremeneke65b0862012-03-06 20:05:56 +0000397 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000398 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000399 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000400 = InitializedEntity::InitializeParameter(S.Context, T,
401 /*Consumed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000402 InitializationKind Kind = InitializationKind::CreateCopy(
403 Element->getBeginLoc(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000404 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000405 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000406 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000407 }
408
409 Expr *OrigElement = Element;
410
411 // Perform lvalue-to-rvalue conversion.
412 Result = S.DefaultLvalueConversion(Element);
413 if (Result.isInvalid())
414 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +0000415 Element = Result.get();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000416
417 // Make sure that we have an Objective-C pointer type or block.
418 if (!Element->getType()->isObjCObjectPointerType() &&
419 !Element->getType()->isBlockPointerType()) {
420 bool Recovered = false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000421
Ted Kremeneke65b0862012-03-06 20:05:56 +0000422 // If this is potentially an Objective-C numeric literal, add the '@'.
Fangrui Song6907ce22018-07-30 19:24:48 +0000423 if (isa<IntegerLiteral>(OrigElement) ||
Ted Kremeneke65b0862012-03-06 20:05:56 +0000424 isa<CharacterLiteral>(OrigElement) ||
425 isa<FloatingLiteral>(OrigElement) ||
426 isa<ObjCBoolLiteralExpr>(OrigElement) ||
427 isa<CXXBoolLiteralExpr>(OrigElement)) {
428 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
429 int Which = isa<CharacterLiteral>(OrigElement) ? 1
430 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
431 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
432 : 3;
Fangrui Song6907ce22018-07-30 19:24:48 +0000433
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000434 S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
435 << Which << OrigElement->getSourceRange()
436 << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
Fangrui Song6907ce22018-07-30 19:24:48 +0000437
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000438 Result =
439 S.BuildObjCNumericLiteral(OrigElement->getBeginLoc(), OrigElement);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000440 if (Result.isInvalid())
441 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +0000442
Ted Kremeneke65b0862012-03-06 20:05:56 +0000443 Element = Result.get();
444 Recovered = true;
445 }
446 }
447 // If this is potentially an Objective-C string literal, add the '@'.
448 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
449 if (String->isAscii()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000450 S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
451 << 0 << OrigElement->getSourceRange()
452 << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
Ted Kremeneke65b0862012-03-06 20:05:56 +0000453
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000454 Result = S.BuildObjCStringLiteral(OrigElement->getBeginLoc(), String);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000455 if (Result.isInvalid())
456 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +0000457
Ted Kremeneke65b0862012-03-06 20:05:56 +0000458 Element = Result.get();
459 Recovered = true;
460 }
461 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000462
Ted Kremeneke65b0862012-03-06 20:05:56 +0000463 if (!Recovered) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000464 S.Diag(Element->getBeginLoc(), diag::err_invalid_collection_element)
465 << Element->getType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000466 return ExprError();
467 }
468 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000469 if (ArrayLiteral)
Ted Kremenek197fee42013-10-09 22:34:33 +0000470 if (ObjCStringLiteral *getString =
471 dyn_cast<ObjCStringLiteral>(OrigElement)) {
472 if (StringLiteral *SL = getString->getString()) {
473 unsigned numConcat = SL->getNumConcatenated();
474 if (numConcat > 1) {
475 // Only warn if the concatenated string doesn't come from a macro.
476 bool hasMacro = false;
477 for (unsigned i = 0; i < numConcat ; ++i)
478 if (SL->getStrTokenLoc(i).isMacroID()) {
479 hasMacro = true;
480 break;
481 }
482 if (!hasMacro)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000483 S.Diag(Element->getBeginLoc(),
Ted Kremenek197fee42013-10-09 22:34:33 +0000484 diag::warn_concatenated_nsarray_literal)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000485 << Element->getType();
Ted Kremenek197fee42013-10-09 22:34:33 +0000486 }
487 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000488 }
489
Fangrui Song6907ce22018-07-30 19:24:48 +0000490 // Make sure that the element has the type that the container factory
491 // function expects.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000492 return S.PerformCopyInitialization(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000493 InitializedEntity::InitializeParameter(S.Context, T,
494 /*Consumed=*/false),
495 Element->getBeginLoc(), Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000496}
497
Patrick Beard0caa3942012-04-19 00:25:12 +0000498ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
499 if (ValueExpr->isTypeDependent()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000500 ObjCBoxedExpr *BoxedExpr =
Craig Topperc3ec1492014-05-26 06:22:03 +0000501 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000502 return BoxedExpr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000503 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000504 ObjCMethodDecl *BoxingMethod = nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000505 QualType BoxedType;
506 // Convert the expression to an RValue, so we can check for pointer types...
507 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
508 if (RValue.isInvalid()) {
509 return ExprError();
510 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000511 SourceLocation Loc = SR.getBegin();
Patrick Beard0caa3942012-04-19 00:25:12 +0000512 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000513 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000514 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
515 QualType PointeeType = PT->getPointeeType();
516 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
517
518 if (!NSStringDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000519 NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
520 Sema::LK_String);
Patrick Beard0caa3942012-04-19 00:25:12 +0000521 if (!NSStringDecl) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000522 return ExprError();
523 }
Jordy Roseaca01f92012-05-12 17:32:52 +0000524 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
525 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000526 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000527
Akira Hatanaka1488ee42019-03-08 04:45:37 +0000528 // The boxed expression can be emitted as a compile time constant if it is
529 // a string literal whose character encoding is compatible with UTF-8.
530 if (auto *CE = dyn_cast<ImplicitCastExpr>(ValueExpr))
531 if (CE->getCastKind() == CK_ArrayToPointerDecay)
532 if (auto *SL =
533 dyn_cast<StringLiteral>(CE->getSubExpr()->IgnoreParens())) {
534 assert((SL->isAscii() || SL->isUTF8()) &&
535 "unexpected character encoding");
536 StringRef Str = SL->getString();
537 const llvm::UTF8 *StrBegin = Str.bytes_begin();
538 const llvm::UTF8 *StrEnd = Str.bytes_end();
539 // Check that this is a valid UTF-8 string.
540 if (llvm::isLegalUTF8String(&StrBegin, StrEnd)) {
541 BoxedType = Context.getAttributedType(
542 AttributedType::getNullabilityAttrKind(
543 NullabilityKind::NonNull),
544 NSStringPointer, NSStringPointer);
545 return new (Context) ObjCBoxedExpr(CE, BoxedType, nullptr, SR);
546 }
547
548 Diag(SL->getBeginLoc(), diag::warn_objc_boxing_invalid_utf8_string)
549 << NSStringPointer << SL->getSourceRange();
550 }
551
Patrick Beard0caa3942012-04-19 00:25:12 +0000552 if (!StringWithUTF8StringMethod) {
553 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
554 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
555
556 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000557 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
558 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000559 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000560 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000561 ObjCMethodDecl *M = ObjCMethodDecl::Create(
562 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
563 NSStringPointer, ReturnTInfo, NSStringDecl,
564 /*isInstance=*/false, /*isVariadic=*/false,
565 /*isPropertyAccessor=*/false,
566 /*isImplicitlyDeclared=*/true,
567 /*isDefined=*/false, ObjCMethodDecl::Required,
568 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000569 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000570 ParmVarDecl *value =
571 ParmVarDecl::Create(Context, M,
572 SourceLocation(), SourceLocation(),
573 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000574 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000575 /*TInfo=*/nullptr,
576 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000577 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000578 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000579 }
Jordy Rose890f4572012-05-12 15:53:41 +0000580
Alex Denisovb7d85632015-07-24 05:09:40 +0000581 if (!validateBoxingMethod(*this, Loc, NSStringDecl,
Jordy Rose08e500c2012-05-12 17:32:44 +0000582 stringWithUTF8String, BoxingMethod))
583 return ExprError();
584
585 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000586 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000587
Patrick Beard0caa3942012-04-19 00:25:12 +0000588 BoxingMethod = StringWithUTF8StringMethod;
589 BoxedType = NSStringPointer;
Alex Lorenz49370ac2017-11-08 21:33:15 +0000590 // Transfer the nullability from method's return type.
591 Optional<NullabilityKind> Nullability =
592 BoxingMethod->getReturnType()->getNullability(Context);
593 if (Nullability)
594 BoxedType = Context.getAttributedType(
595 AttributedType::getNullabilityAttrKind(*Nullability), BoxedType,
596 BoxedType);
Patrick Beard0caa3942012-04-19 00:25:12 +0000597 }
Patrick Beard2565c592012-05-01 21:47:19 +0000598 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000599 // The other types we support are numeric, char and BOOL/bool. We could also
600 // provide limited support for structure types, such as NSRange, NSRect, and
601 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
602 // for more details.
603
604 // Check for a top-level character literal.
605 if (const CharacterLiteral *Char =
606 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
607 // In C, character literals have type 'int'. That's not the type we want
608 // to use to determine the Objective-c literal kind.
609 switch (Char->getKind()) {
610 case CharacterLiteral::Ascii:
Aaron Ballman9a17c852016-01-07 20:59:26 +0000611 case CharacterLiteral::UTF8:
Patrick Beard0caa3942012-04-19 00:25:12 +0000612 ValueType = Context.CharTy;
613 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000614
Patrick Beard0caa3942012-04-19 00:25:12 +0000615 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000616 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000617 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000618
Patrick Beard0caa3942012-04-19 00:25:12 +0000619 case CharacterLiteral::UTF16:
620 ValueType = Context.Char16Ty;
621 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000622
Patrick Beard0caa3942012-04-19 00:25:12 +0000623 case CharacterLiteral::UTF32:
624 ValueType = Context.Char32Ty;
625 break;
626 }
627 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000628 // FIXME: Do I need to do anything special with BoolTy expressions?
Fangrui Song6907ce22018-07-30 19:24:48 +0000629
Patrick Beard0caa3942012-04-19 00:25:12 +0000630 // Look for the appropriate method within NSNumber.
Alex Denisovb7d85632015-07-24 05:09:40 +0000631 BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
Patrick Beard0caa3942012-04-19 00:25:12 +0000632 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000633 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
634 if (!ET->getDecl()->isComplete()) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000635 Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000636 << ValueType << ValueExpr->getSourceRange();
637 return ExprError();
638 }
639
Alex Denisovb7d85632015-07-24 05:09:40 +0000640 BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000641 ET->getDecl()->getIntegerType());
642 BoxedType = NSNumberPointer;
Alex Denisovfde64952015-06-26 05:28:36 +0000643 } else if (ValueType->isObjCBoxableRecordType()) {
644 // Support for structure types, that marked as objc_boxable
645 // struct __attribute__((objc_boxable)) s { ... };
Fangrui Song6907ce22018-07-30 19:24:48 +0000646
Alex Denisovfde64952015-06-26 05:28:36 +0000647 // Look up the NSValue class, if we haven't done so already. It's cached
648 // in the Sema instance.
649 if (!NSValueDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000650 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
651 Sema::LK_Boxed);
Alex Denisovfde64952015-06-26 05:28:36 +0000652 if (!NSValueDecl) {
Alex Denisovfde64952015-06-26 05:28:36 +0000653 return ExprError();
654 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000655
Alex Denisovfde64952015-06-26 05:28:36 +0000656 // generate the pointer to NSValue type.
657 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
658 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
659 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000660
Alex Denisovfde64952015-06-26 05:28:36 +0000661 if (!ValueWithBytesObjCTypeMethod) {
662 IdentifierInfo *II[] = {
663 &Context.Idents.get("valueWithBytes"),
664 &Context.Idents.get("objCType")
665 };
666 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
Fangrui Song6907ce22018-07-30 19:24:48 +0000667
Alex Denisovfde64952015-06-26 05:28:36 +0000668 // Look for the appropriate method within NSValue.
669 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
670 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
671 // Debugger needs to work even if NSValue hasn't been defined.
672 TypeSourceInfo *ReturnTInfo = nullptr;
673 ObjCMethodDecl *M = ObjCMethodDecl::Create(
674 Context,
675 SourceLocation(),
676 SourceLocation(),
677 ValueWithBytesObjCType,
678 NSValuePointer,
679 ReturnTInfo,
680 NSValueDecl,
681 /*isInstance=*/false,
682 /*isVariadic=*/false,
683 /*isPropertyAccessor=*/false,
684 /*isImplicitlyDeclared=*/true,
685 /*isDefined=*/false,
686 ObjCMethodDecl::Required,
687 /*HasRelatedResultType=*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +0000688
Alex Denisovfde64952015-06-26 05:28:36 +0000689 SmallVector<ParmVarDecl *, 2> Params;
Fangrui Song6907ce22018-07-30 19:24:48 +0000690
Alex Denisovfde64952015-06-26 05:28:36 +0000691 ParmVarDecl *bytes =
692 ParmVarDecl::Create(Context, M,
693 SourceLocation(), SourceLocation(),
694 &Context.Idents.get("bytes"),
695 Context.VoidPtrTy.withConst(),
696 /*TInfo=*/nullptr,
697 SC_None, nullptr);
698 Params.push_back(bytes);
Fangrui Song6907ce22018-07-30 19:24:48 +0000699
Alex Denisovfde64952015-06-26 05:28:36 +0000700 QualType ConstCharType = Context.CharTy.withConst();
701 ParmVarDecl *type =
702 ParmVarDecl::Create(Context, M,
703 SourceLocation(), SourceLocation(),
704 &Context.Idents.get("type"),
705 Context.getPointerType(ConstCharType),
706 /*TInfo=*/nullptr,
707 SC_None, nullptr);
708 Params.push_back(type);
Fangrui Song6907ce22018-07-30 19:24:48 +0000709
Alex Denisovfde64952015-06-26 05:28:36 +0000710 M->setMethodParams(Context, Params, None);
711 BoxingMethod = M;
712 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000713
Alex Denisovb7d85632015-07-24 05:09:40 +0000714 if (!validateBoxingMethod(*this, Loc, NSValueDecl,
Alex Denisovfde64952015-06-26 05:28:36 +0000715 ValueWithBytesObjCType, BoxingMethod))
716 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +0000717
Alex Denisovfde64952015-06-26 05:28:36 +0000718 ValueWithBytesObjCTypeMethod = BoxingMethod;
719 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000720
Alex Denisovfde64952015-06-26 05:28:36 +0000721 if (!ValueType.isTriviallyCopyableType(Context)) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000722 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
Alex Denisovfde64952015-06-26 05:28:36 +0000723 << ValueType << ValueExpr->getSourceRange();
724 return ExprError();
725 }
726
727 BoxingMethod = ValueWithBytesObjCTypeMethod;
728 BoxedType = NSValuePointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000729 }
730
731 if (!BoxingMethod) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000732 Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
Patrick Beard0caa3942012-04-19 00:25:12 +0000733 << ValueType << ValueExpr->getSourceRange();
734 return ExprError();
735 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000736
Alex Denisovb7d85632015-07-24 05:09:40 +0000737 DiagnoseUseOfDecl(BoxingMethod, Loc);
Alex Denisovfde64952015-06-26 05:28:36 +0000738
739 ExprResult ConvertedValueExpr;
740 if (ValueType->isObjCBoxableRecordType()) {
741 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
Fangrui Song6907ce22018-07-30 19:24:48 +0000742 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
Alex Denisovfde64952015-06-26 05:28:36 +0000743 ValueExpr);
744 } else {
745 // Convert the expression to the type that the parameter requires.
746 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
747 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
748 ParamDecl);
749 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
750 ValueExpr);
751 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000752
Patrick Beard0caa3942012-04-19 00:25:12 +0000753 if (ConvertedValueExpr.isInvalid())
754 return ExprError();
755 ValueExpr = ConvertedValueExpr.get();
Fangrui Song6907ce22018-07-30 19:24:48 +0000756
757 ObjCBoxedExpr *BoxedExpr =
Patrick Beard0caa3942012-04-19 00:25:12 +0000758 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
759 BoxingMethod, SR);
760 return MaybeBindToTemporary(BoxedExpr);
761}
762
John McCallf2538342012-07-31 05:14:30 +0000763/// Build an ObjC subscript pseudo-object expression, given that
764/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000765ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
766 Expr *IndexExpr,
767 ObjCMethodDecl *getterMethod,
768 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000769 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000770
John McCallf2538342012-07-31 05:14:30 +0000771 // We can't get dependent types here; our callers should have
772 // filtered them out.
773 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
774 "base or index cannot have dependent type here");
775
776 // Filter out placeholders in the index. In theory, overloads could
777 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000778 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
779 if (Result.isInvalid())
780 return ExprError();
781 IndexExpr = Result.get();
Fangrui Song6907ce22018-07-30 19:24:48 +0000782
John McCallf2538342012-07-31 05:14:30 +0000783 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000784 Result = DefaultLvalueConversion(BaseExpr);
785 if (Result.isInvalid())
786 return ExprError();
787 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000788
789 // Build the pseudo-object expression.
James Y Knight6c2f06b2015-12-31 04:43:19 +0000790 return new (Context) ObjCSubscriptRefExpr(
791 BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
792 getterMethod, setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000793}
794
795ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000796 SourceLocation Loc = SR.getBegin();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000797
Alex Denisovb7d85632015-07-24 05:09:40 +0000798 if (!NSArrayDecl) {
799 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
800 Sema::LK_Array);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000801 if (!NSArrayDecl) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000802 return ExprError();
803 }
804 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000805
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000806 // Find the arrayWithObjects:count: method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000807 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000808 if (!ArrayWithObjectsMethod) {
809 Selector
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000810 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
811 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000812 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000813 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000814 Method = ObjCMethodDecl::Create(
815 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000816 Context.getTranslationUnitDecl(), false /*Instance*/,
Alp Toker314cc812014-01-25 16:55:45 +0000817 false /*isVariadic*/,
818 /*isPropertyAccessor=*/false,
819 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
820 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000821 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000822 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000823 SourceLocation(),
824 SourceLocation(),
825 &Context.Idents.get("objects"),
826 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000827 /*TInfo=*/nullptr,
828 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000829 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000830 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000831 SourceLocation(),
832 SourceLocation(),
833 &Context.Idents.get("cnt"),
834 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000835 /*TInfo=*/nullptr, SC_None,
836 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000837 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000838 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000839 }
840
Alex Denisovb7d85632015-07-24 05:09:40 +0000841 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000842 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000843
Jordy Rose4af44872012-05-12 17:32:56 +0000844 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000845 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000846 const PointerType *PtrT = T->getAs<PointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +0000847 if (!PtrT ||
Jordy Rose4af44872012-05-12 17:32:56 +0000848 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
849 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
850 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000851 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000852 diag::note_objc_literal_method_param)
Fangrui Song6907ce22018-07-30 19:24:48 +0000853 << 0 << T
Jordy Rose4af44872012-05-12 17:32:56 +0000854 << Context.getPointerType(IdT.withConst());
855 return ExprError();
856 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000857
Jordy Rose4af44872012-05-12 17:32:56 +0000858 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000859 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000860 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
861 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000862 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000863 diag::note_objc_literal_method_param)
Fangrui Song6907ce22018-07-30 19:24:48 +0000864 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000865 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000866 << "integral";
867 return ExprError();
868 }
869
870 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000871 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000872 }
873
Alp Toker03376dc2014-07-07 09:02:20 +0000874 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000875 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000876
877 // Check that each of the elements provided is valid in a collection literal,
878 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000879 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000880 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
881 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
882 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000883 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000884 if (Converted.isInvalid())
885 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +0000886
Ted Kremeneke65b0862012-03-06 20:05:56 +0000887 ElementsBuffer[I] = Converted.get();
888 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000889
890 QualType Ty
Ted Kremeneke65b0862012-03-06 20:05:56 +0000891 = Context.getObjCObjectPointerType(
892 Context.getObjCInterfaceType(NSArrayDecl));
893
894 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000895 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000896 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000897}
898
Craig Topperd4336e02015-12-24 23:58:15 +0000899ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
900 MutableArrayRef<ObjCDictionaryElement> Elements) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000901 SourceLocation Loc = SR.getBegin();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000902
Alex Denisovb7d85632015-07-24 05:09:40 +0000903 if (!NSDictionaryDecl) {
904 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
905 Sema::LK_Dictionary);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000906 if (!NSDictionaryDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000907 return ExprError();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000908 }
909 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000910
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000911 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
912 // so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000913 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000914 if (!DictionaryWithObjectsMethod) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000915 Selector Sel = NSAPIObj->getNSDictionarySelector(
916 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
917 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000918 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000919 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000920 SourceLocation(), SourceLocation(), Sel,
921 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000922 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000923 Context.getTranslationUnitDecl(),
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000924 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000925 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000926 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
927 ObjCMethodDecl::Required,
928 false);
929 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000930 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000931 SourceLocation(),
932 SourceLocation(),
933 &Context.Idents.get("objects"),
934 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000935 /*TInfo=*/nullptr, SC_None,
936 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000937 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000938 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000939 SourceLocation(),
940 SourceLocation(),
941 &Context.Idents.get("keys"),
942 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000943 /*TInfo=*/nullptr, SC_None,
944 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000945 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000946 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000947 SourceLocation(),
948 SourceLocation(),
949 &Context.Idents.get("cnt"),
950 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000951 /*TInfo=*/nullptr, SC_None,
952 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000953 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000954 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000955 }
956
Jordy Rose08e500c2012-05-12 17:32:44 +0000957 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
958 Method))
959 return ExprError();
960
Jordy Rose4af44872012-05-12 17:32:56 +0000961 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000962 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000963 const PointerType *PtrValue = ValueT->getAs<PointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +0000964 if (!PtrValue ||
Jordy Rose4af44872012-05-12 17:32:56 +0000965 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000966 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000967 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000968 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000969 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000970 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000971 << Context.getPointerType(IdT.withConst());
972 return ExprError();
973 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000974
Jordy Rose4af44872012-05-12 17:32:56 +0000975 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000976 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000977 const PointerType *PtrKey = KeyT->getAs<PointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +0000978 if (!PtrKey ||
Jordy Rose4af44872012-05-12 17:32:56 +0000979 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
980 IdT)) {
981 bool err = true;
982 if (PtrKey) {
983 if (QIDNSCopying.isNull()) {
984 // key argument of selector is id<NSCopying>?
985 if (ObjCProtocolDecl *NSCopyingPDecl =
986 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
987 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
Fangrui Song6907ce22018-07-30 19:24:48 +0000988 QIDNSCopying =
Douglas Gregore9d95f12015-07-07 03:57:35 +0000989 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
990 llvm::makeArrayRef(
991 (ObjCProtocolDecl**) PQ,
Douglas Gregorab209d82015-07-07 03:58:42 +0000992 1),
993 false);
Jordy Rose4af44872012-05-12 17:32:56 +0000994 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
995 }
996 }
997 if (!QIDNSCopying.isNull())
998 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
999 QIDNSCopying);
1000 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001001
Jordy Rose4af44872012-05-12 17:32:56 +00001002 if (err) {
1003 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
1004 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +00001005 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +00001006 diag::note_objc_literal_method_param)
1007 << 1 << KeyT
1008 << Context.getPointerType(IdT.withConst());
1009 return ExprError();
1010 }
1011 }
1012
1013 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +00001014 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001015 if (!CountType->isIntegerType()) {
1016 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
1017 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +00001018 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +00001019 diag::note_objc_literal_method_param)
1020 << 2 << CountType
1021 << "integral";
1022 return ExprError();
1023 }
1024
1025 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
1026 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001027 }
1028
Alp Toker03376dc2014-07-07 09:02:20 +00001029 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001030 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +00001031 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001032 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1033
Fangrui Song6907ce22018-07-30 19:24:48 +00001034 // Check that each of the keys and values provided is valid in a collection
Ted Kremeneke65b0862012-03-06 20:05:56 +00001035 // literal, performing conversions as necessary.
1036 bool HasPackExpansions = false;
Craig Topperd4336e02015-12-24 23:58:15 +00001037 for (ObjCDictionaryElement &Element : Elements) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001038 // Check the key.
Craig Topperd4336e02015-12-24 23:58:15 +00001039 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001040 KeyT);
1041 if (Key.isInvalid())
1042 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001043
Ted Kremeneke65b0862012-03-06 20:05:56 +00001044 // Check the value.
1045 ExprResult Value
Craig Topperd4336e02015-12-24 23:58:15 +00001046 = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001047 if (Value.isInvalid())
1048 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001049
Craig Topperd4336e02015-12-24 23:58:15 +00001050 Element.Key = Key.get();
1051 Element.Value = Value.get();
Fangrui Song6907ce22018-07-30 19:24:48 +00001052
Craig Topperd4336e02015-12-24 23:58:15 +00001053 if (Element.EllipsisLoc.isInvalid())
Ted Kremeneke65b0862012-03-06 20:05:56 +00001054 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001055
Craig Topperd4336e02015-12-24 23:58:15 +00001056 if (!Element.Key->containsUnexpandedParameterPack() &&
1057 !Element.Value->containsUnexpandedParameterPack()) {
1058 Diag(Element.EllipsisLoc,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001059 diag::err_pack_expansion_without_parameter_packs)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001060 << SourceRange(Element.Key->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001061 Element.Value->getEndLoc());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001062 return ExprError();
1063 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001064
Ted Kremeneke65b0862012-03-06 20:05:56 +00001065 HasPackExpansions = true;
1066 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001067
Ted Kremeneke65b0862012-03-06 20:05:56 +00001068 QualType Ty
1069 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +00001070 Context.getObjCInterfaceType(NSDictionaryDecl));
1071 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
Craig Topperd4336e02015-12-24 23:58:15 +00001072 Context, Elements, HasPackExpansions, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +00001073 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001074}
1075
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001076ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +00001077 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +00001078 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +00001079 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +00001080 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +00001081 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +00001082 StrTy = Context.DependentTy;
1083 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +00001084 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1085 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001086 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001087 diag::err_incomplete_type_objc_at_encode,
1088 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001089 return ExprError();
1090
Anders Carlsson315d2292009-06-07 18:45:35 +00001091 std::string Str;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00001092 QualType NotEncodedT;
1093 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1094 if (!NotEncodedT.isNull())
1095 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1096 << EncodedType << NotEncodedT;
Anders Carlsson315d2292009-06-07 18:45:35 +00001097
1098 // The type of @encode is the same as the type of the corresponding string,
1099 // which is an array type.
Eric Fiselier708afb52019-05-16 21:04:15 +00001100 StrTy = Context.getStringLiteralArrayType(Context.CharTy, Str.size());
Anders Carlsson315d2292009-06-07 18:45:35 +00001101 }
Mike Stump11289f42009-09-09 15:08:12 +00001102
Douglas Gregorabd9e962010-04-20 15:39:42 +00001103 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +00001104}
1105
John McCallfaf5fb42010-08-26 23:41:50 +00001106ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1107 SourceLocation EncodeLoc,
1108 SourceLocation LParenLoc,
1109 ParsedType ty,
1110 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001111 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +00001112 TypeSourceInfo *TInfo;
1113 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1114 if (!TInfo)
1115 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
Craig Topper07fa1762015-11-15 02:31:46 +00001116 getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001117
Douglas Gregorabd9e962010-04-20 15:39:42 +00001118 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001119}
1120
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001121static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1122 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001123 SourceLocation LParenLoc,
1124 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001125 ObjCMethodDecl *Method,
1126 ObjCMethodList &MethList) {
1127 ObjCMethodList *M = &MethList;
1128 bool Warned = false;
1129 for (M = M->getNext(); M; M=M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00001130 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001131 if (MatchingMethodDecl == Method ||
1132 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1133 MatchingMethodDecl->getSelector() != Method->getSelector())
1134 continue;
1135 if (!S.MatchTwoMethodDeclarations(Method,
1136 MatchingMethodDecl, Sema::MMS_loose)) {
1137 if (!Warned) {
1138 Warned = true;
Richard Smith01d96982016-12-02 23:00:28 +00001139 S.Diag(AtLoc, diag::warn_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001140 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1141 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001142 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1143 << Method->getDeclName();
1144 }
1145 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1146 << MatchingMethodDecl->getDeclName();
1147 }
1148 }
1149 return Warned;
1150}
1151
1152static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001153 ObjCMethodDecl *Method,
1154 SourceLocation LParenLoc,
1155 SourceLocation RParenLoc,
1156 bool WarnMultipleSelectors) {
1157 if (!WarnMultipleSelectors ||
Richard Smith01d96982016-12-02 23:00:28 +00001158 S.Diags.isIgnored(diag::warn_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001159 return;
1160 bool Warned = false;
1161 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1162 e = S.MethodPool.end(); b != e; b++) {
1163 // first, instance methods
1164 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001165 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001166 Method, InstMethList))
1167 Warned = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00001168
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001169 // second, class methods
1170 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001171 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1172 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001173 return;
1174 }
1175}
1176
John McCallfaf5fb42010-08-26 23:41:50 +00001177ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1178 SourceLocation AtLoc,
1179 SourceLocation SelLoc,
1180 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001181 SourceLocation RParenLoc,
1182 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001183 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00001184 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001185 if (!Method)
1186 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001187 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001188 if (!Method) {
1189 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1190 Selector MatchedSel = OM->getSelector();
1191 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1192 RParenLoc.getLocWithOffset(-1));
1193 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1194 << Sel << MatchedSel
1195 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00001196
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001197 } else
1198 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001199 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001200 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1201 WarnMultipleSelectors);
Chandler Carruth12c8f652015-03-27 00:55:05 +00001202
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001203 if (Method &&
1204 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
Chandler Carruth12c8f652015-03-27 00:55:05 +00001205 !getSourceManager().isInSystemHeader(Method->getLocation()))
1206 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001207
Fangrui Song6907ce22018-07-30 19:24:48 +00001208 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001209 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001210 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001211 switch (Sel.getMethodFamily()) {
1212 case OMF_retain:
1213 case OMF_release:
1214 case OMF_autorelease:
1215 case OMF_retainCount:
1216 case OMF_dealloc:
Fangrui Song6907ce22018-07-30 19:24:48 +00001217 Diag(AtLoc, diag::err_arc_illegal_selector) <<
John McCall31168b02011-06-15 23:02:42 +00001218 Sel << SourceRange(LParenLoc, RParenLoc);
1219 break;
1220
1221 case OMF_None:
1222 case OMF_alloc:
1223 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001224 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001225 case OMF_init:
1226 case OMF_mutableCopy:
1227 case OMF_new:
1228 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001229 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001230 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001231 break;
1232 }
1233 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001234 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001235 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001236}
1237
John McCallfaf5fb42010-08-26 23:41:50 +00001238ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1239 SourceLocation AtLoc,
1240 SourceLocation ProtoLoc,
1241 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001242 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001243 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001244 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001245 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001246 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001247 return true;
1248 }
Alex Lorenzb111da12018-08-17 22:18:08 +00001249 if (!PDecl->hasDefinition()) {
1250 Diag(ProtoLoc, diag::err_atprotocol_protocol) << PDecl;
1251 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
1252 } else {
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001253 PDecl = PDecl->getDefinition();
Alex Lorenzb111da12018-08-17 22:18:08 +00001254 }
Mike Stump11289f42009-09-09 15:08:12 +00001255
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001256 QualType Ty = Context.getObjCProtoType();
1257 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001258 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001259 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001260 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001261}
1262
John McCall5f2d5562011-02-03 09:00:02 +00001263/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001264ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1265 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001266
1267 // If we're not in an ObjC method, error out. Note that, unlike the
1268 // C++ case, we don't require an instance method --- class methods
1269 // still have a 'self', and we really do still need to capture it!
1270 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1271 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001272 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001273
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001274 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001275
1276 return method;
1277}
1278
Douglas Gregor64910ca2011-09-09 20:05:21 +00001279static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001280 QualType origType = T;
1281 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1282 if (T == Context.getObjCInstanceType()) {
1283 return Context.getAttributedType(
1284 AttributedType::getNullabilityAttrKind(*nullability),
1285 Context.getObjCIdType(),
1286 Context.getObjCIdType());
1287 }
1288
1289 return origType;
1290 }
1291
Douglas Gregor64910ca2011-09-09 20:05:21 +00001292 if (T == Context.getObjCInstanceType())
1293 return Context.getObjCIdType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001294
Douglas Gregor813a0662015-06-19 18:14:38 +00001295 return origType;
Douglas Gregor64910ca2011-09-09 20:05:21 +00001296}
1297
Douglas Gregor813a0662015-06-19 18:14:38 +00001298/// Determine the result type of a message send based on the receiver type,
1299/// method, and the kind of message send.
1300///
1301/// This is the "base" result type, which will still need to be adjusted
1302/// to account for nullability.
1303static QualType getBaseMessageSendResultType(Sema &S,
1304 QualType ReceiverType,
1305 ObjCMethodDecl *Method,
1306 bool isClassMessage,
1307 bool isSuperMessage) {
Douglas Gregor33823722011-06-11 01:09:30 +00001308 assert(Method && "Must have a method");
1309 if (!Method->hasRelatedResultType())
Douglas Gregore83b9562015-07-07 03:57:53 +00001310 return Method->getSendResultType(ReceiverType);
Douglas Gregor813a0662015-06-19 18:14:38 +00001311
1312 ASTContext &Context = S.Context;
1313
1314 // Local function that transfers the nullability of the method's
1315 // result type to the returned result.
1316 auto transferNullability = [&](QualType type) -> QualType {
1317 // If the method's result type has nullability, extract it.
Douglas Gregore83b9562015-07-07 03:57:53 +00001318 if (auto nullability = Method->getSendResultType(ReceiverType)
1319 ->getNullability(Context)){
Douglas Gregor813a0662015-06-19 18:14:38 +00001320 // Strip off any outer nullability sugar from the provided type.
1321 (void)AttributedType::stripOuterNullability(type);
1322
1323 // Form a new attributed type using the method result type's nullability.
1324 return Context.getAttributedType(
1325 AttributedType::getNullabilityAttrKind(*nullability),
1326 type,
1327 type);
1328 }
1329
1330 return type;
1331 };
1332
Douglas Gregor33823722011-06-11 01:09:30 +00001333 // If a method has a related return type:
1334 // - if the method found is an instance method, but the message send
1335 // was a class message send, T is the declared return type of the method
1336 // found
1337 if (Method->isInstanceMethod() && isClassMessage)
Fangrui Song6907ce22018-07-30 19:24:48 +00001338 return stripObjCInstanceType(Context,
Douglas Gregore83b9562015-07-07 03:57:53 +00001339 Method->getSendResultType(ReceiverType));
Douglas Gregor813a0662015-06-19 18:14:38 +00001340
1341 // - if the receiver is super, T is a pointer to the class of the
Douglas Gregor33823722011-06-11 01:09:30 +00001342 // enclosing method definition
1343 if (isSuperMessage) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001344 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1345 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1346 return transferNullability(
1347 Context.getObjCObjectPointerType(
1348 Context.getObjCInterfaceType(Class)));
1349 }
Douglas Gregor33823722011-06-11 01:09:30 +00001350 }
Douglas Gregor813a0662015-06-19 18:14:38 +00001351
Douglas Gregor33823722011-06-11 01:09:30 +00001352 // - if the receiver is the name of a class U, T is a pointer to U
Douglas Gregore83b9562015-07-07 03:57:53 +00001353 if (ReceiverType->getAsObjCInterfaceType())
Douglas Gregor813a0662015-06-19 18:14:38 +00001354 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1355 // - if the receiver is of type Class or qualified Class type,
Douglas Gregor33823722011-06-11 01:09:30 +00001356 // T is the declared return type of the method.
1357 if (ReceiverType->isObjCClassType() ||
1358 ReceiverType->isObjCQualifiedClassType())
Fangrui Song6907ce22018-07-30 19:24:48 +00001359 return stripObjCInstanceType(Context,
Douglas Gregore83b9562015-07-07 03:57:53 +00001360 Method->getSendResultType(ReceiverType));
Douglas Gregor813a0662015-06-19 18:14:38 +00001361
Douglas Gregor33823722011-06-11 01:09:30 +00001362 // - if the receiver is id, qualified id, Class, or qualified Class, T
1363 // is the receiver type, otherwise
1364 // - T is the type of the receiver expression.
Douglas Gregor813a0662015-06-19 18:14:38 +00001365 return transferNullability(ReceiverType);
1366}
1367
Alex Lorenzf50d1ac2018-12-20 22:11:11 +00001368QualType Sema::getMessageSendResultType(const Expr *Receiver,
1369 QualType ReceiverType,
Douglas Gregor813a0662015-06-19 18:14:38 +00001370 ObjCMethodDecl *Method,
1371 bool isClassMessage,
1372 bool isSuperMessage) {
1373 // Produce the result type.
1374 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1375 Method,
1376 isClassMessage,
1377 isSuperMessage);
1378
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001379 // If this is a class message, ignore the nullability of the receiver.
Alex Lorenzf50d1ac2018-12-20 22:11:11 +00001380 if (isClassMessage) {
1381 // In a class method, class messages to 'self' that return instancetype can
1382 // be typed as the current class. We can safely do this in ARC because self
1383 // can't be reassigned, and we do it unsafely outside of ARC because in
1384 // practice people never reassign self in class methods and there's some
1385 // virtue in not being aggressively pedantic.
1386 if (Receiver && Receiver->isObjCSelfExpr()) {
1387 assert(ReceiverType->isObjCClassType() && "expected a Class self");
1388 QualType T = Method->getSendResultType(ReceiverType);
1389 AttributedType::stripOuterNullability(T);
1390 if (T == Context.getObjCInstanceType()) {
1391 const ObjCMethodDecl *MD = cast<ObjCMethodDecl>(
1392 cast<ImplicitParamDecl>(
1393 cast<DeclRefExpr>(Receiver->IgnoreParenImpCasts())->getDecl())
1394 ->getDeclContext());
1395 assert(MD->isClassMethod() && "expected a class method");
1396 QualType NewResultType = Context.getObjCObjectPointerType(
1397 Context.getObjCInterfaceType(MD->getClassInterface()));
1398 if (auto Nullability = resultType->getNullability(Context))
1399 NewResultType = Context.getAttributedType(
1400 AttributedType::getNullabilityAttrKind(*Nullability),
1401 NewResultType, NewResultType);
1402 return NewResultType;
1403 }
1404 }
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001405 return resultType;
Alex Lorenzf50d1ac2018-12-20 22:11:11 +00001406 }
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001407
Akira Hatanaka66d405d2018-07-26 17:51:13 +00001408 // There is nothing left to do if the result type cannot have a nullability
1409 // specifier.
1410 if (!resultType->canHaveNullability())
1411 return resultType;
1412
Douglas Gregor813a0662015-06-19 18:14:38 +00001413 // Map the nullability of the result into a table index.
1414 unsigned receiverNullabilityIdx = 0;
1415 if (auto nullability = ReceiverType->getNullability(Context))
1416 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1417
1418 unsigned resultNullabilityIdx = 0;
1419 if (auto nullability = resultType->getNullability(Context))
1420 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1421
1422 // The table of nullability mappings, indexed by the receiver's nullability
1423 // and then the result type's nullability.
1424 static const uint8_t None = 0;
1425 static const uint8_t NonNull = 1;
1426 static const uint8_t Nullable = 2;
1427 static const uint8_t Unspecified = 3;
1428 static const uint8_t nullabilityMap[4][4] = {
1429 // None NonNull Nullable Unspecified
1430 /* None */ { None, None, Nullable, None },
1431 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1432 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1433 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1434 };
1435
1436 unsigned newResultNullabilityIdx
1437 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1438 if (newResultNullabilityIdx == resultNullabilityIdx)
1439 return resultType;
1440
1441 // Strip off the existing nullability. This removes as little type sugar as
1442 // possible.
1443 do {
1444 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1445 resultType = attributed->getModifiedType();
1446 } else {
1447 resultType = resultType.getDesugaredType(Context);
1448 }
1449 } while (resultType->getNullability(Context));
1450
1451 // Add nullability back if needed.
1452 if (newResultNullabilityIdx > 0) {
1453 auto newNullability
1454 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1455 return Context.getAttributedType(
1456 AttributedType::getNullabilityAttrKind(newNullability),
1457 resultType, resultType);
1458 }
1459
1460 return resultType;
Douglas Gregor33823722011-06-11 01:09:30 +00001461}
John McCall5f2d5562011-02-03 09:00:02 +00001462
John McCall5ec7e7d2013-03-19 07:04:25 +00001463/// Look for an ObjC method whose result type exactly matches the given type.
1464static const ObjCMethodDecl *
1465findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1466 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001467 if (MD->getReturnType() == instancetype)
1468 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001469
1470 // For these purposes, a method in an @implementation overrides a
1471 // declaration in the @interface.
1472 if (const ObjCImplDecl *impl =
1473 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1474 const ObjCContainerDecl *iface;
Fangrui Song6907ce22018-07-30 19:24:48 +00001475 if (const ObjCCategoryImplDecl *catImpl =
John McCall5ec7e7d2013-03-19 07:04:25 +00001476 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1477 iface = catImpl->getCategoryDecl();
1478 } else {
1479 iface = impl->getClassInterface();
1480 }
1481
Fangrui Song6907ce22018-07-30 19:24:48 +00001482 const ObjCMethodDecl *ifaceMD =
John McCall5ec7e7d2013-03-19 07:04:25 +00001483 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1484 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1485 }
1486
1487 SmallVector<const ObjCMethodDecl *, 4> overrides;
1488 MD->getOverriddenMethods(overrides);
1489 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1490 if (const ObjCMethodDecl *result =
1491 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1492 return result;
1493 }
1494
Craig Topperc3ec1492014-05-26 06:22:03 +00001495 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001496}
1497
1498void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1499 // Only complain if we're in an ObjC method and the required return
1500 // type doesn't match the method's declared return type.
1501 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1502 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001503 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001504 return;
1505
1506 // Look for a method overridden by this method which explicitly uses
1507 // 'instancetype'.
1508 if (const ObjCMethodDecl *overridden =
1509 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001510 SourceRange range = overridden->getReturnTypeSourceRange();
1511 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001512 if (loc.isInvalid())
1513 loc = overridden->getLocation();
1514 Diag(loc, diag::note_related_result_type_explicit)
1515 << /*current method*/ 1 << range;
1516 return;
1517 }
1518
1519 // Otherwise, if we have an interesting method family, note that.
1520 // This should always trigger if the above didn't.
1521 if (ObjCMethodFamily family = MD->getMethodFamily())
1522 Diag(MD->getLocation(), diag::note_related_result_type_family)
1523 << /*current method*/ 1
1524 << family;
1525}
1526
Douglas Gregor33823722011-06-11 01:09:30 +00001527void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1528 E = E->IgnoreParenImpCasts();
1529 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1530 if (!MsgSend)
1531 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001532
Douglas Gregor33823722011-06-11 01:09:30 +00001533 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1534 if (!Method)
1535 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001536
Douglas Gregor33823722011-06-11 01:09:30 +00001537 if (!Method->hasRelatedResultType())
1538 return;
Alp Toker314cc812014-01-25 16:55:45 +00001539
1540 if (Context.hasSameUnqualifiedType(
1541 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001542 return;
Alp Toker314cc812014-01-25 16:55:45 +00001543
1544 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001545 Context.getObjCInstanceType()))
1546 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001547
Douglas Gregor33823722011-06-11 01:09:30 +00001548 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1549 << Method->isInstanceMethod() << Method->getSelector()
1550 << MsgSend->getType();
1551}
1552
Alex Lorenzf50d1ac2018-12-20 22:11:11 +00001553bool Sema::CheckMessageArgumentTypes(
1554 const Expr *Receiver, QualType ReceiverType, MultiExprArg Args,
1555 Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method,
1556 bool isClassMessage, bool isSuperMessage, SourceLocation lbrac,
1557 SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType,
1558 ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001559 SourceLocation SelLoc;
1560 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1561 SelLoc = SelectorLocs.front();
1562 else
1563 SelLoc = lbrac;
1564
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001565 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001566 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001567 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001568 if (Args[i]->isTypeDependent())
1569 continue;
1570
John McCallcc5788c2013-03-04 07:34:02 +00001571 ExprResult result;
1572 if (getLangOpts().DebuggerSupport) {
1573 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001574 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001575 } else {
1576 result = DefaultArgumentPromotion(Args[i]);
1577 }
1578 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001579 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001580 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001581 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001582
John McCall31168b02011-06-15 23:02:42 +00001583 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001584 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001585 DiagID = diag::err_arc_method_not_found;
1586 else
1587 DiagID = isClassMessage ? diag::warn_class_method_not_found
1588 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001589 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001590 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001591 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001592 if (getLangOpts().ObjCAutoRefCount)
Richard Smithf8812672016-12-02 22:38:31 +00001593 DiagID = diag::err_method_not_found_with_typo;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001594 else
1595 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1596 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001597 Selector MatchedSel = OMD->getSelector();
1598 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian5ab87502014-08-12 22:16:41 +00001599 if (MatchedSel.isUnarySelector())
1600 Diag(SelLoc, DiagID)
1601 << Sel<< isClassMessage << MatchedSel
1602 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1603 else
1604 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001605 }
1606 else
1607 Diag(SelLoc, DiagID)
Fangrui Song6907ce22018-07-30 19:24:48 +00001608 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001609 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001610 // Find the class to which we are sending this message.
1611 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001612 if (ObjCInterfaceDecl *ThisClass =
1613 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1614 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1615 if (!RecRange.isInvalid())
1616 if (ThisClass->lookupClassMethod(Sel))
1617 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1618 << FixItHint::CreateReplacement(RecRange,
1619 ThisClass->getNameAsString());
1620 }
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001621 }
1622 }
John McCall3f4138c2011-07-13 17:56:40 +00001623
1624 // In debuggers, we want to use __unknown_anytype for these
1625 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001626 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001627 ReturnType = Context.UnknownAnyTy;
1628 } else {
1629 ReturnType = Context.getObjCIdType();
1630 }
John McCall7decc9e2010-11-18 06:31:45 +00001631 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001632 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001633 }
Mike Stump11289f42009-09-09 15:08:12 +00001634
Alex Lorenzf50d1ac2018-12-20 22:11:11 +00001635 ReturnType = getMessageSendResultType(Receiver, ReceiverType, Method,
1636 isClassMessage, isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001637 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001638
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001639 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001640 // Method might have more arguments than selector indicates. This is due
1641 // to addition of c-style arguments in method.
1642 if (Method->param_size() > Sel.getNumArgs())
1643 NumNamedArgs = Method->param_size();
1644 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001645 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001646 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001647 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001648 return false;
1649 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001650
Douglas Gregore83b9562015-07-07 03:57:53 +00001651 // Compute the set of type arguments to be substituted into each parameter
1652 // type.
1653 Optional<ArrayRef<QualType>> typeArgs
1654 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001655 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001656 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001657 // We can't do any type-checking on a type-dependent argument.
1658 if (Args[i]->isTypeDependent())
1659 continue;
1660
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001661 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001662
Alp Toker03376dc2014-07-07 09:02:20 +00001663 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001664 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001665
Akira Hatanaka627586b2018-03-02 01:53:15 +00001666 if (param->hasAttr<NoEscapeAttr>())
1667 if (auto *BE = dyn_cast<BlockExpr>(
1668 argExpr->IgnoreParenNoopCasts(Context)))
1669 BE->getBlockDecl()->setDoesNotEscape();
1670
John McCall4124c492011-10-17 18:40:02 +00001671 // Strip the unbridged-cast placeholder expression off unless it's
1672 // a consumed argument.
1673 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1674 !param->hasAttr<CFConsumedAttr>())
1675 argExpr = stripARCUnbridgedCast(argExpr);
1676
John McCallea0a39e2012-11-14 00:49:39 +00001677 // If the parameter is __unknown_anytype, infer its type
1678 // from the argument.
1679 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001680 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001681 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001682 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001683 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001684 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001685 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001686
John McCallcc5788c2013-03-04 07:34:02 +00001687 // Update the parameter type in-place.
1688 param->setType(paramType);
1689 }
1690 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001691 }
1692
Douglas Gregore83b9562015-07-07 03:57:53 +00001693 QualType origParamType = param->getType();
1694 QualType paramType = param->getType();
1695 if (typeArgs)
1696 paramType = paramType.substObjCTypeArgs(
1697 Context,
1698 *typeArgs,
1699 ObjCSubstitutionContext::Parameter);
1700
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001701 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001702 paramType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001703 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001704 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001705
Douglas Gregore83b9562015-07-07 03:57:53 +00001706 InitializedEntity Entity
1707 = InitializedEntity::InitializeParameter(Context, param, paramType);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001708 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001709 if (ArgE.isInvalid())
1710 IsError = true;
Douglas Gregore83b9562015-07-07 03:57:53 +00001711 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001712 Args[i] = ArgE.getAs<Expr>();
Douglas Gregore83b9562015-07-07 03:57:53 +00001713
1714 // If we are type-erasing a block to a block-compatible
1715 // Objective-C pointer type, we may need to extend the lifetime
1716 // of the block object.
1717 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
Bob Wilson7e9fd562015-10-02 01:05:29 +00001718 Args[i]->getType()->isBlockPointerType() &&
1719 origParamType->isObjCObjectPointerType()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001720 ExprResult arg = Args[i];
1721 maybeExtendBlockObject(arg);
1722 Args[i] = arg.get();
1723 }
1724 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001725 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001726
1727 // Promote additional arguments to variadic methods.
1728 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001729 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001730 if (Args[i]->isTypeDependent())
1731 continue;
1732
Jordy Roseaca01f92012-05-12 17:32:52 +00001733 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001734 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001735 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001736 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001737 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001738 } else {
1739 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001740 if (Args.size() != NumNamedArgs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001741 Diag(Args[NumNamedArgs]->getBeginLoc(),
Chris Lattner3b054132008-11-19 05:08:23 +00001742 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001743 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1744 << Method->getSourceRange()
1745 << SourceRange(Args[NumNamedArgs]->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001746 Args.back()->getEndLoc());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001747 }
1748 }
1749
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001750 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001751
1752 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001753 IsError |= CheckObjCMethodCall(
Craig Topper8c2a2a02014-08-30 16:55:39 +00001754 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001755
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001756 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001757}
1758
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001759bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001760 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001761 ObjCMethodDecl *Method =
1762 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1763 return isSelfExpr(RExpr, Method);
1764}
1765
1766bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001767 if (!method) return false;
1768
John McCall31168b02011-06-15 23:02:42 +00001769 receiver = receiver->IgnoreParenLValueCasts();
1770 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001771 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001772 return true;
1773 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001774}
1775
John McCall526ab472011-10-25 17:37:35 +00001776/// LookupMethodInType - Look up a method in an ObjCObjectType.
1777ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1778 bool isInstance) {
1779 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1780 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1781 // Look it up in the main interface (and categories, etc.)
1782 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1783 return method;
1784
1785 // Okay, look for "private" methods declared in any
1786 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001787 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1788 return method;
John McCall526ab472011-10-25 17:37:35 +00001789 }
1790
1791 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001792 for (const auto *I : objType->quals())
1793 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001794 return method;
1795
Craig Topperc3ec1492014-05-26 06:22:03 +00001796 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001797}
1798
Fangrui Song6907ce22018-07-30 19:24:48 +00001799/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001800/// list of a qualified objective pointer type.
1801ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1802 const ObjCObjectPointerType *OPT,
1803 bool Instance)
1804{
Craig Topperc3ec1492014-05-26 06:22:03 +00001805 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001806 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001807 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1808 return MD;
1809 }
1810 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001811 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001812}
1813
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001814/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1815/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001816ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001817HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001818 Expr *BaseExpr, SourceLocation OpLoc,
1819 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001820 SourceLocation MemberLoc,
1821 SourceLocation SuperLoc, QualType SuperType,
1822 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001823 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1824 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001825
Benjamin Kramer365082d2012-05-19 16:34:46 +00001826 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001827 Diag(MemberLoc, diag::err_invalid_property_name)
1828 << MemberName << QualType(OPT, 0);
1829 return ExprError();
1830 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001831
1832 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Fangrui Song6907ce22018-07-30 19:24:48 +00001833
Douglas Gregor4123a862011-11-14 22:10:01 +00001834 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1835 : BaseExpr->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00001836 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001837 diag::err_property_not_found_forward_class,
1838 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001839 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001840
Manman Ren5b786402016-01-28 18:49:28 +00001841 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
1842 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001843 // Check whether we can reference this property.
1844 if (DiagnoseUseOfDecl(PD, MemberLoc))
1845 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001846 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001847 return new (Context)
1848 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1849 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001850 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001851 return new (Context)
1852 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1853 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001854 }
1855 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001856 for (const auto *I : OPT->quals())
Manman Ren5b786402016-01-28 18:49:28 +00001857 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
1858 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001859 // Check whether we can reference this property.
1860 if (DiagnoseUseOfDecl(PD, MemberLoc))
1861 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001862
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001863 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001864 return new (Context) ObjCPropertyRefExpr(
1865 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1866 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001867 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001868 return new (Context)
1869 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1870 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001871 }
1872 // If that failed, look for an "implicit" property by seeing if the nullary
1873 // selector is implemented.
1874
1875 // FIXME: The logic for looking up nullary and unary selectors should be
1876 // shared with the code in ActOnInstanceMessage.
1877
1878 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1879 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fangrui Song6907ce22018-07-30 19:24:48 +00001880
Manman Ren2b2b1a92016-06-28 23:01:49 +00001881 // May be found in property's qualified list.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001882 if (!Getter)
1883 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001884
1885 // If this reference is in an @implementation, check for 'private' methods.
1886 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001887 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001888
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001889 if (Getter) {
1890 // Check if we can reference this property.
1891 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1892 return ExprError();
1893 }
1894 // If we found a getter then this may be a valid dot-reference, we
1895 // will look for the matching setter, in case it is needed.
1896 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001897 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1898 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001899 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fangrui Song6907ce22018-07-30 19:24:48 +00001900
Manman Ren2b2b1a92016-06-28 23:01:49 +00001901 // May be found in property's qualified list.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001902 if (!Setter)
1903 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001904
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001905 if (!Setter) {
1906 // If this reference is in an @implementation, also check for 'private'
1907 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001908 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001909 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001910
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001911 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1912 return ExprError();
1913
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001914 // Special warning if member name used in a property-dot for a setter accessor
1915 // does not use a property with same name; e.g. obj.X = ... for a property with
1916 // name 'x'.
Manman Ren5b786402016-01-28 18:49:28 +00001917 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() &&
1918 !IFace->FindPropertyDeclaration(
1919 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001920 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1921 // Do not warn if user is using property-dot syntax to make call to
1922 // user named setter.
1923 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001924 Diag(MemberLoc,
1925 diag::warn_property_access_suggest)
1926 << MemberName << QualType(OPT, 0) << PDecl->getName()
1927 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001928 }
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001929 }
1930
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001931 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001932 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001933 return new (Context)
1934 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1935 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001936 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001937 return new (Context)
1938 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1939 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001940
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001941 }
1942
1943 // Attempt to correct for typos in property names.
Bruno Ricci70ad3962019-03-25 17:08:51 +00001944 DeclFilterCCC<ObjCPropertyDecl> CCC{};
1945 if (TypoCorrection Corrected = CorrectTypo(
1946 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName,
1947 nullptr, nullptr, CCC, CTK_ErrorRecovery, IFace, false, OPT)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001948 DeclarationName TypoResult = Corrected.getCorrection();
Manman Ren2b2b1a92016-06-28 23:01:49 +00001949 if (TypoResult.isIdentifier() &&
1950 TypoResult.getAsIdentifierInfo() == Member) {
1951 // There is no need to try the correction if it is the same.
1952 NamedDecl *ChosenDecl =
1953 Corrected.isKeyword() ? nullptr : Corrected.getFoundDecl();
1954 if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
1955 if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
1956 // This is a class property, we should not use the instance to
1957 // access it.
1958 Diag(MemberLoc, diag::err_class_property_found) << MemberName
1959 << OPT->getInterfaceDecl()->getName()
1960 << FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
1961 OPT->getInterfaceDecl()->getName());
1962 return ExprError();
1963 }
1964 } else {
1965 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1966 << MemberName << QualType(OPT, 0));
1967 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1968 TypoResult, MemberLoc,
1969 SuperLoc, SuperType, Super);
1970 }
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001971 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001972 ObjCInterfaceDecl *ClassDeclared;
Fangrui Song6907ce22018-07-30 19:24:48 +00001973 if (ObjCIvarDecl *Ivar =
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001974 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1975 QualType T = Ivar->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001976 if (const ObjCObjectPointerType * OBJPT =
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001977 T->getAsObjCInterfacePointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001978 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001979 diag::err_property_not_as_forward_class,
1980 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001981 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001982 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001983 Diag(MemberLoc,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001984 diag::err_ivar_access_using_property_syntax_suggest)
1985 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1986 << FixItHint::CreateReplacement(OpLoc, "->");
1987 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001988 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001989
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001990 Diag(MemberLoc, diag::err_property_not_found)
1991 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001992 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001993 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001994 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001995 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001996}
1997
John McCalldadc5752010-08-24 06:29:42 +00001998ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001999ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
2000 IdentifierInfo &propertyName,
2001 SourceLocation receiverNameLoc,
2002 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00002003
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002004 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002005 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
2006 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00002007
Douglas Gregore83b9562015-07-07 03:57:53 +00002008 QualType SuperType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002009 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00002010 // If the "receiver" is 'super' in a method, handle it as an expression-like
2011 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00002012 if (receiverNamePtr->isStr("super")) {
Eli Friedman24af8502012-02-03 22:47:37 +00002013 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Douglas Gregore83b9562015-07-07 03:57:53 +00002014 if (auto classDecl = CurMethod->getClassInterface()) {
2015 SuperType = QualType(classDecl->getSuperClassType(), 0);
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00002016 if (CurMethod->isInstanceMethod()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00002017 if (SuperType.isNull()) {
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00002018 // The current class does not have a superclass.
Richard Smithf8812672016-12-02 22:38:31 +00002019 Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
Douglas Gregore83b9562015-07-07 03:57:53 +00002020 << CurMethod->getClassInterface()->getIdentifier();
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00002021 return ExprError();
2022 }
Douglas Gregore83b9562015-07-07 03:57:53 +00002023 QualType T = Context.getObjCObjectPointerType(SuperType);
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00002024
Douglas Gregore83b9562015-07-07 03:57:53 +00002025 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00002026 /*BaseExpr*/nullptr,
2027 SourceLocation()/*OpLoc*/,
2028 &propertyName,
2029 propertyNameLoc,
2030 receiverNameLoc, T, true);
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00002031 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002032
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00002033 // Otherwise, if this is a class method, try dispatching to our
2034 // superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00002035 IFace = CurMethod->getClassInterface()->getSuperClass();
Chris Lattnera36ec422010-04-11 08:28:14 +00002036 }
Chris Lattnera36ec422010-04-11 08:28:14 +00002037 }
John McCall5f2d5562011-02-03 09:00:02 +00002038 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002039
2040 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00002041 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
2042 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00002043 return ExprError();
2044 }
2045 }
2046
Saleem Abdulrasoolb3a2d042017-02-20 23:45:49 +00002047 Selector GetterSel;
2048 Selector SetterSel;
2049 if (auto PD = IFace->FindPropertyDeclaration(
2050 &propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) {
2051 GetterSel = PD->getGetterName();
2052 SetterSel = PD->getSetterName();
2053 } else {
2054 GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName);
2055 SetterSel = SelectorTable::constructSetterSelector(
2056 PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName);
2057 }
2058
Chris Lattnera36ec422010-04-11 08:28:14 +00002059 // Search for a declared property first.
Saleem Abdulrasoolb3a2d042017-02-20 23:45:49 +00002060 ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002061
2062 // If this reference is in an @implementation, check for 'private' methods.
2063 if (!Getter)
Saleem Abdulrasoolb3a2d042017-02-20 23:45:49 +00002064 Getter = IFace->lookupPrivateClassMethod(GetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002065
2066 if (Getter) {
2067 // FIXME: refactor/share with ActOnMemberReference().
2068 // Check if we can reference this property.
2069 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
2070 return ExprError();
2071 }
Mike Stump11289f42009-09-09 15:08:12 +00002072
Steve Naroff9527bbf2009-03-09 21:12:44 +00002073 // Look for the matching setter, in case it is needed.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002074 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002075 if (!Setter) {
2076 // If this reference is in an @implementation, also check for 'private'
2077 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00002078 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002079 }
2080 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002081 if (!Setter)
2082 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002083
2084 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2085 return ExprError();
2086
2087 if (Getter || Setter) {
Douglas Gregore83b9562015-07-07 03:57:53 +00002088 if (!SuperType.isNull())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002089 return new (Context)
2090 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2091 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
Douglas Gregore83b9562015-07-07 03:57:53 +00002092 SuperType);
Douglas Gregor33823722011-06-11 01:09:30 +00002093
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002094 return new (Context) ObjCPropertyRefExpr(
2095 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2096 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002097 }
2098 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2099 << &propertyName << Context.getObjCInterfaceType(IFace));
2100}
2101
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002102namespace {
2103
Bruno Ricci70ad3962019-03-25 17:08:51 +00002104class ObjCInterfaceOrSuperCCC final : public CorrectionCandidateCallback {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002105 public:
2106 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2107 // Determine whether "super" is acceptable in the current context.
2108 if (Method && Method->getClassInterface())
2109 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2110 }
2111
Craig Toppere14c0f82014-03-12 04:55:44 +00002112 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002113 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2114 candidate.isKeyword("super");
2115 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002116
2117 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002118 return std::make_unique<ObjCInterfaceOrSuperCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002119 }
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002120};
2121
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002122} // end anonymous namespace
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002123
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002124Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002125 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002126 SourceLocation NameLoc,
2127 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002128 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00002129 ParsedType &ReceiverType) {
David Blaikieefdccaa2016-01-15 23:43:34 +00002130 ReceiverType = nullptr;
Douglas Gregore5798dc2010-04-21 20:38:13 +00002131
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002132 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00002133 // messaging super. If the identifier is "super" and there is a
2134 // trailing dot, it's an instance message.
2135 if (IsSuper && S->isInObjcMethodScope())
2136 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Fangrui Song6907ce22018-07-30 19:24:48 +00002137
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002138 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2139 LookupName(Result, S);
Fangrui Song6907ce22018-07-30 19:24:48 +00002140
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002141 switch (Result.getResultKind()) {
2142 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00002143 // Normal name lookup didn't find anything. If we're in an
2144 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00002145 // FIXME: This is a hack. Ivar lookup should be part of normal
2146 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00002147 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00002148 if (!Method->getClassInterface()) {
2149 // Fall back: let the parser try to parse it as an instance message.
2150 return ObjCInstanceMessage;
2151 }
2152
Douglas Gregorca7136b2010-04-19 20:09:36 +00002153 ObjCInterfaceDecl *ClassDeclared;
Fangrui Song6907ce22018-07-30 19:24:48 +00002154 if (Method->getClassInterface()->lookupInstanceVariable(Name,
Douglas Gregorca7136b2010-04-19 20:09:36 +00002155 ClassDeclared))
2156 return ObjCInstanceMessage;
2157 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002158
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002159 // Break out; we'll perform typo correction below.
2160 break;
2161
2162 case LookupResult::NotFoundInCurrentInstantiation:
2163 case LookupResult::FoundOverloaded:
2164 case LookupResult::FoundUnresolvedValue:
2165 case LookupResult::Ambiguous:
2166 Result.suppressDiagnostics();
2167 return ObjCInstanceMessage;
2168
2169 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00002170 // If the identifier is a class or not, and there is a trailing dot,
2171 // it's an instance message.
2172 if (HasTrailingDot)
2173 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002174 // We found something. If it's a type, then we have a class
2175 // message. Otherwise, it's an instance message.
2176 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00002177 QualType T;
2178 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2179 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002180 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00002181 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002182 DiagnoseUseOfDecl(Type, NameLoc);
2183 }
2184 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00002185 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002186
Douglas Gregore5798dc2010-04-21 20:38:13 +00002187 // We have a class message, and T is the type we're
2188 // messaging. Build source-location information for it.
2189 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00002190 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00002191 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002192 }
2193 }
2194
Bruno Ricci70ad3962019-03-25 17:08:51 +00002195 ObjCInterfaceOrSuperCCC CCC(getCurMethodDecl());
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002196 if (TypoCorrection Corrected = CorrectTypo(
Bruno Ricci70ad3962019-03-25 17:08:51 +00002197 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr, CCC,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002198 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002199 if (Corrected.isKeyword()) {
2200 // If we've found the keyword "super" (the only keyword that would be
2201 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00002202 diagnoseTypo(Corrected,
2203 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002204 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002205 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00002206 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002207 // If we found a declaration, correct when it refers to an Objective-C
2208 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00002209 diagnoseTypo(Corrected,
2210 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002211 QualType T = Context.getObjCInterfaceType(Class);
2212 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2213 ReceiverType = CreateParsedType(T, TSInfo);
2214 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002215 }
2216 }
Richard Smithf9b15102013-08-17 00:46:16 +00002217
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002218 // Fall back: let the parser try to parse it as an instance message.
2219 return ObjCInstanceMessage;
2220}
Steve Naroff9527bbf2009-03-09 21:12:44 +00002221
Fangrui Song6907ce22018-07-30 19:24:48 +00002222ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002223 SourceLocation SuperLoc,
2224 Selector Sel,
2225 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002226 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002227 SourceLocation RBracLoc,
2228 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002229 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00002230 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00002231 if (!Method) {
2232 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2233 return ExprError();
2234 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002235
Douglas Gregor4fdba132010-04-21 20:01:04 +00002236 ObjCInterfaceDecl *Class = Method->getClassInterface();
2237 if (!Class) {
Richard Smithf8812672016-12-02 22:38:31 +00002238 Diag(SuperLoc, diag::err_no_super_class_message)
Douglas Gregor4fdba132010-04-21 20:01:04 +00002239 << Method->getDeclName();
2240 return ExprError();
2241 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002242
Douglas Gregore83b9562015-07-07 03:57:53 +00002243 QualType SuperTy(Class->getSuperClassType(), 0);
2244 if (SuperTy.isNull()) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002245 // The current class does not have a superclass.
Richard Smithf8812672016-12-02 22:38:31 +00002246 Diag(SuperLoc, diag::err_root_class_cannot_use_super)
Ted Kremenek499897b2011-01-23 17:21:34 +00002247 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002248 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002249 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002250
Douglas Gregor4fdba132010-04-21 20:01:04 +00002251 // We are in a method whose class has a superclass, so 'super'
2252 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00002253 if (Method->getSelector() == Sel)
2254 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00002255
Jordan Rose2afd6612012-10-19 16:05:26 +00002256 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00002257 // Since we are in an instance method, this is an instance
2258 // message to the superclass instance.
Douglas Gregor4fdba132010-04-21 20:01:04 +00002259 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00002260 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2261 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002262 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002263 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002264
Douglas Gregor4fdba132010-04-21 20:01:04 +00002265 // Since we are in a class method, this is a class message to
2266 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00002267 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregore83b9562015-07-07 03:57:53 +00002268 SuperTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00002269 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002270 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002271}
2272
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002273ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2274 bool isSuperReceiver,
2275 SourceLocation Loc,
2276 Selector Sel,
2277 ObjCMethodDecl *Method,
2278 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002279 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002280 if (!ReceiverType.isNull())
2281 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2282
2283 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2284 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2285 Sel, Method, Loc, Loc, Loc, Args,
2286 /*isImplicit=*/true);
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002287}
2288
Ted Kremeneke65b0862012-03-06 20:05:56 +00002289static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2290 unsigned DiagID,
2291 bool (*refactor)(const ObjCMessageExpr *,
2292 const NSAPI &, edit::Commit &)) {
2293 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002294 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002295 return;
2296
2297 SourceManager &SM = S.SourceMgr;
2298 edit::Commit ECommit(SM, S.LangOpts);
2299 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2300 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2301 << Msg->getSelector() << Msg->getSourceRange();
2302 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2303 if (!ECommit.isCommitable())
2304 return;
2305 for (edit::Commit::edit_iterator
2306 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2307 const edit::Commit::Edit &Edit = *I;
2308 switch (Edit.Kind) {
2309 case edit::Commit::Act_Insert:
2310 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2311 Edit.Text,
2312 Edit.BeforePrev));
2313 break;
2314 case edit::Commit::Act_InsertFromRange:
2315 Builder.AddFixItHint(
2316 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2317 Edit.getInsertFromRange(SM),
2318 Edit.BeforePrev));
2319 break;
2320 case edit::Commit::Act_Remove:
2321 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2322 break;
2323 }
2324 }
2325 }
2326}
2327
2328static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2329 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2330 edit::rewriteObjCRedundantCallWithLiteral);
2331}
2332
Alex Lorenz0e23c612017-03-06 15:58:34 +00002333static void checkFoundationAPI(Sema &S, SourceLocation Loc,
2334 const ObjCMethodDecl *Method,
2335 ArrayRef<Expr *> Args, QualType ReceiverType,
2336 bool IsClassObjectCall) {
2337 // Check if this is a performSelector method that uses a selector that returns
2338 // a record or a vector type.
Alex Lorenz5ffe4e12017-03-23 10:46:05 +00002339 if (Method->getSelector().getMethodFamily() != OMF_performSelector ||
2340 Args.empty())
Alex Lorenz0e23c612017-03-06 15:58:34 +00002341 return;
2342 const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens());
2343 if (!SE)
2344 return;
2345 ObjCMethodDecl *ImpliedMethod;
2346 if (!IsClassObjectCall) {
2347 const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>();
2348 if (!OPT || !OPT->getInterfaceDecl())
2349 return;
2350 ImpliedMethod =
2351 OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector());
2352 if (!ImpliedMethod)
2353 ImpliedMethod =
2354 OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector());
2355 } else {
2356 const auto *IT = ReceiverType->getAs<ObjCInterfaceType>();
2357 if (!IT)
2358 return;
2359 ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector());
2360 if (!ImpliedMethod)
2361 ImpliedMethod =
2362 IT->getDecl()->lookupPrivateClassMethod(SE->getSelector());
2363 }
2364 if (!ImpliedMethod)
2365 return;
2366 QualType Ret = ImpliedMethod->getReturnType();
2367 if (Ret->isRecordType() || Ret->isVectorType() || Ret->isExtVectorType()) {
2368 QualType Ret = ImpliedMethod->getReturnType();
2369 S.Diag(Loc, diag::warn_objc_unsafe_perform_selector)
2370 << Method->getSelector()
2371 << (!Ret->isRecordType()
2372 ? /*Vector*/ 2
2373 : Ret->isUnionType() ? /*Union*/ 1 : /*Struct*/ 0);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002374 S.Diag(ImpliedMethod->getBeginLoc(),
Alex Lorenz0e23c612017-03-06 15:58:34 +00002375 diag::note_objc_unsafe_perform_selector_method_declared_here)
2376 << ImpliedMethod->getSelector() << Ret;
2377 }
2378}
2379
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002380/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002381/// as formatting string to formatting method.
2382static void
2383DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2384 ObjCMethodDecl *Method,
2385 Selector Sel,
2386 Expr **Args, unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002387 unsigned Idx = 0;
2388 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002389 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2390 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002391 Idx = 0;
2392 Format = true;
2393 }
2394 else if (Method) {
2395 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2396 if (S.GetFormatNSStringIdx(I, Idx)) {
2397 Format = true;
2398 break;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002399 }
2400 }
2401 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002402 if (!Format || NumArgs <= Idx)
2403 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002404
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002405 Expr *FormatExpr = Args[Idx];
2406 if (ObjCStringLiteral *OSL =
2407 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2408 StringLiteral *FormatString = OSL->getString();
2409 if (S.FormatStringHasSArg(FormatString)) {
2410 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2411 << "%s" << 0 << 0;
2412 if (Method)
2413 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2414 << Method->getDeclName();
2415 }
2416 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002417}
2418
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002419/// Build an Objective-C class message expression.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002420///
2421/// This routine takes care of both normal class messages and
2422/// class messages to the superclass.
2423///
2424/// \param ReceiverTypeInfo Type source information that describes the
2425/// receiver of this message. This may be NULL, in which case we are
2426/// sending to the superclass and \p SuperLoc must be a valid source
2427/// location.
2428
2429/// \param ReceiverType The type of the object receiving the
2430/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2431/// type as that refers to. For a superclass send, this is the type of
2432/// the superclass.
2433///
2434/// \param SuperLoc The location of the "super" keyword in a
2435/// superclass message.
2436///
2437/// \param Sel The selector to which the message is being sent.
2438///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002439/// \param Method The method that this class message is invoking, if
2440/// already known.
2441///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002442/// \param LBracLoc The location of the opening square bracket ']'.
2443///
James Dennettffad8b72012-06-22 08:10:18 +00002444/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002445///
James Dennettffad8b72012-06-22 08:10:18 +00002446/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002447ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002448 QualType ReceiverType,
2449 SourceLocation SuperLoc,
2450 Selector Sel,
2451 ObjCMethodDecl *Method,
Fangrui Song6907ce22018-07-30 19:24:48 +00002452 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002453 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002454 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002455 MultiExprArg ArgsIn,
2456 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002457 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002458 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002459 if (LBracLoc.isInvalid()) {
2460 Diag(Loc, diag::err_missing_open_square_message_send)
2461 << FixItHint::CreateInsertion(Loc, "[");
2462 LBracLoc = Loc;
2463 }
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002464 ArrayRef<SourceLocation> SelectorSlotLocs;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002465 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002466 SelectorSlotLocs = SelectorLocs;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002467 else
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002468 SelectorSlotLocs = Loc;
2469 SourceLocation SelLoc = SelectorSlotLocs.front();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002470
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002471 if (ReceiverType->isDependentType()) {
2472 // If the receiver type is dependent, we can't type-check anything
2473 // at this point. Build a dependent expression.
2474 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002475 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002476 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002477 return ObjCMessageExpr::Create(
2478 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2479 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2480 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002481 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002482
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002483 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002484 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002485 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2486 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002487 Diag(Loc, diag::err_invalid_receiver_class_message)
2488 << ReceiverType;
2489 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002490 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002491 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002492 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002493 if (!getLangOpts().CPlusPlus)
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002494 (void)DiagnoseUseOfDecl(Class, SelectorSlotLocs);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002495 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002496 if (!Method) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002497 SourceRange TypeRange
Douglas Gregor4123a862011-11-14 22:10:01 +00002498 = SuperLoc.isValid()? SourceRange(SuperLoc)
2499 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002500 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002501 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002502 ? diag::err_arc_receiver_forward_class
2503 : diag::warn_receiver_forward_class),
2504 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002505 // A forward class used in messaging is treated as a 'Class'
Fangrui Song6907ce22018-07-30 19:24:48 +00002506 Method = LookupFactoryMethodInGlobalPool(Sel,
Douglas Gregorb5186b12010-04-22 17:01:48 +00002507 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002508 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002509 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2510 << Method->getDeclName();
2511 }
2512 if (!Method)
2513 Method = Class->lookupClassMethod(Sel);
2514
2515 // If we have an implementation in scope, check "private" methods.
2516 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002517 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002518
Erik Pilkington42578572018-09-10 22:20:09 +00002519 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs,
2520 nullptr, false, false, Class))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002521 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002522 }
Mike Stump11289f42009-09-09 15:08:12 +00002523
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002524 // Check the argument types and determine the result type.
2525 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002526 ExprValueKind VK = VK_RValue;
2527
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002528 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002529 Expr **Args = ArgsIn.data();
Alex Lorenzf50d1ac2018-12-20 22:11:11 +00002530 if (CheckMessageArgumentTypes(/*Receiver=*/nullptr, ReceiverType,
2531 MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
2532 Method, true, SuperLoc.isValid(), LBracLoc,
2533 RBracLoc, SourceRange(), ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002534 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002535
Alp Toker314cc812014-01-25 16:55:45 +00002536 if (Method && !Method->getReturnType()->isVoidType() &&
2537 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002538 diag::err_illegal_message_expr_incomplete_type))
2539 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002540
Fariborz Jahaniane8b45502014-08-22 19:52:49 +00002541 // Warn about explicit call of +initialize on its own class. But not on 'super'.
Fariborz Jahanian42292282014-08-25 21:27:38 +00002542 if (Method && Method->getMethodFamily() == OMF_initialize) {
2543 if (!SuperLoc.isValid()) {
2544 const ObjCInterfaceDecl *ID =
2545 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2546 if (ID == Class) {
2547 Diag(Loc, diag::warn_direct_initialize_call);
2548 Diag(Method->getLocation(), diag::note_method_declared_at)
2549 << Method->getDeclName();
2550 }
2551 }
2552 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2553 // [super initialize] is allowed only within an +initialize implementation
2554 if (CurMeth->getMethodFamily() != OMF_initialize) {
2555 Diag(Loc, diag::warn_direct_super_initialize_call);
2556 Diag(Method->getLocation(), diag::note_method_declared_at)
2557 << Method->getDeclName();
2558 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2559 << CurMeth->getDeclName();
2560 }
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002561 }
2562 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002563
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002564 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
Fangrui Song6907ce22018-07-30 19:24:48 +00002565
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002566 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002567 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002568 if (SuperLoc.isValid())
Fangrui Song6907ce22018-07-30 19:24:48 +00002569 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2570 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002571 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002572 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002573 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002574 else {
Fangrui Song6907ce22018-07-30 19:24:48 +00002575 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002576 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002577 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002578 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002579 if (!isImplicit)
2580 checkCocoaAPI(*this, Result);
2581 }
Alex Lorenz0e23c612017-03-06 15:58:34 +00002582 if (Method)
2583 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
2584 ReceiverType, /*IsClassObjectCall=*/true);
Douglas Gregoraae38d62010-05-22 05:17:18 +00002585 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002586}
2587
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002588// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002589// ArgExprs is optional - if it is present, the number of expressions
2590// is obtained from Sel.getNumArgs().
Fangrui Song6907ce22018-07-30 19:24:48 +00002591ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002592 ParsedType Receiver,
2593 Selector Sel,
2594 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002595 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002596 SourceLocation RBracLoc,
2597 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002598 TypeSourceInfo *ReceiverTypeInfo;
2599 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2600 if (ReceiverType.isNull())
2601 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002602
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002603 if (!ReceiverTypeInfo)
2604 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2605
Fangrui Song6907ce22018-07-30 19:24:48 +00002606 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002607 /*SuperLoc=*/SourceLocation(), Sel,
2608 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2609 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002610}
2611
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002612ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2613 QualType ReceiverType,
2614 SourceLocation Loc,
2615 Selector Sel,
2616 ObjCMethodDecl *Method,
2617 MultiExprArg Args) {
2618 return BuildInstanceMessage(Receiver, ReceiverType,
2619 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2620 Sel, Method, Loc, Loc, Loc, Args,
2621 /*isImplicit=*/true);
2622}
2623
Alex Lorenz5e895cf2017-03-15 17:16:41 +00002624static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) {
2625 if (!S.NSAPIObj)
2626 return false;
2627 const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext());
2628 if (!Protocol)
2629 return false;
2630 const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
2631 if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002632 S.LookupSingleName(S.TUScope, II, Protocol->getBeginLoc(),
Alex Lorenz5e895cf2017-03-15 17:16:41 +00002633 Sema::LookupOrdinaryName))) {
2634 for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) {
2635 if (P->getCanonicalDecl() == Protocol->getCanonicalDecl())
2636 return true;
2637 }
2638 }
2639 return false;
2640}
2641
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002642/// Build an Objective-C instance message expression.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002643///
2644/// This routine takes care of both normal instance messages and
2645/// instance messages to the superclass instance.
2646///
2647/// \param Receiver The expression that computes the object that will
2648/// receive this message. This may be empty, in which case we are
2649/// sending to the superclass instance and \p SuperLoc must be a valid
2650/// source location.
2651///
2652/// \param ReceiverType The (static) type of the object receiving the
2653/// message. When a \p Receiver expression is provided, this is the
2654/// same type as that expression. For a superclass instance send, this
2655/// is a pointer to the type of the superclass.
2656///
2657/// \param SuperLoc The location of the "super" keyword in a
2658/// superclass instance message.
2659///
2660/// \param Sel The selector to which the message is being sent.
2661///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002662/// \param Method The method that this instance message is invoking, if
2663/// already known.
2664///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002665/// \param LBracLoc The location of the opening square bracket ']'.
2666///
James Dennettffad8b72012-06-22 08:10:18 +00002667/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002668///
James Dennettffad8b72012-06-22 08:10:18 +00002669/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002670ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002671 QualType ReceiverType,
2672 SourceLocation SuperLoc,
2673 Selector Sel,
2674 ObjCMethodDecl *Method,
Fangrui Song6907ce22018-07-30 19:24:48 +00002675 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002676 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002677 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002678 MultiExprArg ArgsIn,
2679 bool isImplicit) {
Chandler Carruth3d402842016-11-04 06:11:54 +00002680 assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
2681 "SuperLoc must be valid so we can "
2682 "use it instead.");
2683
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002684 // The location of the receiver.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002685 SourceLocation Loc = SuperLoc.isValid() ? SuperLoc : Receiver->getBeginLoc();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002686 SourceRange RecRange =
2687 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002688 ArrayRef<SourceLocation> SelectorSlotLocs;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002689 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002690 SelectorSlotLocs = SelectorLocs;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002691 else
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002692 SelectorSlotLocs = Loc;
2693 SourceLocation SelLoc = SelectorSlotLocs.front();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002694
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002695 if (LBracLoc.isInvalid()) {
2696 Diag(Loc, diag::err_missing_open_square_message_send)
2697 << FixItHint::CreateInsertion(Loc, "[");
2698 LBracLoc = Loc;
2699 }
2700
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002701 // If we have a receiver expression, perform appropriate promotions
2702 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002703 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002704 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002705 ExprResult Result;
2706 if (Receiver->getType() == Context.UnknownAnyTy)
2707 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2708 else
2709 Result = CheckPlaceholderExpr(Receiver);
2710 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002711 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002712 }
2713
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002714 if (Receiver->isTypeDependent()) {
2715 // If the receiver is type-dependent, we can't type-check anything
2716 // at this point. Build a dependent expression.
2717 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002718 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002719 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002720 return ObjCMessageExpr::Create(
2721 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2722 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2723 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002724 }
2725
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002726 // If necessary, apply function/array conversion to the receiver.
2727 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002728 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2729 if (Result.isInvalid())
2730 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002731 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002732 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002733
2734 // If the receiver is an ObjC pointer, a block pointer, or an
2735 // __attribute__((NSObject)) pointer, we don't need to do any
2736 // special conversion in order to look up a receiver.
2737 if (ReceiverType->isObjCRetainableType()) {
2738 // do nothing
2739 } else if (!getLangOpts().ObjCAutoRefCount &&
2740 !Context.getObjCIdType().isNull() &&
Fangrui Song6907ce22018-07-30 19:24:48 +00002741 (ReceiverType->isPointerType() ||
John McCall80c93a02013-03-01 09:20:14 +00002742 ReceiverType->isIntegerType())) {
2743 // Implicitly convert integers and pointers to 'id' but emit a warning.
2744 // But not in ARC.
2745 Diag(Loc, diag::warn_bad_receiver_type)
Fangrui Song6907ce22018-07-30 19:24:48 +00002746 << ReceiverType
John McCall80c93a02013-03-01 09:20:14 +00002747 << Receiver->getSourceRange();
2748 if (ReceiverType->isPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002749 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002750 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002751 } else {
2752 // TODO: specialized warning on null receivers?
2753 bool IsNull = Receiver->isNullPointerConstant(Context,
2754 Expr::NPC_ValueDependentIsNull);
2755 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2756 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002757 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002758 }
2759 ReceiverType = Receiver->getType();
2760 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002761 // The receiver must be a complete type.
2762 if (RequireCompleteType(Loc, Receiver->getType(),
2763 diag::err_incomplete_receiver_type))
2764 return ExprError();
2765
John McCall80c93a02013-03-01 09:20:14 +00002766 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2767 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002768 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002769 ReceiverType = Receiver->getType();
2770 }
2771 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002772 }
2773
Alex Lorenzd9f12842017-08-25 16:12:17 +00002774 if (ReceiverType->isObjCIdType() && !isImplicit)
2775 Diag(Receiver->getExprLoc(), diag::warn_messaging_unqualified_id);
2776
John McCall80c93a02013-03-01 09:20:14 +00002777 // There's a somewhat weird interaction here where we assume that we
2778 // won't actually have a method unless we also don't need to do some
2779 // of the more detailed type-checking on the receiver.
2780
Douglas Gregorb5186b12010-04-22 17:01:48 +00002781 if (!Method) {
Douglas Gregorab209d82015-07-07 03:58:42 +00002782 // Handle messages to id and __kindof types (where we use the
2783 // global method pool).
Douglas Gregorab209d82015-07-07 03:58:42 +00002784 const ObjCObjectType *typeBound = nullptr;
2785 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2786 typeBound);
2787 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002788 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
Manman Rend2a3cd72016-04-07 19:30:20 +00002789 SmallVector<ObjCMethodDecl*, 4> Methods;
Manman Ren7ed4f982016-04-07 19:32:24 +00002790 // If we have a type bound, further filter the methods.
Manman Rend2a3cd72016-04-07 19:30:20 +00002791 CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
Manman Ren7ed4f982016-04-07 19:32:24 +00002792 true/*CheckTheOther*/, typeBound);
Manman Rend2a3cd72016-04-07 19:30:20 +00002793 if (!Methods.empty()) {
George Burgess IV52d07de2016-09-01 01:26:58 +00002794 // We choose the first method as the initial candidate, then try to
Manman Rend2a3cd72016-04-07 19:30:20 +00002795 // select a better one.
2796 Method = Methods[0];
2797
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002798 if (ObjCMethodDecl *BestMethod =
Manman Rend2a3cd72016-04-07 19:30:20 +00002799 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002800 Method = BestMethod;
Manman Rend2a3cd72016-04-07 19:30:20 +00002801
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002802 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2803 SourceRange(LBracLoc, RBracLoc),
Manman Rend2a3cd72016-04-07 19:30:20 +00002804 receiverIsIdLike, Methods))
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002805 DiagnoseUseOfDecl(Method, SelectorSlotLocs);
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002806 }
Douglas Gregorab209d82015-07-07 03:58:42 +00002807 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002808 ReceiverType->isObjCQualifiedClassType()) {
2809 // Handle messages to Class.
Nico Weber2e0c8f72014-12-27 03:58:08 +00002810 // We allow sending a message to a qualified Class ("Class<foo>"), which
2811 // is ok as long as one of the protocols implements the selector (if not,
2812 // warn).
Douglas Gregorab209d82015-07-07 03:58:42 +00002813 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2814 const ObjCObjectPointerType *QClassTy
2815 = ReceiverType->getAsObjCQualifiedClassType();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002816 // Search protocols for class methods.
2817 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2818 if (!Method) {
2819 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2820 // warn if instance method found for a Class message.
Alex Lorenz5e895cf2017-03-15 17:16:41 +00002821 if (Method && !isMethodDeclaredInRootProtocol(*this, Method)) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002822 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002823 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002824 Diag(Method->getLocation(), diag::note_method_declared_at)
2825 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002826 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002827 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002828 } else {
2829 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2830 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
Erik Pilkington30628872019-02-04 23:30:57 +00002831 // As a guess, try looking for the method in the current interface.
2832 // This very well may not produce the "right" method.
Erik Pilkington42578572018-09-10 22:20:09 +00002833
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002834 // First check the public methods in the class interface.
2835 Method = ClassDecl->lookupClassMethod(Sel);
2836
2837 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002838 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Erik Pilkington42578572018-09-10 22:20:09 +00002839
Erik Pilkington30628872019-02-04 23:30:57 +00002840 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
Erik Pilkington42578572018-09-10 22:20:09 +00002841 return ExprError();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002842 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002843 }
2844 if (!Method) {
2845 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002846 if (!Receiver || !isSelfExpr(Receiver)) {
Manman Rend2a3cd72016-04-07 19:30:20 +00002847 // If no class (factory) method was found, check if an _instance_
2848 // method of the same name exists in the root class only.
2849 SmallVector<ObjCMethodDecl*, 4> Methods;
2850 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2851 false/*InstanceFirst*/,
2852 true/*CheckTheOther*/);
2853 if (!Methods.empty()) {
George Burgess IV52d07de2016-09-01 01:26:58 +00002854 // We choose the first method as the initial candidate, then try
Manman Rend2a3cd72016-04-07 19:30:20 +00002855 // to select a better one.
2856 Method = Methods[0];
2857
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002858 // If we find an instance method, emit warning.
Manman Rend2a3cd72016-04-07 19:30:20 +00002859 if (Method->isInstanceMethod()) {
2860 if (const ObjCInterfaceDecl *ID =
2861 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2862 if (ID->getSuperClass())
2863 Diag(SelLoc, diag::warn_root_inst_method_not_found)
2864 << Sel << SourceRange(LBracLoc, RBracLoc);
2865 }
2866 }
2867
2868 if (ObjCMethodDecl *BestMethod =
2869 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2870 Methods))
2871 Method = BestMethod;
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002872 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002873 }
2874 }
2875 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002876 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002877 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002878
2879 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2880 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002881 // And as long as message is not deprecated/unavailable (warn if it is).
Fangrui Song6907ce22018-07-30 19:24:48 +00002882 if (const ObjCObjectPointerType *QIdTy
Douglas Gregorb5186b12010-04-22 17:01:48 +00002883 = ReceiverType->getAsObjCQualifiedIdType()) {
2884 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002885 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2886 if (!Method)
2887 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002888 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002889 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002890 } else if (const ObjCObjectPointerType *OCIType
2891 = ReceiverType->getAsObjCInterfacePointerType()) {
2892 // We allow sending a message to a pointer to an interface (an object).
2893 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002894
Douglas Gregor4123a862011-11-14 22:10:01 +00002895 // Try to complete the type. Under ARC, this is a hard error from which
2896 // we don't try to recover.
Richard Smithdb0ac552015-12-18 22:40:25 +00002897 // FIXME: In the non-ARC case, this will still be a hard error if the
2898 // definition is found in a module that's not visible.
Craig Topperc3ec1492014-05-26 06:22:03 +00002899 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002900 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002901 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002902 ? diag::err_arc_receiver_forward_instance
2903 : diag::warn_receiver_forward_instance,
2904 Receiver? Receiver->getSourceRange()
2905 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002906 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002907 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002908
Douglas Gregor4123a862011-11-14 22:10:01 +00002909 forwardClass = OCIType->getInterfaceDecl();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002910 Diag(Receiver ? Receiver->getBeginLoc() : SuperLoc,
2911 diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002912 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002913 } else {
2914 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002915 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002916
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002917 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002918 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002919 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00002920
Douglas Gregorb5186b12010-04-22 17:01:48 +00002921 if (!Method) {
2922 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002923 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002924
David Blaikiebbafb8a2012-03-11 07:00:24 +00002925 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002926 Diag(SelLoc, diag::err_arc_may_not_respond)
2927 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002928 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002929 return ExprError();
2930 }
2931
Douglas Gregor486b74e2011-09-27 16:10:05 +00002932 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002933 // If we still haven't found a method, look in the global pool. This
2934 // behavior isn't very desirable, however we need it for GCC
2935 // compatibility. FIXME: should we deviate??
2936 if (OCIType->qual_empty()) {
Manman Rend2a3cd72016-04-07 19:30:20 +00002937 SmallVector<ObjCMethodDecl*, 4> Methods;
2938 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2939 true/*InstanceFirst*/,
2940 false/*CheckTheOther*/);
2941 if (!Methods.empty()) {
George Burgess IV52d07de2016-09-01 01:26:58 +00002942 // We choose the first method as the initial candidate, then try
Manman Rend2a3cd72016-04-07 19:30:20 +00002943 // to select a better one.
2944 Method = Methods[0];
2945
2946 if (ObjCMethodDecl *BestMethod =
2947 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2948 Methods))
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002949 Method = BestMethod;
Manman Rend2a3cd72016-04-07 19:30:20 +00002950
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002951 AreMultipleMethodsInGlobalPool(Sel, Method,
2952 SourceRange(LBracLoc, RBracLoc),
Manman Rend2a3cd72016-04-07 19:30:20 +00002953 true/*receiverIdOrClass*/,
2954 Methods);
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002955 }
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002956 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002957 Diag(SelLoc, diag::warn_maynot_respond)
2958 << OCIType->getInterfaceDecl()->getIdentifier()
2959 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002960 }
2961 }
2962 }
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002963 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002964 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002965 } else {
John McCall80c93a02013-03-01 09:20:14 +00002966 // Reject other random receiver types (e.g. structs).
2967 Diag(Loc, diag::err_bad_receiver_type)
2968 << ReceiverType << Receiver->getSourceRange();
2969 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002970 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002971 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002972 }
Mike Stump11289f42009-09-09 15:08:12 +00002973
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002974 FunctionScopeInfo *DIFunctionScopeInfo =
2975 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002976 ? getEnclosingFunction() : nullptr;
2977
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002978 if (DIFunctionScopeInfo &&
2979 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002980 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2981 bool isDesignatedInitChain = false;
2982 if (SuperLoc.isValid()) {
2983 if (const ObjCObjectPointerType *
2984 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2985 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002986 // Either we know this is a designated initializer or we
2987 // conservatively assume it because we don't know for sure.
2988 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2989 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002990 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002991 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002992 }
2993 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002994 }
2995 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002996 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002997 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002998 bool isDesignated =
2999 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
3000 assert(isDesignated && InitMethod);
3001 (void)isDesignated;
3002 Diag(SelLoc, SuperLoc.isValid() ?
3003 diag::warn_objc_designated_init_non_designated_init_call :
3004 diag::warn_objc_designated_init_non_super_designated_init_call);
3005 Diag(InitMethod->getLocation(),
3006 diag::note_objc_designated_init_marked_here);
3007 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00003008 }
3009
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00003010 if (DIFunctionScopeInfo &&
3011 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00003012 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
3013 if (SuperLoc.isValid()) {
3014 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
3015 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00003016 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00003017 }
3018 }
3019
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003020 // Check the message arguments.
3021 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003022 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003023 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00003024 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00003025 bool ClassMessage = (ReceiverType->isObjCClassType() ||
3026 ReceiverType->isObjCQualifiedClassType());
Alex Lorenzf50d1ac2018-12-20 22:11:11 +00003027 if (CheckMessageArgumentTypes(Receiver, ReceiverType,
3028 MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
3029 Method, ClassMessage, SuperLoc.isValid(),
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00003030 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003031 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00003032
3033 if (Method && !Method->getReturnType()->isVoidType() &&
3034 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00003035 diag::err_illegal_message_expr_incomplete_type))
3036 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00003037
Fangrui Song6907ce22018-07-30 19:24:48 +00003038 // In ARC, forbid the user from sending messages to
John McCall31168b02011-06-15 23:02:42 +00003039 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003040 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00003041 ObjCMethodFamily family =
3042 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
3043 switch (family) {
3044 case OMF_init:
3045 if (Method)
3046 checkInitMethod(Method, ReceiverType);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003047 break;
John McCall31168b02011-06-15 23:02:42 +00003048
3049 case OMF_None:
3050 case OMF_alloc:
3051 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00003052 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00003053 case OMF_mutableCopy:
3054 case OMF_new:
3055 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00003056 case OMF_initialize:
John McCall31168b02011-06-15 23:02:42 +00003057 break;
3058
3059 case OMF_dealloc:
3060 case OMF_retain:
3061 case OMF_release:
3062 case OMF_autorelease:
3063 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00003064 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
3065 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00003066 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00003067
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003068 case OMF_performSelector:
3069 if (Method && NumArgs >= 1) {
Alex Lorenz51c01282017-02-20 17:55:15 +00003070 if (const auto *SelExp =
3071 dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003072 Selector ArgSel = SelExp->getSelector();
Fangrui Song6907ce22018-07-30 19:24:48 +00003073 ObjCMethodDecl *SelMethod =
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003074 LookupInstanceMethodInGlobalPool(ArgSel,
3075 SelExp->getSourceRange());
3076 if (!SelMethod)
3077 SelMethod =
3078 LookupFactoryMethodInGlobalPool(ArgSel,
3079 SelExp->getSourceRange());
3080 if (SelMethod) {
3081 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
3082 switch (SelFamily) {
3083 case OMF_alloc:
3084 case OMF_copy:
3085 case OMF_mutableCopy:
3086 case OMF_new:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003087 case OMF_init:
3088 // Issue error, unless ns_returns_not_retained.
3089 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003090 // selector names a +1 method
3091 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003092 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00003093 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3094 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003095 }
3096 break;
3097 default:
3098 // +0 call. OK. unless ns_returns_retained.
3099 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
3100 // selector names a +1 method
Fangrui Song6907ce22018-07-30 19:24:48 +00003101 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003102 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00003103 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3104 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003105 }
3106 break;
3107 }
3108 }
3109 } else {
3110 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003111 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003112 Diag(Args[0]->getExprLoc(), diag::note_used_here);
3113 }
3114 }
3115 break;
John McCall31168b02011-06-15 23:02:42 +00003116 }
3117 }
3118
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003119 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
Fangrui Song6907ce22018-07-30 19:24:48 +00003120
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003121 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00003122 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003123 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00003124 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00003125 SuperLoc, /*IsInstanceSuper=*/true,
Fangrui Song6907ce22018-07-30 19:24:48 +00003126 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00003127 makeArrayRef(Args, NumArgs), RBracLoc,
3128 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00003129 else {
John McCall7decc9e2010-11-18 06:31:45 +00003130 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003131 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00003132 makeArrayRef(Args, NumArgs), RBracLoc,
3133 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00003134 if (!isImplicit)
3135 checkCocoaAPI(*this, Result);
3136 }
Alex Lorenz0e23c612017-03-06 15:58:34 +00003137 if (Method) {
3138 bool IsClassObjectCall = ClassMessage;
3139 // 'self' message receivers in class methods should be treated as message
3140 // sends to the class object in order for the semantic checks to be
3141 // performed correctly. Messages to 'super' already count as class messages,
3142 // so they don't need to be handled here.
3143 if (Receiver && isSelfExpr(Receiver)) {
3144 if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
3145 if (OPT->getObjectType()->isObjCClass()) {
3146 if (const auto *CurMeth = getCurMethodDecl()) {
3147 IsClassObjectCall = true;
3148 ReceiverType =
3149 Context.getObjCInterfaceType(CurMeth->getClassInterface());
3150 }
3151 }
3152 }
3153 }
3154 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
3155 ReceiverType, IsClassObjectCall);
3156 }
John McCall31168b02011-06-15 23:02:42 +00003157
David Blaikiebbafb8a2012-03-11 07:00:24 +00003158 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00003159 // In ARC, annotate delegate init calls.
3160 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00003161 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00003162 // Only consider init calls *directly* in init implementations,
3163 // not within blocks.
3164 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
3165 if (method && method->getMethodFamily() == OMF_init) {
3166 // The implicit assignment to self means we also don't want to
3167 // consume the result.
3168 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003169 return Result;
John McCall31168b02011-06-15 23:02:42 +00003170 }
3171 }
3172
3173 // In ARC, check for message sends which are likely to introduce
3174 // retain cycles.
3175 checkRetainCycles(Result);
Brian Kelleycafd9122017-03-29 17:55:11 +00003176 }
Jordan Rose22487652012-10-11 16:06:21 +00003177
Brian Kelleycafd9122017-03-29 17:55:11 +00003178 if (getLangOpts().ObjCWeak) {
Jordan Rose22487652012-10-11 16:06:21 +00003179 if (!isImplicit && Method) {
3180 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
3181 bool IsWeak =
3182 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
3183 if (!IsWeak && Sel.isUnarySelector())
3184 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Akira Hatanaka0a848562019-01-10 20:12:16 +00003185 if (IsWeak && !isUnevaluatedContext() &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003186 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
3187 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00003188 }
3189 }
John McCall31168b02011-06-15 23:02:42 +00003190 }
Alex Denisove1d882c2015-03-04 17:55:52 +00003191
3192 CheckObjCCircularContainer(Result);
3193
Douglas Gregoraae38d62010-05-22 05:17:18 +00003194 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003195}
3196
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003197static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
3198 if (ObjCSelectorExpr *OSE =
3199 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
3200 Selector Sel = OSE->getSelector();
3201 SourceLocation Loc = OSE->getAtLoc();
Chandler Carruth12c8f652015-03-27 00:55:05 +00003202 auto Pos = S.ReferencedSelectors.find(Sel);
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003203 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3204 S.ReferencedSelectors.erase(Pos);
3205 }
3206}
3207
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003208// ActOnInstanceMessage - used for both unary and keyword messages.
3209// ArgExprs is optional - if it is present, the number of expressions
3210// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00003211ExprResult Sema::ActOnInstanceMessage(Scope *S,
Fangrui Song6907ce22018-07-30 19:24:48 +00003212 Expr *Receiver,
John McCalldadc5752010-08-24 06:29:42 +00003213 Selector Sel,
3214 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003215 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00003216 SourceLocation RBracLoc,
3217 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003218 if (!Receiver)
3219 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00003220
3221 // A ParenListExpr can show up while doing error recovery with invalid code.
3222 if (isa<ParenListExpr>(Receiver)) {
3223 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3224 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003225 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00003226 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003227
Fariborz Jahanian17748062013-01-22 19:05:17 +00003228 if (RespondsToSelectorSel.isNull()) {
3229 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3230 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3231 }
3232 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003233 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00003234
John McCallb268a282010-08-23 23:25:46 +00003235 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003236 /*SuperLoc=*/SourceLocation(), Sel,
3237 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3238 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00003239}
Chris Lattner2a3569b2008-04-07 05:30:13 +00003240
John McCall31168b02011-06-15 23:02:42 +00003241enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00003242 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00003243 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00003244
3245 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00003246 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00003247
3248 /// id*, id***, void (^*)(),
3249 ACTC_indirectRetainable,
3250
3251 /// void* might be a normal C type, or it might a CF type.
3252 ACTC_voidPtr,
3253
3254 /// struct A*
3255 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00003256};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003257
John McCalle4fe2452011-10-01 01:01:08 +00003258static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3259 return (ACTC == ACTC_retainable ||
3260 ACTC == ACTC_coreFoundation ||
3261 ACTC == ACTC_voidPtr);
3262}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003263
John McCalle4fe2452011-10-01 01:01:08 +00003264static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3265 return ACTC == ACTC_none ||
3266 ACTC == ACTC_voidPtr ||
3267 ACTC == ACTC_coreFoundation;
3268}
3269
John McCall31168b02011-06-15 23:02:42 +00003270static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00003271 bool isIndirect = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003272
John McCall31168b02011-06-15 23:02:42 +00003273 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00003274 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00003275 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003276 isIndirect = true;
3277 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003278
John McCall31168b02011-06-15 23:02:42 +00003279 // Drill through pointers and arrays recursively.
3280 while (true) {
3281 if (const PointerType *ptr = type->getAs<PointerType>()) {
3282 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003283
3284 // The first level of pointer may be the innermost pointer on a CF type.
3285 if (!isIndirect) {
3286 if (type->isVoidType()) return ACTC_voidPtr;
3287 if (type->isRecordType()) return ACTC_coreFoundation;
3288 }
John McCall31168b02011-06-15 23:02:42 +00003289 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3290 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3291 } else {
3292 break;
3293 }
John McCalle4fe2452011-10-01 01:01:08 +00003294 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00003295 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003296
John McCalle4fe2452011-10-01 01:01:08 +00003297 if (isIndirect) {
3298 if (type->isObjCARCBridgableType())
3299 return ACTC_indirectRetainable;
3300 return ACTC_none;
3301 }
3302
3303 if (type->isObjCARCBridgableType())
3304 return ACTC_retainable;
3305
3306 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00003307}
3308
3309namespace {
John McCalle4fe2452011-10-01 01:01:08 +00003310 /// A result from the cast checker.
3311 enum ACCResult {
3312 /// Cannot be casted.
3313 ACC_invalid,
3314
3315 /// Can be safely retained or not retained.
3316 ACC_bottom,
3317
3318 /// Can be casted at +0.
3319 ACC_plusZero,
3320
3321 /// Can be casted at +1.
3322 ACC_plusOne
3323 };
3324 ACCResult merge(ACCResult left, ACCResult right) {
3325 if (left == right) return left;
3326 if (left == ACC_bottom) return right;
3327 if (right == ACC_bottom) return left;
3328 return ACC_invalid;
3329 }
3330
3331 /// A checker which white-lists certain expressions whose conversion
3332 /// to or from retainable type would otherwise be forbidden in ARC.
3333 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3334 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3335
John McCall31168b02011-06-15 23:02:42 +00003336 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00003337 ARCConversionTypeClass SourceClass;
3338 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003339 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00003340
3341 static bool isCFType(QualType type) {
3342 // Someday this can use ns_bridged. For now, it has to do this.
3343 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00003344 }
John McCalle4fe2452011-10-01 01:01:08 +00003345
3346 public:
3347 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003348 ARCConversionTypeClass target, bool diagnose)
3349 : Context(Context), SourceClass(source), TargetClass(target),
3350 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00003351
3352 using super::Visit;
3353 ACCResult Visit(Expr *e) {
3354 return super::Visit(e->IgnoreParens());
3355 }
3356
3357 ACCResult VisitStmt(Stmt *s) {
3358 return ACC_invalid;
3359 }
3360
3361 /// Null pointer constants can be casted however you please.
3362 ACCResult VisitExpr(Expr *e) {
3363 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3364 return ACC_bottom;
3365 return ACC_invalid;
3366 }
3367
3368 /// Objective-C string literals can be safely casted.
3369 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3370 // If we're casting to any retainable type, go ahead. Global
3371 // strings are immune to retains, so this is bottom.
3372 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3373
3374 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003375 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003376
John McCalle4fe2452011-10-01 01:01:08 +00003377 /// Look through certain implicit and explicit casts.
3378 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003379 switch (e->getCastKind()) {
3380 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00003381 return ACC_bottom;
3382
John McCall31168b02011-06-15 23:02:42 +00003383 case CK_NoOp:
3384 case CK_LValueToRValue:
3385 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003386 case CK_CPointerToObjCPointerCast:
3387 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00003388 case CK_AnyPointerToBlockPointerCast:
3389 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00003390
John McCall31168b02011-06-15 23:02:42 +00003391 default:
John McCalle4fe2452011-10-01 01:01:08 +00003392 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003393 }
3394 }
John McCalle4fe2452011-10-01 01:01:08 +00003395
3396 /// Look through unary extension.
3397 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003398 return Visit(e->getSubExpr());
3399 }
John McCalle4fe2452011-10-01 01:01:08 +00003400
3401 /// Ignore the LHS of a comma operator.
3402 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003403 return Visit(e->getRHS());
3404 }
John McCalle4fe2452011-10-01 01:01:08 +00003405
3406 /// Conditional operators are okay if both sides are okay.
3407 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3408 ACCResult left = Visit(e->getTrueExpr());
3409 if (left == ACC_invalid) return ACC_invalid;
3410 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00003411 }
John McCalle4fe2452011-10-01 01:01:08 +00003412
John McCallfe96e0b2011-11-06 09:01:30 +00003413 /// Look through pseudo-objects.
3414 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3415 // If we're getting here, we should always have a result.
3416 return Visit(e->getResultExpr());
3417 }
3418
John McCalle4fe2452011-10-01 01:01:08 +00003419 /// Statement expressions are okay if their result expression is okay.
3420 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003421 return Visit(e->getSubStmt()->body_back());
3422 }
John McCall31168b02011-06-15 23:02:42 +00003423
John McCalle4fe2452011-10-01 01:01:08 +00003424 /// Some declaration references are okay.
3425 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
John McCalle4fe2452011-10-01 01:01:08 +00003426 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003427 // References to global constants are okay.
John McCalle4fe2452011-10-01 01:01:08 +00003428 if (isAnyRetainable(TargetClass) &&
3429 isAnyRetainable(SourceClass) &&
3430 var &&
Akira Hatanakaad515392017-04-11 22:01:33 +00003431 !var->hasDefinition(Context) &&
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003432 var->getType().isConstQualified()) {
3433
3434 // In system headers, they can also be assumed to be immune to retains.
3435 // These are things like 'kCFStringTransformToLatin'.
3436 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3437 return ACC_bottom;
3438
3439 return ACC_plusZero;
John McCalle4fe2452011-10-01 01:01:08 +00003440 }
3441
3442 // Nothing else.
3443 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00003444 }
John McCalle4fe2452011-10-01 01:01:08 +00003445
3446 /// Some calls are okay.
3447 ACCResult VisitCallExpr(CallExpr *e) {
3448 if (FunctionDecl *fn = e->getDirectCallee())
3449 if (ACCResult result = checkCallToFunction(fn))
3450 return result;
3451
3452 return super::VisitCallExpr(e);
3453 }
3454
3455 ACCResult checkCallToFunction(FunctionDecl *fn) {
3456 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00003457 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003458 return ACC_invalid;
3459
3460 if (!isAnyRetainable(TargetClass))
3461 return ACC_invalid;
3462
3463 // Honor an explicit 'not retained' attribute.
3464 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3465 return ACC_plusZero;
3466
3467 // Honor an explicit 'retained' attribute, except that for
3468 // now we're not going to permit implicit handling of +1 results,
3469 // because it's a bit frightening.
3470 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003471 return Diagnose ? ACC_plusOne
3472 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003473
3474 // Recognize this specific builtin function, which is used by CFSTR.
3475 unsigned builtinID = fn->getBuiltinID();
3476 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3477 return ACC_bottom;
3478
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003479 // Otherwise, don't do anything implicit with an unaudited function.
3480 if (!fn->hasAttr<CFAuditedTransferAttr>())
3481 return ACC_invalid;
Fangrui Song6907ce22018-07-30 19:24:48 +00003482
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003483 // Otherwise, it's +0 unless it follows the create convention.
3484 if (ento::coreFoundation::followsCreateRule(fn))
Fangrui Song6907ce22018-07-30 19:24:48 +00003485 return Diagnose ? ACC_plusOne
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003486 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003487
John McCalle4fe2452011-10-01 01:01:08 +00003488 return ACC_plusZero;
3489 }
3490
3491 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3492 return checkCallToMethod(e->getMethodDecl());
3493 }
3494
3495 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3496 ObjCMethodDecl *method;
3497 if (e->isExplicitProperty())
3498 method = e->getExplicitProperty()->getGetterMethodDecl();
3499 else
3500 method = e->getImplicitPropertyGetter();
3501 return checkCallToMethod(method);
3502 }
3503
3504 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3505 if (!method) return ACC_invalid;
3506
3507 // Check for message sends to functions returning CF types. We
3508 // just obey the Cocoa conventions with these, even though the
3509 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003510 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003511 return ACC_invalid;
Fangrui Song6907ce22018-07-30 19:24:48 +00003512
John McCalle4fe2452011-10-01 01:01:08 +00003513 // If the method is explicitly marked not-retained, it's +0.
3514 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3515 return ACC_plusZero;
3516
3517 // If the method is explicitly marked as returning retained, or its
3518 // selector follows a +1 Cocoa convention, treat it as +1.
3519 if (method->hasAttr<CFReturnsRetainedAttr>())
3520 return ACC_plusOne;
3521
3522 switch (method->getSelector().getMethodFamily()) {
3523 case OMF_alloc:
3524 case OMF_copy:
3525 case OMF_mutableCopy:
3526 case OMF_new:
3527 return ACC_plusOne;
3528
3529 default:
3530 // Otherwise, treat it as +0.
3531 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003532 }
3533 }
John McCalle4fe2452011-10-01 01:01:08 +00003534 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003535} // end anonymous namespace
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003536
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003537bool Sema::isKnownName(StringRef name) {
3538 if (name.empty())
3539 return false;
3540 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003541 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003542 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003543}
3544
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003545static void addFixitForObjCARCConversion(Sema &S,
3546 DiagnosticBuilder &DiagB,
3547 Sema::CheckedConversionKind CCK,
3548 SourceLocation afterLParen,
3549 QualType castType,
3550 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003551 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003552 const char *bridgeKeyword,
3553 const char *CFBridgeName) {
3554 // We handle C-style and implicit casts here.
3555 switch (CCK) {
3556 case Sema::CCK_ImplicitConversion:
Richard Smith1ef75542018-06-27 20:30:34 +00003557 case Sema::CCK_ForBuiltinOverloadedOp:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003558 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003559 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003560 break;
3561 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003562 return;
3563 }
3564
3565 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003566 if (CCK == Sema::CCK_OtherCast) {
3567 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3568 SourceRange range(NCE->getOperatorLoc(),
3569 NCE->getAngleBrackets().getEnd());
3570 SmallString<32> BridgeCall;
Fangrui Song6907ce22018-07-30 19:24:48 +00003571
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003572 SourceManager &SM = S.getSourceManager();
3573 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3574 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3575 BridgeCall += ' ';
Fangrui Song6907ce22018-07-30 19:24:48 +00003576
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003577 BridgeCall += CFBridgeName;
3578 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3579 }
3580 return;
3581 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003582 Expr *castedE = castExpr;
3583 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3584 castedE = CCE->getSubExpr();
3585 castedE = castedE->IgnoreImpCasts();
3586 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003587
3588 SmallString<32> BridgeCall;
3589
3590 SourceManager &SM = S.getSourceManager();
3591 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3592 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3593 BridgeCall += ' ';
3594
3595 BridgeCall += CFBridgeName;
3596
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003597 if (isa<ParenExpr>(castedE)) {
3598 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003599 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003600 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003601 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003602 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003603 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003604 DiagB.AddFixItHint(FixItHint::CreateInsertion(
Craig Topper07fa1762015-11-15 02:31:46 +00003605 S.getLocForEndOfToken(range.getEnd()),
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003606 ")"));
3607 }
3608 return;
3609 }
3610
3611 if (CCK == Sema::CCK_CStyleCast) {
3612 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003613 } else if (CCK == Sema::CCK_OtherCast) {
3614 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3615 std::string castCode = "(";
3616 castCode += bridgeKeyword;
3617 castCode += castType.getAsString();
3618 castCode += ")";
3619 SourceRange Range(NCE->getOperatorLoc(),
3620 NCE->getAngleBrackets().getEnd());
3621 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3622 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003623 } else {
3624 std::string castCode = "(";
3625 castCode += bridgeKeyword;
3626 castCode += castType.getAsString();
3627 castCode += ")";
3628 Expr *castedE = castExpr->IgnoreImpCasts();
3629 SourceRange range = castedE->getSourceRange();
3630 if (isa<ParenExpr>(castedE)) {
3631 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3632 castCode));
3633 } else {
3634 castCode += "(";
3635 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3636 castCode));
3637 DiagB.AddFixItHint(FixItHint::CreateInsertion(
Craig Topper07fa1762015-11-15 02:31:46 +00003638 S.getLocForEndOfToken(range.getEnd()),
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003639 ")"));
3640 }
3641 }
3642}
3643
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003644template <typename T>
3645static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3646 TypedefNameDecl *TDNDecl = TD->getDecl();
3647 QualType QT = TDNDecl->getUnderlyingType();
3648 if (QT->isPointerType()) {
3649 QT = QT->getPointeeType();
3650 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003651 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003652 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003653 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003654 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003655}
3656
3657static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3658 TypedefNameDecl *&TDNDecl) {
3659 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3660 TDNDecl = TD->getDecl();
3661 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3662 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3663 return ObjCBAttr;
3664 T = TDNDecl->getUnderlyingType();
3665 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003666 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003667}
3668
John McCall4124c492011-10-17 18:40:02 +00003669static void
3670diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3671 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003672 Expr *castExpr, Expr *realCast,
3673 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003674 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003675 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003676 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00003677
John McCall4124c492011-10-17 18:40:02 +00003678 if (S.makeUnavailableInSystemHeader(loc,
John McCallc6af8c62015-10-28 05:03:19 +00003679 UnavailableAttr::IR_ARCForbiddenConversion))
John McCall31168b02011-06-15 23:02:42 +00003680 return;
John McCall4124c492011-10-17 18:40:02 +00003681
3682 QualType castExprType = castExpr->getType();
Bob Wilsonf5c53b82016-02-13 01:41:41 +00003683 // Defer emitting a diagnostic for bridge-related casts; that will be
3684 // handled by CheckObjCBridgeRelatedConversions.
Craig Topperc3ec1492014-05-26 06:22:03 +00003685 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003686 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3687 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3688 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003689 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003690 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003691
John McCall640767f2011-06-17 06:50:50 +00003692 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003693 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003694 case ACTC_none:
3695 case ACTC_coreFoundation:
3696 case ACTC_voidPtr:
3697 srcKind = (castExprType->isPointerType() ? 1 : 0);
3698 break;
3699 case ACTC_retainable:
3700 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3701 break;
3702 case ACTC_indirectRetainable:
3703 srcKind = 4;
3704 break;
John McCall31168b02011-06-15 23:02:42 +00003705 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003706
John McCall4124c492011-10-17 18:40:02 +00003707 // Check whether this could be fixed with a bridge cast.
Craig Topper07fa1762015-11-15 02:31:46 +00003708 SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
John McCall4124c492011-10-17 18:40:02 +00003709 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003710
Richard Smith1ef75542018-06-27 20:30:34 +00003711 unsigned convKindForDiag = Sema::isCast(CCK) ? 0 : 1;
3712
John McCall4124c492011-10-17 18:40:02 +00003713 // Bridge from an ARC type to a CF type.
3714 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003715
John McCall4124c492011-10-17 18:40:02 +00003716 S.Diag(loc, diag::err_arc_cast_requires_bridge)
Richard Smith1ef75542018-06-27 20:30:34 +00003717 << convKindForDiag
John McCall4124c492011-10-17 18:40:02 +00003718 << 2 // of C pointer type
3719 << castExprType
3720 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3721 << castType
3722 << castRange
3723 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003724 bool br = S.isKnownName("CFBridgingRelease");
Fangrui Song6907ce22018-07-30 19:24:48 +00003725 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003726 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003727 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003728 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003729 {
Fangrui Song6907ce22018-07-30 19:24:48 +00003730 DiagnosticBuilder DiagB =
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003731 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3732 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003733
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003734 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003735 castType, castExpr, realCast, "__bridge ",
3736 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003737 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003738 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003739 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003740 DiagnosticBuilder DiagB =
3741 (CCK == Sema::CCK_OtherCast && !br) ?
3742 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3743 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3744 diag::note_arc_bridge_transfer)
3745 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003746
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003747 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003748 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003749 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003750 }
John McCall4124c492011-10-17 18:40:02 +00003751
3752 return;
3753 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003754
John McCall4124c492011-10-17 18:40:02 +00003755 // Bridge from a CF type to an ARC type.
3756 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003757 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003758 S.Diag(loc, diag::err_arc_cast_requires_bridge)
Richard Smith1ef75542018-06-27 20:30:34 +00003759 << convKindForDiag
John McCall4124c492011-10-17 18:40:02 +00003760 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3761 << castExprType
3762 << 2 // to C pointer type
3763 << castType
3764 << castRange
3765 << castExpr->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00003766 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003767 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003768 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003769 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003770 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003771 DiagnosticBuilder DiagB =
3772 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3773 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003774 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003775 castType, castExpr, realCast, "__bridge ",
3776 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003777 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003778 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003779 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003780 DiagnosticBuilder DiagB =
3781 (CCK == Sema::CCK_OtherCast && !br) ?
3782 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3783 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3784 diag::note_arc_bridge_retained)
3785 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003786
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003787 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003788 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003789 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003790 }
John McCall4124c492011-10-17 18:40:02 +00003791
3792 return;
John McCall31168b02011-06-15 23:02:42 +00003793 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003794
John McCall4124c492011-10-17 18:40:02 +00003795 S.Diag(loc, diag::err_arc_mismatched_cast)
Richard Smith1ef75542018-06-27 20:30:34 +00003796 << !convKindForDiag
John McCall4124c492011-10-17 18:40:02 +00003797 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003798 << castRange << castExpr->getSourceRange();
3799}
3800
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003801template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003802static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3803 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003804 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003805 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003806 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3807 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003808 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003809 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003810 HadTheAttribute = true;
Fariborz Jahanianc9e266b2014-12-11 22:56:26 +00003811 if (Parm->isStr("id"))
3812 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003813
Craig Topperc3ec1492014-05-26 06:22:03 +00003814 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003815 // Check for an existing type with this name.
3816 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3817 Sema::LookupOrdinaryName);
3818 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003819 Target = R.getFoundDecl();
3820 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3821 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3822 if (const ObjCObjectPointerType *InterfacePointerType =
3823 castType->getAsObjCInterfacePointerType()) {
3824 ObjCInterfaceDecl *CastClass
3825 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003826 if ((CastClass == ExprClass) ||
Fariborz Jahanian27aa9b42015-04-10 22:07:47 +00003827 (CastClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003828 return true;
3829 if (warn)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003830 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
3831 << T << Target->getName() << castType->getPointeeType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003832 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003833 } else if (castType->isObjCIdType() ||
3834 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3835 castType, ExprClass)))
3836 // ok to cast to 'id'.
3837 // casting to id<p-list> is ok if bridge type adopts all of
3838 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003839 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003840 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003841 if (warn) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003842 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
3843 << T << Target->getName() << castType;
3844 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3845 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003846 }
3847 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003848 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003849 }
Fariborz Jahanian696c8872015-04-09 23:39:53 +00003850 } else if (!castType->isObjCIdType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003851 S.Diag(castExpr->getBeginLoc(),
3852 diag::err_objc_cf_bridged_not_interface)
3853 << castExpr->getType() << Parm;
3854 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian696c8872015-04-09 23:39:53 +00003855 if (Target)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003856 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003857 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003858 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003859 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003860 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003861 }
3862 T = TDNDecl->getUnderlyingType();
3863 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003864 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003865}
3866
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003867template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003868static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3869 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003870 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003871 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003872 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3873 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003874 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003875 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003876 HadTheAttribute = true;
John McCallaf6b3f82015-03-10 18:41:23 +00003877 if (Parm->isStr("id"))
3878 return true;
3879
Craig Topperc3ec1492014-05-26 06:22:03 +00003880 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003881 // Check for an existing type with this name.
3882 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3883 Sema::LookupOrdinaryName);
3884 if (S.LookupName(R, S.TUScope)) {
3885 Target = R.getFoundDecl();
3886 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3887 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3888 if (const ObjCObjectPointerType *InterfacePointerType =
3889 castExpr->getType()->getAsObjCInterfacePointerType()) {
3890 ObjCInterfaceDecl *ExprClass
3891 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003892 if ((CastClass == ExprClass) ||
3893 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003894 return true;
3895 if (warn) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003896 S.Diag(castExpr->getBeginLoc(),
3897 diag::warn_objc_invalid_bridge_to_cf)
3898 << castExpr->getType()->getPointeeType() << T;
3899 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003900 }
3901 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003902 } else if (castExpr->getType()->isObjCIdType() ||
3903 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3904 castExpr->getType(), CastClass)))
3905 // ok to cast an 'id' expression to a CFtype.
3906 // ok to cast an 'id<plist>' expression to CFtype provided plist
3907 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003908 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003909 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003910 if (warn) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003911 S.Diag(castExpr->getBeginLoc(),
3912 diag::warn_objc_invalid_bridge_to_cf)
3913 << castExpr->getType() << castType;
3914 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3915 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003916 }
3917 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003918 }
3919 }
3920 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003921 S.Diag(castExpr->getBeginLoc(),
3922 diag::err_objc_ns_bridged_invalid_cfobject)
3923 << castExpr->getType() << castType;
3924 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003925 if (Target)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003926 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003927 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003928 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003929 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003930 }
3931 T = TDNDecl->getUnderlyingType();
3932 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003933 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003934}
3935
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003936void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003937 if (!getLangOpts().ObjC)
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003938 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003939 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003940 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3941 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003942 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003943 bool HasObjCBridgeAttr;
3944 bool ObjCBridgeAttrWillNotWarn =
3945 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3946 false);
3947 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3948 return;
3949 bool HasObjCBridgeMutableAttr;
3950 bool ObjCBridgeMutableAttrWillNotWarn =
3951 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3952 HasObjCBridgeMutableAttr, false);
3953 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3954 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003955
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003956 if (HasObjCBridgeAttr)
3957 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3958 true);
3959 else if (HasObjCBridgeMutableAttr)
3960 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3961 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003962 }
3963 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003964 bool HasObjCBridgeAttr;
3965 bool ObjCBridgeAttrWillNotWarn =
3966 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3967 false);
3968 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3969 return;
3970 bool HasObjCBridgeMutableAttr;
3971 bool ObjCBridgeMutableAttrWillNotWarn =
3972 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3973 HasObjCBridgeMutableAttr, false);
3974 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3975 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003976
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003977 if (HasObjCBridgeAttr)
3978 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3979 true);
3980 else if (HasObjCBridgeMutableAttr)
3981 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3982 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003983 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003984}
3985
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003986void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3987 QualType SrcType = castExpr->getType();
3988 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3989 if (PRE->isExplicitProperty()) {
3990 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3991 SrcType = PDecl->getType();
3992 }
3993 else if (PRE->isImplicitProperty()) {
3994 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3995 SrcType = Getter->getReturnType();
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003996 }
3997 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003998
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003999 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
4000 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
4001 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
4002 return;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004003 CheckObjCBridgeRelatedConversions(castExpr->getBeginLoc(), castType, SrcType,
4004 castExpr);
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00004005}
4006
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00004007bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
4008 CastKind &Kind) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004009 if (!getLangOpts().ObjC)
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00004010 return false;
4011 ARCConversionTypeClass exprACTC =
4012 classifyTypeForARCConversion(castExpr->getType());
4013 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
4014 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
4015 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
4016 CheckTollFreeBridgeCast(castType, castExpr);
4017 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
4018 : CK_CPointerToObjCPointerCast;
4019 return true;
4020 }
4021 return false;
4022}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004023
4024bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
4025 QualType DestType, QualType SrcType,
4026 ObjCInterfaceDecl *&RelatedClass,
4027 ObjCMethodDecl *&ClassMethod,
4028 ObjCMethodDecl *&InstanceMethod,
4029 TypedefNameDecl *&TDNDecl,
George Burgess IV60bc9722016-01-13 23:36:34 +00004030 bool CfToNs, bool Diagnose) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004031 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004032 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
4033 if (!ObjCBAttr)
4034 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004035
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004036 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
4037 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
4038 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
4039 if (!RCId)
4040 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00004041 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004042 // Check for an existing type with this name.
4043 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
4044 Sema::LookupOrdinaryName);
4045 if (!LookupName(R, TUScope)) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004046 if (Diagnose) {
4047 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
4048 << SrcType << DestType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004049 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
George Burgess IV60bc9722016-01-13 23:36:34 +00004050 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004051 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004052 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004053 Target = R.getFoundDecl();
4054 if (Target && isa<ObjCInterfaceDecl>(Target))
4055 RelatedClass = cast<ObjCInterfaceDecl>(Target);
4056 else {
George Burgess IV60bc9722016-01-13 23:36:34 +00004057 if (Diagnose) {
4058 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
4059 << SrcType << DestType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004060 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
George Burgess IV60bc9722016-01-13 23:36:34 +00004061 if (Target)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004062 Diag(Target->getBeginLoc(), diag::note_declared_at);
George Burgess IV60bc9722016-01-13 23:36:34 +00004063 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004064 return false;
4065 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004066
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004067 // Check for an existing class method with the given selector name.
4068 if (CfToNs && CMId) {
4069 Selector Sel = Context.Selectors.getUnarySelector(CMId);
4070 ClassMethod = RelatedClass->lookupMethod(Sel, false);
4071 if (!ClassMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004072 if (Diagnose) {
4073 Diag(Loc, diag::err_objc_bridged_related_known_method)
4074 << SrcType << DestType << Sel << false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004075 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
George Burgess IV60bc9722016-01-13 23:36:34 +00004076 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004077 return false;
4078 }
4079 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004080
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004081 // Check for an existing instance method with the given selector name.
4082 if (!CfToNs && IMId) {
4083 Selector Sel = Context.Selectors.getNullarySelector(IMId);
4084 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
4085 if (!InstanceMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004086 if (Diagnose) {
4087 Diag(Loc, diag::err_objc_bridged_related_known_method)
4088 << SrcType << DestType << Sel << true;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004089 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
George Burgess IV60bc9722016-01-13 23:36:34 +00004090 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004091 return false;
4092 }
4093 }
4094 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004095}
4096
4097bool
4098Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004099 QualType DestType, QualType SrcType,
George Burgess IV60bc9722016-01-13 23:36:34 +00004100 Expr *&SrcExpr, bool Diagnose) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004101 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
4102 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
4103 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
4104 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
4105 if (!CfToNs && !NsToCf)
4106 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004107
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004108 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00004109 ObjCMethodDecl *ClassMethod = nullptr;
4110 ObjCMethodDecl *InstanceMethod = nullptr;
4111 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004112 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
George Burgess IV60bc9722016-01-13 23:36:34 +00004113 ClassMethod, InstanceMethod, TDNDecl,
4114 CfToNs, Diagnose))
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004115 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004116
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004117 if (CfToNs) {
4118 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004119 if (ClassMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004120 if (Diagnose) {
4121 std::string ExpressionString = "[";
4122 ExpressionString += RelatedClass->getNameAsString();
4123 ExpressionString += " ";
4124 ExpressionString += ClassMethod->getSelector().getAsString();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004125 SourceLocation SrcExprEndLoc =
4126 getLocForEndOfToken(SrcExpr->getEndLoc());
George Burgess IV60bc9722016-01-13 23:36:34 +00004127 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
4128 Diag(Loc, diag::err_objc_bridged_related_known_method)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004129 << SrcType << DestType << ClassMethod->getSelector() << false
4130 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(),
4131 ExpressionString)
4132 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
4133 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4134 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
Fangrui Song6907ce22018-07-30 19:24:48 +00004135
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004136 QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
4137 // Argument.
4138 Expr *args[] = { SrcExpr };
4139 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004140 ClassMethod->getLocation(),
4141 ClassMethod->getSelector(), ClassMethod,
4142 MultiExprArg(args, 1));
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004143 SrcExpr = msg.get();
4144 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004145 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004146 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004147 }
4148 else {
4149 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004150 if (InstanceMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004151 if (Diagnose) {
4152 std::string ExpressionString;
4153 SourceLocation SrcExprEndLoc =
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004154 getLocForEndOfToken(SrcExpr->getEndLoc());
George Burgess IV60bc9722016-01-13 23:36:34 +00004155 if (InstanceMethod->isPropertyAccessor())
4156 if (const ObjCPropertyDecl *PDecl =
4157 InstanceMethod->findPropertyDecl()) {
4158 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
4159 ExpressionString = ".";
4160 ExpressionString += PDecl->getNameAsString();
4161 Diag(Loc, diag::err_objc_bridged_related_known_method)
4162 << SrcType << DestType << InstanceMethod->getSelector() << true
4163 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4164 }
4165 if (ExpressionString.empty()) {
4166 // Provide a fixit: [ObjectExpr InstanceMethod]
4167 ExpressionString = " ";
4168 ExpressionString += InstanceMethod->getSelector().getAsString();
4169 ExpressionString += "]";
4170
Fariborz Jahanian88b68982013-12-10 23:18:06 +00004171 Diag(Loc, diag::err_objc_bridged_related_known_method)
George Burgess IV60bc9722016-01-13 23:36:34 +00004172 << SrcType << DestType << InstanceMethod->getSelector() << true
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004173 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "[")
George Burgess IV60bc9722016-01-13 23:36:34 +00004174 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
Fariborz Jahanian88b68982013-12-10 23:18:06 +00004175 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004176 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4177 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
Fangrui Song6907ce22018-07-30 19:24:48 +00004178
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004179 ExprResult msg =
4180 BuildInstanceMessageImplicit(SrcExpr, SrcType,
4181 InstanceMethod->getLocation(),
4182 InstanceMethod->getSelector(),
4183 InstanceMethod, None);
4184 SrcExpr = msg.get();
4185 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004186 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004187 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004188 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004189 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004190}
4191
John McCall4124c492011-10-17 18:40:02 +00004192Sema::ARCConversionResult
Brian Kelley11352a82017-03-29 18:09:02 +00004193Sema::CheckObjCConversion(SourceRange castRange, QualType castType,
4194 Expr *&castExpr, CheckedConversionKind CCK,
4195 bool Diagnose, bool DiagnoseCFAudited,
4196 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00004197 QualType castExprType = castExpr->getType();
4198
4199 // For the purposes of the classification, we assume reference types
4200 // will bind to temporaries.
4201 QualType effCastType = castType;
4202 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
4203 effCastType = ref->getPointeeType();
Fangrui Song6907ce22018-07-30 19:24:48 +00004204
John McCall4124c492011-10-17 18:40:02 +00004205 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
4206 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004207 if (exprACTC == castACTC) {
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004208 // Check for viability and report error if casting an rvalue to a
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004209 // life-time qualifier.
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004210 if (castACTC == ACTC_retainable &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004211 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
George Burgess IV60bc9722016-01-13 23:36:34 +00004212 castType != castExprType) {
Fariborz Jahanian244b1872011-10-29 00:06:10 +00004213 const Type *DT = castType.getTypePtr();
4214 QualType QDT = castType;
4215 // We desugar some types but not others. We ignore those
4216 // that cannot happen in a cast; i.e. auto, and those which
4217 // should not be de-sugared; i.e typedef.
4218 if (const ParenType *PT = dyn_cast<ParenType>(DT))
4219 QDT = PT->desugar();
4220 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
4221 QDT = TP->desugar();
4222 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
4223 QDT = AT->desugar();
4224 if (QDT != castType &&
4225 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004226 if (Diagnose) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004227 SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004228 : castExpr->getExprLoc());
4229 Diag(loc, diag::err_arc_nolifetime_behavior);
4230 }
4231 return ACR_error;
Fariborz Jahanian244b1872011-10-29 00:06:10 +00004232 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004233 }
4234 return ACR_okay;
4235 }
Brian Kelley11352a82017-03-29 18:09:02 +00004236
4237 // The life-time qualifier cast check above is all we need for ObjCWeak.
4238 // ObjCAutoRefCount has more restrictions on what is legal.
4239 if (!getLangOpts().ObjCAutoRefCount)
4240 return ACR_okay;
4241
John McCall4124c492011-10-17 18:40:02 +00004242 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4243
4244 // Allow all of these types to be cast to integer types (but not
4245 // vice-versa).
4246 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4247 return ACR_okay;
Fangrui Song6907ce22018-07-30 19:24:48 +00004248
John McCall4124c492011-10-17 18:40:02 +00004249 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4250 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4251 // must be explicit.
4252 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4253 return ACR_okay;
4254 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
Richard Smith1ef75542018-06-27 20:30:34 +00004255 isCast(CCK))
John McCall4124c492011-10-17 18:40:02 +00004256 return ACR_okay;
4257
Fariborz Jahanian36986c62012-07-27 22:37:07 +00004258 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00004259 // For invalid casts, fall through.
4260 case ACC_invalid:
4261 break;
4262
4263 // Do nothing for both bottom and +0.
4264 case ACC_bottom:
4265 case ACC_plusZero:
4266 return ACR_okay;
4267
4268 // If the result is +1, consume it here.
4269 case ACC_plusOne:
4270 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4271 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00004272 nullptr, VK_RValue);
Tim Shen4a05bb82016-06-21 20:29:17 +00004273 Cleanup.setExprNeedsCleanups(true);
John McCall4124c492011-10-17 18:40:02 +00004274 return ACR_okay;
4275 }
4276
4277 // If this is a non-implicit cast from id or block type to a
4278 // CoreFoundation type, delay complaining in case the cast is used
4279 // in an acceptable context.
Richard Smith1ef75542018-06-27 20:30:34 +00004280 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && isCast(CCK))
John McCall4124c492011-10-17 18:40:02 +00004281 return ACR_unbridged;
4282
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004283 // Issue a diagnostic about a missing @-sign when implicit casting a cstring
4284 // to 'NSString *', instead of falling through to report a "bridge cast"
4285 // diagnostic.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004286 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
George Burgess IV60bc9722016-01-13 23:36:34 +00004287 ConversionToObjCStringLiteralCheck(castType, castExpr, Diagnose))
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004288 return ACR_error;
Fangrui Song6907ce22018-07-30 19:24:48 +00004289
Fariborz Jahanian25eef192013-07-31 21:40:51 +00004290 // Do not issue "bridge cast" diagnostic when implicit casting
4291 // a retainable object to a CF type parameter belonging to an audited
4292 // CF API function. Let caller issue a normal type mismatched diagnostic
4293 // instead.
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004294 if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4295 castACTC != ACTC_coreFoundation) &&
4296 !(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4297 (Opc == BO_NE || Opc == BO_EQ))) {
4298 if (Diagnose)
George Burgess IV60bc9722016-01-13 23:36:34 +00004299 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
4300 castExpr, exprACTC, CCK);
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004301 return ACR_error;
4302 }
John McCall4124c492011-10-17 18:40:02 +00004303 return ACR_okay;
4304}
4305
4306/// Given that we saw an expression with the ARCUnbridgedCastTy
4307/// placeholder type, complain bitterly.
4308void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4309 // We expect the spurious ImplicitCastExpr to already have been stripped.
4310 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4311 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4312
4313 SourceRange castRange;
4314 QualType castType;
4315 CheckedConversionKind CCK;
4316
4317 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4318 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4319 castType = cast->getTypeAsWritten();
4320 CCK = CCK_CStyleCast;
4321 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4322 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4323 castType = cast->getTypeAsWritten();
4324 CCK = CCK_OtherCast;
4325 } else {
Akira Hatanaka2cd7e862017-05-09 01:54:51 +00004326 llvm_unreachable("Unexpected ImplicitCastExpr");
John McCall4124c492011-10-17 18:40:02 +00004327 }
4328
4329 ARCConversionTypeClass castACTC =
4330 classifyTypeForARCConversion(castType.getNonReferenceType());
4331
4332 Expr *castExpr = realCast->getSubExpr();
4333 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4334
4335 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00004336 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00004337}
4338
4339/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4340/// type, remove the placeholder cast.
4341Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4342 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4343
4344 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4345 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4346 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4347 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4348 assert(uo->getOpcode() == UO_Extension);
4349 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
Aaron Ballmana5038552018-01-09 13:07:03 +00004350 return new (Context)
4351 UnaryOperator(sub, UO_Extension, sub->getType(), sub->getValueKind(),
4352 sub->getObjectKind(), uo->getOperatorLoc(), false);
John McCall4124c492011-10-17 18:40:02 +00004353 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4354 assert(!gse->isResultDependent());
4355
4356 unsigned n = gse->getNumAssocs();
Bruno Ricci1ec7fd32019-01-29 12:57:11 +00004357 SmallVector<Expr *, 4> subExprs;
4358 SmallVector<TypeSourceInfo *, 4> subTypes;
4359 subExprs.reserve(n);
4360 subTypes.reserve(n);
4361 for (const GenericSelectionExpr::Association &assoc : gse->associations()) {
4362 subTypes.push_back(assoc.getTypeSourceInfo());
4363 Expr *sub = assoc.getAssociationExpr();
4364 if (assoc.isSelected())
John McCall4124c492011-10-17 18:40:02 +00004365 sub = stripARCUnbridgedCast(sub);
Bruno Ricci1ec7fd32019-01-29 12:57:11 +00004366 subExprs.push_back(sub);
John McCall4124c492011-10-17 18:40:02 +00004367 }
4368
Bruno Riccidb076832019-01-26 14:15:10 +00004369 return GenericSelectionExpr::Create(
4370 Context, gse->getGenericLoc(), gse->getControllingExpr(), subTypes,
4371 subExprs, gse->getDefaultLoc(), gse->getRParenLoc(),
4372 gse->containsUnexpandedParameterPack(), gse->getResultIndex());
John McCall4124c492011-10-17 18:40:02 +00004373 } else {
4374 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4375 return cast<ImplicitCastExpr>(e)->getSubExpr();
4376 }
4377}
4378
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004379bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4380 QualType exprType) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004381 QualType canCastType =
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004382 Context.getCanonicalType(castType).getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +00004383 QualType canExprType =
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004384 Context.getCanonicalType(exprType).getUnqualifiedType();
4385 if (isa<ObjCObjectPointerType>(canCastType) &&
4386 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4387 canExprType->isObjCObjectPointerType()) {
4388 if (const ObjCObjectPointerType *ObjT =
4389 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00004390 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4391 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004392 }
4393 return true;
4394}
4395
John McCall4db5c3c2011-07-07 06:58:02 +00004396/// Look for an ObjCReclaimReturnedObject cast and destroy it.
4397static Expr *maybeUndoReclaimObject(Expr *e) {
Akira Hatanakacc7171a2017-10-10 01:24:33 +00004398 Expr *curExpr = e, *prevExpr = nullptr;
4399
4400 // Walk down the expression until we hit an implicit cast of kind
4401 // ARCReclaimReturnedObject or an Expr that is neither a Paren nor a Cast.
4402 while (true) {
4403 if (auto *pe = dyn_cast<ParenExpr>(curExpr)) {
4404 prevExpr = curExpr;
4405 curExpr = pe->getSubExpr();
4406 continue;
4407 }
4408
4409 if (auto *ce = dyn_cast<CastExpr>(curExpr)) {
4410 if (auto *ice = dyn_cast<ImplicitCastExpr>(ce))
4411 if (ice->getCastKind() == CK_ARCReclaimReturnedObject) {
4412 if (!prevExpr)
4413 return ice->getSubExpr();
4414 if (auto *pe = dyn_cast<ParenExpr>(prevExpr))
4415 pe->setSubExpr(ice->getSubExpr());
4416 else
4417 cast<CastExpr>(prevExpr)->setSubExpr(ice->getSubExpr());
4418 return e;
4419 }
4420
4421 prevExpr = curExpr;
4422 curExpr = ce->getSubExpr();
4423 continue;
4424 }
4425
4426 // Break out of the loop if curExpr is neither a Paren nor a Cast.
4427 break;
4428 }
John McCall4db5c3c2011-07-07 06:58:02 +00004429
4430 return e;
4431}
4432
John McCall31168b02011-06-15 23:02:42 +00004433ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4434 ObjCBridgeCastKind Kind,
4435 SourceLocation BridgeKeywordLoc,
4436 TypeSourceInfo *TSInfo,
4437 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00004438 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4439 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004440 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00004441
John McCall31168b02011-06-15 23:02:42 +00004442 QualType T = TSInfo->getType();
4443 QualType FromType = SubExpr->getType();
4444
John McCall9320b872011-09-09 05:25:32 +00004445 CastKind CK;
4446
John McCall31168b02011-06-15 23:02:42 +00004447 bool MustConsume = false;
4448 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4449 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00004450 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00004451 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4452 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00004453 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4454 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00004455 switch (Kind) {
4456 case OBC_Bridge:
4457 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004458
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004459 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004460 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00004461 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4462 << 2
4463 << FromType
4464 << (T->isBlockPointerType()? 1 : 0)
4465 << T
4466 << SubExpr->getSourceRange()
4467 << Kind;
4468 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4469 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4470 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004471 << FromType << br
Fangrui Song6907ce22018-07-30 19:24:48 +00004472 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4473 br ? "CFBridgingRelease "
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004474 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00004475
4476 Kind = OBC_Bridge;
4477 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004478 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004479
John McCall31168b02011-06-15 23:02:42 +00004480 case OBC_BridgeTransfer:
4481 // We must consume the Objective-C object produced by the cast.
4482 MustConsume = true;
4483 break;
4484 }
4485 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4486 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00004487 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00004488 switch (Kind) {
Fariborz Jahanian214567c2014-10-28 17:26:21 +00004489 case OBC_Bridge:
4490 // Reclaiming a value that's going to be __bridge-casted to CF
4491 // is very dangerous, so we don't do it.
4492 SubExpr = maybeUndoReclaimObject(SubExpr);
4493 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004494
4495 case OBC_BridgeRetained:
John McCall31168b02011-06-15 23:02:42 +00004496 // Produce the object before casting it.
4497 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00004498 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00004499 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004500 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004501
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004502 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004503 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00004504 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4505 << (FromType->isBlockPointerType()? 1 : 0)
4506 << FromType
4507 << 2
4508 << T
4509 << SubExpr->getSourceRange()
4510 << Kind;
Fangrui Song6907ce22018-07-30 19:24:48 +00004511
John McCall31168b02011-06-15 23:02:42 +00004512 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4513 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4514 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004515 << T << br
Fangrui Song6907ce22018-07-30 19:24:48 +00004516 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004517 br ? "CFBridgingRetain " : "__bridge_retained");
Fangrui Song6907ce22018-07-30 19:24:48 +00004518
John McCall31168b02011-06-15 23:02:42 +00004519 Kind = OBC_Bridge;
4520 break;
4521 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004522 }
John McCall31168b02011-06-15 23:02:42 +00004523 } else {
4524 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4525 << FromType << T << Kind
4526 << SubExpr->getSourceRange()
4527 << TSInfo->getTypeLoc().getSourceRange();
4528 return ExprError();
4529 }
4530
John McCall9320b872011-09-09 05:25:32 +00004531 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004532 BridgeKeywordLoc,
4533 TSInfo, SubExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00004534
John McCall31168b02011-06-15 23:02:42 +00004535 if (MustConsume) {
Tim Shen4a05bb82016-06-21 20:29:17 +00004536 Cleanup.setExprNeedsCleanups(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00004537 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004538 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004539 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004540
John McCall31168b02011-06-15 23:02:42 +00004541 return Result;
4542}
4543
4544ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4545 SourceLocation LParenLoc,
4546 ObjCBridgeCastKind Kind,
4547 SourceLocation BridgeKeywordLoc,
4548 ParsedType Type,
4549 SourceLocation RParenLoc,
4550 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004551 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004552 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004553 if (Kind == OBC_Bridge)
4554 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004555 if (!TSInfo)
4556 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00004557 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
John McCall31168b02011-06-15 23:02:42 +00004558 SubExpr);
4559}